| Server IP : 159.203.156.69 / Your IP : 216.73.217.172 Web Server : nginx/1.24.0 System : Linux main-ubuntu 6.8.0-71-generic #71-Ubuntu SMP PREEMPT_DYNAMIC Tue Jul 22 16:52:38 UTC 2025 x86_64 User : root ( 0) PHP Version : 8.3.6 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/tanviranik.com/node_modules/@cloudflare/vite-plugin/dist/ |
Upload File : |
import { builtinModules, createRequire } from "node:module";
import assert from "node:assert";
import { CoreHeaders, CorePaths, Log, LogLevel, Miniflare, Request as Request$1, Response as Response$1, buildPublicUrl, coupleWebSocket, getDefaultDevRegistryPath, getNodeCompat, getWorkerRegistry, kUnsafeEphemeralUniqueKey, parseModuleFallbackRequest } from "miniflare";
import * as wrangler from "wrangler";
import * as nodePath from "node:path";
import path, { dirname, isAbsolute, join, relative, resolve } from "node:path";
import * as util$1 from "node:util";
import { format, inspect, promisify } from "node:util";
import * as vite from "vite";
import { normalizePath, version } from "vite";
import { createHash, randomUUID } from "node:crypto";
import * as fs$2 from "node:fs";
import fs, { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import os, { arch } from "node:os";
import childProcess, { execFile, execFileSync, spawn } from "node:child_process";
import net from "node:net";
import { Buffer as Buffer$1 } from "node:buffer";
import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
import * as fsp from "node:fs/promises";
import fs$1, { constants as constants$1 } from "node:fs/promises";
import { getCloudflarePreset, nonPrefixedNodeModules } from "@cloudflare/unenv-preset";
import process$1 from "node:process";
import v8 from "node:v8";
import { defineEnv } from "unenv";
import * as nativeFs$1 from "fs";
import nativeFs from "fs";
import path$1, { basename, dirname as dirname$1, normalize, posix, relative as relative$1, resolve as resolve$1, sep } from "path";
import { fileURLToPath as fileURLToPath$1 } from "url";
import { createRequire as createRequire$1 } from "module";
import { WebSocketServer } from "ws";
//#region rolldown:runtime
var __create$1 = Object.create;
var __defProp$1 = Object.defineProperty;
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames$1 = Object.getOwnPropertyNames;
var __getProtoOf$1 = Object.getPrototypeOf;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __commonJS$1 = (cb, mod) => function() {
return mod || (0, cb[__getOwnPropNames$1(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps$1 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$1(from), i$1 = 0, n$1 = keys.length, key; i$1 < n$1; i$1++) {
key = keys[i$1];
if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$1(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM$1 = (mod, isNodeMode, target$1) => (target$1 = mod != null ? __create$1(__getProtoOf$1(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$1(target$1, "default", {
value: mod,
enumerable: true
}) : target$1, mod));
var __require$2 = /* @__PURE__ */ createRequire(import.meta.url);
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js
var require_constants$6 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js": ((exports, module) => {
const SEMVER_SPEC_VERSION = "2.0.0";
const MAX_LENGTH$3 = 256;
const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
const MAX_SAFE_COMPONENT_LENGTH$1 = 16;
const MAX_SAFE_BUILD_LENGTH$1 = MAX_LENGTH$3 - 6;
const RELEASE_TYPES = [
"major",
"premajor",
"minor",
"preminor",
"patch",
"prepatch",
"prerelease"
];
module.exports = {
MAX_LENGTH: MAX_LENGTH$3,
MAX_SAFE_COMPONENT_LENGTH: MAX_SAFE_COMPONENT_LENGTH$1,
MAX_SAFE_BUILD_LENGTH: MAX_SAFE_BUILD_LENGTH$1,
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 1,
FLAG_LOOSE: 2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js
var require_debug = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js": ((exports, module) => {
const debug$6 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {};
module.exports = debug$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js
var require_re = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js": ((exports, module) => {
const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, MAX_LENGTH: MAX_LENGTH$2 } = require_constants$6();
const debug$5 = require_debug();
exports = module.exports = {};
const re$4 = exports.re = [];
const safeRe = exports.safeRe = [];
const src = exports.src = [];
const safeSrc = exports.safeSrc = [];
const t$4 = exports.t = {};
let R = 0;
const LETTERDASHNUMBER = "[a-zA-Z0-9-]";
const safeRegexReplacements = [
["\\s", 1],
["\\d", MAX_LENGTH$2],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
];
const makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
return value;
};
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value);
const index = R++;
debug$5(name, index, value);
t$4[name] = index;
src[index] = value;
safeSrc[index] = safe;
re$4[index] = new RegExp(value, isGlobal ? "g" : void 0);
safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
};
createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
createToken("MAINVERSION", `(${src[t$4.NUMERICIDENTIFIER]})\\.(${src[t$4.NUMERICIDENTIFIER]})\\.(${src[t$4.NUMERICIDENTIFIER]})`);
createToken("MAINVERSIONLOOSE", `(${src[t$4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t$4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t$4.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASEIDENTIFIER", `(?:${src[t$4.NONNUMERICIDENTIFIER]}|${src[t$4.NUMERICIDENTIFIER]})`);
createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t$4.NONNUMERICIDENTIFIER]}|${src[t$4.NUMERICIDENTIFIERLOOSE]})`);
createToken("PRERELEASE", `(?:-(${src[t$4.PRERELEASEIDENTIFIER]}(?:\\.${src[t$4.PRERELEASEIDENTIFIER]})*))`);
createToken("PRERELEASELOOSE", `(?:-?(${src[t$4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t$4.PRERELEASEIDENTIFIERLOOSE]})*))`);
createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
createToken("BUILD", `(?:\\+(${src[t$4.BUILDIDENTIFIER]}(?:\\.${src[t$4.BUILDIDENTIFIER]})*))`);
createToken("FULLPLAIN", `v?${src[t$4.MAINVERSION]}${src[t$4.PRERELEASE]}?${src[t$4.BUILD]}?`);
createToken("FULL", `^${src[t$4.FULLPLAIN]}$`);
createToken("LOOSEPLAIN", `[v=\\s]*${src[t$4.MAINVERSIONLOOSE]}${src[t$4.PRERELEASELOOSE]}?${src[t$4.BUILD]}?`);
createToken("LOOSE", `^${src[t$4.LOOSEPLAIN]}$`);
createToken("GTLT", "((?:<|>)?=?)");
createToken("XRANGEIDENTIFIERLOOSE", `${src[t$4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken("XRANGEIDENTIFIER", `${src[t$4.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken("XRANGEPLAIN", `[v=\\s]*(${src[t$4.XRANGEIDENTIFIER]})(?:\\.(${src[t$4.XRANGEIDENTIFIER]})(?:\\.(${src[t$4.XRANGEIDENTIFIER]})(?:${src[t$4.PRERELEASE]})?${src[t$4.BUILD]}?)?)?`);
createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t$4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t$4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t$4.XRANGEIDENTIFIERLOOSE]})(?:${src[t$4.PRERELEASELOOSE]})?${src[t$4.BUILD]}?)?)?`);
createToken("XRANGE", `^${src[t$4.GTLT]}\\s*${src[t$4.XRANGEPLAIN]}$`);
createToken("XRANGELOOSE", `^${src[t$4.GTLT]}\\s*${src[t$4.XRANGEPLAINLOOSE]}$`);
createToken("COERCEPLAIN", `(^|[^\\d])(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
createToken("COERCE", `${src[t$4.COERCEPLAIN]}(?:$|[^\\d])`);
createToken("COERCEFULL", src[t$4.COERCEPLAIN] + `(?:${src[t$4.PRERELEASE]})?(?:${src[t$4.BUILD]})?(?:$|[^\\d])`);
createToken("COERCERTL", src[t$4.COERCE], true);
createToken("COERCERTLFULL", src[t$4.COERCEFULL], true);
createToken("LONETILDE", "(?:~>?)");
createToken("TILDETRIM", `(\\s*)${src[t$4.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = "$1~";
createToken("TILDE", `^${src[t$4.LONETILDE]}${src[t$4.XRANGEPLAIN]}$`);
createToken("TILDELOOSE", `^${src[t$4.LONETILDE]}${src[t$4.XRANGEPLAINLOOSE]}$`);
createToken("LONECARET", "(?:\\^)");
createToken("CARETTRIM", `(\\s*)${src[t$4.LONECARET]}\\s+`, true);
exports.caretTrimReplace = "$1^";
createToken("CARET", `^${src[t$4.LONECARET]}${src[t$4.XRANGEPLAIN]}$`);
createToken("CARETLOOSE", `^${src[t$4.LONECARET]}${src[t$4.XRANGEPLAINLOOSE]}$`);
createToken("COMPARATORLOOSE", `^${src[t$4.GTLT]}\\s*(${src[t$4.LOOSEPLAIN]})$|^$`);
createToken("COMPARATOR", `^${src[t$4.GTLT]}\\s*(${src[t$4.FULLPLAIN]})$|^$`);
createToken("COMPARATORTRIM", `(\\s*)${src[t$4.GTLT]}\\s*(${src[t$4.LOOSEPLAIN]}|${src[t$4.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = "$1$2$3";
createToken("HYPHENRANGE", `^\\s*(${src[t$4.XRANGEPLAIN]})\\s+-\\s+(${src[t$4.XRANGEPLAIN]})\\s*$`);
createToken("HYPHENRANGELOOSE", `^\\s*(${src[t$4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t$4.XRANGEPLAINLOOSE]})\\s*$`);
createToken("STAR", "(<|>)?=?\\s*\\*");
createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js
var require_parse_options = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js": ((exports, module) => {
const looseOption = Object.freeze({ loose: true });
const emptyOpts = Object.freeze({});
const parseOptions$3 = (options) => {
if (!options) return emptyOpts;
if (typeof options !== "object") return looseOption;
return options;
};
module.exports = parseOptions$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js
var require_identifiers = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js": ((exports, module) => {
const numeric = /^[0-9]+$/;
const compareIdentifiers$1 = (a, b) => {
if (typeof a === "number" && typeof b === "number") return a === b ? 0 : a < b ? -1 : 1;
const anum = numeric.test(a);
const bnum = numeric.test(b);
if (anum && bnum) {
a = +a;
b = +b;
}
return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
};
const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a);
module.exports = {
compareIdentifiers: compareIdentifiers$1,
rcompareIdentifiers
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js
var require_semver$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js": ((exports, module) => {
const debug$4 = require_debug();
const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = require_constants$6();
const { safeRe: re$3, t: t$3 } = require_re();
const parseOptions$2 = require_parse_options();
const { compareIdentifiers } = require_identifiers();
var SemVer$15 = class SemVer$15 {
constructor(version$2, options) {
options = parseOptions$2(options);
if (version$2 instanceof SemVer$15) if (version$2.loose === !!options.loose && version$2.includePrerelease === !!options.includePrerelease) return version$2;
else version$2 = version$2.version;
else if (typeof version$2 !== "string") throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version$2}".`);
if (version$2.length > MAX_LENGTH$1) throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
debug$4("SemVer", version$2, options);
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
const m = version$2.trim().match(options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL]);
if (!m) throw new TypeError(`Invalid Version: ${version$2}`);
this.raw = version$2;
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError("Invalid major version");
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError("Invalid minor version");
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError("Invalid patch version");
if (!m[4]) this.prerelease = [];
else this.prerelease = m[4].split(".").map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
}
return id;
});
this.build = m[5] ? m[5].split(".") : [];
this.format();
}
format() {
this.version = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) this.version += `-${this.prerelease.join(".")}`;
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug$4("SemVer.compare", this.version, this.options, other);
if (!(other instanceof SemVer$15)) {
if (typeof other === "string" && other === this.version) return 0;
other = new SemVer$15(other, this.options);
}
if (other.version === this.version) return 0;
return this.compareMain(other) || this.comparePre(other);
}
compareMain(other) {
if (!(other instanceof SemVer$15)) other = new SemVer$15(other, this.options);
if (this.major < other.major) return -1;
if (this.major > other.major) return 1;
if (this.minor < other.minor) return -1;
if (this.minor > other.minor) return 1;
if (this.patch < other.patch) return -1;
if (this.patch > other.patch) return 1;
return 0;
}
comparePre(other) {
if (!(other instanceof SemVer$15)) other = new SemVer$15(other, this.options);
if (this.prerelease.length && !other.prerelease.length) return -1;
else if (!this.prerelease.length && other.prerelease.length) return 1;
else if (!this.prerelease.length && !other.prerelease.length) return 0;
let i$1 = 0;
do {
const a = this.prerelease[i$1];
const b = other.prerelease[i$1];
debug$4("prerelease compare", i$1, a, b);
if (a === void 0 && b === void 0) return 0;
else if (b === void 0) return 1;
else if (a === void 0) return -1;
else if (a === b) continue;
else return compareIdentifiers(a, b);
} while (++i$1);
}
compareBuild(other) {
if (!(other instanceof SemVer$15)) other = new SemVer$15(other, this.options);
let i$1 = 0;
do {
const a = this.build[i$1];
const b = other.build[i$1];
debug$4("build compare", i$1, a, b);
if (a === void 0 && b === void 0) return 0;
else if (b === void 0) return 1;
else if (a === void 0) return -1;
else if (a === b) continue;
else return compareIdentifiers(a, b);
} while (++i$1);
}
inc(release, identifier, identifierBase) {
if (release.startsWith("pre")) {
if (!identifier && identifierBase === false) throw new Error("invalid increment argument: identifier is empty");
if (identifier) {
const match = `-${identifier}`.match(this.options.loose ? re$3[t$3.PRERELEASELOOSE] : re$3[t$3.PRERELEASE]);
if (!match || match[1] !== identifier) throw new Error(`invalid identifier: ${identifier}`);
}
}
switch (release) {
case "premajor":
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc("pre", identifier, identifierBase);
break;
case "preminor":
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc("pre", identifier, identifierBase);
break;
case "prepatch":
this.prerelease.length = 0;
this.inc("patch", identifier, identifierBase);
this.inc("pre", identifier, identifierBase);
break;
case "prerelease":
if (this.prerelease.length === 0) this.inc("patch", identifier, identifierBase);
this.inc("pre", identifier, identifierBase);
break;
case "release":
if (this.prerelease.length === 0) throw new Error(`version ${this.raw} is not a prerelease`);
this.prerelease.length = 0;
break;
case "major":
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case "minor":
if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
this.patch = 0;
this.prerelease = [];
break;
case "patch":
if (this.prerelease.length === 0) this.patch++;
this.prerelease = [];
break;
case "pre": {
const base = Number(identifierBase) ? 1 : 0;
if (this.prerelease.length === 0) this.prerelease = [base];
else {
let i$1 = this.prerelease.length;
while (--i$1 >= 0) if (typeof this.prerelease[i$1] === "number") {
this.prerelease[i$1]++;
i$1 = -2;
}
if (i$1 === -1) {
if (identifier === this.prerelease.join(".") && identifierBase === false) throw new Error("invalid increment argument: identifier already exists");
this.prerelease.push(base);
}
}
if (identifier) {
let prerelease$2 = [identifier, base];
if (identifierBase === false) prerelease$2 = [identifier];
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) this.prerelease = prerelease$2;
} else this.prerelease = prerelease$2;
}
break;
}
default: throw new Error(`invalid increment argument: ${release}`);
}
this.raw = this.format();
if (this.build.length) this.raw += `+${this.build.join(".")}`;
return this;
}
};
module.exports = SemVer$15;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js
var require_parse$2 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js": ((exports, module) => {
const SemVer$14 = require_semver$1();
const parse$9 = (version$2, options, throwErrors = false) => {
if (version$2 instanceof SemVer$14) return version$2;
try {
return new SemVer$14(version$2, options);
} catch (er) {
if (!throwErrors) return null;
throw er;
}
};
module.exports = parse$9;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/valid.js
var require_valid$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/valid.js": ((exports, module) => {
const parse$8 = require_parse$2();
const valid$1 = (version$2, options) => {
const v = parse$8(version$2, options);
return v ? v.version : null;
};
module.exports = valid$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/clean.js
var require_clean = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/clean.js": ((exports, module) => {
const parse$7 = require_parse$2();
const clean$1 = (version$2, options) => {
const s = parse$7(version$2.trim().replace(/^[=v]+/, ""), options);
return s ? s.version : null;
};
module.exports = clean$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/inc.js
var require_inc = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/inc.js": ((exports, module) => {
const SemVer$13 = require_semver$1();
const inc$1 = (version$2, release, options, identifier, identifierBase) => {
if (typeof options === "string") {
identifierBase = identifier;
identifier = options;
options = void 0;
}
try {
return new SemVer$13(version$2 instanceof SemVer$13 ? version$2.version : version$2, options).inc(release, identifier, identifierBase).version;
} catch (er) {
return null;
}
};
module.exports = inc$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/diff.js
var require_diff = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/diff.js": ((exports, module) => {
const parse$6 = require_parse$2();
const diff$1 = (version1, version2) => {
const v1 = parse$6(version1, null, true);
const v2 = parse$6(version2, null, true);
const comparison = v1.compare(v2);
if (comparison === 0) return null;
const v1Higher = comparison > 0;
const highVersion = v1Higher ? v1 : v2;
const lowVersion = v1Higher ? v2 : v1;
const highHasPre = !!highVersion.prerelease.length;
if (!!lowVersion.prerelease.length && !highHasPre) {
if (!lowVersion.patch && !lowVersion.minor) return "major";
if (lowVersion.compareMain(highVersion) === 0) {
if (lowVersion.minor && !lowVersion.patch) return "minor";
return "patch";
}
}
const prefix = highHasPre ? "pre" : "";
if (v1.major !== v2.major) return prefix + "major";
if (v1.minor !== v2.minor) return prefix + "minor";
if (v1.patch !== v2.patch) return prefix + "patch";
return "prerelease";
};
module.exports = diff$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/major.js
var require_major = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/major.js": ((exports, module) => {
const SemVer$12 = require_semver$1();
const major$1 = (a, loose) => new SemVer$12(a, loose).major;
module.exports = major$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/minor.js
var require_minor = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/minor.js": ((exports, module) => {
const SemVer$11 = require_semver$1();
const minor$1 = (a, loose) => new SemVer$11(a, loose).minor;
module.exports = minor$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/patch.js
var require_patch = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/patch.js": ((exports, module) => {
const SemVer$10 = require_semver$1();
const patch$1 = (a, loose) => new SemVer$10(a, loose).patch;
module.exports = patch$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/prerelease.js
var require_prerelease = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/prerelease.js": ((exports, module) => {
const parse$5 = require_parse$2();
const prerelease$1 = (version$2, options) => {
const parsed = parse$5(version$2, options);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
};
module.exports = prerelease$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js
var require_compare = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js": ((exports, module) => {
const SemVer$9 = require_semver$1();
const compare$11 = (a, b, loose) => new SemVer$9(a, loose).compare(new SemVer$9(b, loose));
module.exports = compare$11;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rcompare.js
var require_rcompare = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rcompare.js": ((exports, module) => {
const compare$10 = require_compare();
const rcompare$1 = (a, b, loose) => compare$10(b, a, loose);
module.exports = rcompare$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-loose.js
var require_compare_loose = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-loose.js": ((exports, module) => {
const compare$9 = require_compare();
const compareLoose$1 = (a, b) => compare$9(a, b, true);
module.exports = compareLoose$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-build.js
var require_compare_build = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-build.js": ((exports, module) => {
const SemVer$8 = require_semver$1();
const compareBuild$3 = (a, b, loose) => {
const versionA = new SemVer$8(a, loose);
const versionB = new SemVer$8(b, loose);
return versionA.compare(versionB) || versionA.compareBuild(versionB);
};
module.exports = compareBuild$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/sort.js
var require_sort = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/sort.js": ((exports, module) => {
const compareBuild$2 = require_compare_build();
const sort$1 = (list$1, loose) => list$1.sort((a, b) => compareBuild$2(a, b, loose));
module.exports = sort$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rsort.js
var require_rsort = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rsort.js": ((exports, module) => {
const compareBuild$1 = require_compare_build();
const rsort$1 = (list$1, loose) => list$1.sort((a, b) => compareBuild$1(b, a, loose));
module.exports = rsort$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js
var require_gt = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js": ((exports, module) => {
const compare$8 = require_compare();
const gt$4 = (a, b, loose) => compare$8(a, b, loose) > 0;
module.exports = gt$4;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js
var require_lt = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js": ((exports, module) => {
const compare$7 = require_compare();
const lt$3 = (a, b, loose) => compare$7(a, b, loose) < 0;
module.exports = lt$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js
var require_eq = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js": ((exports, module) => {
const compare$6 = require_compare();
const eq$2 = (a, b, loose) => compare$6(a, b, loose) === 0;
module.exports = eq$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js
var require_neq = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js": ((exports, module) => {
const compare$5 = require_compare();
const neq$2 = (a, b, loose) => compare$5(a, b, loose) !== 0;
module.exports = neq$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js
var require_gte = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js": ((exports, module) => {
const compare$4 = require_compare();
const gte$3 = (a, b, loose) => compare$4(a, b, loose) >= 0;
module.exports = gte$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js
var require_lte = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js": ((exports, module) => {
const compare$3 = require_compare();
const lte$3 = (a, b, loose) => compare$3(a, b, loose) <= 0;
module.exports = lte$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js
var require_cmp = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js": ((exports, module) => {
const eq$1 = require_eq();
const neq$1 = require_neq();
const gt$3 = require_gt();
const gte$2 = require_gte();
const lt$2 = require_lt();
const lte$2 = require_lte();
const cmp$2 = (a, op, b, loose) => {
switch (op) {
case "===":
if (typeof a === "object") a = a.version;
if (typeof b === "object") b = b.version;
return a === b;
case "!==":
if (typeof a === "object") a = a.version;
if (typeof b === "object") b = b.version;
return a !== b;
case "":
case "=":
case "==": return eq$1(a, b, loose);
case "!=": return neq$1(a, b, loose);
case ">": return gt$3(a, b, loose);
case ">=": return gte$2(a, b, loose);
case "<": return lt$2(a, b, loose);
case "<=": return lte$2(a, b, loose);
default: throw new TypeError(`Invalid operator: ${op}`);
}
};
module.exports = cmp$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js
var require_coerce = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js": ((exports, module) => {
const SemVer$7 = require_semver$1();
const parse$4 = require_parse$2();
const { safeRe: re$2, t: t$2 } = require_re();
const coerce$2 = (version$2, options) => {
if (version$2 instanceof SemVer$7) return version$2;
if (typeof version$2 === "number") version$2 = String(version$2);
if (typeof version$2 !== "string") return null;
options = options || {};
let match = null;
if (!options.rtl) match = version$2.match(options.includePrerelease ? re$2[t$2.COERCEFULL] : re$2[t$2.COERCE]);
else {
const coerceRtlRegex = options.includePrerelease ? re$2[t$2.COERCERTLFULL] : re$2[t$2.COERCERTL];
let next;
while ((next = coerceRtlRegex.exec(version$2)) && (!match || match.index + match[0].length !== version$2.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) match = next;
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
}
coerceRtlRegex.lastIndex = -1;
}
if (match === null) return null;
const major$2 = match[2];
return parse$4(`${major$2}.${match[3] || "0"}.${match[4] || "0"}${options.includePrerelease && match[5] ? `-${match[5]}` : ""}${options.includePrerelease && match[6] ? `+${match[6]}` : ""}`, options);
};
module.exports = coerce$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js
var require_lrucache = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js": ((exports, module) => {
var LRUCache = class {
constructor() {
this.max = 1e3;
this.map = /* @__PURE__ */ new Map();
}
get(key) {
const value = this.map.get(key);
if (value === void 0) return;
else {
this.map.delete(key);
this.map.set(key, value);
return value;
}
}
delete(key) {
return this.map.delete(key);
}
set(key, value) {
if (!this.delete(key) && value !== void 0) {
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value;
this.delete(firstKey);
}
this.map.set(key, value);
}
return this;
}
};
module.exports = LRUCache;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js
var require_range = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js": ((exports, module) => {
const SPACE_CHARACTERS = /\s+/g;
var Range$11 = class Range$11 {
constructor(range, options) {
options = parseOptions$1(options);
if (range instanceof Range$11) if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) return range;
else return new Range$11(range.raw, options);
if (range instanceof Comparator$4) {
this.raw = range.value;
this.set = [[range]];
this.formatted = void 0;
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
this.set = this.raw.split("||").map((r$1) => this.parseRange(r$1.trim())).filter((c) => c.length);
if (!this.set.length) throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
if (this.set.length > 1) {
const first = this.set[0];
this.set = this.set.filter((c) => !isNullSet(c[0]));
if (this.set.length === 0) this.set = [first];
else if (this.set.length > 1) {
for (const c of this.set) if (c.length === 1 && isAny(c[0])) {
this.set = [c];
break;
}
}
}
this.formatted = void 0;
}
get range() {
if (this.formatted === void 0) {
this.formatted = "";
for (let i$1 = 0; i$1 < this.set.length; i$1++) {
if (i$1 > 0) this.formatted += "||";
const comps = this.set[i$1];
for (let k = 0; k < comps.length; k++) {
if (k > 0) this.formatted += " ";
this.formatted += comps[k].toString().trim();
}
}
}
return this.formatted;
}
format() {
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
const memoKey = ((this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE)) + ":" + range;
const cached = cache$1.get(memoKey);
if (cached) return cached;
const loose = this.options.loose;
const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug$3("hyphen replace", range);
range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace);
debug$3("comparator trim", range);
range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace);
debug$3("tilde trim", range);
range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace);
debug$3("caret trim", range);
let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
if (loose) rangeList = rangeList.filter((comp) => {
debug$3("loose invalid filter", comp, this.options);
return !!comp.match(re$1[t$1.COMPARATORLOOSE]);
});
debug$3("range list", rangeList);
const rangeMap = /* @__PURE__ */ new Map();
const comparators = rangeList.map((comp) => new Comparator$4(comp, this.options));
for (const comp of comparators) {
if (isNullSet(comp)) return [comp];
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has("")) rangeMap.delete("");
const result = [...rangeMap.values()];
cache$1.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range$11)) throw new TypeError("a Range is required");
return this.set.some((thisComparators) => {
return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
}
test(version$2) {
if (!version$2) return false;
if (typeof version$2 === "string") try {
version$2 = new SemVer$6(version$2, this.options);
} catch (er) {
return false;
}
for (let i$1 = 0; i$1 < this.set.length; i$1++) if (testSet(this.set[i$1], version$2, this.options)) return true;
return false;
}
};
module.exports = Range$11;
const cache$1 = new (require_lrucache())();
const parseOptions$1 = require_parse_options();
const Comparator$4 = require_comparator();
const debug$3 = require_debug();
const SemVer$6 = require_semver$1();
const { safeRe: re$1, t: t$1, comparatorTrimReplace, tildeTrimReplace, caretTrimReplace } = require_re();
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants$6();
const isNullSet = (c) => c.value === "<0.0.0-0";
const isAny = (c) => c.value === "";
const isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
};
const parseComparator = (comp, options) => {
comp = comp.replace(re$1[t$1.BUILD], "");
debug$3("comp", comp, options);
comp = replaceCarets(comp, options);
debug$3("caret", comp);
comp = replaceTildes(comp, options);
debug$3("tildes", comp);
comp = replaceXRanges(comp, options);
debug$3("xrange", comp);
comp = replaceStars(comp, options);
debug$3("stars", comp);
return comp;
};
const isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
const replaceTildes = (comp, options) => {
return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");
};
const replaceTilde = (comp, options) => {
const r$1 = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE];
return comp.replace(r$1, (_, M, m, p$1, pr) => {
debug$3("tilde", comp, _, M, m, p$1, pr);
let ret;
if (isX(M)) ret = "";
else if (isX(m)) ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
else if (isX(p$1)) ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
else if (pr) {
debug$3("replaceTilde pr", pr);
ret = `>=${M}.${m}.${p$1}-${pr} <${M}.${+m + 1}.0-0`;
} else ret = `>=${M}.${m}.${p$1} <${M}.${+m + 1}.0-0`;
debug$3("tilde return", ret);
return ret;
});
};
const replaceCarets = (comp, options) => {
return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");
};
const replaceCaret = (comp, options) => {
debug$3("caret", comp, options);
const r$1 = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET];
const z$1 = options.includePrerelease ? "-0" : "";
return comp.replace(r$1, (_, M, m, p$1, pr) => {
debug$3("caret", comp, _, M, m, p$1, pr);
let ret;
if (isX(M)) ret = "";
else if (isX(m)) ret = `>=${M}.0.0${z$1} <${+M + 1}.0.0-0`;
else if (isX(p$1)) if (M === "0") ret = `>=${M}.${m}.0${z$1} <${M}.${+m + 1}.0-0`;
else ret = `>=${M}.${m}.0${z$1} <${+M + 1}.0.0-0`;
else if (pr) {
debug$3("replaceCaret pr", pr);
if (M === "0") if (m === "0") ret = `>=${M}.${m}.${p$1}-${pr} <${M}.${m}.${+p$1 + 1}-0`;
else ret = `>=${M}.${m}.${p$1}-${pr} <${M}.${+m + 1}.0-0`;
else ret = `>=${M}.${m}.${p$1}-${pr} <${+M + 1}.0.0-0`;
} else {
debug$3("no pr");
if (M === "0") if (m === "0") ret = `>=${M}.${m}.${p$1}${z$1} <${M}.${m}.${+p$1 + 1}-0`;
else ret = `>=${M}.${m}.${p$1}${z$1} <${M}.${+m + 1}.0-0`;
else ret = `>=${M}.${m}.${p$1} <${+M + 1}.0.0-0`;
}
debug$3("caret return", ret);
return ret;
});
};
const replaceXRanges = (comp, options) => {
debug$3("replaceXRanges", comp, options);
return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");
};
const replaceXRange = (comp, options) => {
comp = comp.trim();
const r$1 = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE];
return comp.replace(r$1, (ret, gtlt, M, m, p$1, pr) => {
debug$3("xRange", comp, ret, gtlt, M, m, p$1, pr);
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p$1);
const anyX = xp;
if (gtlt === "=" && anyX) gtlt = "";
pr = options.includePrerelease ? "-0" : "";
if (xM) if (gtlt === ">" || gtlt === "<") ret = "<0.0.0-0";
else ret = "*";
else if (gtlt && anyX) {
if (xm) m = 0;
p$1 = 0;
if (gtlt === ">") {
gtlt = ">=";
if (xm) {
M = +M + 1;
m = 0;
p$1 = 0;
} else {
m = +m + 1;
p$1 = 0;
}
} else if (gtlt === "<=") {
gtlt = "<";
if (xm) M = +M + 1;
else m = +m + 1;
}
if (gtlt === "<") pr = "-0";
ret = `${gtlt + M}.${m}.${p$1}${pr}`;
} else if (xm) ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
else if (xp) ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
debug$3("xRange return", ret);
return ret;
});
};
const replaceStars = (comp, options) => {
debug$3("replaceStars", comp, options);
return comp.trim().replace(re$1[t$1.STAR], "");
};
const replaceGTE0 = (comp, options) => {
debug$3("replaceGTE0", comp, options);
return comp.trim().replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], "");
};
const hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) from = "";
else if (isX(fm)) from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
else if (isX(fp)) from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
else if (fpr) from = `>=${from}`;
else from = `>=${from}${incPr ? "-0" : ""}`;
if (isX(tM)) to = "";
else if (isX(tm)) to = `<${+tM + 1}.0.0-0`;
else if (isX(tp)) to = `<${tM}.${+tm + 1}.0-0`;
else if (tpr) to = `<=${tM}.${tm}.${tp}-${tpr}`;
else if (incPr) to = `<${tM}.${tm}.${+tp + 1}-0`;
else to = `<=${to}`;
return `${from} ${to}`.trim();
};
const testSet = (set, version$2, options) => {
for (let i$1 = 0; i$1 < set.length; i$1++) if (!set[i$1].test(version$2)) return false;
if (version$2.prerelease.length && !options.includePrerelease) {
for (let i$1 = 0; i$1 < set.length; i$1++) {
debug$3(set[i$1].semver);
if (set[i$1].semver === Comparator$4.ANY) continue;
if (set[i$1].semver.prerelease.length > 0) {
const allowed = set[i$1].semver;
if (allowed.major === version$2.major && allowed.minor === version$2.minor && allowed.patch === version$2.patch) return true;
}
}
return false;
}
return true;
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js
var require_comparator = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js": ((exports, module) => {
const ANY$2 = Symbol("SemVer ANY");
var Comparator$3 = class Comparator$3 {
static get ANY() {
return ANY$2;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator$3) if (comp.loose === !!options.loose) return comp;
else comp = comp.value;
comp = comp.trim().split(/\s+/).join(" ");
debug$2("comparator", comp, options);
this.options = options;
this.loose = !!options.loose;
this.parse(comp);
if (this.semver === ANY$2) this.value = "";
else this.value = this.operator + this.semver.version;
debug$2("comp", this);
}
parse(comp) {
const r$1 = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r$1);
if (!m) throw new TypeError(`Invalid comparator: ${comp}`);
this.operator = m[1] !== void 0 ? m[1] : "";
if (this.operator === "=") this.operator = "";
if (!m[2]) this.semver = ANY$2;
else this.semver = new SemVer$5(m[2], this.options.loose);
}
toString() {
return this.value;
}
test(version$2) {
debug$2("Comparator.test", version$2, this.options.loose);
if (this.semver === ANY$2 || version$2 === ANY$2) return true;
if (typeof version$2 === "string") try {
version$2 = new SemVer$5(version$2, this.options);
} catch (er) {
return false;
}
return cmp$1(version$2, this.operator, this.semver, this.options);
}
intersects(comp, options) {
if (!(comp instanceof Comparator$3)) throw new TypeError("a Comparator is required");
if (this.operator === "") {
if (this.value === "") return true;
return new Range$10(comp.value, options).test(this.value);
} else if (comp.operator === "") {
if (comp.value === "") return true;
return new Range$10(this.value, options).test(comp.semver);
}
options = parseOptions(options);
if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) return false;
if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) return false;
if (this.operator.startsWith(">") && comp.operator.startsWith(">")) return true;
if (this.operator.startsWith("<") && comp.operator.startsWith("<")) return true;
if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) return true;
if (cmp$1(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) return true;
if (cmp$1(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) return true;
return false;
}
};
module.exports = Comparator$3;
const parseOptions = require_parse_options();
const { safeRe: re, t } = require_re();
const cmp$1 = require_cmp();
const debug$2 = require_debug();
const SemVer$5 = require_semver$1();
const Range$10 = require_range();
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js
var require_satisfies = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js": ((exports, module) => {
const Range$9 = require_range();
const satisfies$5 = (version$2, range, options) => {
try {
range = new Range$9(range, options);
} catch (er) {
return false;
}
return range.test(version$2);
};
module.exports = satisfies$5;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/to-comparators.js
var require_to_comparators = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/to-comparators.js": ((exports, module) => {
const Range$8 = require_range();
const toComparators$1 = (range, options) => new Range$8(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));
module.exports = toComparators$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/max-satisfying.js": ((exports, module) => {
const SemVer$4 = require_semver$1();
const Range$7 = require_range();
const maxSatisfying$1 = (versions, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range$7(range, options);
} catch (er) {
return null;
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
if (!max || maxSV.compare(v) === -1) {
max = v;
maxSV = new SemVer$4(max, options);
}
}
});
return max;
};
module.exports = maxSatisfying$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-satisfying.js": ((exports, module) => {
const SemVer$3 = require_semver$1();
const Range$6 = require_range();
const minSatisfying$1 = (versions, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range$6(range, options);
} catch (er) {
return null;
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
if (!min || minSV.compare(v) === 1) {
min = v;
minSV = new SemVer$3(min, options);
}
}
});
return min;
};
module.exports = minSatisfying$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-version.js
var require_min_version = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-version.js": ((exports, module) => {
const SemVer$2 = require_semver$1();
const Range$5 = require_range();
const gt$2 = require_gt();
const minVersion$1 = (range, loose) => {
range = new Range$5(range, loose);
let minver = new SemVer$2("0.0.0");
if (range.test(minver)) return minver;
minver = new SemVer$2("0.0.0-0");
if (range.test(minver)) return minver;
minver = null;
for (let i$1 = 0; i$1 < range.set.length; ++i$1) {
const comparators = range.set[i$1];
let setMin = null;
comparators.forEach((comparator) => {
const compver = new SemVer$2(comparator.semver.version);
switch (comparator.operator) {
case ">":
if (compver.prerelease.length === 0) compver.patch++;
else compver.prerelease.push(0);
compver.raw = compver.format();
case "":
case ">=":
if (!setMin || gt$2(compver, setMin)) setMin = compver;
break;
case "<":
case "<=": break;
default: throw new Error(`Unexpected operation: ${comparator.operator}`);
}
});
if (setMin && (!minver || gt$2(minver, setMin))) minver = setMin;
}
if (minver && range.test(minver)) return minver;
return null;
};
module.exports = minVersion$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/valid.js
var require_valid = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/valid.js": ((exports, module) => {
const Range$4 = require_range();
const validRange$1 = (range, options) => {
try {
return new Range$4(range, options).range || "*";
} catch (er) {
return null;
}
};
module.exports = validRange$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/outside.js
var require_outside = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/outside.js": ((exports, module) => {
const SemVer$1 = require_semver$1();
const Comparator$2 = require_comparator();
const { ANY: ANY$1 } = Comparator$2;
const Range$3 = require_range();
const satisfies$4 = require_satisfies();
const gt$1 = require_gt();
const lt$1 = require_lt();
const lte$1 = require_lte();
const gte$1 = require_gte();
const outside$3 = (version$2, range, hilo, options) => {
version$2 = new SemVer$1(version$2, options);
range = new Range$3(range, options);
let gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case ">":
gtfn = gt$1;
ltefn = lte$1;
ltfn = lt$1;
comp = ">";
ecomp = ">=";
break;
case "<":
gtfn = lt$1;
ltefn = gte$1;
ltfn = gt$1;
comp = "<";
ecomp = "<=";
break;
default: throw new TypeError("Must provide a hilo val of \"<\" or \">\"");
}
if (satisfies$4(version$2, range, options)) return false;
for (let i$1 = 0; i$1 < range.set.length; ++i$1) {
const comparators = range.set[i$1];
let high = null;
let low = null;
comparators.forEach((comparator) => {
if (comparator.semver === ANY$1) comparator = new Comparator$2(">=0.0.0");
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, options)) high = comparator;
else if (ltfn(comparator.semver, low.semver, options)) low = comparator;
});
if (high.operator === comp || high.operator === ecomp) return false;
if ((!low.operator || low.operator === comp) && ltefn(version$2, low.semver)) return false;
else if (low.operator === ecomp && ltfn(version$2, low.semver)) return false;
}
return true;
};
module.exports = outside$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/gtr.js
var require_gtr = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/gtr.js": ((exports, module) => {
const outside$2 = require_outside();
const gtr$1 = (version$2, range, options) => outside$2(version$2, range, ">", options);
module.exports = gtr$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/ltr.js
var require_ltr = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/ltr.js": ((exports, module) => {
const outside$1 = require_outside();
const ltr$1 = (version$2, range, options) => outside$1(version$2, range, "<", options);
module.exports = ltr$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/intersects.js
var require_intersects = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/intersects.js": ((exports, module) => {
const Range$2 = require_range();
const intersects$1 = (r1, r2, options) => {
r1 = new Range$2(r1, options);
r2 = new Range$2(r2, options);
return r1.intersects(r2, options);
};
module.exports = intersects$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/simplify.js
var require_simplify = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/simplify.js": ((exports, module) => {
const satisfies$3 = require_satisfies();
const compare$2 = require_compare();
module.exports = (versions, range, options) => {
const set = [];
let first = null;
let prev = null;
const v = versions.sort((a, b) => compare$2(a, b, options));
for (const version$2 of v) if (satisfies$3(version$2, range, options)) {
prev = version$2;
if (!first) first = version$2;
} else {
if (prev) set.push([first, prev]);
prev = null;
first = null;
}
if (first) set.push([first, null]);
const ranges = [];
for (const [min, max] of set) if (min === max) ranges.push(min);
else if (!max && min === v[0]) ranges.push("*");
else if (!max) ranges.push(`>=${min}`);
else if (min === v[0]) ranges.push(`<=${max}`);
else ranges.push(`${min} - ${max}`);
const simplified = ranges.join(" || ");
const original = typeof range.raw === "string" ? range.raw : String(range);
return simplified.length < original.length ? simplified : range;
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/subset.js
var require_subset = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/subset.js": ((exports, module) => {
const Range$1 = require_range();
const Comparator$1 = require_comparator();
const { ANY } = Comparator$1;
const satisfies$2 = require_satisfies();
const compare$1 = require_compare();
const subset$1 = (sub, dom, options = {}) => {
if (sub === dom) return true;
sub = new Range$1(sub, options);
dom = new Range$1(dom, options);
let sawNonNull = false;
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options);
sawNonNull = sawNonNull || isSub !== null;
if (isSub) continue OUTER;
}
if (sawNonNull) return false;
}
return true;
};
const minimumVersionWithPreRelease = [new Comparator$1(">=0.0.0-0")];
const minimumVersion = [new Comparator$1(">=0.0.0")];
const simpleSubset = (sub, dom, options) => {
if (sub === dom) return true;
if (sub.length === 1 && sub[0].semver === ANY) if (dom.length === 1 && dom[0].semver === ANY) return true;
else if (options.includePrerelease) sub = minimumVersionWithPreRelease;
else sub = minimumVersion;
if (dom.length === 1 && dom[0].semver === ANY) if (options.includePrerelease) return true;
else dom = minimumVersion;
const eqSet = /* @__PURE__ */ new Set();
let gt$5, lt$4;
for (const c of sub) if (c.operator === ">" || c.operator === ">=") gt$5 = higherGT(gt$5, c, options);
else if (c.operator === "<" || c.operator === "<=") lt$4 = lowerLT(lt$4, c, options);
else eqSet.add(c.semver);
if (eqSet.size > 1) return null;
let gtltComp;
if (gt$5 && lt$4) {
gtltComp = compare$1(gt$5.semver, lt$4.semver, options);
if (gtltComp > 0) return null;
else if (gtltComp === 0 && (gt$5.operator !== ">=" || lt$4.operator !== "<=")) return null;
}
for (const eq$3 of eqSet) {
if (gt$5 && !satisfies$2(eq$3, String(gt$5), options)) return null;
if (lt$4 && !satisfies$2(eq$3, String(lt$4), options)) return null;
for (const c of dom) if (!satisfies$2(eq$3, String(c), options)) return false;
return true;
}
let higher, lower;
let hasDomLT, hasDomGT;
let needDomLTPre = lt$4 && !options.includePrerelease && lt$4.semver.prerelease.length ? lt$4.semver : false;
let needDomGTPre = gt$5 && !options.includePrerelease && gt$5.semver.prerelease.length ? gt$5.semver : false;
if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt$4.operator === "<" && needDomLTPre.prerelease[0] === 0) needDomLTPre = false;
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";
hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";
if (gt$5) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) needDomGTPre = false;
}
if (c.operator === ">" || c.operator === ">=") {
higher = higherGT(gt$5, c, options);
if (higher === c && higher !== gt$5) return false;
} else if (gt$5.operator === ">=" && !satisfies$2(gt$5.semver, String(c), options)) return false;
}
if (lt$4) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) needDomLTPre = false;
}
if (c.operator === "<" || c.operator === "<=") {
lower = lowerLT(lt$4, c, options);
if (lower === c && lower !== lt$4) return false;
} else if (lt$4.operator === "<=" && !satisfies$2(lt$4.semver, String(c), options)) return false;
}
if (!c.operator && (lt$4 || gt$5) && gtltComp !== 0) return false;
}
if (gt$5 && hasDomLT && !lt$4 && gtltComp !== 0) return false;
if (lt$4 && hasDomGT && !gt$5 && gtltComp !== 0) return false;
if (needDomGTPre || needDomLTPre) return false;
return true;
};
const higherGT = (a, b, options) => {
if (!a) return b;
const comp = compare$1(a.semver, b.semver, options);
return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
};
const lowerLT = (a, b, options) => {
if (!a) return b;
const comp = compare$1(a.semver, b.semver, options);
return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
};
module.exports = subset$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/index.js
var require_semver = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/index.js": ((exports, module) => {
const internalRe = require_re();
const constants$5 = require_constants$6();
const SemVer = require_semver$1();
const identifiers = require_identifiers();
const parse$3 = require_parse$2();
const valid = require_valid$1();
const clean = require_clean();
const inc = require_inc();
const diff = require_diff();
const major = require_major();
const minor = require_minor();
const patch = require_patch();
const prerelease = require_prerelease();
const compare = require_compare();
const rcompare = require_rcompare();
const compareLoose = require_compare_loose();
const compareBuild = require_compare_build();
const sort = require_sort();
const rsort = require_rsort();
const gt = require_gt();
const lt = require_lt();
const eq = require_eq();
const neq = require_neq();
const gte = require_gte();
const lte = require_lte();
const cmp = require_cmp();
const coerce$1 = require_coerce();
const Comparator = require_comparator();
const Range = require_range();
const satisfies$1 = require_satisfies();
const toComparators = require_to_comparators();
const maxSatisfying = require_max_satisfying();
const minSatisfying = require_min_satisfying();
const minVersion = require_min_version();
const validRange = require_valid();
const outside = require_outside();
const gtr = require_gtr();
const ltr = require_ltr();
const intersects = require_intersects();
const simplifyRange = require_simplify();
const subset = require_subset();
module.exports = {
parse: parse$3,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce: coerce$1,
Comparator,
Range,
satisfies: satisfies$1,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants$5.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants$5.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers
};
}) });
//#endregion
//#region src/assert-wrangler-version.ts
var import_semver = require_semver();
/**
* Asserts that the installed version of Wrangler that gets pulled in at runtime by the `@cloudflare/vite-plugin`
* matches the version that `@cloudflare/vite-plugin` actually depends upon.
*
* This can sometime be broken by package managers that deduplicate dependencies, such as `pnpm`.
*/
async function assertWranglerVersion() {
const installedVersion = (await import("wrangler/package.json", { with: { type: "json" } })).default.version;
const peerDependency = (await import("../package.json", { with: { type: "json" } })).default.peerDependencies.wrangler;
if (peerDependency.startsWith("workspace:")) return;
if (!(0, import_semver.satisfies)(installedVersion, peerDependency)) throw new Error(`The installed version of Wrangler (${installedVersion}) does not satisfy the peer dependency required by @cloudflare/vite-plugin (${peerDependency}).\nPlease install wrangler@${peerDependency}.`);
}
//#endregion
//#region src/build-constants.ts
/**
* The default compatibility date to use when the user omits one.
* This value is injected at build time and remains fixed for each release.
*/
const DEFAULT_COMPAT_DATE = "2026-05-15";
//#endregion
//#region ../../node_modules/.pnpm/@remix-run+node-fetch-server@0.8.0/node_modules/@remix-run/node-fetch-server/dist/node-fetch-server.js
async function* readStream(stream$2) {
let reader = stream$2.getReader();
try {
while (true) {
let result = await reader.read();
if (result.done) break;
yield result.value;
}
} finally {
reader.releaseLock();
}
}
function createRequest(req, res, options) {
let controller = new AbortController();
res.on("close", () => {
controller.abort();
});
let method = req.method ?? "GET";
let headers = createHeaders(req);
let protocol = options?.protocol ?? ("encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:");
let host = options?.host ?? headers.get("Host") ?? "localhost";
let url = new URL(req.url, `${protocol}//${host}`);
let init = {
method,
headers,
signal: controller.signal
};
if (method !== "GET" && method !== "HEAD") {
init.body = new ReadableStream({ start(controller2) {
req.on("data", (chunk) => {
controller2.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
});
req.on("end", () => {
controller2.close();
});
} });
init.duplex = "half";
}
return new Request(url, init);
}
function createHeaders(req) {
let headers = new Headers();
let rawHeaders = req.rawHeaders;
for (let i$1 = 0; i$1 < rawHeaders.length; i$1 += 2) {
if (rawHeaders[i$1].startsWith(":")) continue;
headers.append(rawHeaders[i$1], rawHeaders[i$1 + 1]);
}
return headers;
}
async function sendResponse(res, response) {
let headers = {};
for (let [key, value] of response.headers) if (key in headers) if (Array.isArray(headers[key])) headers[key].push(value);
else headers[key] = [headers[key], value];
else headers[key] = value;
res.writeHead(response.status, headers);
if (response.body != null && res.req.method !== "HEAD") {
for await (let chunk of readStream(response.body)) if (res.write(chunk) === false) await new Promise((resolve$4) => {
res.once("drain", resolve$4);
});
}
res.end();
}
//#endregion
//#region src/constants.ts
var import_gte = /* @__PURE__ */ __toESM$1(require_gte(), 1);
const ROUTER_WORKER_NAME = "__router-worker__";
const ASSET_WORKER_NAME = "__asset-worker__";
const VITE_PROXY_WORKER_NAME = "__vite_proxy_worker__";
const PROXY_SHARED_SECRET = randomUUID();
const kRequestType = Symbol("kRequestType");
//#endregion
//#region ../workers-utils/dist/chunk-OZQVB3L3.mjs
var INHERIT_SYMBOL = Symbol.for("inherit_binding");
var SERVICE_TAG_PREFIX = "cf:service=";
var ENVIRONMENT_TAG_PREFIX = "cf:environment=";
var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
//#endregion
//#region ../workers-utils/dist/chunk-DCOBXSFB.mjs
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$1, value) => __defProp(target$1, "name", {
value,
configurable: true
});
var __require$1 = /* @__PURE__ */ ((x) => typeof __require$2 !== "undefined" ? __require$2 : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof __require$2 !== "undefined" ? __require$2 : a)[b] }) : x)(function(x) {
if (typeof __require$2 !== "undefined") return __require$2.apply(this, arguments);
throw Error("Dynamic require of \"" + x + "\" is not supported");
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target$1, all$1) => {
for (var name in all$1) __defProp(target$1, name, {
get: all$1[name],
enumerable: true
});
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __reExport = (target$1, mod, secondTarget) => (__copyProps(target$1, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target$1) => (target$1 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target$1, "default", {
value: mod,
enumerable: true
}) : target$1, mod));
//#endregion
//#region ../workers-utils/dist/chunk-BLWXWFJK.mjs
function isCompatDate(str) {
return /^\d{4}-\d{2}-\d{2}$/.test(str);
}
__name(isCompatDate, "isCompatDate");
function formatCompatibilityDate(date) {
const compatDate = date.toISOString().slice(0, 10);
assert(isCompatDate(compatDate));
return compatDate;
}
__name(formatCompatibilityDate, "formatCompatibilityDate");
function getTodaysCompatDate() {
return formatCompatibilityDate(/* @__PURE__ */ new Date());
}
__name(getTodaysCompatDate, "getTodaysCompatDate");
function assertNever(_value) {}
__name(assertNever, "assertNever");
function mapWorkerMetadataBindings(bindings) {
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
}];
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 "stream":
configObj.stream = { binding: binding.name };
break;
case "media":
configObj.media = { 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 "artifacts":
configObj.artifacts = [...configObj.artifacts ?? [], {
binding: binding.name,
namespace: binding.namespace
}];
break;
case "unsafe_hello_world":
configObj.unsafe_hello_world = [...configObj.unsafe_hello_world ?? [], {
binding: binding.name,
enable_timer: binding.enable_timer
}];
break;
case "flagship":
configObj.flagship = [...configObj.flagship ?? [], {
binding: binding.name,
app_id: binding.app_id
}];
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((p$1) => p$1.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,
allowed_sender_addresses: binding.allowed_sender_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 "ai_search_namespace":
configObj.ai_search_namespaces = [...configObj.ai_search_namespaces ?? [], {
binding: binding.name,
namespace: binding.namespace
}];
break;
case "ai_search":
configObj.ai_search = [...configObj.ai_search ?? [], {
binding: binding.name,
instance_name: binding.instance_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":
configObj.assets = { binding: binding.name };
break;
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;
case "worker_loader":
configObj.worker_loaders = [...configObj.worker_loaders ?? [], { binding: binding.name }];
break;
case "ratelimit":
configObj.ratelimits = [...configObj.ratelimits ?? [], {
name: binding.name,
namespace_id: binding.namespace_id,
simple: {
limit: binding.simple.limit,
period: binding.simple.period
}
}];
break;
case "vpc_service":
configObj.vpc_services = [...configObj.vpc_services ?? [], {
binding: binding.name,
service_id: binding.service_id
}];
break;
case "vpc_network":
if (binding.tunnel_id !== void 0) configObj.vpc_networks = [...configObj.vpc_networks ?? [], {
binding: binding.name,
tunnel_id: binding.tunnel_id
}];
else if (binding.network_id !== void 0) configObj.vpc_networks = [...configObj.vpc_networks ?? [], {
binding: binding.name,
network_id: binding.network_id
}];
break;
default: configObj.unsafe = {
bindings: [...configObj.unsafe?.bindings ?? [], binding],
metadata: configObj.unsafe?.metadata ?? void 0
};
}
return configObj;
}, {});
}
__name(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
function convertWorkerToWranglerConfig(config) {
const mappedBindings = mapWorkerMetadataBindings(config.bindings);
const durableObjectClassNames = config.bindings.filter((binding) => binding.type === "durable_object_namespace" && binding.script_name === config.name).map((durableObject) => durableObject.class_name);
const allRoutes = [...config.routes.map((r$1) => ({
pattern: r$1.pattern,
zone_name: r$1.zone_name
})), ...config.domains.map((c) => ({
pattern: c.hostname,
zone_name: c.zone_name,
custom_domain: true,
enabled: c.enabled,
previews_enabled: c.previews_enabled
}))];
return {
name: config.name,
main: config.entrypoint,
workers_dev: config.subdomain.enabled,
preview_urls: config.subdomain.previews_enabled,
compatibility_date: config.compatibility_date ?? getTodaysCompatDate(),
compatibility_flags: config.compatibility_flags,
...allRoutes.length ? { routes: allRoutes } : {},
placement: config.placement?.mode === "smart" ? { mode: "smart" } : void 0,
limits: config.limits,
...durableObjectClassNames.length && config.migration_tag ? { migrations: [{
tag: config.migration_tag,
new_classes: durableObjectClassNames
}] } : {},
...config.schedules.length ? { triggers: { crons: config.schedules.map((scheduled) => scheduled.cron) } } : {},
tail_consumers: config.tail_consumers ?? void 0,
observability: config.observability,
...mappedBindings
};
}
__name(convertWorkerToWranglerConfig, "convertWorkerToWranglerConfig");
function constructWranglerConfig(workerOrWorkers) {
let workers;
if (Array.isArray(workerOrWorkers)) workers = workerOrWorkers;
else workers = [workerOrWorkers];
const topLevelEnv = workers.find((w) => !w.tags?.some((t$5) => t$5.startsWith(ENVIRONMENT_TAG_PREFIX)));
const workerName = topLevelEnv?.name ?? workers[0].name;
const entrypoint = topLevelEnv?.entrypoint ?? workers[0].entrypoint;
let combinedConfig;
if (topLevelEnv) combinedConfig = convertWorkerToWranglerConfig(topLevelEnv);
else combinedConfig = {
name: workerName,
main: entrypoint
};
for (const env$1 of workers) {
const serviceTag = env$1.tags?.find((t$5) => t$5 === `${SERVICE_TAG_PREFIX}${workerName}`);
const envTag = env$1.tags?.find((t$5) => t$5.startsWith(ENVIRONMENT_TAG_PREFIX));
if (serviceTag !== `${SERVICE_TAG_PREFIX}${workerName}` || envTag === void 0) continue;
const [_, envName] = envTag.split("=");
combinedConfig.env ??= {};
combinedConfig.env[envName] = convertWorkerToWranglerConfig(env$1);
}
return combinedConfig;
}
__name(constructWranglerConfig, "constructWranglerConfig");
//#endregion
//#region ../workers-utils/dist/chunk-O4YGOZSW.mjs
var MetricsRegistry = class {
static {
__name(this, "MetricsRegistry");
}
counters = [];
/**
* Create and register a new counter metric.
*
* @param name - The metric name (e.g. "service_request_total")
* @param help - A human-readable description of the metric
* @returns A Counter that can be incremented
*/
createCounter(name, help) {
const entry = {
name,
help,
value: 0
};
this.counters.push(entry);
return {
inc: /* @__PURE__ */ __name(() => {
entry.value++;
}, "inc"),
add: /* @__PURE__ */ __name((amount) => {
if (amount < 0) throw new Error("Counter value cannot decrease");
entry.value += amount;
}, "add")
};
}
/**
* Serialize all registered metrics in Prometheus text exposition format.
*
* @see https://prometheus.io/docs/instrumenting/exposition_formats/#text-based-format
*/
metrics() {
return this.counters.map((c) => {
let result = "";
if (c.help.length > 0) result += `# HELP ${c.name} ${c.help}
`;
result += `# TYPE ${c.name} counter
`;
result += `${c.name} ${c.value}
`;
return result;
}).join("");
}
};
//#endregion
//#region ../workers-utils/dist/chunk-GMTGAG26.mjs
var UserError = class extends Error {
static {
__name(this, "UserError");
}
telemetryMessage;
constructor(message, options) {
super(message, options);
Object.setPrototypeOf(this, new.target.prototype);
this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
}
};
var DeprecationError = class extends UserError {
static {
__name(this, "DeprecationError");
}
constructor(message, options) {
super(`Deprecation:
${message}`, options);
}
};
var FatalError = class extends UserError {
static {
__name(this, "FatalError");
}
code;
constructor(message, options) {
super(message, options);
this.code = options.code;
}
};
var CommandLineArgsError = class extends UserError {
static {
__name(this, "CommandLineArgsError");
}
};
var JsonFriendlyFatalError = class extends FatalError {
static {
__name(this, "JsonFriendlyFatalError");
}
};
var MissingConfigError = class extends Error {
static {
__name(this, "MissingConfigError");
}
telemetryMessage;
constructor(key) {
super(`Missing config value for ${key}`);
this.telemetryMessage = `Missing config value for ${key}`;
}
};
function createFatalError(message, isJson, options) {
if (isJson) return new JsonFriendlyFatalError(JSON.stringify(message), options);
return new FatalError(`${message}`, options);
}
__name(createFatalError, "createFatalError");
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 ch = text.charCodeAt(pos);
if (ch >= 48 && ch <= 57) value2 = value2 * 16 + ch - 48;
else if (ch >= 65 && ch <= 70) value2 = value2 * 16 + ch - 65 + 10;
else if (ch >= 97 && ch <= 102) value2 = value2 * 16 + ch - 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 && isDigit(text.charCodeAt(pos))) pos++;
}
if (pos < text.length && text.charCodeAt(pos) === 46) {
pos++;
if (pos < text.length && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(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 && isDigit(text.charCodeAt(pos))) {
pos++;
while (pos < text.length && isDigit(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 ch = text.charCodeAt(pos);
if (ch === 34) {
result += text.substring(start, pos);
pos++;
break;
}
if (ch === 92) {
result += text.substring(start, pos);
pos++;
if (pos >= len) {
scanError = 2;
break;
}
switch (text.charCodeAt(pos++)) {
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 (ch >= 0 && ch <= 31) if (isLineBreak(ch)) {
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) {
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;
case 34:
pos++;
value = scanString();
return token = 10;
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 ch = text.charCodeAt(pos);
if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
pos += 2;
commentClosed = true;
break;
}
pos++;
if (isLineBreak(ch)) {
if (ch === 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;
case 45:
value += String.fromCharCode(code);
pos++;
if (pos === len || !isDigit(text.charCodeAt(pos))) return token = 16;
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;
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")
};
}
__name(createScanner, "createScanner");
function isWhiteSpace(ch) {
return ch === 32 || ch === 9;
}
__name(isWhiteSpace, "isWhiteSpace");
function isLineBreak(ch) {
return ch === 10 || ch === 13;
}
__name(isLineBreak, "isLineBreak");
function isDigit(ch) {
return ch >= 48 && ch <= 57;
}
__name(isDigit, "isDigit");
var CharacterCodes;
(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 = {}));
function format$1(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;
addEdit(repeat(indentValue, initialIndentLevel), 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;
}
__name(format$1, "format");
function repeat(s, count) {
let result = "";
for (let i$1 = 0; i$1 < count; i$1++) result += s;
return result;
}
__name(repeat, "repeat");
function computeIndentLevel(content, options) {
let i$1 = 0;
let nChars = 0;
const tabSize = options.tabSize || 4;
while (i$1 < content.length) {
let ch = content.charAt(i$1);
if (ch === " ") nChars++;
else if (ch === " ") nChars += tabSize;
else break;
i$1++;
}
return Math.floor(nChars / tabSize);
}
__name(computeIndentLevel, "computeIndentLevel");
function getEOL(options, text) {
for (let i$1 = 0; i$1 < text.length; i$1++) {
const ch = text.charAt(i$1);
if (ch === "\r") {
if (i$1 + 1 < text.length && text.charAt(i$1 + 1) === "\n") return "\r\n";
return "\r";
} else if (ch === "\n") return "\n";
}
return options && options.eol || "\n";
}
__name(getEOL, "getEOL");
function isEOL(text, offset) {
return "\r\n".indexOf(text.charAt(offset)) !== -1;
}
__name(isEOL, "isEOL");
var ParseOptions;
(function(ParseOptions2) {
ParseOptions2.DEFAULT = { allowTrailingComma: false };
})(ParseOptions || (ParseOptions = {}));
function parse$2(text, errors$1 = [], 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");
visit(text, {
onObjectBegin: /* @__PURE__ */ __name(() => {
const object = {};
onValue(object);
previousParents.push(currentParent);
currentParent = object;
currentProperty = null;
}, "onObjectBegin"),
onObjectProperty: /* @__PURE__ */ __name((name) => {
currentProperty = name;
}, "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((error, offset, length) => {
errors$1.push({
error,
offset,
length
});
}, "onError")
}, options);
return currentParent[0];
}
__name(parse$2, "parse");
function parseTree(text, errors$1 = [], 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");
visit(text, {
onObjectBegin: /* @__PURE__ */ __name((offset) => {
currentParent = onValue({
type: "object",
offset,
length: -1,
parent: currentParent,
children: []
});
}, "onObjectBegin"),
onObjectProperty: /* @__PURE__ */ __name((name, offset, length) => {
currentParent = onValue({
type: "property",
offset,
length: -1,
parent: currentParent,
children: []
});
currentParent.children.push({
type: "string",
value: name,
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((sep$1, offset, length) => {
if (currentParent.type === "property") {
if (sep$1 === ":") currentParent.colonOffset = offset;
else if (sep$1 === ",") ensurePropertyComplete(offset);
}
}, "onSeparator"),
onError: /* @__PURE__ */ __name((error, offset, length) => {
errors$1.push({
error,
offset,
length
});
}, "onError")
}, options);
const result = currentParent.children[0];
if (result) delete result.parent;
return result;
}
__name(parseTree, "parseTree");
function findNodeAtLocation(root, path2) {
if (!root) return;
let node = root;
for (let segment of path2) if (typeof segment === "string") {
if (node.type !== "object" || !Array.isArray(node.children)) return;
let found = false;
for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
node = propertyNode.children[1];
found = true;
break;
}
if (!found) return;
} else {
const index = segment;
if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
node = node.children[index];
}
return node;
}
__name(findNodeAtLocation, "findNodeAtLocation");
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$1 = 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);
break;
case 5:
handleError(15);
break;
case 3:
handleError(13);
break;
case 1:
if (!disallowComments) handleError(11);
break;
case 2:
handleError(12);
break;
case 6:
handleError(16);
break;
}
switch (token) {
case 12:
case 13:
if (disallowComments) handleError(10);
else onComment();
break;
case 16:
handleError(1);
break;
case 15:
case 14: break;
default: return token;
}
}
}
__name(scanNext, "scanNext");
function handleError(error, skipUntilAfter = [], skipUntil2 = []) {
onError$1(error);
if (skipUntilAfter.length + skipUntil2.length > 0) {
let token = _scanner.getToken();
while (token !== 17) {
if (skipUntilAfter.indexOf(token) !== -1) {
scanNext();
break;
} else if (skipUntil2.indexOf(token) !== -1) break;
token = scanNext();
}
}
}
__name(handleError, "handleError");
function parseString2(isValue) {
const value = _scanner.getTokenValue();
if (isValue) onLiteralValue(value);
else {
onObjectProperty(value);
_jsonPath.push(value);
}
scanNext();
return true;
}
__name(parseString2, "parseString");
function parseLiteral() {
switch (_scanner.getToken()) {
case 11:
const tokenValue = _scanner.getTokenValue();
let value = Number(tokenValue);
if (isNaN(value)) {
handleError(2);
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]);
return false;
}
parseString2(false);
if (_scanner.getToken() === 6) {
onSeparator(":");
scanNext();
if (!parseValue2()) handleError(4, [], [2, 5]);
} else handleError(5, [], [2, 5]);
_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]);
needsComma = true;
}
onObjectEnd();
if (_scanner.getToken() !== 2) handleError(7, [2], []);
else scanNext();
return true;
}
__name(parseObject, "parseObject");
function parseArray2() {
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 (!parseValue2()) handleError(4, [], [4, 5]);
needsComma = true;
}
onArrayEnd();
if (!isFirstElement) _jsonPath.pop();
if (_scanner.getToken() !== 4) handleError(8, [4], []);
else scanNext();
return true;
}
__name(parseArray2, "parseArray");
function parseValue2() {
switch (_scanner.getToken()) {
case 3: return parseArray2();
case 1: return parseObject();
case 10: return parseString2(true);
default: return parseLiteral();
}
}
__name(parseValue2, "parseValue");
scanNext();
if (_scanner.getToken() === 17) {
if (options.allowEmptyContent) return true;
handleError(4, [], []);
return false;
}
if (!parseValue2()) {
handleError(4, [], []);
return false;
}
if (_scanner.getToken() !== 17) handleError(9, [], []);
return true;
}
__name(visit, "visit");
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";
}
}
__name(getNodeType, "getNodeType");
function setProperty(text, originalPath, value, options) {
const path2 = originalPath.slice();
const root = parseTree(text, []);
let parent = void 0;
let lastSegment = void 0;
while (path2.length > 0) {
lastSegment = path2.pop();
parent = findNodeAtLocation(root, path2);
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) removeEnd = parent.children[1].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((p$1) => p$1.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;
edit = {
offset,
length: parent.offset + parent.length - 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}`);
}
__name(setProperty, "setProperty");
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 = format$1(newText, {
offset: begin,
length: end - begin
}, {
...options.formattingOptions,
keepLines: false
});
for (let i$1 = edits.length - 1; i$1 >= 0; i$1--) {
const edit2 = edits[i$1];
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)
}];
}
__name(withFormatting, "withFormatting");
function applyEdit(text, edit) {
return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
__name(applyEdit, "applyEdit");
var ScanError;
(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 = {}));
var SyntaxKind;
(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 = {}));
var parse2 = parse$2;
var ParseErrorCode;
(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 = {}));
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>";
}
__name(printParseErrorCode, "printParseErrorCode");
function format2(documentText, range, options) {
return format$1(documentText, range, options);
}
__name(format2, "format");
function modify(text, path2, value, options) {
return setProperty(text, path2, value, options);
}
__name(modify, "modify");
function applyEdits(text, edits) {
let sortedEdits = edits.slice(0).sort((a, b) => {
const diff$2 = a.offset - b.offset;
if (diff$2 === 0) return a.length - b.length;
return diff$2;
});
let lastModifiedOffset = text.length;
for (let i$1 = sortedEdits.length - 1; i$1 >= 0; i$1--) {
let e = sortedEdits[i$1];
if (e.offset + e.length <= lastModifiedOffset) text = applyEdit(text, e);
else throw new Error("Overlapping edit");
lastModifiedOffset = e.offset;
}
return text;
}
__name(applyEdits, "applyEdits");
function getLineColFromPtr(string, ptr) {
let lines = string.slice(0, ptr).split(/\r\n|\n|\r/g);
return [lines.length, lines.pop().length + 1];
}
__name(getLineColFromPtr, "getLineColFromPtr");
function makeCodeBlock(string, line, column) {
let lines = string.split(/\r\n|\n|\r/g);
let codeblock = "";
let numberLen = (Math.log10(line + 1) | 0) + 1;
for (let i$1 = line - 1; i$1 <= line + 1; i$1++) {
let l = lines[i$1 - 1];
if (!l) continue;
codeblock += i$1.toString().padEnd(numberLen, " ");
codeblock += ": ";
codeblock += l;
codeblock += "\n";
if (i$1 === line) {
codeblock += " ".repeat(numberLen + column + 2);
codeblock += "^\n";
}
}
return codeblock;
}
__name(makeCodeBlock, "makeCodeBlock");
var TomlError = class extends Error {
static {
__name(this, "TomlError");
}
line;
column;
codeblock;
constructor(message, options) {
const [line, column] = getLineColFromPtr(options.toml, options.ptr);
const codeblock = makeCodeBlock(options.toml, line, column);
super(`Invalid TOML document: ${message}
${codeblock}`, options);
this.line = line;
this.column = column;
this.codeblock = codeblock;
}
};
function isEscaped(str, ptr) {
let i$1 = 0;
while (str[ptr - ++i$1] === "\\");
return --i$1 && i$1 % 2;
}
__name(isEscaped, "isEscaped");
function indexOfNewline(str, start = 0, end = str.length) {
let idx = str.indexOf("\n", start);
if (str[idx - 1] === "\r") idx--;
return idx <= end ? idx : -1;
}
__name(indexOfNewline, "indexOfNewline");
function skipComment(str, ptr) {
for (let i$1 = ptr; i$1 < str.length; i$1++) {
let c = str[i$1];
if (c === "\n") return i$1;
if (c === "\r" && str[i$1 + 1] === "\n") return i$1 + 1;
if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in comments", {
toml: str,
ptr
});
}
return str.length;
}
__name(skipComment, "skipComment");
function skipVoid(str, ptr, banNewLines, banComments) {
let c;
while ((c = str[ptr]) === " " || c === " " || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n")) ptr++;
return banComments || c !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
}
__name(skipVoid, "skipVoid");
function skipUntil(str, ptr, sep$1, end, banNewLines = false) {
if (!end) {
ptr = indexOfNewline(str, ptr);
return ptr < 0 ? str.length : ptr;
}
for (let i$1 = ptr; i$1 < str.length; i$1++) {
let c = str[i$1];
if (c === "#") i$1 = indexOfNewline(str, i$1);
else if (c === sep$1) return i$1 + 1;
else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i$1 + 1] === "\n")) return i$1;
}
throw new TomlError("cannot find end of structure", {
toml: str,
ptr
});
}
__name(skipUntil, "skipUntil");
function getStringEnd(str, seek) {
let first = str[seek];
let target$1 = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
seek += target$1.length - 1;
do
seek = str.indexOf(target$1, ++seek);
while (seek > -1 && first !== "'" && isEscaped(str, seek));
if (seek > -1) {
seek += target$1.length;
if (target$1.length > 1) {
if (str[seek] === first) seek++;
if (str[seek] === first) seek++;
}
}
return seek;
}
__name(getStringEnd, "getStringEnd");
var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
var TomlDate = class _TomlDate extends Date {
static {
__name(this, "TomlDate");
}
#hasDate = false;
#hasTime = false;
#offset = null;
constructor(date) {
let hasDate = true;
let hasTime = true;
let offset = "Z";
if (typeof date === "string") {
let match = date.match(DATE_TIME_RE);
if (match) {
if (!match[1]) {
hasDate = false;
date = `0000-01-01T${date}`;
}
hasTime = !!match[2];
hasTime && date[10] === " " && (date = date.replace(" ", "T"));
if (match[2] && +match[2] > 23) date = "";
else {
offset = match[3] || null;
date = date.toUpperCase();
if (!offset && hasTime) date += "Z";
}
} else date = "";
}
super(date);
if (!isNaN(this.getTime())) {
this.#hasDate = hasDate;
this.#hasTime = hasTime;
this.#offset = offset;
}
}
isDateTime() {
return this.#hasDate && this.#hasTime;
}
isLocal() {
return !this.#hasDate || !this.#hasTime || !this.#offset;
}
isDate() {
return this.#hasDate && !this.#hasTime;
}
isTime() {
return this.#hasTime && !this.#hasDate;
}
isValid() {
return this.#hasDate || this.#hasTime;
}
toISOString() {
let iso = super.toISOString();
if (this.isDate()) return iso.slice(0, 10);
if (this.isTime()) return iso.slice(11, 23);
if (this.#offset === null) return iso.slice(0, -1);
if (this.#offset === "Z") return iso;
let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
offset = this.#offset[0] === "-" ? offset : -offset;
return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
}
static wrapAsOffsetDateTime(jsDate, offset = "Z") {
let date = new _TomlDate(jsDate);
date.#offset = offset;
return date;
}
static wrapAsLocalDateTime(jsDate) {
let date = new _TomlDate(jsDate);
date.#offset = null;
return date;
}
static wrapAsLocalDate(jsDate) {
let date = new _TomlDate(jsDate);
date.#hasTime = false;
date.#offset = null;
return date;
}
static wrapAsLocalTime(jsDate) {
let date = new _TomlDate(jsDate);
date.#hasDate = false;
date.#offset = null;
return date;
}
};
var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
var LEADING_ZERO = /^[+-]?0[0-9_]/;
var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
var ESC_MAP = {
b: "\b",
t: " ",
n: "\n",
f: "\f",
r: "\r",
"\"": "\"",
"\\": "\\"
};
function parseString(str, ptr = 0, endPtr = str.length) {
let isLiteral = str[ptr] === "'";
let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
if (isMultiline) {
endPtr -= 2;
if (str[ptr += 2] === "\r") ptr++;
if (str[ptr] === "\n") ptr++;
}
let tmp = 0;
let isEscape;
let parsed = "";
let sliceStart = ptr;
while (ptr < endPtr - 1) {
let c = str[ptr++];
if (c === "\n" || c === "\r" && str[ptr] === "\n") {
if (!isMultiline) throw new TomlError("newlines are not allowed in strings", {
toml: str,
ptr: ptr - 1
});
} else if (c < " " && c !== " " || c === "") throw new TomlError("control characters are not allowed in strings", {
toml: str,
ptr: ptr - 1
});
if (isEscape) {
isEscape = false;
if (c === "u" || c === "U") {
let code = str.slice(ptr, ptr += c === "u" ? 4 : 8);
if (!ESCAPE_REGEX.test(code)) throw new TomlError("invalid unicode escape", {
toml: str,
ptr: tmp
});
try {
parsed += String.fromCodePoint(parseInt(code, 16));
} catch {
throw new TomlError("invalid unicode escape", {
toml: str,
ptr: tmp
});
}
} else if (isMultiline && (c === "\n" || c === " " || c === " " || c === "\r")) {
ptr = skipVoid(str, ptr - 1, true);
if (str[ptr] !== "\n" && str[ptr] !== "\r") throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
toml: str,
ptr: tmp
});
ptr = skipVoid(str, ptr);
} else if (c in ESC_MAP) parsed += ESC_MAP[c];
else throw new TomlError("unrecognized escape sequence", {
toml: str,
ptr: tmp
});
sliceStart = ptr;
} else if (!isLiteral && c === "\\") {
tmp = ptr - 1;
isEscape = true;
parsed += str.slice(sliceStart, tmp);
}
}
return parsed + str.slice(sliceStart, endPtr - 1);
}
__name(parseString, "parseString");
function parseValue(value, toml, ptr, integersAsBigInt) {
if (value === "true") return true;
if (value === "false") return false;
if (value === "-inf") return -Infinity;
if (value === "inf" || value === "+inf") return Infinity;
if (value === "nan" || value === "+nan" || value === "-nan") return NaN;
if (value === "-0") return integersAsBigInt ? 0n : 0;
let isInt = INT_REGEX.test(value);
if (isInt || FLOAT_REGEX.test(value)) {
if (LEADING_ZERO.test(value)) throw new TomlError("leading zeroes are not allowed", {
toml,
ptr
});
value = value.replace(/_/g, "");
let numeric$1 = +value;
if (isNaN(numeric$1)) throw new TomlError("invalid number", {
toml,
ptr
});
if (isInt) {
if ((isInt = !Number.isSafeInteger(numeric$1)) && !integersAsBigInt) throw new TomlError("integer value cannot be represented losslessly", {
toml,
ptr
});
if (isInt || integersAsBigInt === true) numeric$1 = BigInt(value);
}
return numeric$1;
}
const date = new TomlDate(value);
if (!date.isValid()) throw new TomlError("invalid value", {
toml,
ptr
});
return date;
}
__name(parseValue, "parseValue");
function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
let value = str.slice(startPtr, endPtr);
let commentIdx = value.indexOf("#");
if (commentIdx > -1) {
skipComment(str, commentIdx);
value = value.slice(0, commentIdx);
}
let trimmed = value.trimEnd();
if (!allowNewLines) {
let newlineIdx = value.indexOf("\n", trimmed.length);
if (newlineIdx > -1) throw new TomlError("newlines are not allowed in inline tables", {
toml: str,
ptr: startPtr + newlineIdx
});
}
return [trimmed, commentIdx];
}
__name(sliceAndTrimEndOf, "sliceAndTrimEndOf");
function extractValue(str, ptr, end, depth$1, integersAsBigInt) {
if (depth$1 === 0) throw new TomlError("document contains excessively nested structures. aborting.", {
toml: str,
ptr
});
let c = str[ptr];
if (c === "[" || c === "{") {
let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth$1, integersAsBigInt) : parseInlineTable(str, ptr, depth$1, integersAsBigInt);
let newPtr = end ? skipUntil(str, endPtr2, ",", end) : endPtr2;
if (endPtr2 - newPtr && end === "}") {
let nextNewLine = indexOfNewline(str, endPtr2, newPtr);
if (nextNewLine > -1) throw new TomlError("newlines are not allowed in inline tables", {
toml: str,
ptr: nextNewLine
});
}
return [value, newPtr];
}
let endPtr;
if (c === "\"" || c === "'") {
endPtr = getStringEnd(str, ptr);
let parsed = parseString(str, ptr, endPtr);
if (end) {
endPtr = skipVoid(str, endPtr, end !== "]");
if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") throw new TomlError("unexpected character encountered", {
toml: str,
ptr: endPtr
});
endPtr += +(str[endPtr] === ",");
}
return [parsed, endPtr];
}
endPtr = skipUntil(str, ptr, ",", end);
let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
if (!slice[0]) throw new TomlError("incomplete key-value declaration: no value specified", {
toml: str,
ptr
});
if (end && slice[1] > -1) {
endPtr = skipVoid(str, ptr + slice[1]);
endPtr += +(str[endPtr] === ",");
}
return [parseValue(slice[0], str, ptr, integersAsBigInt), endPtr];
}
__name(extractValue, "extractValue");
var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
function parseKey(str, ptr, end = "=") {
let dot = ptr - 1;
let parsed = [];
let endPtr = str.indexOf(end, ptr);
if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
toml: str,
ptr
});
do {
let c = str[ptr = ++dot];
if (c !== " " && c !== " ") if (c === "\"" || c === "'") {
if (c === str[ptr + 1] && c === str[ptr + 2]) throw new TomlError("multiline strings are not allowed in keys", {
toml: str,
ptr
});
let eos = getStringEnd(str, ptr);
if (eos < 0) throw new TomlError("unfinished string encountered", {
toml: str,
ptr
});
dot = str.indexOf(".", eos);
let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
let newLine = indexOfNewline(strEnd);
if (newLine > -1) throw new TomlError("newlines are not allowed in keys", {
toml: str,
ptr: ptr + dot + newLine
});
if (strEnd.trimStart()) throw new TomlError("found extra tokens after the string part", {
toml: str,
ptr: eos
});
if (endPtr < eos) {
endPtr = str.indexOf(end, eos);
if (endPtr < 0) throw new TomlError("incomplete key-value: cannot find end of key", {
toml: str,
ptr
});
}
parsed.push(parseString(str, ptr, eos));
} else {
dot = str.indexOf(".", ptr);
let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
if (!KEY_PART_RE.test(part)) throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
toml: str,
ptr
});
parsed.push(part.trimEnd());
}
} while (dot + 1 && dot < endPtr);
return [parsed, skipVoid(str, endPtr + 1, true, true)];
}
__name(parseKey, "parseKey");
function parseInlineTable(str, ptr, depth$1, integersAsBigInt) {
let res = {};
let seen = /* @__PURE__ */ new Set();
let c;
let comma$1 = 0;
ptr++;
while ((c = str[ptr++]) !== "}" && c) {
let err = {
toml: str,
ptr: ptr - 1
};
if (c === "\n") throw new TomlError("newlines are not allowed in inline tables", err);
else if (c === "#") throw new TomlError("inline tables cannot contain comments", err);
else if (c === ",") throw new TomlError("expected key-value, found comma", err);
else if (c !== " " && c !== " ") {
let k;
let t$5 = res;
let hasOwn$1 = false;
let [key, keyEndPtr] = parseKey(str, ptr - 1);
for (let i$1 = 0; i$1 < key.length; i$1++) {
if (i$1) t$5 = hasOwn$1 ? t$5[k] : t$5[k] = {};
k = key[i$1];
if ((hasOwn$1 = Object.hasOwn(t$5, k)) && (typeof t$5[k] !== "object" || seen.has(t$5[k]))) throw new TomlError("trying to redefine an already defined value", {
toml: str,
ptr
});
if (!hasOwn$1 && k === "__proto__") Object.defineProperty(t$5, k, {
enumerable: true,
configurable: true,
writable: true
});
}
if (hasOwn$1) throw new TomlError("trying to redefine an already defined value", {
toml: str,
ptr
});
let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth$1 - 1, integersAsBigInt);
seen.add(value);
t$5[k] = value;
ptr = valueEndPtr;
comma$1 = str[ptr - 1] === "," ? ptr - 1 : 0;
}
}
if (comma$1) throw new TomlError("trailing commas are not allowed in inline tables", {
toml: str,
ptr: comma$1
});
if (!c) throw new TomlError("unfinished table encountered", {
toml: str,
ptr
});
return [res, ptr];
}
__name(parseInlineTable, "parseInlineTable");
function parseArray(str, ptr, depth$1, integersAsBigInt) {
let res = [];
let c;
ptr++;
while ((c = str[ptr++]) !== "]" && c) if (c === ",") throw new TomlError("expected value, found comma", {
toml: str,
ptr: ptr - 1
});
else if (c === "#") ptr = skipComment(str, ptr);
else if (c !== " " && c !== " " && c !== "\n" && c !== "\r") {
let e = extractValue(str, ptr - 1, "]", depth$1 - 1, integersAsBigInt);
res.push(e[0]);
ptr = e[1];
}
if (!c) throw new TomlError("unfinished array encountered", {
toml: str,
ptr
});
return [res, ptr];
}
__name(parseArray, "parseArray");
function peekTable(key, table, meta, type) {
let t$5 = table;
let m = meta;
let k;
let hasOwn$1 = false;
let state;
for (let i$1 = 0; i$1 < key.length; i$1++) {
if (i$1) {
t$5 = hasOwn$1 ? t$5[k] : t$5[k] = {};
m = (state = m[k]).c;
if (type === 0 && (state.t === 1 || state.t === 2)) return null;
if (state.t === 2) {
let l = t$5.length - 1;
t$5 = t$5[l];
m = m[l].c;
}
}
k = key[i$1];
if ((hasOwn$1 = Object.hasOwn(t$5, k)) && m[k]?.t === 0 && m[k]?.d) return null;
if (!hasOwn$1) {
if (k === "__proto__") {
Object.defineProperty(t$5, k, {
enumerable: true,
configurable: true,
writable: true
});
Object.defineProperty(m, k, {
enumerable: true,
configurable: true,
writable: true
});
}
m[k] = {
t: i$1 < key.length - 1 && type === 2 ? 3 : type,
d: false,
i: 0,
c: {}
};
}
}
state = m[k];
if (state.t !== type && !(type === 1 && state.t === 3)) return null;
if (type === 2) {
if (!state.d) {
state.d = true;
t$5[k] = [];
}
t$5[k].push(t$5 = {});
state.c[state.i++] = state = {
t: 1,
d: false,
i: 0,
c: {}
};
}
if (state.d) return null;
state.d = true;
if (type === 1) t$5 = hasOwn$1 ? t$5[k] : t$5[k] = {};
else if (type === 0 && hasOwn$1) return null;
return [
k,
t$5,
state.c
];
}
__name(peekTable, "peekTable");
function parse3(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
let res = {};
let meta = {};
let tbl = res;
let m = meta;
for (let ptr = skipVoid(toml, 0); ptr < toml.length;) {
if (toml[ptr] === "[") {
let isTableArray = toml[++ptr] === "[";
let k = parseKey(toml, ptr += +isTableArray, "]");
if (isTableArray) {
if (toml[k[1] - 1] !== "]") throw new TomlError("expected end of table declaration", {
toml,
ptr: k[1] - 1
});
k[1]++;
}
let p$1 = peekTable(k[0], res, meta, isTableArray ? 2 : 1);
if (!p$1) throw new TomlError("trying to redefine an already defined table or value", {
toml,
ptr
});
m = p$1[2];
tbl = p$1[1];
ptr = k[1];
} else {
let k = parseKey(toml, ptr);
let p$1 = peekTable(k[0], tbl, m, 0);
if (!p$1) throw new TomlError("trying to redefine an already defined table or value", {
toml,
ptr
});
let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
p$1[1][p$1[0]] = v[0];
ptr = v[1];
}
ptr = skipVoid(toml, ptr, true);
if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") throw new TomlError("each key-value declaration must be followed by an end-of-line", {
toml,
ptr
});
ptr = skipVoid(toml, ptr);
}
return res;
}
__name(parse3, "parse");
var BARE_KEY = /^[a-z0-9-_]+$/i;
function extendedTypeOf(obj) {
let type = typeof obj;
if (type === "object") {
if (Array.isArray(obj)) return "array";
if (obj instanceof Date) return "date";
}
return type;
}
__name(extendedTypeOf, "extendedTypeOf");
function isArrayOfTables(obj) {
for (let i$1 = 0; i$1 < obj.length; i$1++) if (extendedTypeOf(obj[i$1]) !== "object") return false;
return obj.length != 0;
}
__name(isArrayOfTables, "isArrayOfTables");
function formatString(s) {
return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
}
__name(formatString, "formatString");
function stringifyValue(val, type, depth$1, numberAsFloat) {
if (depth$1 === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
if (type === "number") {
if (isNaN(val)) return "nan";
if (val === Infinity) return "inf";
if (val === -Infinity) return "-inf";
if (numberAsFloat && Number.isInteger(val)) return val.toFixed(1);
return val.toString();
}
if (type === "bigint" || type === "boolean") return val.toString();
if (type === "string") return formatString(val);
if (type === "date") {
if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
return val.toISOString();
}
if (type === "object") return stringifyInlineTable(val, depth$1, numberAsFloat);
if (type === "array") return stringifyArray(val, depth$1, numberAsFloat);
}
__name(stringifyValue, "stringifyValue");
function stringifyInlineTable(obj, depth$1, numberAsFloat) {
let keys = Object.keys(obj);
if (keys.length === 0) return "{}";
let res = "{ ";
for (let i$1 = 0; i$1 < keys.length; i$1++) {
let k = keys[i$1];
if (i$1) res += ", ";
res += BARE_KEY.test(k) ? k : formatString(k);
res += " = ";
res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth$1 - 1, numberAsFloat);
}
return res + " }";
}
__name(stringifyInlineTable, "stringifyInlineTable");
function stringifyArray(array, depth$1, numberAsFloat) {
if (array.length === 0) return "[]";
let res = "[ ";
for (let i$1 = 0; i$1 < array.length; i$1++) {
if (i$1) res += ", ";
if (array[i$1] === null || array[i$1] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
res += stringifyValue(array[i$1], extendedTypeOf(array[i$1]), depth$1 - 1, numberAsFloat);
}
return res + " ]";
}
__name(stringifyArray, "stringifyArray");
function stringifyArrayTable(array, key, depth$1, numberAsFloat) {
if (depth$1 === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
let res = "";
for (let i$1 = 0; i$1 < array.length; i$1++) {
res += `${res && "\n"}[[${key}]]
`;
res += stringifyTable(0, array[i$1], key, depth$1, numberAsFloat);
}
return res;
}
__name(stringifyArrayTable, "stringifyArrayTable");
function stringifyTable(tableKey, obj, prefix, depth$1, numberAsFloat) {
if (depth$1 === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
let preamble = "";
let tables = "";
let keys = Object.keys(obj);
for (let i$1 = 0; i$1 < keys.length; i$1++) {
let k = keys[i$1];
if (obj[k] !== null && obj[k] !== void 0) {
let type = extendedTypeOf(obj[k]);
if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
let key = BARE_KEY.test(k) ? k : formatString(k);
if (type === "array" && isArrayOfTables(obj[k])) tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth$1 - 1, numberAsFloat);
else if (type === "object") {
let tblKey = prefix ? `${prefix}.${key}` : key;
tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth$1 - 1, numberAsFloat);
} else {
preamble += key;
preamble += " = ";
preamble += stringifyValue(obj[k], type, depth$1, numberAsFloat);
preamble += "\n";
}
}
}
if (tableKey && (preamble || !tables)) preamble = preamble ? `[${tableKey}]
${preamble}` : `[${tableKey}]`;
return preamble && tables ? `${preamble}
${tables}` : preamble || tables;
}
__name(stringifyTable, "stringifyTable");
function stringify$3(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
if (extendedTypeOf(obj) !== "object") throw new TypeError("stringify can only be called with an object");
let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
if (str[str.length - 1] !== "\n") return str + "\n";
return str;
}
__name(stringify$3, "stringify");
var dist_default = {
parse: parse3,
stringify: stringify$3,
TomlDate,
TomlError
};
var 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";
}
};
var APIError = class extends ParseError {
static {
__name(this, "APIError");
}
#status;
code;
accountTag;
constructor({ status,...rest }) {
super(rest);
this.name = this.constructor.name;
this.#status = status;
}
get status() {
return this.#status;
}
isGatewayError() {
if (this.#status !== void 0) return [524].includes(this.#status);
return false;
}
isRetryable() {
return String(this.#status).startsWith("5");
}
#reportable = true;
get reportable() {
return this.#reportable;
}
preventReport() {
this.#reportable = false;
}
};
function parseTOML(tomlContent, filePath) {
try {
return dist_default.parse(tomlContent);
} catch (err) {
if (!(err instanceof TomlError)) throw err;
const location = {
lineText: tomlContent.split("\n")[err.line - 1],
line: err.line,
column: err.column - 1,
file: filePath,
fileText: tomlContent
};
throw new ParseError({
text: err.message.substring(0, err.message.indexOf("\n")),
location,
telemetryMessage: "TOML parse error"
});
}
}
__name(parseTOML, "parseTOML");
function parsePackageJSON(input, file2) {
return parseJSON(input, file2);
}
__name(parsePackageJSON, "parsePackageJSON");
function parseJSON(input, file2) {
return parseJSONC(input, file2, {
allowEmptyContent: false,
allowTrailingComma: false,
disallowComments: true
});
}
__name(parseJSON, "parseJSON");
function parseJSONC(input, file2, options = { allowTrailingComma: true }) {
const errors$1 = [];
const data$1 = parse2(input, errors$1, options);
if (errors$1.length) throw new ParseError({
text: printParseErrorCode(errors$1[0].error),
location: {
...indexLocation({
file: file2,
fileText: input
}, errors$1[0].offset + 1),
length: errors$1[0].length
},
telemetryMessage: "JSON(C) parse error"
});
return data$1;
}
__name(parseJSONC, "parseJSONC");
function readFileSyncToBuffer(file2) {
try {
return readFileSync(file2);
} catch (err) {
const { message } = err;
throw new ParseError({
text: `Could not read file: ${file2}`,
notes: [{ text: message.replace(file2, resolve(file2)) }],
telemetryMessage: false
});
}
}
__name(readFileSyncToBuffer, "readFileSyncToBuffer");
function readFileSync$1(file2) {
try {
return removeBOMAndValidate(readFileSync(file2), file2);
} catch (err) {
if (err instanceof ParseError) throw err;
const { message } = err;
throw new ParseError({
text: `Could not read file: ${file2}`,
notes: [{ text: message.replace(file2, resolve(file2)) }],
telemetryMessage: "Could not read file"
});
}
}
__name(readFileSync$1, "readFileSync");
function indexLocation(file2, index) {
let lineText, line = 0, column = 0, cursor = 0;
const { fileText = "" } = file2;
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,
...file2
};
}
__name(indexLocation, "indexLocation");
function searchLocation(file2, query) {
let lineText, length, line = 0, column = 0;
const queryText = String(query);
const { fileText = "" } = file2;
for (const content of fileText.split("\n")) {
line++;
const index = content.indexOf(queryText);
if (index >= 0) {
lineText = content;
column = index;
length = queryText.length;
break;
}
}
return {
lineText,
line,
column,
length,
...file2
};
}
__name(searchLocation, "searchLocation");
var units = {
nanoseconds: 1e-9,
nanosecond: 1e-9,
microseconds: 1e-6,
microsecond: 1e-6,
milliseconds: .001,
millisecond: .001,
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: .001,
msec: .001,
secs: 1,
sec: 1,
mins: 60,
min: 60,
ns: 1e-9,
us: 1e-6,
ms: .001,
mo: 18144e3,
yr: 220752e3,
s: 1,
m: 60,
h: 3600,
d: 86400,
w: 604800,
y: 220752e3
};
function parseHumanDuration(s) {
const unitsMap = new Map(Object.entries(units));
s = s.trim().toLowerCase();
let base = 1;
for (const [name, _] of unitsMap) if (s.endsWith(name)) {
s = s.substring(0, s.length - name.length);
base = unitsMap.get(name) || 1;
break;
}
return Number(s) * base;
}
__name(parseHumanDuration, "parseHumanDuration");
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);
}
__name(parseNonHyphenedUuid, "parseNonHyphenedUuid");
function parseByteSize(s, base = void 0) {
const match = s.match(/^(\d*\.*\d*)\s*([kKmMgGtTpP]{0,1})([i]{0,1}[bB]{0,1})$/);
if (!match) return NaN;
const size = match[1];
if (size.length === 0 || isNaN(Number(size))) return NaN;
const unit = match[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 = match[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));
}
__name(parseByteSize, "parseByteSize");
var 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"
}
];
function removeBOMAndValidate(buffer$1, file2) {
for (const bom of UNSUPPORTED_BOMS) if (buffer$1.length >= bom.buffer.length && buffer$1.subarray(0, bom.buffer.length).equals(bom.buffer)) throw new ParseError({
text: `Configuration file contains ${bom.encoding} byte order marker`,
notes: [{ text: `The file "${file2}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.` }],
location: {
file: file2,
line: 1,
column: 0
},
telemetryMessage: `${bom.encoding} BOM detected`
});
const content = buffer$1.toString("utf-8");
if (content.charCodeAt(0) === 65279) return content.slice(1);
return content;
}
__name(removeBOMAndValidate, "removeBOMAndValidate");
function absolute(input, root) {
return isAbsolute(input) ? input : resolve(root || ".", input);
}
__name(absolute, "absolute");
function up(base, options) {
let { last, cwd } = options || {};
let tmp = absolute(base, cwd);
let root = absolute(last || "/", cwd);
let prev, arr = [];
while (prev !== root) {
arr.push(tmp);
tmp = dirname(prev = tmp);
if (tmp === prev) break;
}
return arr;
}
__name(up, "up");
function file(name, options) {
let dir, tmp;
for (dir of up(options && options.cwd || "", options)) try {
tmp = join(dir, name);
if (statSync(tmp).isFile()) return tmp;
} catch {}
}
__name(file, "file");
function dedent(templ) {
var values = [];
for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
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(match) {
var _a, _b;
return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 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, i$1) {
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, i2) {
return i2 === 0 ? str : "" + endentation + str;
}).join("\n");
string += indentedValue + strings[i$1 + 1];
});
return string;
}
__name(dedent, "dedent");
var esm_default = dedent;
function resolveWranglerConfigPath({ config, script }, options) {
if (config !== void 0) return {
userConfigPath: config,
configPath: config,
deployConfigPath: void 0,
redirected: false
};
return findWranglerConfig$1(script !== void 0 ? path.dirname(script) : process.cwd(), options);
}
__name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
function findWranglerConfig$1(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
const userConfigPath = file(`wrangler.json`, { cwd: referencePath }) ?? file(`wrangler.jsonc`, { cwd: referencePath }) ?? file(`wrangler.toml`, { cwd: referencePath });
if (!useRedirectIfAvailable) return {
userConfigPath,
configPath: userConfigPath,
deployConfigPath: void 0,
redirected: false
};
const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig(referencePath, userConfigPath);
return {
userConfigPath,
configPath,
deployConfigPath,
redirected
};
}
__name(findWranglerConfig$1, "findWranglerConfig");
function findRedirectedWranglerConfig(cwd, userConfigPath) {
const deployConfigPath = file(PATH_TO_DEPLOY_CONFIG, { cwd });
if (deployConfigPath === void 0) return {
configPath: userConfigPath,
deployConfigPath,
redirected: false
};
let redirectedConfigPath;
const deployConfigFile = readFileSync$1(deployConfigPath);
try {
const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
redirectedConfigPath = deployConfig.configPath && path.resolve(path.dirname(deployConfigPath), deployConfig.configPath);
} catch (e) {
throw new UserError(`Failed to parse the deploy configuration file at ${path.relative(".", deployConfigPath)}`, {
cause: e,
telemetryMessage: false
});
}
if (!redirectedConfigPath) throw new UserError(esm_default`
A deploy configuration file was found at "${path.relative(".", deployConfigPath)}".
But this is not valid - the required "configPath" property was not found.
Instead this file contains:
\`\`\`
${deployConfigFile}
\`\`\`
`, { telemetryMessage: false });
if (!existsSync(redirectedConfigPath)) throw new UserError(esm_default`
There is a deploy configuration at "${path.relative(".", deployConfigPath)}".
But the redirected configuration path it points to, "${path.relative(".", redirectedConfigPath)}", does not exist.
`, { telemetryMessage: false });
if (userConfigPath) {
if (path.join(path.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
Found both a user configuration file at "${path.relative(".", userConfigPath)}"
and a deploy configuration file at "${path.relative(".", deployConfigPath)}".
But these do not share the same base path so it is not clear which should be used.
`, { telemetryMessage: false });
}
return {
configPath: redirectedConfigPath,
deployConfigPath,
redirected: true
};
}
__name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
function isRedirectedConfig(config) {
return config.configPath !== void 0 && config.configPath !== config.userConfigPath;
}
__name(isRedirectedConfig, "isRedirectedConfig");
function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
return isRedirectedConfig({
configPath,
userConfigPath
});
}
__name(isRedirectedRawConfig, "isRedirectedRawConfig");
function configFormat(configPath) {
if (configPath?.endsWith("toml")) return "toml";
if (configPath?.endsWith("jsonc")) return "jsonc";
if (configPath?.endsWith("json")) return "json";
return "none";
}
__name(configFormat, "configFormat");
function configFileName(configPath) {
switch (configFormat(configPath)) {
case "toml": return "wrangler.toml";
case "json": return "wrangler.json";
case "jsonc": return "wrangler.jsonc";
default: return "Wrangler configuration";
}
}
__name(configFileName, "configFileName");
function formatConfigSnippet(snippet, configPath, formatted = true) {
if (configFormat(configPath) === "toml") return dist_default.stringify(snippet);
else return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
}
__name(formatConfigSnippet, "formatConfigSnippet");
function isDirectory(path2) {
return fs.statSync(path2, { throwIfNoEntry: false })?.isDirectory() ?? false;
}
__name(isDirectory, "isDirectory");
function removeDir(dirPath, { fireAndForget = false } = {}) {
const result = fs.promises.rm(dirPath, {
recursive: true,
force: true,
maxRetries: 5,
retryDelay: 100
});
if (fireAndForget) result.catch(() => {});
else return result;
}
__name(removeDir, "removeDir");
function removeDirSync(dirPath) {
fs.rmSync(dirPath, {
recursive: true,
force: true,
maxRetries: 5,
retryDelay: 100
});
}
__name(removeDirSync, "removeDirSync");
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/symbols.js
var require_symbols = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/symbols.js": ((exports, module) => {
module.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"),
kHTTP2InitialWindowSize: Symbol("http2 initial window size"),
kHTTP2ConnectionWindowSize: Symbol("http2 connection window size"),
kEnableConnectProtocol: Symbol("http2session connect protocol"),
kRemoteSettings: Symbol("http2session remote settings"),
kHTTP2Stream: Symbol("http2session client stream"),
kPingInterval: Symbol("ping interval"),
kNoProxyAgent: Symbol("no proxy agent"),
kHttpProxyAgent: Symbol("http proxy agent"),
kHttpsProxyAgent: Symbol("https proxy agent"),
kSocks5ProxyAgent: Symbol("socks5 proxy agent")
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/timers.js
var require_timers = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/timers.js": ((exports, module) => {
/**
* This module offers an optimized timer implementation designed for scenarios
* where high precision is not critical.
*
* The timer achieves faster performance by using a low-resolution approach,
* with an accuracy target of within 500ms. This makes it particularly useful
* for timers with delays of 1 second or more, where exact timing is less
* crucial.
*
* It's important to note that Node.js timers are inherently imprecise, as
* delays can occur due to the event loop being blocked by other operations.
* Consequently, timers may trigger later than their scheduled time.
*/
/**
* The fastNow variable contains the internal fast timer clock value.
*
* @type {number}
*/
let fastNow = 0;
/**
* RESOLUTION_MS represents the target resolution time in milliseconds.
*
* @type {number}
* @default 1000
*/
const RESOLUTION_MS = 1e3;
/**
* TICK_MS defines the desired interval in milliseconds between each tick.
* The target value is set to half the resolution time, minus 1 ms, to account
* for potential event loop overhead.
*
* @type {number}
* @default 499
*/
const TICK_MS = (RESOLUTION_MS >> 1) - 1;
/**
* fastNowTimeout is a Node.js timer used to manage and process
* the FastTimers stored in the `fastTimers` array.
*
* @type {NodeJS.Timeout}
*/
let fastNowTimeout;
/**
* The kFastTimer symbol is used to identify FastTimer instances.
*
* @type {Symbol}
*/
const kFastTimer = Symbol("kFastTimer");
/**
* The fastTimers array contains all active FastTimers.
*
* @type {FastTimer[]}
*/
const fastTimers = [];
/**
* These constants represent the various states of a FastTimer.
*/
/**
* The `NOT_IN_LIST` constant indicates that the FastTimer is not included
* in the `fastTimers` array. Timers with this status will not be processed
* during the next tick by the `onTick` function.
*
* A FastTimer can be re-added to the `fastTimers` array by invoking the
* `refresh` method on the FastTimer instance.
*
* @type {-2}
*/
const NOT_IN_LIST = -2;
/**
* The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled
* for removal from the `fastTimers` array. A FastTimer in this state will
* be removed in the next tick by the `onTick` function and will no longer
* be processed.
*
* This status is also set when the `clear` method is called on the FastTimer instance.
*
* @type {-1}
*/
const TO_BE_CLEARED = -1;
/**
* The `PENDING` constant signifies that the FastTimer is awaiting processing
* in the next tick by the `onTick` function. Timers with this status will have
* their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.
*
* @type {0}
*/
const PENDING = 0;
/**
* The `ACTIVE` constant indicates that the FastTimer is active and waiting
* for its timer to expire. During the next tick, the `onTick` function will
* check if the timer has expired, and if so, it will execute the associated callback.
*
* @type {1}
*/
const ACTIVE = 1;
/**
* The onTick function processes the fastTimers array.
*
* @returns {void}
*/
function onTick() {
/**
* Increment the fastNow value by the TICK_MS value, despite the actual time
* that has passed since the last tick. This approach ensures independence
* from the system clock and delays caused by a blocked event loop.
*
* @type {number}
*/
fastNow += TICK_MS;
/**
* The `idx` variable is used to iterate over the `fastTimers` array.
* Expired timers are removed by replacing them with the last element in the array.
* Consequently, `idx` is only incremented when the current element is not removed.
*
* @type {number}
*/
let idx = 0;
/**
* The len variable will contain the length of the fastTimers array
* and will be decremented when a FastTimer should be removed from the
* fastTimers array.
*
* @type {number}
*/
let len = fastTimers.length;
while (idx < len) {
/**
* @type {FastTimer}
*/
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();
}
function refreshTimeout() {
if (fastNowTimeout?.refresh) fastNowTimeout.refresh();
else {
clearTimeout(fastNowTimeout);
fastNowTimeout = setTimeout(onTick, TICK_MS);
fastNowTimeout?.unref();
}
}
/**
* The `FastTimer` class is a data structure designed to store and manage
* timer information.
*/
var FastTimer = class {
[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$1, delay, arg) {
this._onTimeout = callback$1;
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;
}
};
/**
* This module exports a setTimeout and clearTimeout function that can be
* used as a drop-in replacement for the native functions.
*/
module.exports = {
setTimeout(callback$1, delay, arg) {
return delay <= RESOLUTION_MS ? setTimeout(callback$1, delay, arg) : new FastTimer(callback$1, delay, arg);
},
clearTimeout(timeout$1) {
if (timeout$1[kFastTimer])
/**
* @type {FastTimer}
*/
timeout$1.clear();
else clearTimeout(timeout$1);
},
setFastTimeout(callback$1, delay, arg) {
return new FastTimer(callback$1, delay, arg);
},
clearFastTimeout(timeout$1) {
timeout$1.clear();
},
now() {
return fastNow;
},
tick(delay = 0) {
fastNow += delay - RESOLUTION_MS + 1;
onTick();
onTick();
},
reset() {
fastNow = 0;
fastTimers.length = 0;
clearTimeout(fastNowTimeout);
fastNowTimeout = null;
},
kFastTimer
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/errors.js
var require_errors = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/errors.js": ((exports, module) => {
const kUndiciError = Symbol.for("undici.error.UND_ERR");
var UndiciError$4 = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "UndiciError";
this.code = "UND_ERR";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kUndiciError] === true;
}
get [kUndiciError]() {
return true;
}
};
const kConnectTimeoutError = Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
var ConnectTimeoutError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "ConnectTimeoutError";
this.message = message || "Connect Timeout Error";
this.code = "UND_ERR_CONNECT_TIMEOUT";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kConnectTimeoutError] === true;
}
get [kConnectTimeoutError]() {
return true;
}
};
const kHeadersTimeoutError = Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT");
var HeadersTimeoutError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "HeadersTimeoutError";
this.message = message || "Headers Timeout Error";
this.code = "UND_ERR_HEADERS_TIMEOUT";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kHeadersTimeoutError] === true;
}
get [kHeadersTimeoutError]() {
return true;
}
};
const kHeadersOverflowError = Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
var HeadersOverflowError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "HeadersOverflowError";
this.message = message || "Headers Overflow Error";
this.code = "UND_ERR_HEADERS_OVERFLOW";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kHeadersOverflowError] === true;
}
get [kHeadersOverflowError]() {
return true;
}
};
const kBodyTimeoutError = Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
var BodyTimeoutError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "BodyTimeoutError";
this.message = message || "Body Timeout Error";
this.code = "UND_ERR_BODY_TIMEOUT";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kBodyTimeoutError] === true;
}
get [kBodyTimeoutError]() {
return true;
}
};
const kInvalidArgumentError = Symbol.for("undici.error.UND_ERR_INVALID_ARG");
var InvalidArgumentError$37 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "InvalidArgumentError";
this.message = message || "Invalid Argument Error";
this.code = "UND_ERR_INVALID_ARG";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kInvalidArgumentError] === true;
}
get [kInvalidArgumentError]() {
return true;
}
};
const kInvalidReturnValueError = Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
var InvalidReturnValueError$2 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "InvalidReturnValueError";
this.message = message || "Invalid Return Value Error";
this.code = "UND_ERR_INVALID_RETURN_VALUE";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kInvalidReturnValueError] === true;
}
get [kInvalidReturnValueError]() {
return true;
}
};
const kAbortError = Symbol.for("undici.error.UND_ERR_ABORT");
var AbortError$2 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "AbortError";
this.message = message || "The operation was aborted";
this.code = "UND_ERR_ABORT";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kAbortError] === true;
}
get [kAbortError]() {
return true;
}
};
const kRequestAbortedError = Symbol.for("undici.error.UND_ERR_ABORTED");
var RequestAbortedError$9 = class extends AbortError$2 {
constructor(message) {
super(message);
this.name = "AbortError";
this.message = message || "Request aborted";
this.code = "UND_ERR_ABORTED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kRequestAbortedError] === true;
}
get [kRequestAbortedError]() {
return true;
}
};
const kInformationalError = Symbol.for("undici.error.UND_ERR_INFO");
var InformationalError$4 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "InformationalError";
this.message = message || "Request information";
this.code = "UND_ERR_INFO";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kInformationalError] === true;
}
get [kInformationalError]() {
return true;
}
};
const kRequestContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
var RequestContentLengthMismatchError$2 = class extends UndiciError$4 {
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";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kRequestContentLengthMismatchError] === true;
}
get [kRequestContentLengthMismatchError]() {
return true;
}
};
const kResponseContentLengthMismatchError = Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH");
var ResponseContentLengthMismatchError$1 = class extends UndiciError$4 {
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";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kResponseContentLengthMismatchError] === true;
}
get [kResponseContentLengthMismatchError]() {
return true;
}
};
const kClientDestroyedError = Symbol.for("undici.error.UND_ERR_DESTROYED");
var ClientDestroyedError$2 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "ClientDestroyedError";
this.message = message || "The client is destroyed";
this.code = "UND_ERR_DESTROYED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kClientDestroyedError] === true;
}
get [kClientDestroyedError]() {
return true;
}
};
const kClientClosedError = Symbol.for("undici.error.UND_ERR_CLOSED");
var ClientClosedError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "ClientClosedError";
this.message = message || "The client is closed";
this.code = "UND_ERR_CLOSED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kClientClosedError] === true;
}
get [kClientClosedError]() {
return true;
}
};
const kSocketError = Symbol.for("undici.error.UND_ERR_SOCKET");
var SocketError$4 = class extends UndiciError$4 {
constructor(message, socket) {
super(message);
this.name = "SocketError";
this.message = message || "Socket error";
this.code = "UND_ERR_SOCKET";
this.socket = socket;
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kSocketError] === true;
}
get [kSocketError]() {
return true;
}
};
const kNotSupportedError = Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
var NotSupportedError$2 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "NotSupportedError";
this.message = message || "Not supported error";
this.code = "UND_ERR_NOT_SUPPORTED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kNotSupportedError] === true;
}
get [kNotSupportedError]() {
return true;
}
};
const kBalancedPoolMissingUpstreamError = Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
var BalancedPoolMissingUpstreamError$1 = class extends UndiciError$4 {
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";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kBalancedPoolMissingUpstreamError] === true;
}
get [kBalancedPoolMissingUpstreamError]() {
return true;
}
};
const kHTTPParserError = Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
var HTTPParserError$1 = class extends Error {
constructor(message, code, data$1) {
super(message);
this.name = "HTTPParserError";
this.code = code ? `HPE_${code}` : void 0;
this.data = data$1 ? data$1.toString() : void 0;
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kHTTPParserError] === true;
}
get [kHTTPParserError]() {
return true;
}
};
const kResponseExceededMaxSizeError = Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
var ResponseExceededMaxSizeError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "ResponseExceededMaxSizeError";
this.message = message || "Response content exceeded max size";
this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kResponseExceededMaxSizeError] === true;
}
get [kResponseExceededMaxSizeError]() {
return true;
}
};
const kRequestRetryError = Symbol.for("undici.error.UND_ERR_REQ_RETRY");
var RequestRetryError$1 = class extends UndiciError$4 {
constructor(message, code, { headers, data: data$1 }) {
super(message);
this.name = "RequestRetryError";
this.message = message || "Request retry error";
this.code = "UND_ERR_REQ_RETRY";
this.statusCode = code;
this.data = data$1;
this.headers = headers;
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kRequestRetryError] === true;
}
get [kRequestRetryError]() {
return true;
}
};
const kResponseError = Symbol.for("undici.error.UND_ERR_RESPONSE");
var ResponseError$1 = class extends UndiciError$4 {
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;
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kResponseError] === true;
}
get [kResponseError]() {
return true;
}
};
const kSecureProxyConnectionError = Symbol.for("undici.error.UND_ERR_PRX_TLS");
var SecureProxyConnectionError$1 = class extends UndiciError$4 {
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;
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kSecureProxyConnectionError] === true;
}
get [kSecureProxyConnectionError]() {
return true;
}
};
const kMaxOriginsReachedError = Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
var MaxOriginsReachedError$1 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "MaxOriginsReachedError";
this.message = message || "Maximum allowed origins reached";
this.code = "UND_ERR_MAX_ORIGINS_REACHED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kMaxOriginsReachedError] === true;
}
get [kMaxOriginsReachedError]() {
return true;
}
};
var Socks5ProxyError$1 = class extends UndiciError$4 {
constructor(message, code) {
super(message);
this.name = "Socks5ProxyError";
this.message = message || "SOCKS5 proxy error";
this.code = code || "UND_ERR_SOCKS5";
}
};
const kMessageSizeExceededError = Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
var MessageSizeExceededError$2 = class extends UndiciError$4 {
constructor(message) {
super(message);
this.name = "MessageSizeExceededError";
this.message = message || "Max decompressed message size exceeded";
this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kMessageSizeExceededError] === true;
}
get [kMessageSizeExceededError]() {
return true;
}
};
module.exports = {
AbortError: AbortError$2,
HTTPParserError: HTTPParserError$1,
UndiciError: UndiciError$4,
HeadersTimeoutError: HeadersTimeoutError$1,
HeadersOverflowError: HeadersOverflowError$1,
BodyTimeoutError: BodyTimeoutError$1,
RequestContentLengthMismatchError: RequestContentLengthMismatchError$2,
ConnectTimeoutError: ConnectTimeoutError$1,
InvalidArgumentError: InvalidArgumentError$37,
InvalidReturnValueError: InvalidReturnValueError$2,
RequestAbortedError: RequestAbortedError$9,
ClientDestroyedError: ClientDestroyedError$2,
ClientClosedError: ClientClosedError$1,
InformationalError: InformationalError$4,
SocketError: SocketError$4,
NotSupportedError: NotSupportedError$2,
ResponseContentLengthMismatchError: ResponseContentLengthMismatchError$1,
BalancedPoolMissingUpstreamError: BalancedPoolMissingUpstreamError$1,
ResponseExceededMaxSizeError: ResponseExceededMaxSizeError$1,
RequestRetryError: RequestRetryError$1,
ResponseError: ResponseError$1,
SecureProxyConnectionError: SecureProxyConnectionError$1,
MaxOriginsReachedError: MaxOriginsReachedError$1,
Socks5ProxyError: Socks5ProxyError$1,
MessageSizeExceededError: MessageSizeExceededError$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/constants.js
var require_constants$5 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/constants.js": ((exports, module) => {
/**
* @see https://developer.mozilla.org/docs/Web/HTTP/Headers
*/
const wellknownHeaderNames$1 = [
"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"
];
/** @type {Record<typeof wellknownHeaderNames[number]|Lowercase<typeof wellknownHeaderNames[number]>, string>} */
const headerNameLowerCasedRecord$3 = {};
Object.setPrototypeOf(headerNameLowerCasedRecord$3, null);
/**
* @type {Record<Lowercase<typeof wellknownHeaderNames[number]>, Buffer>}
*/
const wellknownHeaderNameBuffers = {};
Object.setPrototypeOf(wellknownHeaderNameBuffers, null);
/**
* @param {string} header Lowercased header
* @returns {Buffer}
*/
function getHeaderNameAsBuffer(header) {
let buffer$1 = wellknownHeaderNameBuffers[header];
if (buffer$1 === void 0) buffer$1 = Buffer.from(header);
return buffer$1;
}
for (let i$1 = 0; i$1 < wellknownHeaderNames$1.length; ++i$1) {
const key = wellknownHeaderNames$1[i$1];
const lowerCasedKey = key.toLowerCase();
headerNameLowerCasedRecord$3[key] = headerNameLowerCasedRecord$3[lowerCasedKey] = lowerCasedKey;
}
module.exports = {
wellknownHeaderNames: wellknownHeaderNames$1,
headerNameLowerCasedRecord: headerNameLowerCasedRecord$3,
getHeaderNameAsBuffer
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/tree.js
var require_tree = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/tree.js": ((exports, module) => {
const { wellknownHeaderNames, headerNameLowerCasedRecord: headerNameLowerCasedRecord$2 } = require_constants$5();
var TstNode = class 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");
if ((this.code = key.charCodeAt(index)) > 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;
/**
* @type {TstNode}
*/
let node = this;
while (true) {
const code = key.charCodeAt(index);
if (code > 127) throw new TypeError("key must be ascii string");
if (node.code === code) if (length === ++index) {
node.value = value;
break;
} else if (node.middle !== null) node = node.middle;
else {
node.middle = new TstNode(key, value, index);
break;
}
else if (node.code < code) if (node.left !== null) node = node.left;
else {
node.left = new TstNode(key, value, index);
break;
}
else if (node.right !== null) node = node.right;
else {
node.right = new TstNode(key, value, index);
break;
}
}
}
/**
* @param {Uint8Array} key
* @returns {TstNode | null}
*/
search(key) {
const keylength = key.length;
let index = 0;
/**
* @type {TstNode|null}
*/
let node = this;
while (node !== null && index < keylength) {
let code = key[index];
if (code <= 90 && code >= 65) code |= 32;
while (node !== null) {
if (code === node.code) {
if (keylength === ++index) return node;
node = node.middle;
break;
}
node = node.code < code ? node.left : node.right;
}
}
return null;
}
};
var TernarySearchTree = class {
/** @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;
}
};
const tree$1 = new TernarySearchTree();
for (let i$1 = 0; i$1 < wellknownHeaderNames.length; ++i$1) {
const key = headerNameLowerCasedRecord$2[wellknownHeaderNames[i$1]];
tree$1.insert(key, key);
}
module.exports = {
TernarySearchTree,
tree: tree$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/util.js
var require_util$5 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/util.js": ((exports, module) => {
const assert$33 = __require$2("node:assert");
const { kDestroyed: kDestroyed$2, kBodyUsed: kBodyUsed$1, kListeners, kBody: kBody$2 } = require_symbols();
const { IncomingMessage } = __require$2("node:http");
const stream$1 = __require$2("node:stream");
const net$5 = __require$2("node:net");
const { stringify: stringify$2 } = __require$2("node:querystring");
const { EventEmitter: EE$2 } = __require$2("node:events");
const timers$1 = require_timers();
const { InvalidArgumentError: InvalidArgumentError$36, ConnectTimeoutError } = require_errors();
const { headerNameLowerCasedRecord: headerNameLowerCasedRecord$1 } = require_constants$5();
const { tree } = require_tree();
const [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v) => Number(v));
var BodyAsyncIterable$1 = class {
constructor(body) {
this[kBody$2] = body;
this[kBodyUsed$1] = false;
}
async *[Symbol.asyncIterator]() {
assert$33(!this[kBodyUsed$1], "disturbed");
this[kBodyUsed$1] = true;
yield* this[kBody$2];
}
};
function noop$9() {}
/**
* @param {*} body
* @returns {*}
*/
function wrapRequestBody$1(body) {
if (isStream$1(body)) {
if (bodyLength(body) === 0) body.on("data", function() {
assert$33(false);
});
if (typeof body.readableDidRead !== "boolean") {
body[kBodyUsed$1] = false;
EE$2.prototype.on.call(body, "data", function() {
this[kBodyUsed$1] = true;
});
}
return body;
} else if (body && typeof body.pipeTo === "function") return new BodyAsyncIterable$1(body);
else if (body && isFormDataLike$1(body)) return body;
else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable$1(body)) return new BodyAsyncIterable$1(body);
else return body;
}
/**
* @param {*} obj
* @returns {obj is import('node:stream').Stream}
*/
function isStream$1(obj) {
return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
}
/**
* @param {*} object
* @returns {object is Blob}
* based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
*/
function isBlobLike$1(object) {
if (object === null) return false;
else if (object instanceof Blob) 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");
}
}
/**
* @param {string} url The path to check for query strings or fragments.
* @returns {boolean} Returns true if the path contains a query string or fragment.
*/
function pathHasQueryOrFragment$1(url) {
return url.includes("?") || url.includes("#");
}
/**
* @param {string} url The URL to add the query params to
* @param {import('node:querystring').ParsedUrlQueryInput} queryParams The object to serialize into a URL query string
* @returns {string} The URL with the query params added
*/
function serializePathWithQuery$4(url, queryParams) {
if (pathHasQueryOrFragment$1(url)) throw new Error("Query params cannot be passed when url already contains \"?\" or \"#\".");
const stringified = stringify$2(queryParams);
if (stringified) url += "?" + stringified;
return url;
}
/**
* @param {number|string|undefined} port
* @returns {boolean}
*/
function isValidPort(port) {
const value = parseInt(port, 10);
return value === Number(port) && value >= 0 && value <= 65535;
}
/**
* Check if the value is a valid http or https prefixed string.
*
* @param {string} value
* @returns {boolean}
*/
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] === ":");
}
/**
* @param {string|URL|Record<string,string>} url
* @returns {URL}
*/
function parseURL(url) {
if (typeof url === "string") {
/**
* @type {URL}
*/
url = new URL(url);
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) throw new InvalidArgumentError$36("Invalid URL protocol: the URL must start with `http:` or `https:`.");
return url;
}
if (!url || typeof url !== "object") throw new InvalidArgumentError$36("Invalid URL: The URL argument must be a non-null object.");
if (!(url instanceof URL)) {
if (url.port != null && url.port !== "" && isValidPort(url.port) === false) throw new InvalidArgumentError$36("Invalid URL: port must be a valid integer or a string representation of an integer.");
if (url.path != null && typeof url.path !== "string") throw new InvalidArgumentError$36("Invalid URL path: the path must be a string or null/undefined.");
if (url.pathname != null && typeof url.pathname !== "string") throw new InvalidArgumentError$36("Invalid URL pathname: the pathname must be a string or null/undefined.");
if (url.hostname != null && typeof url.hostname !== "string") throw new InvalidArgumentError$36("Invalid URL hostname: the hostname must be a string or null/undefined.");
if (url.origin != null && typeof url.origin !== "string") throw new InvalidArgumentError$36("Invalid URL origin: the origin must be a string or null/undefined.");
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) throw new InvalidArgumentError$36("Invalid URL protocol: the URL must start with `http:` or `https:`.");
const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
let path$2 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
if (origin[origin.length - 1] === "/") origin = origin.slice(0, origin.length - 1);
if (path$2 && path$2[0] !== "/") path$2 = `/${path$2}`;
return new URL(`${origin}${path$2}`);
}
if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) throw new InvalidArgumentError$36("Invalid URL protocol: the URL must start with `http:` or `https:`.");
return url;
}
/**
* @param {string|URL|Record<string, string>} url
* @returns {URL}
*/
function parseOrigin(url) {
url = parseURL(url);
if (url.pathname !== "/" || url.search || url.hash) throw new InvalidArgumentError$36("invalid url");
return url;
}
/**
* @param {string} host
* @returns {string}
*/
function getHostname(host) {
if (host[0] === "[") {
const idx$1 = host.indexOf("]");
assert$33(idx$1 !== -1);
return host.substring(1, idx$1);
}
const idx = host.indexOf(":");
if (idx === -1) return host;
return host.substring(0, idx);
}
/**
* IP addresses are not valid server names per RFC6066
* Currently, the only server names supported are DNS hostnames
* @param {string|null} host
* @returns {string|null}
*/
function getServerName$1(host) {
if (!host) return null;
assert$33(typeof host === "string");
const servername = getHostname(host);
if (net$5.isIP(servername)) return "";
return servername;
}
/**
* @function
* @template T
* @param {T} obj
* @returns {T}
*/
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
/**
* @param {*} obj
* @returns {obj is AsyncIterable}
*/
function isAsyncIterable(obj) {
return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
}
/**
* @param {*} obj
* @returns {obj is Iterable}
*/
function isIterable$1(obj) {
return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
}
/**
* Checks whether an object has a safe Symbol.iterator — i.e. one that is
* either own or inherited from a non-Object.prototype chain. This prevents
* prototype-pollution attacks from injecting a fake iterator on
* Object.prototype.
* @param {object} obj
* @returns {boolean}
*/
function hasSafeIterator$3(obj) {
const prototype = Object.getPrototypeOf(obj);
return Object.prototype.hasOwnProperty.call(obj, Symbol.iterator) || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
}
/**
* @param {Blob|Buffer|import ('stream').Stream} body
* @returns {number|null}
*/
function bodyLength(body) {
if (body == null) return 0;
else if (isStream$1(body)) {
const state = body._readableState;
return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
} else if (isBlobLike$1(body)) return body.size != null ? body.size : null;
else if (isBuffer$1(body)) return body.byteLength;
return null;
}
/**
* @param {import ('stream').Stream} body
* @returns {boolean}
*/
function isDestroyed(body) {
return body && !!(body.destroyed || body[kDestroyed$2] || stream$1.isDestroyed?.(body));
}
/**
* @param {import ('stream').Stream} stream
* @param {Error} [err]
* @returns {void}
*/
function destroy$1(stream$2, err) {
if (stream$2 == null || !isStream$1(stream$2) || isDestroyed(stream$2)) return;
if (typeof stream$2.destroy === "function") {
if (Object.getPrototypeOf(stream$2).constructor === IncomingMessage) stream$2.socket = null;
stream$2.destroy(err);
} else if (err) queueMicrotask(() => {
stream$2.emit("error", err);
});
if (stream$2.destroyed !== true) stream$2[kDestroyed$2] = true;
}
const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
/**
* @param {string} val
* @returns {number | null}
*/
function parseKeepAliveTimeout(val) {
const m = val.match(KEEPALIVE_TIMEOUT_EXPR);
return m ? parseInt(m[1], 10) * 1e3 : null;
}
/**
* Retrieves a header name and returns its lowercase value.
* @param {string | Buffer} value Header name
* @returns {string}
*/
function headerNameToString(value) {
return typeof value === "string" ? headerNameLowerCasedRecord$1[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
}
/**
* Receive the buffer as a string and return its lowercase value.
* @param {Buffer} value Header name
* @returns {string}
*/
function bufferToLowerCasedHeaderName$2(value) {
return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
}
/**
* @param {(Buffer | string)[]} headers
* @param {Record<string, string | string[]>} [obj]
* @returns {Record<string, string | string[]>}
*/
function parseHeaders$2(headers, obj) {
if (obj === void 0) obj = {};
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) {
const key = headerNameToString(headers[i$1]);
let val = obj[key];
if (val !== void 0) if (!Object.hasOwn(obj, key)) {
const headersValue = typeof headers[i$1 + 1] === "string" ? headers[i$1 + 1] : Array.isArray(headers[i$1 + 1]) ? headers[i$1 + 1].map((x) => x.toString("latin1")) : headers[i$1 + 1].toString("latin1");
if (key === "__proto__") Object.defineProperty(obj, key, {
value: headersValue,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = headersValue;
} else {
if (typeof val === "string") {
val = [val];
obj[key] = val;
}
val.push(headers[i$1 + 1].toString("latin1"));
}
else obj[key] = typeof headers[i$1 + 1] === "string" ? headers[i$1 + 1] : Array.isArray(headers[i$1 + 1]) ? headers[i$1 + 1].map((x) => x.toString("latin1")) : headers[i$1 + 1].toString("latin1");
}
return obj;
}
/**
* @param {Buffer[]} headers
* @returns {string[]}
*/
function parseRawHeaders(headers) {
const headersLength = headers.length;
/**
* @type {string[]}
*/
const ret = new Array(headersLength);
let key;
let val;
for (let n$1 = 0; n$1 < headersLength; n$1 += 2) {
key = headers[n$1];
val = headers[n$1 + 1];
typeof key !== "string" && (key = key.toString());
typeof val !== "string" && (val = val.toString("latin1"));
ret[n$1] = key;
ret[n$1 + 1] = val;
}
return ret;
}
/**
* @param {string[]} headers
* @param {Buffer[]} headers
*/
function encodeRawHeaders(headers) {
if (!Array.isArray(headers)) throw new TypeError("expected headers to be an array");
return headers.map((x) => Buffer.from(x));
}
/**
* @param {*} buffer
* @returns {buffer is Buffer}
*/
function isBuffer$1(buffer$1) {
return buffer$1 instanceof Uint8Array || Buffer.isBuffer(buffer$1);
}
/**
* Asserts that the handler object is a request handler.
*
* @param {object} handler
* @param {string} method
* @param {string} [upgrade]
* @returns {asserts handler is import('../api/api-request').RequestHandler}
*/
function assertRequestHandler$1(handler, method, upgrade$1) {
if (!handler || typeof handler !== "object") throw new InvalidArgumentError$36("handler must be an object");
if (typeof handler.onRequestStart === "function") return;
if (typeof handler.onConnect !== "function") throw new InvalidArgumentError$36("invalid onConnect method");
if (typeof handler.onError !== "function") throw new InvalidArgumentError$36("invalid onError method");
if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) throw new InvalidArgumentError$36("invalid onBodySent method");
if (upgrade$1 || method === "CONNECT") {
if (typeof handler.onUpgrade !== "function") throw new InvalidArgumentError$36("invalid onUpgrade method");
} else {
if (typeof handler.onHeaders !== "function") throw new InvalidArgumentError$36("invalid onHeaders method");
if (typeof handler.onData !== "function") throw new InvalidArgumentError$36("invalid onData method");
if (typeof handler.onComplete !== "function") throw new InvalidArgumentError$36("invalid onComplete method");
}
}
/**
* A body is disturbed if it has been read from and it cannot be re-used without
* losing state or data.
* @param {import('node:stream').Readable} body
* @returns {boolean}
*/
function isDisturbed$3(body) {
return !!(body && (stream$1.isDisturbed(body) || body[kBodyUsed$1]));
}
/**
* @typedef {object} SocketInfo
* @property {string} [localAddress]
* @property {number} [localPort]
* @property {string} [remoteAddress]
* @property {number} [remotePort]
* @property {string} [remoteFamily]
* @property {number} [timeout]
* @property {number} bytesWritten
* @property {number} bytesRead
*/
/**
* @param {import('net').Socket} socket
* @returns {SocketInfo}
*/
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
};
}
/**
* @param {Iterable} iterable
* @returns {ReadableStream}
*/
function ReadableStreamFrom$3(iterable) {
let iterator;
return new ReadableStream({
start() {
iterator = iterable[Symbol.asyncIterator]();
},
pull(controller) {
return iterator.next().then(({ done, value }) => {
if (done) return queueMicrotask(() => {
controller.close();
controller.byobRequest?.respond(0);
});
else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
if (buf.byteLength) return controller.enqueue(new Uint8Array(buf));
else return this.pull(controller);
}
});
},
cancel() {
return iterator.return();
},
type: "bytes"
});
}
/**
* The object should be a FormData instance and contains all the required
* methods.
* @param {*} object
* @returns {object is FormData}
*/
function isFormDataLike$1(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";
}
function addAbortListener$2(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);
}
const validTokenChars = new Uint8Array([
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]);
/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2.6
* @param {number} c
* @returns {boolean}
*/
function isTokenCharCode(c) {
return validTokenChars[c] === 1;
}
const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
/**
* @param {string} characters
* @returns {boolean}
*/
function isValidHTTPToken$3(characters) {
if (characters.length >= 12) return tokenRegExp.test(characters);
if (characters.length === 0) return false;
for (let i$1 = 0; i$1 < characters.length; i$1++) if (validTokenChars[characters.charCodeAt(i$1)] !== 1) return false;
return true;
}
/**
* Matches if val contains an invalid field-vchar
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
*/
const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
/**
* @param {string} characters
* @returns {boolean}
*/
function isValidHeaderValue$3(characters) {
return !headerCharRegex.test(characters);
}
const rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/;
/**
* @typedef {object} RangeHeader
* @property {number} start
* @property {number | null} end
* @property {number | null} size
*/
/**
* Parse accordingly to RFC 9110
* @see https://www.rfc-editor.org/rfc/rfc9110#field.content-range
* @param {string} [range]
* @returns {RangeHeader|null}
*/
function parseRangeHeader$1(range) {
if (range == null || range === "") return {
start: 0,
end: null,
size: null
};
const m = range ? range.match(rangeHeaderRegex) : null;
return m ? {
start: parseInt(m[1]),
end: m[2] ? parseInt(m[2]) : null,
size: m[3] ? parseInt(m[3]) : null
} : null;
}
/**
* @template {import("events").EventEmitter} T
* @param {T} obj
* @param {string} name
* @param {(...args: any[]) => void} listener
* @returns {T}
*/
function addListener(obj, name, listener) {
(obj[kListeners] ??= []).push([name, listener]);
obj.on(name, listener);
return obj;
}
/**
* @template {import("events").EventEmitter} T
* @param {T} obj
* @returns {T}
*/
function removeAllListeners$1(obj) {
if (obj[kListeners] != null) {
for (const [name, listener] of obj[kListeners]) obj.removeListener(name, listener);
obj[kListeners] = null;
}
return obj;
}
/**
* @param {import ('../dispatcher/client')} client
* @param {import ('../core/request')} request
* @param {Error} err
*/
function errorRequest(client, request$2, err) {
try {
request$2.onError(err);
assert$33(request$2.aborted);
} catch (err$1) {
client.emit("error", err$1);
}
}
/**
* @param {WeakRef<net.Socket>} socketWeakRef
* @param {object} opts
* @param {number} opts.timeout
* @param {string} opts.hostname
* @param {number} opts.port
* @returns {() => void}
*/
const setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
if (!opts.timeout) return noop$9;
let s1 = null;
let s2 = null;
const fastTimer = timers$1.setFastTimeout(() => {
s1 = setImmediate(() => {
s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
});
}, opts.timeout);
return () => {
timers$1.clearFastTimeout(fastTimer);
clearImmediate(s1);
clearImmediate(s2);
};
} : (socketWeakRef, opts) => {
if (!opts.timeout) return noop$9;
let s1 = null;
const fastTimer = timers$1.setFastTimeout(() => {
s1 = setImmediate(() => {
onConnectTimeout(socketWeakRef.deref(), opts);
});
}, opts.timeout);
return () => {
timers$1.clearFastTimeout(fastTimer);
clearImmediate(s1);
};
};
/**
* @param {net.Socket} socket
* @param {object} opts
* @param {number} opts.timeout
* @param {string} opts.hostname
* @param {number} opts.port
*/
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$1(socket, new ConnectTimeoutError(message));
}
/**
* @param {string} urlString
* @returns {string}
*/
function getProtocolFromUrlString$1(urlString) {
if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") switch (urlString[4]) {
case ":": return "http:";
case "s": if (urlString[5] === ":") return "https:";
}
return urlString.slice(0, urlString.indexOf(":") + 1);
}
const kEnumerableProperty$11 = Object.create(null);
kEnumerableProperty$11.enumerable = true;
const normalizedMethodRecordsBase$2 = {
delete: "DELETE",
DELETE: "DELETE",
get: "GET",
GET: "GET",
head: "HEAD",
HEAD: "HEAD",
options: "OPTIONS",
OPTIONS: "OPTIONS",
post: "POST",
POST: "POST",
put: "PUT",
PUT: "PUT"
};
const normalizedMethodRecords$2 = {
...normalizedMethodRecordsBase$2,
patch: "patch",
PATCH: "PATCH"
};
Object.setPrototypeOf(normalizedMethodRecordsBase$2, null);
Object.setPrototypeOf(normalizedMethodRecords$2, null);
module.exports = {
kEnumerableProperty: kEnumerableProperty$11,
isDisturbed: isDisturbed$3,
isBlobLike: isBlobLike$1,
parseOrigin,
parseURL,
getServerName: getServerName$1,
isStream: isStream$1,
isIterable: isIterable$1,
hasSafeIterator: hasSafeIterator$3,
isAsyncIterable,
isDestroyed,
headerNameToString,
bufferToLowerCasedHeaderName: bufferToLowerCasedHeaderName$2,
addListener,
removeAllListeners: removeAllListeners$1,
errorRequest,
parseRawHeaders,
encodeRawHeaders,
parseHeaders: parseHeaders$2,
parseKeepAliveTimeout,
destroy: destroy$1,
bodyLength,
deepClone,
ReadableStreamFrom: ReadableStreamFrom$3,
isBuffer: isBuffer$1,
assertRequestHandler: assertRequestHandler$1,
getSocketInfo,
isFormDataLike: isFormDataLike$1,
pathHasQueryOrFragment: pathHasQueryOrFragment$1,
serializePathWithQuery: serializePathWithQuery$4,
addAbortListener: addAbortListener$2,
isValidHTTPToken: isValidHTTPToken$3,
isValidHeaderValue: isValidHeaderValue$3,
isTokenCharCode,
parseRangeHeader: parseRangeHeader$1,
normalizedMethodRecordsBase: normalizedMethodRecordsBase$2,
normalizedMethodRecords: normalizedMethodRecords$2,
isValidPort,
isHttpOrHttpsPrefixed,
nodeMajor,
nodeMinor,
safeHTTPMethods: Object.freeze([
"GET",
"HEAD",
"OPTIONS",
"TRACE"
]),
wrapRequestBody: wrapRequestBody$1,
setupConnectTimeout,
getProtocolFromUrlString: getProtocolFromUrlString$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/stats.js
var require_stats = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/stats.js": ((exports, module) => {
const { kConnected: kConnected$4, kPending: kPending$4, kRunning: kRunning$5, kSize: kSize$5, kFree: kFree$1, kQueued: kQueued$1 } = require_symbols();
var ClientStats$1 = class {
constructor(client) {
this.connected = client[kConnected$4];
this.pending = client[kPending$4];
this.running = client[kRunning$5];
this.size = client[kSize$5];
}
};
var PoolStats$1 = class {
constructor(pool) {
this.connected = pool[kConnected$4];
this.free = pool[kFree$1];
this.pending = pool[kPending$4];
this.queued = pool[kQueued$1];
this.running = pool[kRunning$5];
this.size = pool[kSize$5];
}
};
module.exports = {
ClientStats: ClientStats$1,
PoolStats: PoolStats$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/diagnostics.js
var require_diagnostics = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/diagnostics.js": ((exports, module) => {
const diagnosticsChannel$1 = __require$2("node:diagnostics_channel");
const util$26 = __require$2("node:util");
const undiciDebugLog = util$26.debuglog("undici");
const fetchDebuglog = util$26.debuglog("fetch");
const websocketDebuglog = util$26.debuglog("websocket");
const channels$7 = {
beforeConnect: diagnosticsChannel$1.channel("undici:client:beforeConnect"),
connected: diagnosticsChannel$1.channel("undici:client:connected"),
connectError: diagnosticsChannel$1.channel("undici:client:connectError"),
sendHeaders: diagnosticsChannel$1.channel("undici:client:sendHeaders"),
create: diagnosticsChannel$1.channel("undici:request:create"),
bodySent: diagnosticsChannel$1.channel("undici:request:bodySent"),
bodyChunkSent: diagnosticsChannel$1.channel("undici:request:bodyChunkSent"),
bodyChunkReceived: diagnosticsChannel$1.channel("undici:request:bodyChunkReceived"),
headers: diagnosticsChannel$1.channel("undici:request:headers"),
trailers: diagnosticsChannel$1.channel("undici:request:trailers"),
error: diagnosticsChannel$1.channel("undici:request:error"),
open: diagnosticsChannel$1.channel("undici:websocket:open"),
close: diagnosticsChannel$1.channel("undici:websocket:close"),
socketError: diagnosticsChannel$1.channel("undici:websocket:socket_error"),
ping: diagnosticsChannel$1.channel("undici:websocket:ping"),
pong: diagnosticsChannel$1.channel("undici:websocket:pong"),
proxyConnected: diagnosticsChannel$1.channel("undici:proxy:connected")
};
let isTrackingClientEvents = false;
function trackClientEvents(debugLog = undiciDebugLog) {
if (isTrackingClientEvents) return;
if (channels$7.beforeConnect.hasSubscribers || channels$7.connected.hasSubscribers || channels$7.connectError.hasSubscribers || channels$7.sendHeaders.hasSubscribers) {
isTrackingClientEvents = true;
return;
}
isTrackingClientEvents = true;
diagnosticsChannel$1.subscribe("undici:client:beforeConnect", (evt) => {
const { connectParams: { version: version$2, protocol, port, host } } = evt;
debugLog("connecting to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version$2);
});
diagnosticsChannel$1.subscribe("undici:client:connected", (evt) => {
const { connectParams: { version: version$2, protocol, port, host } } = evt;
debugLog("connected to %s%s using %s%s", host, port ? `:${port}` : "", protocol, version$2);
});
diagnosticsChannel$1.subscribe("undici:client:connectError", (evt) => {
const { connectParams: { version: version$2, protocol, port, host }, error } = evt;
debugLog("connection to %s%s using %s%s errored - %s", host, port ? `:${port}` : "", protocol, version$2, error.message);
});
diagnosticsChannel$1.subscribe("undici:client:sendHeaders", (evt) => {
const { request: { method, path: path$2, origin } } = evt;
debugLog("sending request to %s %s%s", method, origin, path$2);
});
}
let isTrackingRequestEvents = false;
function trackRequestEvents(debugLog = undiciDebugLog) {
if (isTrackingRequestEvents) return;
if (channels$7.headers.hasSubscribers || channels$7.trailers.hasSubscribers || channels$7.error.hasSubscribers) {
isTrackingRequestEvents = true;
return;
}
isTrackingRequestEvents = true;
diagnosticsChannel$1.subscribe("undici:request:headers", (evt) => {
const { request: { method, path: path$2, origin }, response: { statusCode } } = evt;
debugLog("received response to %s %s%s - HTTP %d", method, origin, path$2, statusCode);
});
diagnosticsChannel$1.subscribe("undici:request:trailers", (evt) => {
const { request: { method, path: path$2, origin } } = evt;
debugLog("trailers received from %s %s%s", method, origin, path$2);
});
diagnosticsChannel$1.subscribe("undici:request:error", (evt) => {
const { request: { method, path: path$2, origin }, error } = evt;
debugLog("request to %s %s%s errored - %s", method, origin, path$2, error.message);
});
}
let isTrackingWebSocketEvents = false;
function trackWebSocketEvents(debugLog = websocketDebuglog) {
if (isTrackingWebSocketEvents) return;
if (channels$7.open.hasSubscribers || channels$7.close.hasSubscribers || channels$7.socketError.hasSubscribers || channels$7.ping.hasSubscribers || channels$7.pong.hasSubscribers) {
isTrackingWebSocketEvents = true;
return;
}
isTrackingWebSocketEvents = true;
diagnosticsChannel$1.subscribe("undici:websocket:open", (evt) => {
if (evt.address != null) {
const { address, port } = evt.address;
debugLog("connection opened %s%s", address, port ? `:${port}` : "");
} else debugLog("connection opened");
});
diagnosticsChannel$1.subscribe("undici:websocket:close", (evt) => {
const { websocket, code, reason } = evt;
debugLog("closed connection to %s - %s %s", websocket.url, code, reason);
});
diagnosticsChannel$1.subscribe("undici:websocket:socket_error", (err) => {
debugLog("connection errored - %s", err.message);
});
diagnosticsChannel$1.subscribe("undici:websocket:ping", (evt) => {
debugLog("ping received");
});
diagnosticsChannel$1.subscribe("undici:websocket:pong", (evt) => {
debugLog("pong received");
});
}
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);
}
module.exports = { channels: channels$7 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/request.js
var require_request$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/request.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$35, NotSupportedError: NotSupportedError$1 } = require_errors();
const assert$32 = __require$2("node:assert");
const { isValidHTTPToken: isValidHTTPToken$2, isValidHeaderValue: isValidHeaderValue$2, isStream, destroy, isBuffer, isFormDataLike, isIterable, hasSafeIterator: hasSafeIterator$2, isBlobLike, serializePathWithQuery: serializePathWithQuery$3, assertRequestHandler, getServerName, normalizedMethodRecords: normalizedMethodRecords$1, getProtocolFromUrlString } = require_util$5();
const { channels: channels$6 } = require_diagnostics();
const { headerNameLowerCasedRecord } = require_constants$5();
const invalidPathRegex = /[^\u0021-\u00ff]/;
const kHandler = Symbol("handler");
var Request$6 = class {
constructor(origin, { path: path$2, method, body, headers, query, idempotent, blocking, upgrade: upgrade$1, headersTimeout, bodyTimeout, reset, expectContinue, servername, throwOnError, maxRedirections, typeOfService }, handler) {
if (typeof path$2 !== "string") throw new InvalidArgumentError$35("path must be a string");
else if (path$2[0] !== "/" && !(path$2.startsWith("http://") || path$2.startsWith("https://")) && method !== "CONNECT") throw new InvalidArgumentError$35("path must be an absolute URL or start with a slash");
else if (invalidPathRegex.test(path$2)) throw new InvalidArgumentError$35("invalid request path");
if (typeof method !== "string") throw new InvalidArgumentError$35("method must be a string");
else if (normalizedMethodRecords$1[method] === void 0 && !isValidHTTPToken$2(method)) throw new InvalidArgumentError$35("invalid request method");
if (upgrade$1 && typeof upgrade$1 !== "string") throw new InvalidArgumentError$35("upgrade must be a string");
if (upgrade$1 && !isValidHeaderValue$2(upgrade$1)) throw new InvalidArgumentError$35("invalid upgrade header");
if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) throw new InvalidArgumentError$35("invalid headersTimeout");
if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) throw new InvalidArgumentError$35("invalid bodyTimeout");
if (reset != null && typeof reset !== "boolean") throw new InvalidArgumentError$35("invalid reset");
if (expectContinue != null && typeof expectContinue !== "boolean") throw new InvalidArgumentError$35("invalid expectContinue");
if (throwOnError != null) throw new InvalidArgumentError$35("invalid throwOnError");
if (maxRedirections != null && maxRedirections !== 0) throw new InvalidArgumentError$35("maxRedirections is not supported, use the redirect interceptor");
if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) throw new InvalidArgumentError$35("typeOfService must be an integer between 0 and 255");
this.headersTimeout = headersTimeout;
this.bodyTimeout = bodyTimeout;
this.method = method;
this.typeOfService = typeOfService ?? 0;
this.abort = null;
if (body == null) this.body = null;
else if (isStream(body)) {
this.body = body;
const rState = this.body._readableState;
if (!rState || !rState.autoDestroy) {
this.endHandler = function autoDestroy() {
destroy(this);
};
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$35("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$1 || null;
this.path = query ? serializePathWithQuery$3(path$2, query) : path$2;
this.origin = origin;
this.protocol = getProtocolFromUrlString(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$35("headers array must be even");
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) processHeader(this, headers[i$1], headers[i$1 + 1]);
} else if (headers && typeof headers === "object") if (hasSafeIterator$2(headers)) for (const header of headers) {
if (!Array.isArray(header) || header.length !== 2) throw new InvalidArgumentError$35("headers must be in key-value pair format");
processHeader(this, header[0], header[1]);
}
else {
const keys = Object.keys(headers);
for (let i$1 = 0; i$1 < keys.length; ++i$1) processHeader(this, keys[i$1], headers[keys[i$1]]);
}
else if (headers != null) throw new InvalidArgumentError$35("headers must be an object or an array");
assertRequestHandler(handler, method, upgrade$1);
this.servername = servername || getServerName(this.host) || null;
this[kHandler] = handler;
if (channels$6.create.hasSubscribers) channels$6.create.publish({ request: this });
}
onBodySent(chunk) {
if (channels$6.bodyChunkSent.hasSubscribers) channels$6.bodyChunkSent.publish({
request: this,
chunk
});
if (this[kHandler].onBodySent) try {
return this[kHandler].onBodySent(chunk);
} catch (err) {
this.abort(err);
}
}
onRequestSent() {
if (channels$6.bodySent.hasSubscribers) channels$6.bodySent.publish({ request: this });
if (this[kHandler].onRequestSent) try {
return this[kHandler].onRequestSent();
} catch (err) {
this.abort(err);
}
}
onConnect(abort$1) {
assert$32(!this.aborted);
assert$32(!this.completed);
if (this.error) abort$1(this.error);
else {
this.abort = abort$1;
return this[kHandler].onConnect(abort$1);
}
}
onResponseStarted() {
return this[kHandler].onResponseStarted?.();
}
onHeaders(statusCode, headers, resume$1, statusText) {
assert$32(!this.aborted);
assert$32(!this.completed);
if (channels$6.headers.hasSubscribers) channels$6.headers.publish({
request: this,
response: {
statusCode,
headers,
statusText
}
});
try {
return this[kHandler].onHeaders(statusCode, headers, resume$1, statusText);
} catch (err) {
this.abort(err);
}
}
onData(chunk) {
assert$32(!this.aborted);
assert$32(!this.completed);
if (channels$6.bodyChunkReceived.hasSubscribers) channels$6.bodyChunkReceived.publish({
request: this,
chunk
});
try {
return this[kHandler].onData(chunk);
} catch (err) {
this.abort(err);
return false;
}
}
onUpgrade(statusCode, headers, socket) {
assert$32(!this.aborted);
assert$32(!this.completed);
return this[kHandler].onUpgrade(statusCode, headers, socket);
}
onComplete(trailers) {
this.onFinally();
assert$32(!this.aborted);
assert$32(!this.completed);
this.completed = true;
if (channels$6.trailers.hasSubscribers) channels$6.trailers.publish({
request: this,
trailers
});
try {
return this[kHandler].onComplete(trailers);
} catch (err) {
this.onError(err);
}
}
onError(error) {
this.onFinally();
if (channels$6.error.hasSubscribers) channels$6.error.publish({
request: this,
error
});
if (this.aborted) return;
this.aborted = true;
return this[kHandler].onError(error);
}
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(request$2, key, val) {
if (val && typeof val === "object" && !Array.isArray(val)) throw new InvalidArgumentError$35(`invalid ${key} header`);
else if (val === void 0) return;
let headerName = headerNameLowerCasedRecord[key];
if (headerName === void 0) {
headerName = key.toLowerCase();
if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken$2(headerName)) throw new InvalidArgumentError$35("invalid header key");
}
if (Array.isArray(val)) {
const arr = [];
for (let i$1 = 0; i$1 < val.length; i$1++) if (typeof val[i$1] === "string") {
if (!isValidHeaderValue$2(val[i$1])) throw new InvalidArgumentError$35(`invalid ${key} header`);
arr.push(val[i$1]);
} else if (val[i$1] === null) arr.push("");
else if (typeof val[i$1] === "object") throw new InvalidArgumentError$35(`invalid ${key} header`);
else arr.push(`${val[i$1]}`);
val = arr;
} else if (typeof val === "string") {
if (!isValidHeaderValue$2(val)) throw new InvalidArgumentError$35(`invalid ${key} header`);
} else if (val === null) val = "";
else val = `${val}`;
if (headerName === "host") {
if (request$2.host !== null) throw new InvalidArgumentError$35("duplicate host header");
if (typeof val !== "string") throw new InvalidArgumentError$35("invalid host header");
request$2.host = val;
} else if (headerName === "content-length") {
if (request$2.contentLength !== null) throw new InvalidArgumentError$35("duplicate content-length header");
request$2.contentLength = parseInt(val, 10);
if (!Number.isFinite(request$2.contentLength)) throw new InvalidArgumentError$35("invalid content-length header");
} else if (request$2.contentType === null && headerName === "content-type") {
request$2.contentType = val;
request$2.headers.push(key, val);
} else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") throw new InvalidArgumentError$35(`invalid ${headerName} header`);
else if (headerName === "connection") {
const value = typeof val === "string" ? val : null;
if (value === null) throw new InvalidArgumentError$35("invalid connection header");
for (const token of value.toLowerCase().split(",")) {
const trimmed = token.trim();
if (!isValidHTTPToken$2(trimmed)) throw new InvalidArgumentError$35("invalid connection header");
if (trimmed === "close") request$2.reset = true;
}
} else if (headerName === "expect") throw new NotSupportedError$1("expect header not supported");
else request$2.headers.push(key, val);
}
module.exports = Request$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/wrap-handler.js
var require_wrap_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/wrap-handler.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$34 } = require_errors();
module.exports = class WrapHandler$4 {
#handler;
constructor(handler) {
this.#handler = handler;
}
static wrap(handler) {
return handler.onRequestStart ? handler : new WrapHandler$4(handler);
}
onConnect(abort$1, context) {
return this.#handler.onConnect?.(abort$1, context);
}
onResponseStarted() {
return this.#handler.onResponseStarted?.();
}
onHeaders(statusCode, rawHeaders, resume$1, statusMessage) {
return this.#handler.onHeaders?.(statusCode, rawHeaders, resume$1, statusMessage);
}
onUpgrade(statusCode, rawHeaders, socket) {
return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
}
onData(data$1) {
return this.#handler.onData?.(data$1);
}
onComplete(trailers) {
return this.#handler.onComplete?.(trailers);
}
onError(err) {
if (!this.#handler.onError) throw err;
return this.#handler.onError?.(err);
}
onRequestStart(controller, context) {
this.#handler.onConnect?.((reason) => controller.abort(reason), context);
}
onRequestUpgrade(controller, statusCode, headers, socket) {
const rawHeaders = [];
for (const [key, val] of Object.entries(headers)) rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
const rawHeaders = [];
for (const [key, val] of Object.entries(headers)) rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) controller.pause();
}
onResponseData(controller, data$1) {
if (this.#handler.onData?.(data$1) === false) controller.pause();
}
onResponseEnd(controller, trailers) {
const rawTrailers = [];
for (const [key, val] of Object.entries(trailers)) rawTrailers.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
this.#handler.onComplete?.(rawTrailers);
}
onResponseError(controller, err) {
if (!this.#handler.onError) throw new InvalidArgumentError$34("invalid onError method");
this.#handler.onError?.(err);
}
};
function toRawHeaderValue(value) {
return Array.isArray(value) ? value.map((item) => Buffer.from(item, "latin1")) : Buffer.from(value, "latin1");
}
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/dispatcher.js": ((exports, module) => {
const EventEmitter$2 = __require$2("node:events");
const WrapHandler$3 = require_wrap_handler();
const wrapInterceptor = (dispatch) => (opts, handler) => dispatch(opts, WrapHandler$3.wrap(handler));
var Dispatcher$4 = class extends EventEmitter$2 {
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: (target$1, key) => key === "dispatch" ? dispatch : target$1[key] });
}
};
module.exports = Dispatcher$4;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/unwrap-handler.js
var require_unwrap_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/unwrap-handler.js": ((exports, module) => {
const { parseHeaders: parseHeaders$1 } = require_util$5();
const { InvalidArgumentError: InvalidArgumentError$33 } = require_errors();
const kResume$4 = Symbol("resume");
var UnwrapController = class {
#paused = false;
#reason = null;
#aborted = false;
#abort;
[kResume$4] = null;
constructor(abort$1) {
this.#abort = abort$1;
}
pause() {
this.#paused = true;
}
resume() {
if (this.#paused) {
this.#paused = false;
this[kResume$4]?.();
}
}
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;
}
};
module.exports = class UnwrapHandler$1 {
#handler;
#controller;
constructor(handler) {
this.#handler = handler;
}
static unwrap(handler) {
return !handler.onRequestStart ? handler : new UnwrapHandler$1(handler);
}
onConnect(abort$1, context) {
this.#controller = new UnwrapController(abort$1);
this.#handler.onRequestStart?.(this.#controller, context);
}
onResponseStarted() {
return this.#handler.onResponseStarted?.();
}
onUpgrade(statusCode, rawHeaders, socket) {
this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders$1(rawHeaders), socket);
}
onHeaders(statusCode, rawHeaders, resume$1, statusMessage) {
this.#controller[kResume$4] = resume$1;
this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders$1(rawHeaders), statusMessage);
return !this.#controller.paused;
}
onData(data$1) {
this.#handler.onResponseData?.(this.#controller, data$1);
return !this.#controller.paused;
}
onComplete(rawTrailers) {
this.#handler.onResponseEnd?.(this.#controller, parseHeaders$1(rawTrailers));
}
onError(err) {
if (!this.#handler.onResponseError) throw new InvalidArgumentError$33("invalid onError method");
this.#handler.onResponseError?.(this.#controller, err);
}
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/dispatcher-base.js": ((exports, module) => {
const Dispatcher$3 = require_dispatcher();
const UnwrapHandler = require_unwrap_handler();
const { ClientDestroyedError: ClientDestroyedError$1, ClientClosedError, InvalidArgumentError: InvalidArgumentError$32 } = require_errors();
const { kDestroy: kDestroy$6, kClose: kClose$8, kClosed: kClosed$3, kDestroyed: kDestroyed$1, kDispatch: kDispatch$6 } = require_symbols();
const kOnDestroyed = Symbol("onDestroyed");
const kOnClosed = Symbol("onClosed");
var DispatcherBase$6 = class extends Dispatcher$3 {
/** @type {boolean} */
[kDestroyed$1] = false;
/** @type {Array<Function|null} */
[kOnDestroyed] = null;
/** @type {boolean} */
[kClosed$3] = false;
/** @type {Array<Function>|null} */
[kOnClosed] = null;
/** @returns {boolean} */
get destroyed() {
return this[kDestroyed$1];
}
/** @returns {boolean} */
get closed() {
return this[kClosed$3];
}
close(callback$1) {
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
this.close((err, data$1) => {
return err ? reject(err) : resolve$4(data$1);
});
});
if (typeof callback$1 !== "function") throw new InvalidArgumentError$32("invalid callback");
if (this[kDestroyed$1]) {
const err = new ClientDestroyedError$1();
queueMicrotask(() => callback$1(err, null));
return;
}
if (this[kClosed$3]) {
if (this[kOnClosed]) this[kOnClosed].push(callback$1);
else queueMicrotask(() => callback$1(null, null));
return;
}
this[kClosed$3] = true;
this[kOnClosed] ??= [];
this[kOnClosed].push(callback$1);
const onClosed = () => {
const callbacks = this[kOnClosed];
this[kOnClosed] = null;
for (let i$1 = 0; i$1 < callbacks.length; i$1++) callbacks[i$1](null, null);
};
this[kClose$8]().then(() => this.destroy()).then(() => queueMicrotask(onClosed));
}
destroy(err, callback$1) {
if (typeof err === "function") {
callback$1 = err;
err = null;
}
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
this.destroy(err, (err$1, data$1) => {
return err$1 ? reject(err$1) : resolve$4(data$1);
});
});
if (typeof callback$1 !== "function") throw new InvalidArgumentError$32("invalid callback");
if (this[kDestroyed$1]) {
if (this[kOnDestroyed]) this[kOnDestroyed].push(callback$1);
else queueMicrotask(() => callback$1(null, null));
return;
}
if (!err) err = new ClientDestroyedError$1();
this[kDestroyed$1] = true;
this[kOnDestroyed] ??= [];
this[kOnDestroyed].push(callback$1);
const onDestroyed = () => {
const callbacks = this[kOnDestroyed];
this[kOnDestroyed] = null;
for (let i$1 = 0; i$1 < callbacks.length; i$1++) callbacks[i$1](null, null);
};
this[kDestroy$6](err).then(() => queueMicrotask(onDestroyed));
}
dispatch(opts, handler) {
if (!handler || typeof handler !== "object") throw new InvalidArgumentError$32("handler must be an object");
handler = UnwrapHandler.unwrap(handler);
try {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$32("opts must be an object.");
if (this[kDestroyed$1] || this[kOnDestroyed]) throw new ClientDestroyedError$1();
if (this[kClosed$3]) throw new ClientClosedError();
return this[kDispatch$6](opts, handler);
} catch (err) {
if (typeof handler.onError !== "function") throw err;
handler.onError(err);
return false;
}
}
};
module.exports = DispatcherBase$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/connect.js
var require_connect = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/connect.js": ((exports, module) => {
const net$4 = __require$2("node:net");
const assert$31 = __require$2("node:assert");
const util$25 = require_util$5();
const { InvalidArgumentError: InvalidArgumentError$31 } = require_errors();
let tls$1;
const SessionCache = class 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$1 = this._sessionCache.get(key);
if (ref$1 !== void 0 && ref$1.deref() === void 0) this._sessionCache.delete(key);
});
}
get(sessionKey) {
const ref$1 = this._sessionCache.get(sessionKey);
return ref$1 ? ref$1.deref() : null;
}
set(sessionKey, session) {
if (this._maxCachedSessions === 0) return;
this._sessionCache.set(sessionKey, new WeakRef(session));
this._sessionRegistry.register(session, sessionKey);
}
};
function buildConnector$6({ allowH2, useH2c, maxCachedSessions, socketPath, timeout: timeout$1, session: customSession,...opts }) {
if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) throw new InvalidArgumentError$31("maxCachedSessions must be a positive integer or zero");
const options = {
path: socketPath,
...opts
};
const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
timeout$1 = timeout$1 == null ? 1e4 : timeout$1;
allowH2 = allowH2 != null ? allowH2 : false;
return function connect$2({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback$1) {
let socket;
if (protocol === "https:") {
if (!tls$1) tls$1 = __require$2("node:tls");
servername = servername || options.servername || util$25.getServerName(host) || null;
const sessionKey = servername || hostname;
assert$31(sessionKey);
const session = customSession || sessionCache.get(sessionKey) || null;
port = port || 443;
socket = tls$1.connect({
highWaterMark: 16384,
...options,
servername,
session,
localAddress,
ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
socket: httpSocket,
port,
host: hostname
});
socket.on("session", function(session$1) {
sessionCache.set(sessionKey, session$1);
});
} else {
assert$31(!httpSocket, "httpSocket can only be sent on TLS update");
port = port || 80;
socket = net$4.connect({
highWaterMark: 64 * 1024,
...options,
localAddress,
port,
host: hostname
});
if (useH2c === true) socket.alpnProtocol = "h2";
}
if (options.keepAlive == null || options.keepAlive) {
const keepAliveInitialDelay = options.keepAliveInitialDelay === void 0 ? 6e4 : options.keepAliveInitialDelay;
socket.setKeepAlive(true, keepAliveInitialDelay);
}
const clearConnectTimeout = util$25.setupConnectTimeout(new WeakRef(socket), {
timeout: timeout$1,
hostname,
port
});
socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
queueMicrotask(clearConnectTimeout);
if (callback$1) {
const cb = callback$1;
callback$1 = null;
cb(null, this);
}
}).on("error", function(err) {
queueMicrotask(clearConnectTimeout);
if (callback$1) {
const cb = callback$1;
callback$1 = null;
cb(err);
}
});
return socket;
};
}
module.exports = buildConnector$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/utils.js
var require_utils$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/utils.js": ((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.enumToMap = enumToMap;
function enumToMap(obj, filter = [], exceptions = []) {
const emptyFilter = (filter?.length ?? 0) === 0;
const emptyExceptions = (exceptions?.length ?? 0) === 0;
return Object.fromEntries(Object.entries(obj).filter(([, value]) => {
return typeof value === "number" && (emptyFilter || filter.includes(value)) && (emptyExceptions || !exceptions.includes(value));
}));
}
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/constants.js
var require_constants$4 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/constants.js": ((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
const utils_1 = require_utils$1();
exports.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,
CB_PROTOCOL_COMPLETE: 38
};
exports.TYPE = {
BOTH: 0,
REQUEST: 1,
RESPONSE: 2
};
exports.FLAGS = {
CONNECTION_KEEP_ALIVE: 1,
CONNECTION_CLOSE: 2,
CONNECTION_UPGRADE: 4,
CHUNKED: 8,
UPGRADE: 16,
CONTENT_LENGTH: 32,
SKIPBODY: 64,
TRAILING: 128,
TRANSFER_ENCODING: 512
};
exports.LENIENT_FLAGS = {
HEADERS: 1,
CHUNKED_LENGTH: 2,
KEEP_ALIVE: 4,
TRANSFER_ENCODING: 8,
VERSION: 16,
DATA_AFTER_CLOSE: 32,
OPTIONAL_LF_AFTER_CR: 64,
OPTIONAL_CRLF_AFTER_CHUNK: 128,
OPTIONAL_CR_BEFORE_LF: 256,
SPACES_AFTER_CHUNK_SIZE: 512
};
exports.METHODS = {
"DELETE": 0,
"GET": 1,
"HEAD": 2,
"POST": 3,
"PUT": 4,
"CONNECT": 5,
"OPTIONS": 6,
"TRACE": 7,
"COPY": 8,
"LOCK": 9,
"MKCOL": 10,
"MOVE": 11,
"PROPFIND": 12,
"PROPPATCH": 13,
"SEARCH": 14,
"UNLOCK": 15,
"BIND": 16,
"REBIND": 17,
"UNBIND": 18,
"ACL": 19,
"REPORT": 20,
"MKACTIVITY": 21,
"CHECKOUT": 22,
"MERGE": 23,
"M-SEARCH": 24,
"NOTIFY": 25,
"SUBSCRIBE": 26,
"UNSUBSCRIBE": 27,
"PATCH": 28,
"PURGE": 29,
"MKCALENDAR": 30,
"LINK": 31,
"UNLINK": 32,
"SOURCE": 33,
"PRI": 34,
"DESCRIBE": 35,
"ANNOUNCE": 36,
"SETUP": 37,
"PLAY": 38,
"PAUSE": 39,
"TEARDOWN": 40,
"GET_PARAMETER": 41,
"SET_PARAMETER": 42,
"REDIRECT": 43,
"RECORD": 44,
"FLUSH": 45,
"QUERY": 46
};
exports.STATUSES = {
CONTINUE: 100,
SWITCHING_PROTOCOLS: 101,
PROCESSING: 102,
EARLY_HINTS: 103,
RESPONSE_IS_STALE: 110,
REVALIDATION_FAILED: 111,
DISCONNECTED_OPERATION: 112,
HEURISTIC_EXPIRATION: 113,
MISCELLANEOUS_WARNING: 199,
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,
IM_USED: 226,
MISCELLANEOUS_PERSISTENT_WARNING: 299,
MULTIPLE_CHOICES: 300,
MOVED_PERMANENTLY: 301,
FOUND: 302,
SEE_OTHER: 303,
NOT_MODIFIED: 304,
USE_PROXY: 305,
SWITCH_PROXY: 306,
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,
ENHANCE_YOUR_CALM: 420,
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,
REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
LOGIN_TIMEOUT: 440,
NO_RESPONSE: 444,
RETRY_WITH: 449,
BLOCKED_BY_PARENTAL_CONTROL: 450,
UNAVAILABLE_FOR_LEGAL_REASONS: 451,
CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460,
INVALID_X_FORWARDED_FOR: 463,
REQUEST_HEADER_TOO_LARGE: 494,
SSL_CERTIFICATE_ERROR: 495,
SSL_CERTIFICATE_REQUIRED: 496,
HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497,
INVALID_TOKEN: 498,
CLIENT_CLOSED_REQUEST: 499,
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,
WEB_SERVER_IS_DOWN: 521,
CONNECTION_TIMEOUT: 522,
ORIGIN_IS_UNREACHABLE: 523,
TIMEOUT_OCCURED: 524,
SSL_HANDSHAKE_FAILED: 525,
INVALID_SSL_CERTIFICATE: 526,
RAILGUN_ERROR: 527,
SITE_IS_OVERLOADED: 529,
SITE_IS_FROZEN: 530,
IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561,
NETWORK_READ_TIMEOUT: 598,
NETWORK_CONNECT_TIMEOUT: 599
};
exports.FINISH = {
SAFE: 0,
SAFE_WITH_CB: 1,
UNSAFE: 2
};
exports.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
};
exports.METHODS_HTTP = [
exports.METHODS.DELETE,
exports.METHODS.GET,
exports.METHODS.HEAD,
exports.METHODS.POST,
exports.METHODS.PUT,
exports.METHODS.CONNECT,
exports.METHODS.OPTIONS,
exports.METHODS.TRACE,
exports.METHODS.COPY,
exports.METHODS.LOCK,
exports.METHODS.MKCOL,
exports.METHODS.MOVE,
exports.METHODS.PROPFIND,
exports.METHODS.PROPPATCH,
exports.METHODS.SEARCH,
exports.METHODS.UNLOCK,
exports.METHODS.BIND,
exports.METHODS.REBIND,
exports.METHODS.UNBIND,
exports.METHODS.ACL,
exports.METHODS.REPORT,
exports.METHODS.MKACTIVITY,
exports.METHODS.CHECKOUT,
exports.METHODS.MERGE,
exports.METHODS["M-SEARCH"],
exports.METHODS.NOTIFY,
exports.METHODS.SUBSCRIBE,
exports.METHODS.UNSUBSCRIBE,
exports.METHODS.PATCH,
exports.METHODS.PURGE,
exports.METHODS.MKCALENDAR,
exports.METHODS.LINK,
exports.METHODS.UNLINK,
exports.METHODS.PRI,
exports.METHODS.SOURCE,
exports.METHODS.QUERY
];
exports.METHODS_ICE = [exports.METHODS.SOURCE];
exports.METHODS_RTSP = [
exports.METHODS.OPTIONS,
exports.METHODS.DESCRIBE,
exports.METHODS.ANNOUNCE,
exports.METHODS.SETUP,
exports.METHODS.PLAY,
exports.METHODS.PAUSE,
exports.METHODS.TEARDOWN,
exports.METHODS.GET_PARAMETER,
exports.METHODS.SET_PARAMETER,
exports.METHODS.REDIRECT,
exports.METHODS.RECORD,
exports.METHODS.FLUSH,
exports.METHODS.GET,
exports.METHODS.POST
];
exports.METHOD_MAP = (0, utils_1.enumToMap)(exports.METHODS);
exports.H_METHOD_MAP = Object.fromEntries(Object.entries(exports.METHODS).filter(([k]) => k.startsWith("H")));
exports.STATUSES_HTTP = [
exports.STATUSES.CONTINUE,
exports.STATUSES.SWITCHING_PROTOCOLS,
exports.STATUSES.PROCESSING,
exports.STATUSES.EARLY_HINTS,
exports.STATUSES.RESPONSE_IS_STALE,
exports.STATUSES.REVALIDATION_FAILED,
exports.STATUSES.DISCONNECTED_OPERATION,
exports.STATUSES.HEURISTIC_EXPIRATION,
exports.STATUSES.MISCELLANEOUS_WARNING,
exports.STATUSES.OK,
exports.STATUSES.CREATED,
exports.STATUSES.ACCEPTED,
exports.STATUSES.NON_AUTHORITATIVE_INFORMATION,
exports.STATUSES.NO_CONTENT,
exports.STATUSES.RESET_CONTENT,
exports.STATUSES.PARTIAL_CONTENT,
exports.STATUSES.MULTI_STATUS,
exports.STATUSES.ALREADY_REPORTED,
exports.STATUSES.TRANSFORMATION_APPLIED,
exports.STATUSES.IM_USED,
exports.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING,
exports.STATUSES.MULTIPLE_CHOICES,
exports.STATUSES.MOVED_PERMANENTLY,
exports.STATUSES.FOUND,
exports.STATUSES.SEE_OTHER,
exports.STATUSES.NOT_MODIFIED,
exports.STATUSES.USE_PROXY,
exports.STATUSES.SWITCH_PROXY,
exports.STATUSES.TEMPORARY_REDIRECT,
exports.STATUSES.PERMANENT_REDIRECT,
exports.STATUSES.BAD_REQUEST,
exports.STATUSES.UNAUTHORIZED,
exports.STATUSES.PAYMENT_REQUIRED,
exports.STATUSES.FORBIDDEN,
exports.STATUSES.NOT_FOUND,
exports.STATUSES.METHOD_NOT_ALLOWED,
exports.STATUSES.NOT_ACCEPTABLE,
exports.STATUSES.PROXY_AUTHENTICATION_REQUIRED,
exports.STATUSES.REQUEST_TIMEOUT,
exports.STATUSES.CONFLICT,
exports.STATUSES.GONE,
exports.STATUSES.LENGTH_REQUIRED,
exports.STATUSES.PRECONDITION_FAILED,
exports.STATUSES.PAYLOAD_TOO_LARGE,
exports.STATUSES.URI_TOO_LONG,
exports.STATUSES.UNSUPPORTED_MEDIA_TYPE,
exports.STATUSES.RANGE_NOT_SATISFIABLE,
exports.STATUSES.EXPECTATION_FAILED,
exports.STATUSES.IM_A_TEAPOT,
exports.STATUSES.PAGE_EXPIRED,
exports.STATUSES.ENHANCE_YOUR_CALM,
exports.STATUSES.MISDIRECTED_REQUEST,
exports.STATUSES.UNPROCESSABLE_ENTITY,
exports.STATUSES.LOCKED,
exports.STATUSES.FAILED_DEPENDENCY,
exports.STATUSES.TOO_EARLY,
exports.STATUSES.UPGRADE_REQUIRED,
exports.STATUSES.PRECONDITION_REQUIRED,
exports.STATUSES.TOO_MANY_REQUESTS,
exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL,
exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE,
exports.STATUSES.LOGIN_TIMEOUT,
exports.STATUSES.NO_RESPONSE,
exports.STATUSES.RETRY_WITH,
exports.STATUSES.BLOCKED_BY_PARENTAL_CONTROL,
exports.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS,
exports.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST,
exports.STATUSES.INVALID_X_FORWARDED_FOR,
exports.STATUSES.REQUEST_HEADER_TOO_LARGE,
exports.STATUSES.SSL_CERTIFICATE_ERROR,
exports.STATUSES.SSL_CERTIFICATE_REQUIRED,
exports.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT,
exports.STATUSES.INVALID_TOKEN,
exports.STATUSES.CLIENT_CLOSED_REQUEST,
exports.STATUSES.INTERNAL_SERVER_ERROR,
exports.STATUSES.NOT_IMPLEMENTED,
exports.STATUSES.BAD_GATEWAY,
exports.STATUSES.SERVICE_UNAVAILABLE,
exports.STATUSES.GATEWAY_TIMEOUT,
exports.STATUSES.HTTP_VERSION_NOT_SUPPORTED,
exports.STATUSES.VARIANT_ALSO_NEGOTIATES,
exports.STATUSES.INSUFFICIENT_STORAGE,
exports.STATUSES.LOOP_DETECTED,
exports.STATUSES.BANDWIDTH_LIMIT_EXCEEDED,
exports.STATUSES.NOT_EXTENDED,
exports.STATUSES.NETWORK_AUTHENTICATION_REQUIRED,
exports.STATUSES.WEB_SERVER_UNKNOWN_ERROR,
exports.STATUSES.WEB_SERVER_IS_DOWN,
exports.STATUSES.CONNECTION_TIMEOUT,
exports.STATUSES.ORIGIN_IS_UNREACHABLE,
exports.STATUSES.TIMEOUT_OCCURED,
exports.STATUSES.SSL_HANDSHAKE_FAILED,
exports.STATUSES.INVALID_SSL_CERTIFICATE,
exports.STATUSES.RAILGUN_ERROR,
exports.STATUSES.SITE_IS_OVERLOADED,
exports.STATUSES.SITE_IS_FROZEN,
exports.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR,
exports.STATUSES.NETWORK_READ_TIMEOUT,
exports.STATUSES.NETWORK_CONNECT_TIMEOUT
];
exports.ALPHA = [];
for (let i$1 = "A".charCodeAt(0); i$1 <= "Z".charCodeAt(0); i$1++) {
exports.ALPHA.push(String.fromCharCode(i$1));
exports.ALPHA.push(String.fromCharCode(i$1 + 32));
}
exports.NUM_MAP = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9
};
exports.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
};
exports.NUM = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
exports.MARK = [
"-",
"_",
".",
"!",
"~",
"*",
"'",
"(",
")"
];
exports.USERINFO_CHARS = exports.ALPHANUM.concat(exports.MARK).concat([
"%",
";",
":",
"&",
"=",
"+",
"$",
","
]);
exports.URL_CHAR = [
"!",
"\"",
"$",
"%",
"&",
"'",
"(",
")",
"*",
"+",
",",
"-",
".",
"/",
":",
";",
"<",
"=",
">",
"@",
"[",
"\\",
"]",
"^",
"_",
"`",
"{",
"|",
"}",
"~"
].concat(exports.ALPHANUM);
exports.HEX = exports.NUM.concat([
"a",
"b",
"c",
"d",
"e",
"f",
"A",
"B",
"C",
"D",
"E",
"F"
]);
exports.TOKEN = [
"!",
"#",
"$",
"%",
"&",
"'",
"*",
"+",
"-",
".",
"^",
"_",
"`",
"|",
"~"
].concat(exports.ALPHANUM);
exports.HEADER_CHARS = [" "];
for (let i$1 = 32; i$1 <= 255; i$1++) if (i$1 !== 127) exports.HEADER_CHARS.push(i$1);
exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
exports.QUOTED_STRING = [" ", " "];
for (let i$1 = 33; i$1 <= 255; i$1++) if (i$1 !== 34 && i$1 !== 92) exports.QUOTED_STRING.push(i$1);
exports.HTAB_SP_VCHAR_OBS_TEXT = [" ", " "];
for (let i$1 = 33; i$1 <= 126; i$1++) exports.HTAB_SP_VCHAR_OBS_TEXT.push(i$1);
for (let i$1 = 128; i$1 <= 255; i$1++) exports.HTAB_SP_VCHAR_OBS_TEXT.push(i$1);
exports.MAJOR = exports.NUM_MAP;
exports.MINOR = exports.MAJOR;
exports.SPECIAL_HEADERS = {
"connection": exports.HEADER_STATE.CONNECTION,
"content-length": exports.HEADER_STATE.CONTENT_LENGTH,
"proxy-connection": exports.HEADER_STATE.CONNECTION,
"transfer-encoding": exports.HEADER_STATE.TRANSFER_ENCODING,
"upgrade": exports.HEADER_STATE.UPGRADE
};
exports.default = {
ERROR: exports.ERROR,
TYPE: exports.TYPE,
FLAGS: exports.FLAGS,
LENIENT_FLAGS: exports.LENIENT_FLAGS,
METHODS: exports.METHODS,
STATUSES: exports.STATUSES,
FINISH: exports.FINISH,
HEADER_STATE: exports.HEADER_STATE,
ALPHA: exports.ALPHA,
NUM_MAP: exports.NUM_MAP,
HEX_MAP: exports.HEX_MAP,
NUM: exports.NUM,
ALPHANUM: exports.ALPHANUM,
MARK: exports.MARK,
USERINFO_CHARS: exports.USERINFO_CHARS,
URL_CHAR: exports.URL_CHAR,
HEX: exports.HEX,
TOKEN: exports.TOKEN,
HEADER_CHARS: exports.HEADER_CHARS,
CONNECTION_TOKEN_CHARS: exports.CONNECTION_TOKEN_CHARS,
QUOTED_STRING: exports.QUOTED_STRING,
HTAB_SP_VCHAR_OBS_TEXT: exports.HTAB_SP_VCHAR_OBS_TEXT,
MAJOR: exports.MAJOR,
MINOR: exports.MINOR,
SPECIAL_HEADERS: exports.SPECIAL_HEADERS,
METHODS_HTTP: exports.METHODS_HTTP,
METHODS_ICE: exports.METHODS_ICE,
METHODS_RTSP: exports.METHODS_RTSP,
METHOD_MAP: exports.METHOD_MAP,
H_METHOD_MAP: exports.H_METHOD_MAP,
STATUSES_HTTP: exports.STATUSES_HTTP
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/llhttp-wasm.js": ((exports, module) => {
const { Buffer: Buffer$5 } = __require$2("node:buffer");
const wasmBase64$1 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR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oAgwiAEcEQEHU1QAoAgAaIAAgBSgCCCICNgIIIAIgADYCDAwDCyAFQRRqIgMoAgAiAkUEQCAFKAIQIgJFDQIgBUEQaiEDCwNAIAMhByACIgBBFGoiAygCACICDQAgAEEQaiEDIAAoAhAiAg0ACyAHQQA2AgAMAgsgBSAAQX5xNgIEIAEgBGogBDYCACABIARBAXI2AgQMAwtBACEACyAGRQ0AAkAgBSgCHCICQQJ0QfTXAGoiAygCACAFRgRAIAMgADYCACAADQFByNUAQcjVACgCAEF+IAJ3cTYCAAwCCyAGQRBBFCAGKAIQIAVGG2ogADYCACAARQ0BCyAAIAY2AhggBSgCECICBEAgACACNgIQIAIgADYCGAsgBUEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgBGogBDYCACABIARBAXI2AgQgAUHY1QAoAgBHDQBBzNUAIAQ2AgAMAQsgBEH/AU0EQCAEQXhxQezVAGohAAJ/QcTVACgCACICQQEgBEEDdnQiA3FFBEBBxNUAIAIgA3I2AgAgAAwBCyAAKAIICyICIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggMAQtBHyECIARB////B00EQCAEQSYgBEEIdmciAGt2QQFxIABBAXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAygCHCICQQJrDvwBAfkBAgMEBQYHCAkKCwwNDg8QERL4ARP3ARQV9gEWF/UBGBkaGxwdHh8g/QH7ASH0ASIjJCUmJygpKivzASwtLi8wMTLyAfEBMzTwAe8BNTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5P+gFQUVJT7gHtAVTsAVXrAVZXWFla6gFbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAa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kACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAg7jAQABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEjJCUnKCmeA5sDmgORA4oDgwOAA/0C+wL4AvIC8QL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AgAUEBaiEBDJ8CCyADQTI2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM7QILIAEgBEcEQAJAA0AgAS0AAEEwayIAQf8BcUEKTwRAQTohAgzXAgsgAykDICILQpmz5syZs+bMGVYNASADIAtCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAMgCiALfDcDICAEIAFBAWoiAUcNAAtBwAAhAgzuAgsgAygCBCEAIANBADYCBCADIAAgAUEBaiIBEDEiAA0XDOICC0HAACECDOwCCyABIARGBEBByQAhAgzsAgsCQANAAkAgAS0AAEEJaw4YAAKiAqICqQKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogIAogILIAQgAUEBaiIBRw0AC0HJACECDOwCCyABQQFqIQEgA0Evai0AAEEBcQ2lAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgzrAgsgASAERwRAA0AgAS0AAEEgRw0VIAQgAUEBaiIBRw0AC0H4ACECDOsCC0H4ACECDOoCCyADQQI6ACgMOAtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQM6AILQQAhAgzOAgtBDSECDM0CC0ETIQIMzAILQRUhAgzLAgtBFiECDMoCC0EYIQIMyQILQRkhAgzIAgtBGiECDMcCC0EbIQIMxgILQRwhAgzFAgtBHSECDMQCC0EeIQIMwwILQR8hAgzCAgtBICECDMECC0EiIQIMwAILQSMhAgy/AgtBJSECDL4CC0HlACECDL0CCyADQT02AhwgAyABNgIUIAMgADYCDEEAIQIM1QILIANBGzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDNQCCyADQSA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzTAgsgA0ETNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0gILIANBCzYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNECCyADQRA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzQAgsgA0EgNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzwILIANBCzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM4CCyADQQw2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzNAgtBACECIANBADYCHCADIAE2AhQgA0HdDjYCECADQRI2AgwMzAILAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB/QEhAgzMAgsCQAJAIAMtADZBAUcNAEEAIQACQCADKAI4IgJFDQAgAigCYCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUcNASADQfwBNgIcIAMgATYCFCADQdwZNgIQIANBFTYCDEEAIQIMzQILQdwBIQIMswILIANBADYCHCADIAE2AhQgA0H5CzYCECADQR82AgxBACECDMsCCwJAAkAgAy0AKEEBaw4CBAEAC0HbASECDLICC0HUASECDLECCyADQQI6ADFBACEAAkAgAygCOCICRQ0AIAIoAgAiAkUNACADIAIRAAAhAAsgAEUEQEHdASECDLECCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQbQMNgIQIANBEDYCDEEAIQIMygILIANB+wE2AhwgAyABNgIUIANBgRo2AhAgA0EVNgIMQQAhAgzJAgsgASAERgRAQfoBIQIMyQILIAEtAABByABGDQEgA0EBOgAoC0HAASECDK4CC0HaASECDK0CCyABIARHBEAgA0EMNgIIIAMgATYCBEHZASECDK0CC0H5ASECDMUCCyABIARGBEBB+AEhAgzFAgsgAS0AAEHIAEcNBCABQQFqIQFB2AEhAgyrAgsgASAERgRAQfcBIQIMxAILAkACQCABLQAAQcUAaw4QAAUFBQUFBQUFBQUFBQUFAQULIAFBAWohAUHWASECDKsCCyABQQFqIQFB1wEhAgyqAgtB9gEhAiABIARGDcICIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbrVAGotAABHDQMgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMMCCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIARQRAQeMBIQIMqgILIANB9QE2AhwgAyABNgIUIAMgADYCDEEAIQIMwgILQfQBIQIgASAERg3BAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEG41QBqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzCAgsgA0GBBDsBKCADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIADQMMAgsgA0EANgIAC0EAIQIgA0EANgIcIAMgATYCFCADQeUfNgIQIANBCDYCDAy/AgtB1QEhAgylAgsgA0HzATYCHCADIAE2AhQgAyAANgIMQQAhAgy9AgtBACEAAkAgAygCOCICRQ0AIAIoAkAiAkUNACADIAIRAAAhAAsgAEUNbiAAQRVHBEAgA0EANgIcIAMgATYCFCADQYIPNgIQIANBIDYCDEEAIQIMvQILIANBjwE2AhwgAyABNgIUIANB7Bs2AhAgA0EVNgIMQQAhAgy8AgsgASAERwRAIANBDTYCCCADIAE2AgRB0wEhAgyjAgtB8gEhAgy7AgsgASAERgRAQfEBIQIMuwILAkACQAJAIAEtAABByABrDgsAAQgICAgICAgIAggLIAFBAWohAUHQASECDKMCCyABQQFqIQFB0QEhAgyiAgsgAUEBaiEBQdIBIQIMoQILQfABIQIgASAERg25AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBtdUAai0AAEcNBCAAQQJGDQMgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuQILQe8BIQIgASAERg24AiADKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABBs9UAai0AAEcNAyAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuAILQe4BIQIgASAERg23AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMtwILIAMoAgQhACADQgA3AwAgAyAAIAVBAWoiARArIgBFDQIgA0HsATYCHCADIAE2AhQgAyAANgIMQQAhAgy2AgsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNnAIgA0HtATYCHCADIAE2AhQgAyAANgIMQQAhAgy0AgtBzwEhAgyaAgtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDLQCC0HOASECDJoCCyADQesBNgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMsgILIAEgBEYEQEHrASECDLICCyABLQAAQS9GBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GyODYCECADQQg2AgxBACECDLECC0HNASECDJcCCyABIARHBEAgA0EONgIIIAMgATYCBEHMASECDJcCC0HqASECDK8CCyABIARGBEBB6QEhAgyvAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBywEhAgyWAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZcCIANB6AE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAEgBEYEQEHnASECDK4CCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5gE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILQcoBIQIMlAILIAEgBEYEQEHlASECDK0CC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDQIgA0HiATYCHCADIAE2AhQgAyAANgIMQQAhAgyvAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZoCIANB4wE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ2YAiADQeQBNgIcIAMgATYCFCADIAA2AgwMrQILQckBIQIMkwILQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgytAgtByAEhAgyTAgsgA0HhATYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDKsCCyABIARGBEBB4QEhAgyrAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBmRE2AhAgA0EJNgIMQQAhAgyrAgtBxwEhAgyRAgsgASAERgRAQeABIQIMqgILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyrAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqgILQcYBIQIMkAILIAEgBEYEQEHfASECDKkCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqgILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKkCC0HFASECDI8CCyABIARGBEBB3gEhAgyoAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKkCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyoAgtBxAEhAgyOAgsgASAERgRAQd0BIQIMpwILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUHDASECDI8CCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKcCCyADQQA2AhwgAyABNgIUIANBjQs2AhAgA0ENNgIMQQAhAgymAgsgASAERwRAIANBDzYCCCADIAE2AgRBASECDI0CC0HcASECDKUCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB2wEhAgymAgsgAygCBCEAIANBADYCBCADIAAgARAtIgBFBEAgAUEBaiEBDAQLIANB2gE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMpQILIAMoAgQhACADQQA2AgQgAyAAIAEQLSIADQEgAUEBagshAUHBASECDIoCCyADQdkBNgIcIAMgADYCDCADIAFBAWo2AhRBACECDKICC0HCASECDIgCCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQeQcNgIQIANBGTYCDEEAIQIMoAILIAEgBEYEQEHZASECDKACCwJAAkACQCABLQAAQQprDgQBAgIAAgsgAUEBaiEBDAILIAFBAWohAQwBCyADLQAuQcAAcUUNAQtBACEAAkAgAygCOCICRQ0AIAIoAjwiAkUNACADIAIRAAAhAAsgAEUNoAEgAEEVRgRAIANB2QA2AhwgAyABNgIUIANBtxo2AhAgA0EVNgIMQQAhAgyfAgsgA0EANgIcIAMgATYCFCADQYANNgIQIANBGzYCDEEAIQIMngILIANBADYCHCADIAE2AhQgA0HcKDYCECADQQI2AgxBACECDJ0CCyABIARHBEAgA0EMNgIIIAMgATYCBEG/ASECDIQCC0HYASECDJwCCyABIARGBEBB1wEhAgycAgsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBwQBrDhUAAQIDWgQFBlpaWgcICQoLDA0ODxBaCyABQ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ohACAEIAFBAWoiAUcNAAsgAyAFNgIADPwBCyADQQA2AgAgBkEBaiEBQQ0MKAtBtgEhAiABIARGDfoBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPsBCyADQQA2AgAgBkEBaiEBQQwMJwtBtQEhAiABIARGDfkBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQerUAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPoBCyADQQA2AgAgBkEBaiEBQQMMJgtBtAEhAiABIARGDfgBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQejUAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPkBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQbMBIQIM+AELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBmQEhAgzfAQsgAUEBaiEBQZoBIQIM3gELQbIBIQIgASAERg32ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm1ABqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz3AQsgA0EANgIAIAZBAWohAUEnDCMLQbEBIQIgASAERg31ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk1ABqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz2AQsgA0EANgIAIAZBAWohAUEcDCILQbABIQIgASAERg30ASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHe1ABqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz1AQsgA0EANgIAIAZBAWohAUEGDCELQa8BIQIgASAERg3zASADKAIAIgAgBCABa2ohBSABIABrQQ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BRw0ACyADIAU2AgAM7AELIANBADYCACAGQQFqIQFBFwwYC0GmASECIAEgBEYN6gEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBwdQAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6wELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBpQEhAgzqAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYsBIQIM0QELIAFBAWohAUGMASECDNABC0GkASECIAEgBEYN6AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBptUAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6QELIANBADYCACAGQQFqIQFBCQwVC0GjASECIAEgBEYN5wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBpNUAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6AELIANBADYCACAGQQFqIQFBHwwUC0GiASECIAEgBEYN5gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtQAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5wELIANBADYCACAGQQFqIQFBAgwTC0GhASECIAEgBEYN5QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQbzUAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOUBCyABIARGBEBBoAEhAgzlAQtBASABLQAAQd8ARw0RGiABQQFqIQFBhwEhAgzLAQsgA0EANgIAIAZBAWohAUGIASECDMoBC0GfASECIAEgBEYN4gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBhNUAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4wELIANBADYCACAGQQ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QFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzZAQsgA0EANgIAIAZBAWohAUEWDAULQZQBIQIgASAERg3XASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzYAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGTASECDNcBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUH5ACECDL4BCyABQQFqIQFB+gAhAgy9AQtBkgEhAiABIARGDdUBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQaDUAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNYBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGRASECDNQBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC4iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB/h82AhAgA0EGNgIMDNEBC0H4ACECDLcBCyADQZABNgIcIAMgATYCFCADIAA2AgxBACECDM8BC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgzOAQtB9wAhAgy0AQsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDMwBCyABIARGBEBBjwEhAgzMAQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GbHzYCECADQQY2AgxBACECDMwBC0ECIQIMsgELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GOASECDMoBCyABIARGBEBBjQEhAgzKAQsCQCABLQAAQQlrDgRKAABKAAtB9QAhAgywAQsgAy0AKUEFRgRAQfYAIQIMsAELQfQAIQIMrwELIAEgBEYEQEGMASECD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EBaiIBRw0AC0H9ACECDKsBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQdsANgIcIAMgATYCFCADIAA2AgxBACECDKoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDKkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNByADQfoANgIcIAMgATYCFCADIAA2AgxBACECDKgBCyADQQA2AhwgAyABNgIUIANB5Ag2AhAgA0EHNgIMQQAhAgynAQsgASAERg0BIAFBAWoLIQFBBiECDIwBC0H8ACECDKQBCwJAAkACQAJAA0AgAS0AAEGgyABqLQAAIgBBBUcEQCAAQQFrDgQpAgMEBQsgBCABQQFqIgFHDQALQfsAIQIMpwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMpgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMpQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMpAELIANBADYCHCADIAE2AhQgA0G8CjYCECADQQc2AgxBACECDKMBC0HPACECDIkBC0HRACECDIgBC0HnACECDIcBCyABIARGBEBB+gAhAgygAQsCQCABLQAAQQlrDgQgAAAgAAsgAUEBaiEBQeYAIQIMhgELIAEgBEYEQEH5ACECDJ8BCwJAIAEtAABBCWsOBB8AAB8AC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQRAQeIBIQIMhgELIABBFUcEQCADQQA2AhwgAyABNgIUIANByQ02AhAgA0EaNgIMQQAhAgyfAQsgA0H4ADYCHCADIAE2AhQgA0HqGjYCECADQRU2AgxBACECDJ4BCyABIARHBEAgA0ENNgIIIAMgATYCBEHkACECDIUBC0H3ACECDJ0BCyABIARGBEBB9gAhAgydAQsCQAJAAkAgAS0AAEHIAGsOCwABCwsLCwsLCwsCCwsgAUEBaiEBQd0AIQIMhQELIAFBAWohAUHgACECDIQBCyABQQFqIQFB4wAhAgyDAQtB9QAhAiABIARGDZsBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbXVAGotAABHDQggAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJwBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIABEAgA0H0ADYCHCADIAE2AhQgAyAANgIMQQAhAgycAQtB4gAhAgyCAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJwBC0HhACECDIIBCyADQfMANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMmgELIAMtACkiAEEja0ELSQ0JAkAgAEEGSw0AQQEgAHRBygBxRQ0ADAoLQQAhAiADQQA2AhwgAyABNgIUIANB7Qk2AhAgA0EINgIMDJkBC0HyACECIAEgBEYNmAEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBs9UAai0AAEcNBSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMmQELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfEANgIcIAMgATYCFCADIAA2AgxBACECDJkBC0HfACECDH8LQQAhAAJAIAMoAjgiAkUNACACKAI0IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANB6g02AhAgA0EmNgIMQQAhAgyZAQtB3gAhAgx/CyADQfAANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMlwELIAMtAClBIUYNBiADQQA2AhwgAyABNgIUIANBkQo2AhAgA0EINgIMQQAhAgyWAQtB7wAhAiABIARGDZUBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDVAGotAABHDQIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIARQ0CIANB7QA2AhwgAyABNgIUIAMgADYCDEEAIQIMlQELIANBADYCAAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDYABIANB7gA2AhwgAyABNgIUIAMgADYCDEEAIQIMkwELQdwAIQIMeQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJMBC0HbACECDHkLIANB7AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyRAQsgAy0AKSIAQSNJDQAgAEEuRg0AIANBADYCHCADIAE2AhQgA0HJCTYCECADQQg2AgxBACECDJABC0HaACECDHYLIAEgBEYEQEHrACECDI8BCwJAIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMjwELQdkAIQIMdQsgASAERwRAIANBDjYCCCADIAE2AgRB2AAhAgx1C0HqACECDI0BCyABIARGBEBB6QAhAgyNAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1wAhAgx0CyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeiADQegANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyABIARGBEBB5wAhAgyMAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELQdYAIQIMcgsgASAERgRAQeUAIQIMiwELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDI0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNfSADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeyADQeQANgIcIAMgATYCFCADIAA2AgwMiwELQdQAIQIMcQsgAy0AKUEiRg2GAUHTACECDHALQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFBEBB1QAhAgxwCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQaQNNgIQIANBITYCDEEAIQIMiQELIANB4QA2AhwgAyABNgIUIANB0Bo2AhAgA0EVNgIMQQAhAgyIAQsgASAERgRAQeAAIQIMiAELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HSACECDHALIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIgBCyADQQA2AhwgAyABNgIUIANBthE2AhAgA0EJNgIMQQAhAgyHAQsgASAERgRAQd8AIQIMhwELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBthE2AhAgA0ECNgIMQQAhAgyGAQsgASAERgRAQd0AIQIMhgELIAEtAAAiAkENRgRAIAFBAWohAUHQACECDG0LIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyFAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0HKLTYCECADQQc2AgwMgwELIAEgBEYEQEHbACECDIMBCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc4AIQIMaAsgASAERgRAQdoAIQIMgQELIAEtAABBCWsOBAABAQABC0EAIQ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MDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==";
let wasmBuffer$1;
Object.defineProperty(module, "exports", { get: () => {
return wasmBuffer$1 ? wasmBuffer$1 : wasmBuffer$1 = Buffer$5.from(wasmBase64$1, "base64");
} });
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js": ((exports, module) => {
const { Buffer: Buffer$4 } = __require$2("node:buffer");
const wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQA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kECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQ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oC0G4AQwnC0G5AQwmC0G6AQwlC0G7AQwkC0G8AQwjC0G9AQwiC0G+AQwhC0G/AQwgC0HAAQwfC0HBAQweC0HCAQwdC0EBDBwLQcMBDBsLQcQBDBoLQcUBDBkLQcYBDBgLQccBDBcLQcgBDBYLQckBDBULQcoBDBQLQcsBDBMLQcwBDBILQc0BDBELQc4BDBALQc8BDA8LQdABDA4LQdEBDA0LQdIBDAwLQdMBDAsLQdQBDAoLQdUBDAkLQdYBDAgLQeMBDAcLQdcBDAYLQdgBDAULQdkBDAQLQdoBDAMLQdsBDAILQd0BDAELQdwBCyECA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAn8CQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAwJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAk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CBCADIAAgARAzIgBFBEAgAUEBaiEBDOsCCyADQR02AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8gILIABBO0cNASABQQFqIQELQSYhAgzXAgtBACECIANBADYCHCADIAE2AhQgA0GfFTYCECADQQw2AgwM7wILIAEgBEcEQANAIAEtAABBIEcNhAIgBCABQQFqIgFHDQALQSwhAgzvAgtBLCECDO4CCyABIARGBEBBNCECDO4CCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtBNCECDO8CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNnwIgA0EyNgIcIAMgATYCFCADIAA2AgxBACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUEQCABQQFqIQEMnwILIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgztAgsgASAERwRAAkADQCABLQAAQTBrIgBB/wFxQQpPBEBBOiECDNcCCyADKQMgIgtCmbPmzJmz5swZVg0BIAMgC0IKfiIKNwMgIAogAK1C/wGDIgtCf4VWDQEgAyAKIAt8NwMgIAQgAUEBaiIBRw0AC0HAACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABQQFqIgEQMSIADRcM4gILQcAAIQIM7AILIAEgBEYEQEHJACECDOwCCwJAA0ACQCABLQAAQQlrDhgAAqICogKpAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAgCiAgsgBCABQQFqIgFHDQALQckAIQIM7AILIAFBAWohASADQS9qLQAAQQFxDaUCIANBADYCHCADIAE2AhQgA0GXEDYCECADQQo2AgxBACECDOsCCyABIARHBEADQCABLQAAQSBHDRUgBCABQQFqIgFHDQALQfgAIQIM6wILQfgAIQIM6gILIANBAjoAKAw4C0EAIQIgA0EANgIcIANBvws2AhAgA0ECNgIMIAMgAUEBajYCFAzoAgtBACECDM4CC0ENIQIMzQILQRMhAgzMAgtBFSECDMsCC0EWIQIMygILQRghAgzJAgtBGSECDMgCC0EaIQIMxwILQRshAgzGAgtBHCECDMUCC0Ed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QILIAEgBEcEQCADQQw2AgggAyABNgIEQdkBIQIMrQILQfkBIQIMxQILIAEgBEYEQEH4ASECDMUCCyABLQAAQcgARw0EIAFBAWohAUHYASECDKsCCyABIARGBEBB9wEhAgzEAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQdYBIQIMqwILIAFBAWohAUHXASECDKoCC0H2ASECIAEgBEYNwgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABButUAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMwwILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgBFBEBB4wEhAgyqAgsgA0H1ATYCHCADIAE2AhQgAyAANgIMQQAhAgzCAgtB9AEhAiABIARGDcECIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjVAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMICCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB5R82AhAgA0EINgIMDL8CC0HVASECDKUCCyADQfMBNgIcIAMgATYCFCADIAA2AgxBACECDL0CC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ1uIABBFUcEQCADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgy9AgsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDLwCCyABIARHBEAgA0ENNgIIIAMgATYCBEHTASECDKMCC0HyASECDLsCCyABIARGBEBB8QEhAgy7AgsCQAJAAkAgAS0AAEHIAGsOCwABCAgICAgICAgCCAsgAUEBaiEBQdABIQIMowILIAFBAWohAUHRASECDKICCyABQQFqIQFB0gEhAgyhAgtB8AEhAiABIARGDbkCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEG11QBqLQAARw0EIABBAkYNAyAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy5AgtB7wEhAiABIARGDbgCIAMoAgAiACAEIAFraiEGIAEgAGtBAWohBQNAIAEtAAAgAEGz1QBqLQAARw0DIABBAUYNAiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy4AgtB7gEhAiABIARGDbcCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEGw1QBqLQAARw0CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy3AgsgAygCBCEAIANCADcDACADIAAgBUEBaiIBECsiAEUNAiADQewBNgIcIAMgATYCFCADIAA2AgxBACECDLYCCyADQQA2AgALIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ2cAiADQe0BNgIcIAMgATYCFCADIAA2AgxBACECDLQCC0HPASECDJoCC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMtAILQc4BIQIMmgILIANB6wE2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyyAgsgASAERgRAQesBIQIMsgILIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMsQILQc0BIQIMlwILIAEgBEcEQCADQQ42AgggAyABNgIEQcwBIQIMlwILQeoBIQIMrwILIAEgBEYEQEHpASECDK8CCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHLASECDJYCCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNlwIgA0HoATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgASAERgRAQecBIQIMrgILAkAgAS0AAEEuRgRAIAFBAWohAQwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmAIgA0HmATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgtBygEhAgyUAgsgASAERgRAQeUBIQIMrQILQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDK8CCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmgIgA0HjATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5AE2AhwgAyABNgIUIAMgADYCDAytAgtByQEhAgyTAgtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GkDTYCECADQSE2AgxBACECDK0CC0HIASECDJMCCyADQeEBNgIcIAMgATYCFCADQdAaNgIQIANBFTYCDEEAIQIMqwILIAEgBEYEQEHhASECDKsCCwJAIAEtAABBIEYEQCADQQA7ATQgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GZETYCECADQQk2AgxBACECDKsCC0HHASECDJECCyABIARGBEBB4AEhAgyqAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKsCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyqAgtBxgEhAgyQAgsgASAERgRAQd8BIQIMqQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyqAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqQILQcUBIQIMjwILIAEgBEYEQEHeASECDKgCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqQILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKgCC0HEASECDI4CCyABIARGBEBB3QEhAgynAgsCQAJAAkACQCABLQAAQQprDhcCAwMAAwMDAwMDAwMDAwMDAwMDAwMDAQMLIAFBAWoMBQsgAUEBaiEBQcMBIQIMjwILIAFBAWohASADQS9qLQAAQQFxDQggA0EANgIcIAMgATYCFCADQY0LNgIQIANBDTYCDEEAIQIMpwILIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKYCCyABIARHBEAgA0EPNgIIIAMgATYCBEEBIQIMjQILQdwBIQIMpQILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0HbASECDKYCCyADKAIEIQAgA0EANgIEIAMgACABEC0iAEUEQCABQQFqIQEMBAsgA0HaATYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgylAgsgAygCBCEAIANBADYCBCADIAAgARAtIgANASABQQFqCyEBQcEBIQIMigILIANB2QE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMogILQcIBIQIMiAILIANBL2otAABBAXENASADQQA2AhwgAyABNgIUIANB5Bw2AhAgA0EZNgIMQQAhAgygAgsgASAERgRAQdkBIQIMoAILAkACQAJAIAEtAABBCmsOBAECAgACCyABQQFqIQ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ECDPcBC0HLASECIAEgBEYNjwIgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBkdUAai0AAEcNPCAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMkAILIANBADYCACAGQQFqIQFBGgw8C0HKASECIAEgBEYNjgIgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBjdUAai0AAEcNOyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMjwILIANBADYCACAGQQFqIQFBIQw7CyABIARGBEBByQEhAgyOAgsCQAJAIAEtAABBwQBrDhQAPT09PT09PT09PT09PT09PT09AT0LIAFBAWohAUGtASECDPUBCyABQQFqIQFBsAEhAgz0AQsgASAERgRAQcgBIQIMjQILAkACQCABLQAAQdUAaw4LADw8PDw8PDw8PAE8CyABQQFqIQFBrgEhAgz0AQsgAUEBaiEBQa8BIQIM8wELQccBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw04IABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEqDDgLIAEgBEYEQEHGASECDIsCCyABLQAAQdAARw04IAFBAWohAUElDDcLQcUBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGB1QBqLQAARw02IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEODDYLIAEgBEYEQEHEASECDIkCCyABLQAAQcUARw02IAFBAWohAUGrASECDO8BCyABIARGBEBBwwEhAgyIAgsCQAJAAkACQCABLQAAQcIAaw4PAAECOTk5OTk5OTk5OTkDOQsgAUEBaiEBQacBIQIM8QELIAFBAWohAUGoASECDPABCyABQQFqIQFBqQEhAgzvAQsgAUEBaiEBQaoBIQIM7gELQcIBIQIgASAERg2GAiADKAIAIgAg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QakBIQIgASAERg3tASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHR1ABqLQAARw0aIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzuAQsgA0EANgIAIAZBAWohAUEeDBoLQagBIQIgASAERg3sASADKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEHK1ABqLQAARw0ZIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAztAQsgA0EANgIAIAZBAWohAUEVDBkLQacBIQIgASAERg3rASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHH1ABqLQAARw0YIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzsAQsgA0EANgIAIAZBAWohAUEXDBgLQaYBIQIgASAERg3qASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHB1ABqLQAARw0XIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzrAQsgA0EANgIAIAZBAWohAUEYDBcLIAEgBEYEQEGlASECDOoBCwJAAkAgAS0AAEHJAGsOBwAZGRkZGQEZCyABQQFqIQFBiwEhAgzRAQsgAUEBaiEBQYwBIQIM0AELQaQBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw0VIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEJDBULQaMBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw0UIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEfDBQLQaIBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEG+1ABqLQAARw0TIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUECDBMLQaEBIQIgASAERg3lASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYDQCABLQAAIABBvNQAai0AAEcNESAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5QELIAEgBEYEQEGgASECDOUBC0EBIAEtAABB3wBHDREaIAFBAWohAUGHASECDMsBCyADQQA2AgAgBkEBaiEBQYgBIQIMygELQZ8BIQIgASAERg3iASADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw0PIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzjAQsgA0EANgIAIAZBAWohAUEpDA8LQZ4BIQIgASAERg3hASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEG41ABqLQAARw0OIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAziAQsgA0EANgIAIAZBAWohAUEtDA4LIAEgBEYEQEGdASECDOEBCyABLQAAQcUARw0OIAFBAWohAUGEASECDMcBCyABIARGBEBBnAEhAgzgAQsCQAJAIAEtAABBzABrDggADw8PDw8PAQ8LIAFBAWohAUGCASECDMcBCyABQQFqIQFBgwEhAgzGAQtBmwEhAiABIARGDd4BIAMoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQbPUAGotAABHDQsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN8BCyADQQA2AgAgBkEBaiEBQSMMCwtBmgEhAiABIARGDd0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDUAGotAABHDQogAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN4BCyADQQA2AgAgBkEBaiEBQQAMCgsgASAERgRAQZkBIQIM3QELAkACQCABLQAAQcgAaw4IAAwMDAwMDAEMCyABQQFqIQFB/QAhAgzEAQsgAUE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DQAgAyACEQAAIQALIABFDQAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GCDzYCECADQSA2AgxBACECDM4BC0H3ACECDLQBCyADQY8BNgIcIAMgATYCFCADQewbNgIQIANBFTYCDEEAIQIMzAELIAEgBEYEQEGPASECDMwBCwJAIAEtAABBIEYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZsfNgIQIANBBjYCDEEAIQIMzAELQQIhAgyyAQsDQCABLQAAQSBHDQIgBCABQQFqIgFHDQALQY4BIQIMygELIAEgBEYEQEGNASECDMoBCwJAIAEtAABBCWsOBEoAAEoAC0H1ACECDLABCyADLQApQQVGBEBB9gAhAgywAQtB9AAhAgyvAQsgASAERgRAQYwBIQIMyAELIANBEDYCCCADIAE2AgQMCgsgASAERgRAQYsBIQIMxwELAkAgAS0AAEEJaw4ERwAARwALQfMAIQIMrQELIAEgBEcEQCADQRA2AgggAyABNgIEQfEAIQIMrQELQYoBIQIMxQELAkAgASAERwRAA0AgAS0AAEGg0ABqLQAAIgBBA0cEQAJAIABBAWsOAkkABAtB8AAhAgyvAQsgBCABQQFqIgFHDQALQYgBIQIMxgELQYgBIQIMxQELIANBADYCHCADIAE2AhQgA0HbIDYCECADQQc2AgxBACECDMQBCyABIARGBEBBiQEhAgzEAQsCQAJAAkAgAS0AAEGg0gBqLQAAQQFrDgNGAgABC0HyACECDKwBCyADQQA2AhwgAyABNgIUIANBtBI2AhAgA0EHNgIMQQAhAgzEAQtB6gAhAgyqAQsgASAERwRAIAFBAWohAUHvACECDKoBC0GHASECDMIBCyAEIAEiAEYEQEGGASECDMIBCyAALQAAIgFBL0YEQCAAQQFqIQFB7gAhAgypAQsgAUEJayICQRdLDQEgACEBQQEgAnRBm4CABHENQQwBCyAEIAEiAEYEQEGFASECDMEBCyAALQAAQS9HDQAgAEEBaiEBDAMLQQAhAiADQQA2AhwgAyAANgIUIANB2yA2AhAgA0EHNgIMDL8BCwJAAkACQAJAAkADQCABLQAAQaDOAGotAAAiAEEFRwRAAkACQCAAQQFrDghHBQYHCAAEAQgLQesAIQIMrQELIAFBAWohAUHtACECDKwBCyAEIAFBAWoiAUcNAAtBhAEhAgzDAQsgAUEBagwUCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDMEBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDMABCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDL8BCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy+AQsgASAERgRAQYMBIQIMvgELAkAgAS0AAEGgzgBqLQAAQQFrDgg+BAUGAAgCAwcLIAFBAWohAQtBAyECDKMBCyABQQFqDA0LQQAhAiADQQA2AhwgA0HREjYCECADQQc2AgwgAyABQQFqNgIUDLoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDLkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDLgBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDLcBCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy2AQtB7AAhAgycAQsgASAERgRAQYIBIQIMtQELIAFBAWoMAgsgASAERgRAQYEBIQIMtAELIAFBAWoMAQsgASAERg0BIAFBAWoLIQFBBCECDJgBC0GAASECDLABCwNAIAEtAABBoMwAai0AACIAQQJHBEAgAEEBRwRAQekAIQIMmQELDDELIAQgAUEBaiIBRw0AC0H/ACECDK8BCyABIARGBEBB/gAhAgyvAQsCQCABLQAAQQlrDjcvAwYvBAYGBgYGBgYGBgYGBgYGBgYGBgUGBgIGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYABgsgAUEBagshAUEFIQIMlAELIAFBAWoMBgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgypAQsgA0EANgIcIAMgATYCFCADQY0UNgIQIANBBzYCDEEAIQIMqAELAkACQAJAAkADQCABLQAAQaDKAGotAAAiAEEFRwRAAkAgAEEBaw4GLgMEBQYABgtB6AAhAgyUAQsgBCABQQFqIgFHDQALQf0AIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqAELIANBADYCHCADIAE2AhQgA0HkCDYCECADQQc2AgxBACECDKcBCyABIARGDQEgAUEBagshAUEGIQIMjAELQfwAIQIMpAELAkACQAJAAkADQCABLQAAQaDIAGotAAAiAEEFRwRAIABBAWsOBCkCAwQFCyAEIAFBAWoiAUcNAAtB+wAhAgynAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgymAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgylAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgykAQsgA0EANgIcIAMgATYCFCADQbwKNgIQIANBBzYCDEEAIQIMowELQc8AIQIMiQELQdEAIQIMiAELQecAIQIMhwELIAEgBEYEQEH6ACECDKABCwJAIAEtAABBCWsOBCAAACAACyABQQFqIQFB5gAhAgyGAQsgASAERgRAQfkAIQIMnwELAkAgAS0AAEEJaw4EHwAAHwALQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFBEBB4gEhAgyGAQsgAEEVRwRAIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDJ8BCyADQfgANgIcIAMgATYCFCADQeoaNgIQIANBFTYCDEEAIQIMngELIAEgBEcEQCADQQ02AgggAyABNgIEQeQAIQIMhQELQfcAIQIMnQELIAEgBEYEQEH2ACECDJ0BCwJAAkACQCABLQAAQcgAaw4LAAELCwsLCwsLCwILCyABQQFqIQFB3QAhAgyFAQsgAUEBaiEBQeAAIQIMhAELIAFBAWohAUHjACECDIMBC0H1ACECIAEgBEYNmwEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBtdUAai0AAEcNCCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMnAELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfQANgIcIAMgATYCFCADIAA2AgxBACECDJwBC0HiACECDIIBC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMnAELQeEAIQIMggELIANB8wA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyaAQsgAy0AKSIAQSNrQQtJDQkCQCAAQQZLDQBBASAAdEHKAHFFDQAMCgtBACECIANBADYCHCADIAE2AhQgA0HtCTYCECADQQg2AgwMmQELQfIAIQIgASAERg2YASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGz1QBqLQAARw0FIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAQsgAygCBCEAIANCADcDACADIAAgBkEBaiIBECsiAARAIANB8QA2AhwgAyABNgIUIAMgADYCDEEAIQIMmQELQd8AIQIMfwtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJkBC0HeACECDH8LIANB8AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyXAQsgAy0AKUEhRg0GIANBADYCHCADIAE2AhQgA0GRCjYCECADQQg2AgxBACECDJYBC0HvACECIAEgBEYNlQEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMlgELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgBFDQIgA0HtADYCHCADIAE2AhQgAyAANgIMQQAhAgyVAQsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNgAEgA0HuADYCHCADIAE2AhQgAyAANgIMQQAhAgyTAQtB3AAhAgx5C0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMkwELQdsAIQIMeQsgA0HsADYCHCADIAE2AhQgA0GAGzYCECADQRU2AgxBACECDJEBCyADLQApIgBBI0kNACAAQS5GDQAgA0EANgIcIAMgATYCFCADQckJNgIQIANBCDYCDEEAIQIMkAELQdoAIQIMdgsgASAERgRAQesAIQIMjwELAkAgAS0AAEEvRgRAIAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBsjg2AhAgA0EINgIMQQAhAgyPAQtB2QAhAgx1CyABIARHBEAgA0EONgIIIAMgATYCBEHYACECDHULQeoAIQIMjQELIAEgBEYEQEHpACECDI0BCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHXACECDHQLIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ16IANB6AA2Ah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Q0VUU1BBRFRQLw==";
let wasmBuffer;
Object.defineProperty(module, "exports", { get: () => {
return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer$4.from(wasmBase64, "base64");
} });
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/constants.js
var require_constants$3 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/constants.js": ((exports, module) => {
const corsSafeListedMethods = [
"GET",
"HEAD",
"POST"
];
const corsSafeListedMethodsSet$1 = new Set(corsSafeListedMethods);
const nullBodyStatus$2 = [
101,
204,
205,
304
];
const redirectStatus = [
301,
302,
303,
307,
308
];
const redirectStatusSet$3 = new Set(redirectStatus);
/**
* @see https://fetch.spec.whatwg.org/#block-bad-port
*/
const badPorts = [
"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"
];
const badPortsSet$1 = new Set(badPorts);
/**
* @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-header
*/
const referrerPolicyTokens$1 = [
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
];
/**
* @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
*/
const referrerPolicy$1 = ["", ...referrerPolicyTokens$1];
const referrerPolicyTokensSet = new Set(referrerPolicyTokens$1);
const requestRedirect$1 = [
"follow",
"manual",
"error"
];
const safeMethods = [
"GET",
"HEAD",
"OPTIONS",
"TRACE"
];
const safeMethodsSet$1 = new Set(safeMethods);
const requestMode$1 = [
"navigate",
"same-origin",
"no-cors",
"cors"
];
const requestCredentials$1 = [
"omit",
"same-origin",
"include"
];
const requestCache$1 = [
"default",
"no-store",
"reload",
"no-cache",
"force-cache",
"only-if-cached"
];
/**
* @see https://fetch.spec.whatwg.org/#request-body-header-name
*/
const requestBodyHeader$1 = [
"content-encoding",
"content-language",
"content-location",
"content-type",
"content-length"
];
/**
* @see https://fetch.spec.whatwg.org/#enumdef-requestduplex
*/
const requestDuplex$1 = ["half"];
/**
* @see http://fetch.spec.whatwg.org/#forbidden-method
*/
const forbiddenMethods = [
"CONNECT",
"TRACE",
"TRACK"
];
const forbiddenMethodsSet$1 = new Set(forbiddenMethods);
const subresource = [
"audio",
"audioworklet",
"font",
"image",
"manifest",
"paintworklet",
"script",
"style",
"track",
"video",
"xslt",
""
];
const subresourceSet$1 = new Set(subresource);
module.exports = {
subresource,
forbiddenMethods,
requestBodyHeader: requestBodyHeader$1,
referrerPolicy: referrerPolicy$1,
requestRedirect: requestRedirect$1,
requestMode: requestMode$1,
requestCredentials: requestCredentials$1,
requestCache: requestCache$1,
redirectStatus,
corsSafeListedMethods,
nullBodyStatus: nullBodyStatus$2,
safeMethods,
badPorts,
requestDuplex: requestDuplex$1,
subresourceSet: subresourceSet$1,
badPortsSet: badPortsSet$1,
redirectStatusSet: redirectStatusSet$3,
corsSafeListedMethodsSet: corsSafeListedMethodsSet$1,
safeMethodsSet: safeMethodsSet$1,
forbiddenMethodsSet: forbiddenMethodsSet$1,
referrerPolicyTokens: referrerPolicyTokensSet
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/global.js
var require_global$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/global.js": ((exports, module) => {
const globalOrigin = Symbol.for("undici.globalOrigin.1");
function getGlobalOrigin$2() {
return globalThis[globalOrigin];
}
function setGlobalOrigin$1(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
});
}
module.exports = {
getGlobalOrigin: getGlobalOrigin$2,
setGlobalOrigin: setGlobalOrigin$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/encoding/index.js
var require_encoding = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/encoding/index.js": ((exports, module) => {
const textDecoder = new TextDecoder();
/**
* @see https://encoding.spec.whatwg.org/#utf-8-decode
* @param {Uint8Array} buffer
*/
function utf8DecodeBytes$3(buffer$1) {
if (buffer$1.length === 0) return "";
if (buffer$1[0] === 239 && buffer$1[1] === 187 && buffer$1[2] === 191) buffer$1 = buffer$1.subarray(3);
return textDecoder.decode(buffer$1);
}
module.exports = { utf8DecodeBytes: utf8DecodeBytes$3 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/infra/index.js
var require_infra = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/infra/index.js": ((exports, module) => {
const assert$30 = __require$2("node:assert");
const { utf8DecodeBytes: utf8DecodeBytes$2 } = require_encoding();
/**
* @param {(char: string) => boolean} condition
* @param {string} input
* @param {{ position: number }} position
* @returns {string}
*
* @see https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
*/
function collectASequenceOfCodePoints$2(condition, input, position) {
let result = "";
while (position.position < input.length && condition(input[position.position])) {
result += input[position.position];
position.position++;
}
return result;
}
/**
* A faster collectASequenceOfCodePoints that only works when comparing a single character.
* @param {string} char
* @param {string} input
* @param {{ position: number }} position
* @returns {string}
*
* @see https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
*/
function collectASequenceOfCodePointsFast$3(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);
}
const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
/**
* @param {string} data
* @returns {Uint8Array | 'failure'}
*
* @see https://infra.spec.whatwg.org/#forgiving-base64-decode
*/
function forgivingBase64$1(data$1) {
data$1 = data$1.replace(ASCII_WHITESPACE_REPLACE_REGEX, "");
let dataLength = data$1.length;
if (dataLength % 4 === 0) {
if (data$1.charCodeAt(dataLength - 1) === 61) {
--dataLength;
if (data$1.charCodeAt(dataLength - 1) === 61) --dataLength;
}
}
if (dataLength % 4 === 1) return "failure";
if (/[^+/0-9A-Za-z]/.test(data$1.length === dataLength ? data$1 : data$1.substring(0, dataLength))) return "failure";
const buffer$1 = Buffer.from(data$1, "base64");
return new Uint8Array(buffer$1.buffer, buffer$1.byteOffset, buffer$1.byteLength);
}
/**
* @param {number} char
* @returns {boolean}
*
* @see https://infra.spec.whatwg.org/#ascii-whitespace
*/
function isASCIIWhitespace(char) {
return char === 9 || char === 10 || char === 12 || char === 13 || char === 32;
}
/**
* @param {Uint8Array} input
* @returns {string}
*
* @see https://infra.spec.whatwg.org/#isomorphic-decode
*/
function isomorphicDecode$2(input) {
const length = input.length;
if (65535 > length) return String.fromCharCode.apply(null, input);
let result = "";
let i$1 = 0;
let addition = 65535;
while (i$1 < length) {
if (i$1 + addition > length) addition = length - i$1;
result += String.fromCharCode.apply(null, input.subarray(i$1, i$1 += addition));
}
return result;
}
const invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
/**
* @param {string} input
* @returns {string}
*
* @see https://infra.spec.whatwg.org/#isomorphic-encode
*/
function isomorphicEncode$3(input) {
assert$30(!invalidIsomorphicEncodeValueRegex.test(input));
return input;
}
/**
* @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
* @param {Uint8Array} bytes
*/
function parseJSONFromBytes$1(bytes) {
return JSON.parse(utf8DecodeBytes$2(bytes));
}
/**
* @param {string} str
* @param {boolean} [leading=true]
* @param {boolean} [trailing=true]
* @returns {string}
*
* @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
*/
function removeASCIIWhitespace$1(str, leading = true, trailing = true) {
return removeChars$3(str, leading, trailing, isASCIIWhitespace);
}
/**
* @param {string} str
* @param {boolean} leading
* @param {boolean} trailing
* @param {(charCode: number) => boolean} predicate
* @returns {string}
*/
function removeChars$3(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);
}
function serializeJavascriptValueToJSONString$1(value) {
const result = JSON.stringify(value);
if (result === void 0) throw new TypeError("Value is not JSON serializable");
assert$30(typeof result === "string");
return result;
}
module.exports = {
collectASequenceOfCodePoints: collectASequenceOfCodePoints$2,
collectASequenceOfCodePointsFast: collectASequenceOfCodePointsFast$3,
forgivingBase64: forgivingBase64$1,
isASCIIWhitespace,
isomorphicDecode: isomorphicDecode$2,
isomorphicEncode: isomorphicEncode$3,
parseJSONFromBytes: parseJSONFromBytes$1,
removeASCIIWhitespace: removeASCIIWhitespace$1,
removeChars: removeChars$3,
serializeJavascriptValueToJSONString: serializeJavascriptValueToJSONString$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/data-url.js": ((exports, module) => {
const assert$29 = __require$2("node:assert");
const { forgivingBase64, collectASequenceOfCodePoints: collectASequenceOfCodePoints$1, collectASequenceOfCodePointsFast: collectASequenceOfCodePointsFast$2, isomorphicDecode: isomorphicDecode$1, removeASCIIWhitespace, removeChars: removeChars$2 } = require_infra();
const encoder = new TextEncoder();
/**
* @see https://mimesniff.spec.whatwg.org/#http-token-code-point
*/
const HTTP_TOKEN_CODEPOINTS$1 = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u;
const HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u;
/**
* @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
*/
const HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u;
/** @param {URL} dataURL */
function dataURLProcessor$1(dataURL) {
assert$29(dataURL.protocol === "data:");
let input = URLSerializer$4(dataURL, true);
input = input.slice(5);
const position = { position: 0 };
let mimeType = collectASequenceOfCodePointsFast$2(",", input, position);
const mimeTypeLength = mimeType.length;
mimeType = removeASCIIWhitespace(mimeType, true, true);
if (position.position >= input.length) return "failure";
position.position++;
let body = stringPercentDecode(input.slice(mimeTypeLength + 1));
if (/;(?:\u0020*)base64$/iu.test(mimeType)) {
body = forgivingBase64(isomorphicDecode$1(body));
if (body === "failure") return "failure";
mimeType = mimeType.slice(0, -6);
mimeType = mimeType.replace(/(\u0020+)$/u, "");
mimeType = mimeType.slice(0, -1);
}
if (mimeType.startsWith(";")) mimeType = "text/plain" + mimeType;
let mimeTypeRecord = parseMIMEType$3(mimeType);
if (mimeTypeRecord === "failure") mimeTypeRecord = parseMIMEType$3("text/plain;charset=US-ASCII");
return {
mimeType: mimeTypeRecord,
body
};
}
/**
* @param {URL} url
* @param {boolean} excludeFragment
*/
function URLSerializer$4(url, excludeFragment = false) {
if (!excludeFragment) return url.href;
const href = url.href;
const hashLength = url.hash.length;
const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
if (!hashLength && href.endsWith("#")) return serialized.slice(0, -1);
return serialized;
}
/** @param {string} input */
function stringPercentDecode(input) {
return percentDecode(encoder.encode(input));
}
/**
* @param {number} byte
*/
function isHexCharByte(byte) {
return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
}
/**
* @param {number} byte
*/
function hexByteToNumber(byte) {
return byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55;
}
/** @param {Uint8Array} input */
function percentDecode(input) {
const length = input.length;
/** @type {Uint8Array} */
const output = new Uint8Array(length);
let j = 0;
let i$1 = 0;
while (i$1 < length) {
const byte = input[i$1];
if (byte !== 37) output[j++] = byte;
else if (byte === 37 && !(isHexCharByte(input[i$1 + 1]) && isHexCharByte(input[i$1 + 2]))) output[j++] = 37;
else {
output[j++] = hexByteToNumber(input[i$1 + 1]) << 4 | hexByteToNumber(input[i$1 + 2]);
i$1 += 2;
}
++i$1;
}
return length === j ? output : output.subarray(0, j);
}
/** @param {string} input */
function parseMIMEType$3(input) {
input = removeHTTPWhitespace$1(input, true, true);
const position = { position: 0 };
const type = collectASequenceOfCodePointsFast$2("/", input, position);
if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS$1.test(type)) return "failure";
if (position.position >= input.length) return "failure";
position.position++;
let subtype = collectASequenceOfCodePointsFast$2(";", input, position);
subtype = removeHTTPWhitespace$1(subtype, false, true);
if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS$1.test(subtype)) return "failure";
const typeLowercase = type.toLowerCase();
const subtypeLowercase = subtype.toLowerCase();
const mimeType = {
type: typeLowercase,
subtype: subtypeLowercase,
parameters: /* @__PURE__ */ new Map(),
essence: `${typeLowercase}/${subtypeLowercase}`
};
while (position.position < input.length) {
position.position++;
collectASequenceOfCodePoints$1((char) => HTTP_WHITESPACE_REGEX.test(char), input, position);
let parameterName = collectASequenceOfCodePoints$1((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$1(input, position, true);
collectASequenceOfCodePointsFast$2(";", input, position);
} else {
parameterValue = collectASequenceOfCodePointsFast$2(";", input, position);
parameterValue = removeHTTPWhitespace$1(parameterValue, false, true);
if (parameterValue.length === 0) continue;
}
if (parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS$1.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName)) mimeType.parameters.set(parameterName, parameterValue);
}
return mimeType;
}
/**
* @param {string} input
* @param {{ position: number }} position
* @param {boolean} [extractValue=false]
*/
function collectAnHTTPQuotedString$1(input, position, extractValue$1 = false) {
const positionStart = position.position;
let value = "";
assert$29(input[position.position] === "\"");
position.position++;
while (true) {
value += collectASequenceOfCodePoints$1((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 {
assert$29(quoteOrBackslash === "\"");
break;
}
}
if (extractValue$1) return value;
return input.slice(positionStart, position.position);
}
/**
* @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
*/
function serializeAMimeType$3(mimeType) {
assert$29(mimeType !== "failure");
const { parameters, essence } = mimeType;
let serialization = essence;
for (let [name, value] of parameters.entries()) {
serialization += ";";
serialization += name;
serialization += "=";
if (!HTTP_TOKEN_CODEPOINTS$1.test(value)) {
value = value.replace(/[\\"]/gu, "\\$&");
value = "\"" + value;
value += "\"";
}
serialization += value;
}
return serialization;
}
/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {number} char
*/
function isHTTPWhiteSpace(char) {
return char === 13 || char === 10 || char === 9 || char === 32;
}
/**
* @see https://fetch.spec.whatwg.org/#http-whitespace
* @param {string} str
* @param {boolean} [leading=true]
* @param {boolean} [trailing=true]
*/
function removeHTTPWhitespace$1(str, leading = true, trailing = true) {
return removeChars$2(str, leading, trailing, isHTTPWhiteSpace);
}
/**
* @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type
* @param {Exclude<ReturnType<typeof parseMIMEType>, 'failure'>} mimeType
*/
function minimizeSupportedMimeType$1(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 "";
}
module.exports = {
dataURLProcessor: dataURLProcessor$1,
URLSerializer: URLSerializer$4,
stringPercentDecode,
parseMIMEType: parseMIMEType$3,
collectAnHTTPQuotedString: collectAnHTTPQuotedString$1,
serializeAMimeType: serializeAMimeType$3,
removeHTTPWhitespace: removeHTTPWhitespace$1,
minimizeSupportedMimeType: minimizeSupportedMimeType$1,
HTTP_TOKEN_CODEPOINTS: HTTP_TOKEN_CODEPOINTS$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/runtime-features.js
var require_runtime_features = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/runtime-features.js": ((exports, module) => {
/** @typedef {`node:${string}`} NodeModuleName */
/** @type {Record<NodeModuleName, () => any>} */
const lazyLoaders = {
__proto__: null,
"node:crypto": () => __require$2("node:crypto"),
"node:sqlite": () => __require$2("node:sqlite"),
"node:worker_threads": () => __require$2("node:worker_threads"),
"node:zlib": () => __require$2("node:zlib")
};
/**
* @param {NodeModuleName} moduleName
* @returns {boolean}
*/
function detectRuntimeFeatureByNodeModule(moduleName) {
try {
lazyLoaders[moduleName]();
return true;
} catch (err) {
if (err.code !== "ERR_UNKNOWN_BUILTIN_MODULE" && err.code !== "ERR_NO_CRYPTO") throw err;
return false;
}
}
/**
* @param {NodeModuleName} moduleName
* @param {string} property
* @returns {boolean}
*/
function detectRuntimeFeatureByExportedProperty(moduleName, property) {
return typeof lazyLoaders[moduleName]()[property] !== "undefined";
}
const runtimeFeaturesByExportedProperty = ["markAsUncloneable", "zstd"];
/** @type {Record<RuntimeFeatureByExportedProperty, [NodeModuleName, string]>} */
const exportedPropertyLookup = {
markAsUncloneable: ["node:worker_threads", "markAsUncloneable"],
zstd: ["node:zlib", "createZstdDecompress"]
};
/** @typedef {typeof runtimeFeaturesByExportedProperty[number]} RuntimeFeatureByExportedProperty */
const runtimeFeaturesAsNodeModule = ["crypto", "sqlite"];
/** @typedef {typeof runtimeFeaturesAsNodeModule[number]} RuntimeFeatureByNodeModule */
const features = [...runtimeFeaturesAsNodeModule, ...runtimeFeaturesByExportedProperty];
/** @typedef {typeof features[number]} Feature */
/**
* @param {Feature} feature
* @returns {boolean}
*/
function detectRuntimeFeature(feature) {
if (runtimeFeaturesAsNodeModule.includes(feature)) return detectRuntimeFeatureByNodeModule(`node:${feature}`);
else if (runtimeFeaturesByExportedProperty.includes(feature)) {
const [moduleName, property] = exportedPropertyLookup[feature];
return detectRuntimeFeatureByExportedProperty(moduleName, property);
}
throw new TypeError(`unknown feature: ${feature}`);
}
/**
* @class
* @name RuntimeFeatures
*/
var RuntimeFeatures = class {
/** @type {Map<Feature, boolean>} */
#map = /* @__PURE__ */ new Map();
/**
* Clears all cached feature detections.
*/
clear() {
this.#map.clear();
}
/**
* @param {Feature} feature
* @returns {boolean}
*/
has(feature) {
return this.#map.get(feature) ?? this.#detectRuntimeFeature(feature);
}
/**
* @param {Feature} feature
* @param {boolean} value
*/
set(feature, value) {
if (features.includes(feature) === false) throw new TypeError(`unknown feature: ${feature}`);
this.#map.set(feature, value);
}
/**
* @param {Feature} feature
* @returns {boolean}
*/
#detectRuntimeFeature(feature) {
const result = detectRuntimeFeature(feature);
this.#map.set(feature, result);
return result;
}
};
const instance = new RuntimeFeatures();
module.exports.runtimeFeatures = instance;
module.exports.default = instance;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/webidl/index.js
var require_webidl = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/webidl/index.js": ((exports, module) => {
const assert$28 = __require$2("node:assert");
const { types: types$3, inspect: inspect$1 } = __require$2("node:util");
const { runtimeFeatures: runtimeFeatures$7 } = require_runtime_features();
const UNDEFINED = 1;
const BOOLEAN = 2;
const STRING = 3;
const SYMBOL = 4;
const NUMBER = 5;
const BIGINT = 6;
const NULL = 7;
const OBJECT = 8;
const FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
/** @type {import('../../../types/webidl').Webidl} */
const webidl$16 = {
converters: {},
util: {},
errors: {},
is: {}
};
/**
* @description Instantiate an error.
*
* @param {Object} opts
* @param {string} opts.header
* @param {string} opts.message
* @returns {TypeError}
*/
webidl$16.errors.exception = function(message) {
return /* @__PURE__ */ new TypeError(`${message.header}: ${message.message}`);
};
/**
* @description Instantiate an error when conversion from one type to another has failed.
*
* @param {Object} opts
* @param {string} opts.prefix
* @param {string} opts.argument
* @param {string[]} opts.types
* @returns {TypeError}
*/
webidl$16.errors.conversionFailed = function(opts) {
const plural = opts.types.length === 1 ? "" : " one of";
const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
return webidl$16.errors.exception({
header: opts.prefix,
message
});
};
/**
* @description Instantiate an error when an invalid argument is provided
*
* @param {Object} context
* @param {string} context.prefix
* @param {string} context.value
* @param {string} context.type
* @returns {TypeError}
*/
webidl$16.errors.invalidArgument = function(context) {
return webidl$16.errors.exception({
header: context.prefix,
message: `"${context.value}" is an invalid ${context.type}.`
});
};
webidl$16.brandCheck = function(V, I) {
if (!FunctionPrototypeSymbolHasInstance(I, V)) {
const err = /* @__PURE__ */ new TypeError("Illegal invocation");
err.code = "ERR_INVALID_THIS";
throw err;
}
};
webidl$16.brandCheckMultiple = function(List) {
const prototypes = List.map((c) => webidl$16.util.MakeTypeAssertion(c));
return (V) => {
if (prototypes.every((typeCheck) => !typeCheck(V))) {
const err = /* @__PURE__ */ new TypeError("Illegal invocation");
err.code = "ERR_INVALID_THIS";
throw err;
}
};
};
webidl$16.argumentLengthCheck = function({ length }, min, ctx) {
if (length < min) throw webidl$16.errors.exception({
message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
header: ctx
});
};
webidl$16.illegalConstructor = function() {
throw webidl$16.errors.exception({
header: "TypeError",
message: "Illegal constructor"
});
};
webidl$16.util.MakeTypeAssertion = function(I) {
return (O) => FunctionPrototypeSymbolHasInstance(I, O);
};
webidl$16.util.Type = function(V) {
switch (typeof V) {
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 (V === null) return NULL;
return OBJECT;
}
};
webidl$16.util.Types = {
UNDEFINED,
BOOLEAN,
STRING,
SYMBOL,
NUMBER,
BIGINT,
NULL,
OBJECT
};
webidl$16.util.TypeValueToString = function(o) {
switch (webidl$16.util.Type(o)) {
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$16.util.markAsUncloneable = runtimeFeatures$7.has("markAsUncloneable") ? __require$2("node:worker_threads").markAsUncloneable : () => {};
webidl$16.util.ConvertToInt = function(V, bitLength, signedness, flags) {
let upperBound;
let lowerBound;
if (bitLength === 64) {
upperBound = Math.pow(2, 53) - 1;
if (signedness === "unsigned") lowerBound = 0;
else lowerBound = Math.pow(-2, 53) + 1;
} else if (signedness === "unsigned") {
lowerBound = 0;
upperBound = Math.pow(2, bitLength) - 1;
} else {
lowerBound = Math.pow(-2, bitLength) - 1;
upperBound = Math.pow(2, bitLength - 1) - 1;
}
let x = Number(V);
if (x === 0) x = 0;
if (webidl$16.util.HasFlag(flags, webidl$16.attributes.EnforceRange)) {
if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) throw webidl$16.errors.exception({
header: "Integer conversion",
message: `Could not convert ${webidl$16.util.Stringify(V)} to an integer.`
});
x = webidl$16.util.IntegerPart(x);
if (x < lowerBound || x > upperBound) throw webidl$16.errors.exception({
header: "Integer conversion",
message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
});
return x;
}
if (!Number.isNaN(x) && webidl$16.util.HasFlag(flags, webidl$16.attributes.Clamp)) {
x = Math.min(Math.max(x, lowerBound), upperBound);
if (Math.floor(x) % 2 === 0) x = Math.floor(x);
else x = Math.ceil(x);
return x;
}
if (Number.isNaN(x) || x === 0 && Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) return 0;
x = webidl$16.util.IntegerPart(x);
x = x % Math.pow(2, bitLength);
if (signedness === "signed" && x >= Math.pow(2, bitLength) - 1) return x - Math.pow(2, bitLength);
return x;
};
webidl$16.util.IntegerPart = function(n$1) {
const r$1 = Math.floor(Math.abs(n$1));
if (n$1 < 0) return -1 * r$1;
return r$1;
};
webidl$16.util.Stringify = function(V) {
switch (webidl$16.util.Type(V)) {
case SYMBOL: return `Symbol(${V.description})`;
case OBJECT: return inspect$1(V);
case STRING: return `"${V}"`;
case BIGINT: return `${V}n`;
default: return `${V}`;
}
};
webidl$16.util.IsResizableArrayBuffer = function(V) {
if (types$3.isArrayBuffer(V)) return V.resizable;
if (types$3.isSharedArrayBuffer(V)) return V.growable;
throw webidl$16.errors.exception({
header: "IsResizableArrayBuffer",
message: `"${webidl$16.util.Stringify(V)}" is not an array buffer.`
});
};
webidl$16.util.HasFlag = function(flags, attributes) {
return typeof flags === "number" && (flags & attributes) === attributes;
};
webidl$16.sequenceConverter = function(converter) {
return (V, prefix, argument, Iterable) => {
if (webidl$16.util.Type(V) !== OBJECT) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} (${webidl$16.util.Stringify(V)}) is not iterable.`
});
/** @type {Generator} */
const method = typeof Iterable === "function" ? Iterable() : V?.[Symbol.iterator]?.();
const seq = [];
let index = 0;
if (method === void 0 || typeof method.next !== "function") throw webidl$16.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$16.recordConverter = function(keyConverter, valueConverter) {
return (O, prefix, argument) => {
if (webidl$16.util.Type(O) !== OBJECT) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} ("${webidl$16.util.TypeValueToString(O)}") is not an Object.`
});
const result = {};
if (!types$3.isProxy(O)) {
const keys$1 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)];
for (const key of keys$1) {
const keyName = webidl$16.util.Stringify(key);
const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`);
result[typedKey] = valueConverter(O[key], prefix, `${argument}[${keyName}]`);
}
return result;
}
const keys = Reflect.ownKeys(O);
for (const key of keys) if (Reflect.getOwnPropertyDescriptor(O, key)?.enumerable) {
const typedKey = keyConverter(key, prefix, argument);
result[typedKey] = valueConverter(O[key], prefix, argument);
}
return result;
};
};
webidl$16.interfaceConverter = function(TypeCheck, name) {
return (V, prefix, argument) => {
if (!TypeCheck(V)) throw webidl$16.errors.exception({
header: prefix,
message: `Expected ${argument} ("${webidl$16.util.Stringify(V)}") to be an instance of ${name}.`
});
return V;
};
};
webidl$16.dictionaryConverter = function(converters) {
converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
return (dictionary, prefix, argument) => {
const dict = {};
if (dictionary != null && webidl$16.util.Type(dictionary) !== OBJECT) throw webidl$16.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$16.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$16.errors.exception({
header: prefix,
message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(", ")}.`
});
dict[key] = value;
}
}
return dict;
};
};
webidl$16.nullableConverter = function(converter) {
return (V, prefix, argument) => {
if (V === null) return V;
return converter(V, prefix, argument);
};
};
/**
* @param {*} value
* @returns {boolean}
*/
webidl$16.is.USVString = function(value) {
return typeof value === "string" && value.isWellFormed();
};
webidl$16.is.ReadableStream = webidl$16.util.MakeTypeAssertion(ReadableStream);
webidl$16.is.Blob = webidl$16.util.MakeTypeAssertion(Blob);
webidl$16.is.URLSearchParams = webidl$16.util.MakeTypeAssertion(URLSearchParams);
webidl$16.is.File = webidl$16.util.MakeTypeAssertion(File);
webidl$16.is.URL = webidl$16.util.MakeTypeAssertion(URL);
webidl$16.is.AbortSignal = webidl$16.util.MakeTypeAssertion(AbortSignal);
webidl$16.is.MessagePort = webidl$16.util.MakeTypeAssertion(MessagePort);
webidl$16.is.BufferSource = function(V) {
return types$3.isArrayBuffer(V) || ArrayBuffer.isView(V) && types$3.isArrayBuffer(V.buffer);
};
webidl$16.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
const jsBufferSource = bufferSource;
let jsArrayBuffer = jsBufferSource;
let offset = 0;
let length = 0;
if (types$3.isTypedArray(jsBufferSource) || types$3.isDataView(jsBufferSource)) {
jsArrayBuffer = jsBufferSource.buffer;
offset = jsBufferSource.byteOffset;
length = jsBufferSource.byteLength;
} else {
assert$28(types$3.isAnyArrayBuffer(jsBufferSource));
length = jsBufferSource.byteLength;
}
if (jsArrayBuffer.detached) return new Uint8Array(0);
const bytes = new Uint8Array(length);
const view = new Uint8Array(jsArrayBuffer, offset, length);
bytes.set(view);
return bytes;
};
webidl$16.converters.DOMString = function(V, prefix, argument, flags) {
if (V === null && webidl$16.util.HasFlag(flags, webidl$16.attributes.LegacyNullToEmptyString)) return "";
if (typeof V === "symbol") throw webidl$16.errors.exception({
header: prefix,
message: `${argument} is a symbol, which cannot be converted to a DOMString.`
});
return String(V);
};
webidl$16.converters.ByteString = function(V, prefix, argument) {
if (typeof V === "symbol") throw webidl$16.errors.exception({
header: prefix,
message: `${argument} is a symbol, which cannot be converted to a ByteString.`
});
const x = String(V);
for (let index = 0; index < x.length; index++) if (x.charCodeAt(index) > 255) throw new TypeError(`Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`);
return x;
};
/**
* @param {unknown} value
* @returns {string}
* @see https://webidl.spec.whatwg.org/#es-USVString
*/
webidl$16.converters.USVString = function(value) {
if (typeof value === "string") return value.toWellFormed();
return `${value}`.toWellFormed();
};
webidl$16.converters.boolean = function(V) {
return Boolean(V);
};
webidl$16.converters.any = function(V) {
return V;
};
webidl$16.converters["long long"] = function(V, prefix, argument) {
return webidl$16.util.ConvertToInt(V, 64, "signed", 0, prefix, argument);
};
webidl$16.converters["unsigned long long"] = function(V, prefix, argument) {
return webidl$16.util.ConvertToInt(V, 64, "unsigned", 0, prefix, argument);
};
webidl$16.converters["unsigned long"] = function(V, prefix, argument) {
return webidl$16.util.ConvertToInt(V, 32, "unsigned", 0, prefix, argument);
};
webidl$16.converters["unsigned short"] = function(V, prefix, argument, flags) {
return webidl$16.util.ConvertToInt(V, 16, "unsigned", flags, prefix, argument);
};
webidl$16.converters.ArrayBuffer = function(V, prefix, argument, flags) {
if (webidl$16.util.Type(V) !== OBJECT || !types$3.isArrayBuffer(V)) throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: ["ArrayBuffer"]
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowResizable) && webidl$16.util.IsResizableArrayBuffer(V)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a resizable ArrayBuffer.`
});
return V;
};
webidl$16.converters.SharedArrayBuffer = function(V, prefix, argument, flags) {
if (webidl$16.util.Type(V) !== OBJECT || !types$3.isSharedArrayBuffer(V)) throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: ["SharedArrayBuffer"]
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowResizable) && webidl$16.util.IsResizableArrayBuffer(V)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a resizable SharedArrayBuffer.`
});
return V;
};
webidl$16.converters.TypedArray = function(V, T, prefix, argument, flags) {
if (webidl$16.util.Type(V) !== OBJECT || !types$3.isTypedArray(V) || V.constructor.name !== T.name) throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: [T.name]
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowShared) && types$3.isSharedArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a shared array buffer.`
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowResizable) && webidl$16.util.IsResizableArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a resizable array buffer.`
});
return V;
};
webidl$16.converters.DataView = function(V, prefix, argument, flags) {
if (webidl$16.util.Type(V) !== OBJECT || !types$3.isDataView(V)) throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: ["DataView"]
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowShared) && types$3.isSharedArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a shared array buffer.`
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowResizable) && webidl$16.util.IsResizableArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a resizable array buffer.`
});
return V;
};
webidl$16.converters.ArrayBufferView = function(V, prefix, argument, flags) {
if (webidl$16.util.Type(V) !== OBJECT || !types$3.isArrayBufferView(V)) throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: ["ArrayBufferView"]
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowShared) && types$3.isSharedArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a shared array buffer.`
});
if (!webidl$16.util.HasFlag(flags, webidl$16.attributes.AllowResizable) && webidl$16.util.IsResizableArrayBuffer(V.buffer)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a view on a resizable array buffer.`
});
return V;
};
webidl$16.converters.BufferSource = function(V, prefix, argument, flags) {
if (types$3.isArrayBuffer(V)) return webidl$16.converters.ArrayBuffer(V, prefix, argument, flags);
if (types$3.isArrayBufferView(V)) {
flags &= ~webidl$16.attributes.AllowShared;
return webidl$16.converters.ArrayBufferView(V, prefix, argument, flags);
}
if (types$3.isSharedArrayBuffer(V)) throw webidl$16.errors.exception({
header: prefix,
message: `${argument} cannot be a SharedArrayBuffer.`
});
throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: ["ArrayBuffer", "ArrayBufferView"]
});
};
webidl$16.converters.AllowSharedBufferSource = function(V, prefix, argument, flags) {
if (types$3.isArrayBuffer(V)) return webidl$16.converters.ArrayBuffer(V, prefix, argument, flags);
if (types$3.isSharedArrayBuffer(V)) return webidl$16.converters.SharedArrayBuffer(V, prefix, argument, flags);
if (types$3.isArrayBufferView(V)) {
flags |= webidl$16.attributes.AllowShared;
return webidl$16.converters.ArrayBufferView(V, prefix, argument, flags);
}
throw webidl$16.errors.conversionFailed({
prefix,
argument: `${argument} ("${webidl$16.util.Stringify(V)}")`,
types: [
"ArrayBuffer",
"SharedArrayBuffer",
"ArrayBufferView"
]
});
};
webidl$16.converters["sequence<ByteString>"] = webidl$16.sequenceConverter(webidl$16.converters.ByteString);
webidl$16.converters["sequence<sequence<ByteString>>"] = webidl$16.sequenceConverter(webidl$16.converters["sequence<ByteString>"]);
webidl$16.converters["record<ByteString, ByteString>"] = webidl$16.recordConverter(webidl$16.converters.ByteString, webidl$16.converters.ByteString);
webidl$16.converters.Blob = webidl$16.interfaceConverter(webidl$16.is.Blob, "Blob");
webidl$16.converters.AbortSignal = webidl$16.interfaceConverter(webidl$16.is.AbortSignal, "AbortSignal");
/**
* [LegacyTreatNonObjectAsNull]
* callback EventHandlerNonNull = any (Event event);
* typedef EventHandlerNonNull? EventHandler;
* @param {*} V
*/
webidl$16.converters.EventHandlerNonNull = function(V) {
if (webidl$16.util.Type(V) !== OBJECT) return null;
if (typeof V === "function") return V;
return () => {};
};
webidl$16.attributes = {
Clamp: 1,
EnforceRange: 2,
AllowShared: 4,
AllowResizable: 8,
LegacyNullToEmptyString: 16
};
module.exports = { webidl: webidl$16 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/util.js
var require_util$4 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/util.js": ((exports, module) => {
const { Transform: Transform$2 } = __require$2("node:stream");
const zlib$1 = __require$2("node:zlib");
const { redirectStatusSet: redirectStatusSet$2, referrerPolicyTokens, badPortsSet } = require_constants$3();
const { getGlobalOrigin: getGlobalOrigin$1 } = require_global$1();
const { collectAnHTTPQuotedString, parseMIMEType: parseMIMEType$2 } = require_data_url();
const { performance: performance$1 } = __require$2("node:perf_hooks");
const { ReadableStreamFrom: ReadableStreamFrom$2, isValidHTTPToken: isValidHTTPToken$1, normalizedMethodRecordsBase: normalizedMethodRecordsBase$1 } = require_util$5();
const assert$27 = __require$2("node:assert");
const { isUint8Array: isUint8Array$1 } = __require$2("node:util/types");
const { webidl: webidl$15 } = require_webidl();
const { isomorphicEncode: isomorphicEncode$2, collectASequenceOfCodePoints, removeChars: removeChars$1 } = require_infra();
function responseURL(response) {
const urlList = response.urlList;
const length = urlList.length;
return length === 0 ? null : urlList[length - 1].toString();
}
function responseLocationURL$1(response, requestFragment) {
if (!redirectStatusSet$2.has(response.status)) return null;
let location = response.headersList.get("location", true);
if (location !== null && isValidHeaderValue$1(location)) {
if (!isValidEncodedURL(location)) location = normalizeBinaryStringToUtf8(location);
location = new URL(location, responseURL(response));
}
if (location && !location.hash) location.hash = requestFragment;
return location;
}
/**
* @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2
* @param {string} url
* @returns {boolean}
*/
function isValidEncodedURL(url) {
for (let i$1 = 0; i$1 < url.length; ++i$1) {
const code = url.charCodeAt(i$1);
if (code > 126 || code < 32) return false;
}
return true;
}
/**
* If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it.
* Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well.
* @param {string} value
* @returns {string}
*/
function normalizeBinaryStringToUtf8(value) {
return Buffer.from(value, "binary").toString("utf8");
}
/** @returns {URL} */
function requestCurrentURL$1(request$2) {
return request$2.urlList[request$2.urlList.length - 1];
}
function requestBadPort$1(request$2) {
const url = requestCurrentURL$1(request$2);
if (urlIsHttpHttpsScheme$2(url) && badPortsSet.has(url.port)) return "blocked";
return "allowed";
}
function isErrorLike$2(object) {
return object instanceof Error || object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException";
}
function isValidReasonPhrase$1(statusText) {
for (let i$1 = 0; i$1 < statusText.length; ++i$1) {
const c = statusText.charCodeAt(i$1);
if (!(c === 9 || c >= 32 && c <= 126 || c >= 128 && c <= 255)) return false;
}
return true;
}
/**
* @see https://fetch.spec.whatwg.org/#header-name
* @param {string} potentialValue
*/
const isValidHeaderName$2 = isValidHTTPToken$1;
/**
* @see https://fetch.spec.whatwg.org/#header-value
* @param {string} potentialValue
*/
function isValidHeaderValue$1(potentialValue) {
return (potentialValue[0] === " " || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
}
/**
* Parse a referrer policy from a Referrer-Policy header
* @see https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header
*/
function parseReferrerPolicy(actualResponse) {
const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
let policy = "";
if (policyHeader.length) for (let i$1 = policyHeader.length; i$1 !== 0; i$1--) {
const token = policyHeader[i$1 - 1].trim();
if (referrerPolicyTokens.has(token)) {
policy = token;
break;
}
}
return policy;
}
/**
* Given a request request and a response actualResponse, this algorithm
* updates request’s referrer policy according to the Referrer-Policy
* header (if any) in actualResponse.
* @see https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
* @param {import('./request').Request} request
* @param {import('./response').Response} actualResponse
*/
function setRequestReferrerPolicyOnRedirect$1(request$2, actualResponse) {
const policy = parseReferrerPolicy(actualResponse);
if (policy !== "") request$2.referrerPolicy = policy;
}
function crossOriginResourcePolicyCheck$1() {
return "allowed";
}
function corsCheck$1() {
return "success";
}
function TAOCheck$1() {
return "success";
}
function appendFetchMetadata$1(httpRequest) {
let header = null;
header = httpRequest.mode;
httpRequest.headersList.set("sec-fetch-mode", header, true);
}
function appendRequestOriginHeader$1(request$2) {
let serializedOrigin = request$2.origin;
if (serializedOrigin === "client" || serializedOrigin === void 0) return;
if (request$2.responseTainting === "cors" || request$2.mode === "websocket") request$2.headersList.append("origin", serializedOrigin, true);
else if (request$2.method !== "GET" && request$2.method !== "HEAD") {
switch (request$2.referrerPolicy) {
case "no-referrer":
serializedOrigin = null;
break;
case "no-referrer-when-downgrade":
case "strict-origin":
case "strict-origin-when-cross-origin":
if (request$2.origin && urlHasHttpsScheme$1(request$2.origin) && !urlHasHttpsScheme$1(requestCurrentURL$1(request$2))) serializedOrigin = null;
break;
case "same-origin":
if (!sameOrigin$2(request$2, requestCurrentURL$1(request$2))) serializedOrigin = null;
break;
default:
}
request$2.headersList.append("origin", serializedOrigin, true);
}
}
function coarsenTime(timestamp, crossOriginIsolatedCapability) {
return timestamp;
}
function clampAndCoarsenConnectionTimingInfo$1(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
};
}
function coarsenedSharedCurrentTime$1(crossOriginIsolatedCapability) {
return coarsenTime(performance$1.now(), crossOriginIsolatedCapability);
}
function createOpaqueTimingInfo$1(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
};
}
function makePolicyContainer$1() {
return { referrerPolicy: "strict-origin-when-cross-origin" };
}
function clonePolicyContainer$1(policyContainer) {
return { referrerPolicy: policyContainer.referrerPolicy };
}
/**
* Determine request’s Referrer
*
* @see https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
*/
function determineRequestsReferrer$1(request$2) {
const policy = request$2.referrerPolicy;
assert$27(policy);
let referrerSource = null;
if (request$2.referrer === "client") {
const globalOrigin$1 = getGlobalOrigin$1();
if (!globalOrigin$1 || globalOrigin$1.origin === "null") return "no-referrer";
referrerSource = new URL(globalOrigin$1);
} else if (webidl$15.is.URL(request$2.referrer)) referrerSource = request$2.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$1(request$2);
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) return "no-referrer";
return referrerOrigin;
}
case "strict-origin-when-cross-origin": {
const currentURL = requestCurrentURL$1(request$2);
if (sameOrigin$2(referrerURL, currentURL)) return referrerURL;
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) return "no-referrer";
return referrerOrigin;
}
case "same-origin":
if (sameOrigin$2(request$2, referrerURL)) return referrerURL;
return "no-referrer";
case "origin-when-cross-origin":
if (sameOrigin$2(request$2, referrerURL)) return referrerURL;
return referrerOrigin;
case "no-referrer-when-downgrade": {
const currentURL = requestCurrentURL$1(request$2);
if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) return "no-referrer";
return referrerURL;
}
}
}
/**
* Certain portions of URLs must not be included when sending a URL as the
* value of a `Referer` header: a URLs fragment, username, and password
* components must be stripped from the URL before it’s sent out. This
* algorithm accepts a origin-only flag, which defaults to false. If set to
* true, the algorithm will additionally remove the URL’s path and query
* components, leaving only the scheme, host, and port.
*
* @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
* @param {URL} url
* @param {boolean} [originOnly=false]
*/
function stripURLForReferrer(url, originOnly = false) {
assert$27(webidl$15.is.URL(url));
url = new URL(url);
if (urlIsLocal$1(url)) return "no-referrer";
url.username = "";
url.password = "";
url.hash = "";
if (originOnly === true) {
url.pathname = "";
url.search = "";
}
return url;
}
const isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
const isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
/**
* Check if host matches one of the CIDR notations 127.0.0.0/8 or ::1/128.
*
* @param {string} origin
* @returns {boolean}
*/
function isOriginIPPotentiallyTrustworthy(origin) {
if (origin.includes(":")) {
if (origin[0] === "[" && origin[origin.length - 1] === "]") origin = origin.slice(1, -1);
return isPotentiallyTrustworthyIPv6(origin);
}
return isPotentialleTrustworthyIPv4(origin);
}
/**
* A potentially trustworthy origin is one which a user agent can generally
* trust as delivering data securely.
*
* Return value `true` means `Potentially Trustworthy`.
* Return value `false` means `Not Trustworthy`.
*
* @see https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy
* @param {string} origin
* @returns {boolean}
*/
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;
}
/**
* A potentially trustworthy URL is one which either inherits context from its
* creator (about:blank, about:srcdoc, data) or one whose origin is a
* potentially trustworthy origin.
*
* Return value `true` means `Potentially Trustworthy`.
* Return value `false` means `Not Trustworthy`.
*
* @see https://www.w3.org/TR/secure-contexts/#is-url-trustworthy
* @param {URL} url
* @returns {boolean}
*/
function isURLPotentiallyTrustworthy(url) {
if (!webidl$15.is.URL(url)) return false;
if (url.href === "about:blank" || url.href === "about:srcdoc") return true;
if (url.protocol === "data:") return true;
if (url.protocol === "blob:") return true;
return isOriginPotentiallyTrustworthy(url.origin);
}
function tryUpgradeRequestToAPotentiallyTrustworthyURL$1(request$2) {}
/**
* @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
* @param {URL} A
* @param {URL} B
*/
function sameOrigin$2(A, B) {
if (A.origin === B.origin && A.origin === "null") return true;
if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) return true;
return false;
}
function isAborted$4(fetchParams) {
return fetchParams.controller.state === "aborted";
}
function isCancelled$2(fetchParams) {
return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
}
/**
* @see https://fetch.spec.whatwg.org/#concept-method-normalize
* @param {string} method
*/
function normalizeMethod(method) {
return normalizedMethodRecordsBase$1[method.toLowerCase()] ?? method;
}
const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
/**
* @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
* @param {string} name name of the instance
* @param {((target: any) => any)} kInternalIterator
* @param {string | number} [keyIndex]
* @param {string | number} [valueIndex]
*/
function createIterator(name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
class 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$1, kind) {
this.#target = target$1;
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 ${name} Iterator.`);
const index = this.#index;
const values = kInternalIterator(this.#target);
if (index >= values.length) 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: `${name} Iterator`
},
next: {
writable: true,
enumerable: true,
configurable: true
}
});
/**
* @param {unknown} target
* @param {'key' | 'value' | 'key+value'} kind
* @returns {IterableIterator<any>}
*/
return function(target$1, kind) {
return new FastIterableIterator(target$1, kind);
};
}
/**
* @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
* @param {string} name name of the instance
* @param {any} object class
* @param {(target: any) => any} kInternalIterator
* @param {string | number} [keyIndex]
* @param {string | number} [valueIndex]
*/
function iteratorMixin$2(name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex);
const properties = {
keys: {
writable: true,
enumerable: true,
configurable: true,
value: function keys() {
webidl$15.brandCheck(this, object);
return makeIterator(this, "key");
}
},
values: {
writable: true,
enumerable: true,
configurable: true,
value: function values() {
webidl$15.brandCheck(this, object);
return makeIterator(this, "value");
}
},
entries: {
writable: true,
enumerable: true,
configurable: true,
value: function entries() {
webidl$15.brandCheck(this, object);
return makeIterator(this, "key+value");
}
},
forEach: {
writable: true,
enumerable: true,
configurable: true,
value: function forEach(callbackfn, thisArg = globalThis) {
webidl$15.brandCheck(this, object);
webidl$15.argumentLengthCheck(arguments, 1, `${name}.forEach`);
if (typeof callbackfn !== "function") throw new TypeError(`Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`);
for (const { 0: key, 1: value } of makeIterator(this, "key+value")) callbackfn.call(thisArg, value, key, this);
}
}
};
return Object.defineProperties(object.prototype, {
...properties,
[Symbol.iterator]: {
writable: true,
enumerable: false,
configurable: true,
value: properties.entries.value
}
});
}
/**
* @param {import('./body').ExtractBodyResult} body
* @param {(bytes: Uint8Array) => void} processBody
* @param {(error: Error) => void} processBodyError
* @returns {void}
*
* @see https://fetch.spec.whatwg.org/#body-fully-read
*/
function fullyReadBody$2(body, processBody, processBodyError) {
const successSteps = processBody;
const errorSteps = processBodyError;
try {
readAllBytes$1(body.stream.getReader(), successSteps, errorSteps);
} catch (e) {
errorSteps(e);
}
}
/**
* @param {ReadableStreamController<Uint8Array>} controller
*/
function readableStreamClose$2(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;
}
}
/**
* @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
* @see https://streams.spec.whatwg.org/#read-loop
* @param {ReadableStream<Uint8Array<ArrayBuffer>>} reader
* @param {(bytes: Uint8Array) => void} successSteps
* @param {(error: Error) => void} failureSteps
* @returns {Promise<void>}
*/
async function readAllBytes$1(reader, successSteps, failureSteps) {
try {
const bytes = [];
let byteLength = 0;
do {
const { done, value: chunk } = await reader.read();
if (done) {
successSteps(Buffer.concat(bytes, byteLength));
return;
}
if (!isUint8Array$1(chunk)) {
failureSteps(/* @__PURE__ */ new TypeError("Received non-Uint8Array chunk"));
return;
}
bytes.push(chunk);
byteLength += chunk.length;
} while (true);
} catch (e) {
failureSteps(e);
}
}
/**
* @see https://fetch.spec.whatwg.org/#is-local
* @param {URL} url
* @returns {boolean}
*/
function urlIsLocal$1(url) {
assert$27("protocol" in url);
const protocol = url.protocol;
return protocol === "about:" || protocol === "blob:" || protocol === "data:";
}
/**
* @param {string|URL} url
* @returns {boolean}
*/
function urlHasHttpsScheme$1(url) {
return typeof url === "string" && url[5] === ":" && url[0] === "h" && url[1] === "t" && url[2] === "t" && url[3] === "p" && url[4] === "s" || url.protocol === "https:";
}
/**
* @see https://fetch.spec.whatwg.org/#http-scheme
* @param {URL} url
*/
function urlIsHttpHttpsScheme$2(url) {
assert$27("protocol" in url);
const protocol = url.protocol;
return protocol === "http:" || protocol === "https:";
}
/**
* @typedef {Object} RangeHeaderValue
* @property {number|null} rangeStartValue
* @property {number|null} rangeEndValue
*/
/**
* @see https://fetch.spec.whatwg.org/#simple-range-header-value
* @param {string} value
* @param {boolean} allowWhitespace
* @return {RangeHeaderValue|'failure'}
*/
function simpleRangeHeaderValue$1(value, allowWhitespace) {
const data$1 = value;
if (!data$1.startsWith("bytes")) return "failure";
const position = { position: 5 };
if (allowWhitespace) collectASequenceOfCodePoints((char) => char === " " || char === " ", data$1, position);
if (data$1.charCodeAt(position.position) !== 61) return "failure";
position.position++;
if (allowWhitespace) collectASequenceOfCodePoints((char) => char === " " || char === " ", data$1, position);
const rangeStart = collectASequenceOfCodePoints((char) => {
const code = char.charCodeAt(0);
return code >= 48 && code <= 57;
}, data$1, position);
const rangeStartValue = rangeStart.length ? Number(rangeStart) : null;
if (allowWhitespace) collectASequenceOfCodePoints((char) => char === " " || char === " ", data$1, position);
if (data$1.charCodeAt(position.position) !== 45) return "failure";
position.position++;
if (allowWhitespace) collectASequenceOfCodePoints((char) => char === " " || char === " ", data$1, position);
const rangeEnd = collectASequenceOfCodePoints((char) => {
const code = char.charCodeAt(0);
return code >= 48 && code <= 57;
}, data$1, position);
const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null;
if (position.position < data$1.length) return "failure";
if (rangeEndValue === null && rangeStartValue === null) return "failure";
if (rangeStartValue > rangeEndValue) return "failure";
return {
rangeStartValue,
rangeEndValue
};
}
/**
* @see https://fetch.spec.whatwg.org/#build-a-content-range
* @param {number} rangeStart
* @param {number} rangeEnd
* @param {number} fullLength
*/
function buildContentRange$1(rangeStart, rangeEnd, fullLength) {
let contentRange = "bytes ";
contentRange += isomorphicEncode$2(`${rangeStart}`);
contentRange += "-";
contentRange += isomorphicEncode$2(`${rangeEnd}`);
contentRange += "/";
contentRange += isomorphicEncode$2(`${fullLength}`);
return contentRange;
}
var InflateStream = class extends Transform$2 {
#zlibOptions;
/** @param {zlib.ZlibOptions} [zlibOptions] */
constructor(zlibOptions) {
super();
this.#zlibOptions = zlibOptions;
}
_transform(chunk, encoding, callback$1) {
if (!this._inflateStream) {
if (chunk.length === 0) {
callback$1();
return;
}
this._inflateStream = (chunk[0] & 15) === 8 ? zlib$1.createInflate(this.#zlibOptions) : zlib$1.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$1);
}
_final(callback$1) {
if (this._inflateStream) {
this._inflateStream.end();
this._inflateStream = null;
}
callback$1();
}
};
/**
* @param {zlib.ZlibOptions} [zlibOptions]
* @returns {InflateStream}
*/
function createInflate$2(zlibOptions) {
return new InflateStream(zlibOptions);
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type
* @param {import('./headers').HeadersList} headers
*/
function extractMimeType$2(headers) {
let charset = null;
let essence = null;
let mimeType = null;
const values = getDecodeSplit$1("content-type", headers);
if (values === null) return "failure";
for (const value of values) {
const temporaryMimeType = parseMIMEType$2(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;
}
/**
* @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split
* @param {string|null} value
*/
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 {
assert$27(input.charCodeAt(position.position) === 44);
position.position++;
}
temporaryValue = removeChars$1(temporaryValue, true, true, (char) => char === 9 || char === 32);
values.push(temporaryValue);
temporaryValue = "";
}
return values;
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split
* @param {string} name lowercase header name
* @param {import('./headers').HeadersList} list
*/
function getDecodeSplit$1(name, list$1) {
const value = list$1.get(name, true);
if (value === null) return null;
return gettingDecodingSplitting(value);
}
function hasAuthenticationEntry$1(request$2) {
return false;
}
/**
* @see https://url.spec.whatwg.org/#include-credentials
* @param {URL} url
*/
function includesCredentials$1(url) {
return !!(url.username || url.password);
}
/**
* @see https://html.spec.whatwg.org/multipage/document-sequences.html#traversable-navigable
* @param {object|string} navigable
*/
function isTraversableNavigable$1(navigable) {
return navigable != null && navigable !== "client" && navigable !== "no-traversable";
}
var EnvironmentSettingsObjectBase = class {
get baseUrl() {
return getGlobalOrigin$1();
}
get origin() {
return this.baseUrl?.origin;
}
policyContainer = makePolicyContainer$1();
};
var EnvironmentSettingsObject = class {
settingsObject = new EnvironmentSettingsObjectBase();
};
const environmentSettingsObject$4 = new EnvironmentSettingsObject();
module.exports = {
isAborted: isAborted$4,
isCancelled: isCancelled$2,
isValidEncodedURL,
ReadableStreamFrom: ReadableStreamFrom$2,
tryUpgradeRequestToAPotentiallyTrustworthyURL: tryUpgradeRequestToAPotentiallyTrustworthyURL$1,
clampAndCoarsenConnectionTimingInfo: clampAndCoarsenConnectionTimingInfo$1,
coarsenedSharedCurrentTime: coarsenedSharedCurrentTime$1,
determineRequestsReferrer: determineRequestsReferrer$1,
makePolicyContainer: makePolicyContainer$1,
clonePolicyContainer: clonePolicyContainer$1,
appendFetchMetadata: appendFetchMetadata$1,
appendRequestOriginHeader: appendRequestOriginHeader$1,
TAOCheck: TAOCheck$1,
corsCheck: corsCheck$1,
crossOriginResourcePolicyCheck: crossOriginResourcePolicyCheck$1,
createOpaqueTimingInfo: createOpaqueTimingInfo$1,
setRequestReferrerPolicyOnRedirect: setRequestReferrerPolicyOnRedirect$1,
isValidHTTPToken: isValidHTTPToken$1,
requestBadPort: requestBadPort$1,
requestCurrentURL: requestCurrentURL$1,
responseURL,
responseLocationURL: responseLocationURL$1,
isURLPotentiallyTrustworthy,
isValidReasonPhrase: isValidReasonPhrase$1,
sameOrigin: sameOrigin$2,
normalizeMethod,
iteratorMixin: iteratorMixin$2,
createIterator,
isValidHeaderName: isValidHeaderName$2,
isValidHeaderValue: isValidHeaderValue$1,
isErrorLike: isErrorLike$2,
fullyReadBody: fullyReadBody$2,
readableStreamClose: readableStreamClose$2,
urlIsLocal: urlIsLocal$1,
urlHasHttpsScheme: urlHasHttpsScheme$1,
urlIsHttpHttpsScheme: urlIsHttpHttpsScheme$2,
readAllBytes: readAllBytes$1,
simpleRangeHeaderValue: simpleRangeHeaderValue$1,
buildContentRange: buildContentRange$1,
createInflate: createInflate$2,
extractMimeType: extractMimeType$2,
getDecodeSplit: getDecodeSplit$1,
environmentSettingsObject: environmentSettingsObject$4,
isOriginIPPotentiallyTrustworthy,
hasAuthenticationEntry: hasAuthenticationEntry$1,
includesCredentials: includesCredentials$1,
isTraversableNavigable: isTraversableNavigable$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/formdata.js
var require_formdata = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/formdata.js": ((exports, module) => {
const { iteratorMixin: iteratorMixin$1 } = require_util$4();
const { kEnumerableProperty: kEnumerableProperty$10 } = require_util$5();
const { webidl: webidl$14 } = require_webidl();
const nodeUtil$2 = __require$2("node:util");
var FormData$2 = class FormData$2 {
#state = [];
constructor(form = void 0) {
webidl$14.util.markAsUncloneable(this);
if (form !== void 0) throw webidl$14.errors.conversionFailed({
prefix: "FormData constructor",
argument: "Argument 1",
types: ["undefined"]
});
}
append(name, value, filename = void 0) {
webidl$14.brandCheck(this, FormData$2);
const prefix = "FormData.append";
webidl$14.argumentLengthCheck(arguments, 2, prefix);
name = webidl$14.converters.USVString(name);
if (arguments.length === 3 || webidl$14.is.Blob(value)) {
value = webidl$14.converters.Blob(value, prefix, "value");
if (filename !== void 0) filename = webidl$14.converters.USVString(filename);
} else value = webidl$14.converters.USVString(value);
const entry = makeEntry$1(name, value, filename);
this.#state.push(entry);
}
delete(name) {
webidl$14.brandCheck(this, FormData$2);
webidl$14.argumentLengthCheck(arguments, 1, "FormData.delete");
name = webidl$14.converters.USVString(name);
this.#state = this.#state.filter((entry) => entry.name !== name);
}
get(name) {
webidl$14.brandCheck(this, FormData$2);
webidl$14.argumentLengthCheck(arguments, 1, "FormData.get");
name = webidl$14.converters.USVString(name);
const idx = this.#state.findIndex((entry) => entry.name === name);
if (idx === -1) return null;
return this.#state[idx].value;
}
getAll(name) {
webidl$14.brandCheck(this, FormData$2);
webidl$14.argumentLengthCheck(arguments, 1, "FormData.getAll");
name = webidl$14.converters.USVString(name);
return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value);
}
has(name) {
webidl$14.brandCheck(this, FormData$2);
webidl$14.argumentLengthCheck(arguments, 1, "FormData.has");
name = webidl$14.converters.USVString(name);
return this.#state.findIndex((entry) => entry.name === name) !== -1;
}
set(name, value, filename = void 0) {
webidl$14.brandCheck(this, FormData$2);
const prefix = "FormData.set";
webidl$14.argumentLengthCheck(arguments, 2, prefix);
name = webidl$14.converters.USVString(name);
if (arguments.length === 3 || webidl$14.is.Blob(value)) {
value = webidl$14.converters.Blob(value, prefix, "value");
if (filename !== void 0) filename = webidl$14.converters.USVString(filename);
} else value = webidl$14.converters.USVString(value);
const entry = makeEntry$1(name, value, filename);
const idx = this.#state.findIndex((entry$1) => entry$1.name === name);
if (idx !== -1) this.#state = [
...this.#state.slice(0, idx),
entry,
...this.#state.slice(idx + 1).filter((entry$1) => entry$1.name !== name)
];
else this.#state.push(entry);
}
[nodeUtil$2.inspect.custom](depth$1, options) {
const state = this.#state.reduce((a, b) => {
if (a[b.name]) if (Array.isArray(a[b.name])) a[b.name].push(b.value);
else a[b.name] = [a[b.name], b.value];
else a[b.name] = b.value;
return a;
}, { __proto__: null });
options.depth ??= depth$1;
options.colors ??= true;
const output = nodeUtil$2.formatWithOptions(options, state);
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;
}
};
const { getFormDataState, setFormDataState: setFormDataState$1 } = FormData$2;
Reflect.deleteProperty(FormData$2, "getFormDataState");
Reflect.deleteProperty(FormData$2, "setFormDataState");
iteratorMixin$1("FormData", FormData$2, getFormDataState, "name", "value");
Object.defineProperties(FormData$2.prototype, {
append: kEnumerableProperty$10,
delete: kEnumerableProperty$10,
get: kEnumerableProperty$10,
getAll: kEnumerableProperty$10,
has: kEnumerableProperty$10,
set: kEnumerableProperty$10,
[Symbol.toStringTag]: {
value: "FormData",
configurable: true
}
});
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
* @param {string} name
* @param {string|Blob} value
* @param {?string} filename
* @returns
*/
function makeEntry$1(name, value, filename) {
if (typeof value === "string") {} else {
if (!webidl$14.is.File(value)) value = new File([value], "blob", { type: value.type });
if (filename !== void 0) {
/** @type {FilePropertyBag} */
const options = {
type: value.type,
lastModified: value.lastModified
};
value = new File([value], filename, options);
}
}
return {
name,
value
};
}
webidl$14.is.FormData = webidl$14.util.MakeTypeAssertion(FormData$2);
module.exports = {
FormData: FormData$2,
makeEntry: makeEntry$1,
setFormDataState: setFormDataState$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/formdata-parser.js": ((exports, module) => {
const { bufferToLowerCasedHeaderName: bufferToLowerCasedHeaderName$1 } = require_util$5();
const { HTTP_TOKEN_CODEPOINTS } = require_data_url();
const { makeEntry } = require_formdata();
const { webidl: webidl$13 } = require_webidl();
const assert$26 = __require$2("node:assert");
const { isomorphicDecode } = require_infra();
const dd = Buffer.from("--");
const decoder = new TextDecoder();
const decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
/**
* @param {string} chars
*/
function isAsciiString(chars$1) {
for (let i$1 = 0; i$1 < chars$1.length; ++i$1) if ((chars$1.charCodeAt(i$1) & -128) !== 0) return false;
return true;
}
/**
* @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary
* @param {string} boundary
*/
function validateBoundary(boundary) {
const length = boundary.length;
if (length < 27 || length > 70) return false;
for (let i$1 = 0; i$1 < length; ++i$1) {
const cp = boundary.charCodeAt(i$1);
if (!(cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 39 || cp === 45 || cp === 95)) return false;
}
return true;
}
/**
* @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser
* @param {Buffer} input
* @param {ReturnType<import('./data-url')['parseMIMEType']>} mimeType
*/
function multipartFormDataParser$1(input, mimeType) {
assert$26(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 };
const firstBoundaryIndex = input.indexOf(boundary);
if (firstBoundaryIndex === -1) throw parsingError("no boundary found in multipart body");
position.position = firstBoundaryIndex;
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 (bufferStartsWith(input, dd, position)) return entryList;
if (input[position.position] !== 13 || input[position.position + 1] !== 10) throw parsingError("expected CRLF");
position.position += 2;
let { name, filename, contentType, encoding } = parseMultipartFormDataHeaders(input, position);
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 File([body], filename, { type: contentType });
} else value = decoderIgnoreBOM.decode(Buffer.from(body));
assert$26(webidl$13.is.USVString(name));
assert$26(typeof value === "string" && webidl$13.is.USVString(value) || webidl$13.is.File(value));
entryList.push(makeEntry(name, value, filename));
}
}
/**
* Parses content-disposition attributes (e.g., name="value" or filename*=utf-8''encoded)
* @param {Buffer} input
* @param {{ position: number }} position
* @returns {{ name: string, value: string }}
*/
function parseContentDispositionAttribute(input, position) {
if (input[position.position] === 59) position.position++;
collectASequenceOfBytes((char) => char === 32 || char === 9, input, position);
const attributeName = collectASequenceOfBytes((char) => isToken(char) && char !== 61 && char !== 42, input, position);
if (attributeName.length === 0) return null;
const attrNameStr = attributeName.toString("ascii").toLowerCase();
const isExtended = input[position.position] === 42;
if (isExtended) position.position++;
if (input[position.position] !== 61) return null;
position.position++;
collectASequenceOfBytes((char) => char === 32 || char === 9, input, position);
let value;
if (isExtended) {
const headerValue = collectASequenceOfBytes((char) => char !== 32 && char !== 13 && char !== 10 && char !== 59, input, position);
if (headerValue[0] !== 117 && headerValue[0] !== 85 || headerValue[1] !== 116 && headerValue[1] !== 84 || headerValue[2] !== 102 && headerValue[2] !== 70 || headerValue[3] !== 45 || headerValue[4] !== 56) throw parsingError("unknown encoding, expected utf-8''");
value = decodeURIComponent(decoder.decode(headerValue.subarray(7)));
} else if (input[position.position] === 34) {
position.position++;
const quotedValue = collectASequenceOfBytes((char) => char !== 10 && char !== 13 && char !== 34, input, position);
if (input[position.position] !== 34) throw parsingError("Closing quote not found");
position.position++;
value = decoder.decode(quotedValue).replace(/%0A/gi, "\n").replace(/%0D/gi, "\r").replace(/%22/g, "\"");
} else {
const tokenValue = collectASequenceOfBytes((char) => isToken(char) && char !== 59, input, position);
value = decoder.decode(tokenValue);
}
return {
name: attrNameStr,
value
};
}
/**
* @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers
* @param {Buffer} input
* @param {{ position: number }} position
*/
function parseMultipartFormDataHeaders(input, position) {
let name = null;
let filename = null;
let contentType = null;
let encoding = null;
while (true) {
if (input[position.position] === 13 && input[position.position + 1] === 10) {
if (name === null) throw parsingError("header name is null");
return {
name,
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$1(headerName)) {
case "content-disposition":
name = filename = null;
if (collectASequenceOfBytes((char) => isToken(char), input, position).toString("ascii").toLowerCase() !== "form-data") throw parsingError("expected form-data for content-disposition header");
while (position.position < input.length && input[position.position] !== 13 && input[position.position + 1] !== 10) {
const attribute = parseContentDispositionAttribute(input, position);
if (!attribute) break;
if (attribute.name === "name") name = attribute.value;
else if (attribute.name === "filename") filename = attribute.value;
}
if (name === null) throw parsingError("name attribute is required in content-disposition header");
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;
}
}
/**
* @param {(char: number) => boolean} condition
* @param {Buffer} input
* @param {{ position: number }} position
*/
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);
}
/**
* @param {Buffer} buf
* @param {boolean} leading
* @param {boolean} trailing
* @param {(charCode: number) => boolean} predicate
* @returns {Buffer}
*/
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);
}
/**
* Checks if {@param buffer} starts with {@param start}
* @param {Buffer} buffer
* @param {Buffer} start
* @param {{ position: number }} position
*/
function bufferStartsWith(buffer$1, start, position) {
if (buffer$1.length < start.length) return false;
for (let i$1 = 0; i$1 < start.length; i$1++) if (start[i$1] !== buffer$1[position.position + i$1]) return false;
return true;
}
function parsingError(cause) {
return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
}
/**
* CTL = <any US-ASCII control character
* (octets 0 - 31) and DEL (127)>
* @param {number} char
*/
function isCTL(char) {
return char <= 31 || char === 127;
}
/**
* tspecials := "(" / ")" / "<" / ">" / "@" /
* "," / ";" / ":" / "\" / <">
* "/" / "[" / "]" / "?" / "="
* ; Must be in quoted-string,
* ; to use within parameter values
* @param {number} char
*/
function isTSpecial(char) {
return char === 40 || char === 41 || char === 60 || char === 62 || char === 64 || char === 44 || char === 59 || char === 58 || char === 92 || char === 34 || char === 47 || char === 91 || char === 93 || char === 63 || char === 61;
}
/**
* token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
* or tspecials>
* @param {number} char
*/
function isToken(char) {
return char <= 127 && char !== 32 && char !== 9 && !isCTL(char) && !isTSpecial(char);
}
module.exports = {
multipartFormDataParser: multipartFormDataParser$1,
validateBoundary
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/promise.js
var require_promise = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/promise.js": ((exports, module) => {
/**
* @template {*} T
* @typedef {Object} DeferredPromise
* @property {Promise<T>} promise
* @property {(value?: T) => void} resolve
* @property {(reason?: any) => void} reject
*/
/**
* @template {*} T
* @returns {DeferredPromise<T>} An object containing a promise and its resolve/reject methods.
*/
function createDeferredPromise$4() {
let res;
let rej;
return {
promise: new Promise((resolve$4, reject) => {
res = resolve$4;
rej = reject;
}),
resolve: res,
reject: rej
};
}
module.exports = { createDeferredPromise: createDeferredPromise$4 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/body.js
var require_body = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/body.js": ((exports, module) => {
const util$24 = require_util$5();
const { ReadableStreamFrom: ReadableStreamFrom$1, readableStreamClose: readableStreamClose$1, fullyReadBody: fullyReadBody$1, extractMimeType: extractMimeType$1 } = require_util$4();
const { FormData: FormData$1, setFormDataState } = require_formdata();
const { webidl: webidl$12 } = require_webidl();
const assert$25 = __require$2("node:assert");
const { isErrored: isErrored$1, isDisturbed: isDisturbed$2 } = __require$2("node:stream");
const { isUint8Array } = __require$2("node:util/types");
const { serializeAMimeType: serializeAMimeType$2 } = require_data_url();
const { multipartFormDataParser } = require_formdata_parser();
const { createDeferredPromise: createDeferredPromise$3 } = require_promise();
const { parseJSONFromBytes } = require_infra();
const { utf8DecodeBytes: utf8DecodeBytes$1 } = require_encoding();
const { runtimeFeatures: runtimeFeatures$6 } = require_runtime_features();
const random = runtimeFeatures$6.has("crypto") ? __require$2("node:crypto").randomInt : (max) => Math.floor(Math.random() * max);
const textEncoder$1 = new TextEncoder();
function noop$8() {}
const streamRegistry$1 = new FinalizationRegistry((weakRef) => {
const stream$2 = weakRef.deref();
if (stream$2 && !stream$2.locked && !isDisturbed$2(stream$2) && !isErrored$1(stream$2)) stream$2.cancel("Response object has been garbage collected").catch(noop$8);
});
/**
* Extract a body with type from a byte sequence or BodyInit object
*
* @param {import('../../../types').BodyInit} object - The BodyInit object to extract from
* @param {boolean} [keepalive=false] - If true, indicates that the body
* @returns {[{stream: ReadableStream, source: any, length: number | null}, string | null]} - Returns a tuple containing the body and its type
*
* @see https://fetch.spec.whatwg.org/#concept-bodyinit-extract
*/
function extractBody$5(object, keepalive = false) {
let stream$2 = null;
let controller = null;
if (webidl$12.is.ReadableStream(object)) stream$2 = object;
else if (webidl$12.is.Blob(object)) stream$2 = object.stream();
else stream$2 = new ReadableStream({
pull() {},
start(c) {
controller = c;
},
cancel() {},
type: "bytes"
});
assert$25(webidl$12.is.ReadableStream(stream$2));
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$12.is.URLSearchParams(object)) {
source = object.toString();
type = "application/x-www-form-urlencoded;charset=UTF-8";
} else if (webidl$12.is.BufferSource(object)) source = webidl$12.util.getCopyOfBytesHeldByBufferSource(object);
else if (webidl$12.is.FormData(object)) {
const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
const prefix = `--${boundary}\r\nContent-Disposition: form-data`;
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
const formdataEscape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n");
const blobParts = [];
const rn = new Uint8Array([13, 10]);
length = 0;
let hasUnknownSizeValue = false;
for (const [name, value] of object) if (typeof value === "string") {
const chunk$1 = textEncoder$1.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name))}"\r\n\r\n${normalizeLinefeeds(value)}\r\n`);
blobParts.push(chunk$1);
length += chunk$1.byteLength;
} else {
const chunk$1 = textEncoder$1.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
Content-Type: ${value.type || "application/octet-stream"}\r\n\r\n`);
blobParts.push(chunk$1, value, rn);
if (typeof value.size === "number") length += chunk$1.byteLength + value.size + rn.byteLength;
else hasUnknownSizeValue = true;
}
const chunk = textEncoder$1.encode(`--${boundary}--\r\n`);
blobParts.push(chunk);
length += chunk.byteLength;
if (hasUnknownSizeValue) length = null;
source = object;
action = async function* () {
for (const part of blobParts) if (part.stream) yield* part.stream();
else yield part;
};
type = `multipart/form-data; boundary=${boundary}`;
} else if (webidl$12.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 (util$24.isDisturbed(object) || object.locked) throw new TypeError("Response body object should not be disturbed or locked");
stream$2 = webidl$12.is.ReadableStream(object) ? object : ReadableStreamFrom$1(object);
}
if (typeof source === "string" || isUint8Array(source)) action = () => {
length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
return source;
};
if (action != null) (async () => {
const result = action();
const iterator = result?.[Symbol.asyncIterator]?.();
if (iterator) for await (const bytes of iterator) {
if (isErrored$1(stream$2)) break;
if (bytes.length) controller.enqueue(new Uint8Array(bytes));
}
else if (result?.length && !isErrored$1(stream$2)) controller.enqueue(typeof result === "string" ? textEncoder$1.encode(result) : new Uint8Array(result));
queueMicrotask(() => readableStreamClose$1(controller));
})();
return [{
stream: stream$2,
source,
length
}, type];
}
/**
* @typedef {object} ExtractBodyResult
* @property {ReadableStream<Uint8Array<ArrayBuffer>>} stream - The ReadableStream containing the body data
* @property {any} source - The original source of the body data
* @property {number | null} length - The length of the body data, or null
*/
/**
* Safely extract a body with type from a byte sequence or BodyInit object.
*
* @param {import('../../../types').BodyInit} object - The BodyInit object to extract from
* @param {boolean} [keepalive=false] - If true, indicates that the body
* @returns {[ExtractBodyResult, string | null]} - Returns a tuple containing the body and its type
*
* @see https://fetch.spec.whatwg.org/#bodyinit-safely-extract
*/
function safelyExtractBody$1(object, keepalive = false) {
if (webidl$12.is.ReadableStream(object)) {
assert$25(!util$24.isDisturbed(object), "The body has already been consumed.");
assert$25(!object.locked, "The stream is locked.");
}
return extractBody$5(object, keepalive);
}
function cloneBody$2(body) {
const { 0: out1, 1: out2 } = body.stream.tee();
body.stream = out1;
return {
stream: out2,
length: body.length,
source: body.source
};
}
function bodyMixinMethods(instance$1, getInternalState) {
return {
blob() {
return consumeBody(this, (bytes) => {
let mimeType = bodyMimeType(getInternalState(this));
if (mimeType === null) mimeType = "";
else if (mimeType) mimeType = serializeAMimeType$2(mimeType);
return new Blob([bytes], { type: mimeType });
}, instance$1, getInternalState);
},
arrayBuffer() {
return consumeBody(this, (bytes) => {
return new Uint8Array(bytes).buffer;
}, instance$1, getInternalState);
},
text() {
return consumeBody(this, utf8DecodeBytes$1, instance$1, getInternalState);
},
json() {
return consumeBody(this, parseJSONFromBytes, instance$1, 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 FormData$1();
setFormDataState(fd, parsed);
return fd;
}
case "application/x-www-form-urlencoded": {
const entries = new URLSearchParams(value.toString());
const fd = new FormData$1();
for (const [name, value$1] of entries) fd.append(name, value$1);
return fd;
}
}
throw new TypeError("Content-Type was not one of \"multipart/form-data\" or \"application/x-www-form-urlencoded\".");
}, instance$1, getInternalState);
},
bytes() {
return consumeBody(this, (bytes) => {
return new Uint8Array(bytes);
}, instance$1, getInternalState);
}
};
}
function mixinBody$2(prototype, getInternalState) {
Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
}
/**
* @see https://fetch.spec.whatwg.org/#concept-body-consume-body
* @param {any} object internal state
* @param {(value: unknown) => unknown} convertBytesToJSValue
* @param {any} instance
* @param {(target: any) => any} getInternalState
*/
function consumeBody(object, convertBytesToJSValue, instance$1, getInternalState) {
try {
webidl$12.brandCheck(object, instance$1);
} catch (e) {
return Promise.reject(e);
}
object = getInternalState(object);
if (bodyUnusable$2(object)) return Promise.reject(/* @__PURE__ */ new TypeError("Body is unusable: Body has already been read"));
const promise$1 = createDeferredPromise$3();
const errorSteps = promise$1.reject;
const successSteps = (data$1) => {
try {
promise$1.resolve(convertBytesToJSValue(data$1));
} catch (e) {
errorSteps(e);
}
};
if (object.body == null) {
successSteps(Buffer.allocUnsafe(0));
return promise$1.promise;
}
fullyReadBody$1(object.body, successSteps, errorSteps);
return promise$1.promise;
}
/**
* @see https://fetch.spec.whatwg.org/#body-unusable
* @param {any} object internal state
*/
function bodyUnusable$2(object) {
const body = object.body;
return body != null && (body.stream.locked || util$24.isDisturbed(body.stream));
}
/**
* @see https://fetch.spec.whatwg.org/#concept-body-mime-type
* @param {any} requestOrResponse internal state
*/
function bodyMimeType(requestOrResponse) {
/** @type {import('./headers').HeadersList} */
const headers = requestOrResponse.headersList;
const mimeType = extractMimeType$1(headers);
if (mimeType === "failure") return null;
return mimeType;
}
module.exports = {
extractBody: extractBody$5,
safelyExtractBody: safelyExtractBody$1,
cloneBody: cloneBody$2,
mixinBody: mixinBody$2,
streamRegistry: streamRegistry$1,
bodyUnusable: bodyUnusable$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client-h1.js": ((exports, module) => {
const assert$24 = __require$2("node:assert");
const util$23 = require_util$5();
const { channels: channels$5 } = require_diagnostics();
const timers = require_timers();
const { RequestContentLengthMismatchError: RequestContentLengthMismatchError$1, ResponseContentLengthMismatchError, RequestAbortedError: RequestAbortedError$8, HeadersTimeoutError, HeadersOverflowError, SocketError: SocketError$3, InformationalError: InformationalError$3, BodyTimeoutError, HTTPParserError, ResponseExceededMaxSizeError } = require_errors();
const { kUrl: kUrl$7, kReset: kReset$1, kClient: kClient$3, kParser, kBlocking, kRunning: kRunning$4, kPending: kPending$3, kSize: kSize$4, kWriting, kQueue: kQueue$3, kNoRef, kKeepAliveDefaultTimeout: kKeepAliveDefaultTimeout$1, kHostHeader: kHostHeader$1, kPendingIdx: kPendingIdx$2, kRunningIdx: kRunningIdx$2, kError: kError$2, kPipelining: kPipelining$1, kSocket: kSocket$1, kKeepAliveTimeoutValue: kKeepAliveTimeoutValue$1, kMaxHeadersSize: kMaxHeadersSize$1, kKeepAliveMaxTimeout: kKeepAliveMaxTimeout$1, kKeepAliveTimeoutThreshold: kKeepAliveTimeoutThreshold$1, kHeadersTimeout: kHeadersTimeout$1, kBodyTimeout: kBodyTimeout$2, kStrictContentLength: kStrictContentLength$2, kMaxRequests: kMaxRequests$1, kCounter: kCounter$1, kMaxResponseSize: kMaxResponseSize$1, kOnError: kOnError$2, kResume: kResume$3, kHTTPContext: kHTTPContext$2, kClosed: kClosed$2 } = require_symbols();
const constants$4 = require_constants$4();
const EMPTY_BUF = Buffer.alloc(0);
const FastBuffer = Buffer[Symbol.species];
const removeAllListeners = util$23.removeAllListeners;
let extractBody$4;
function lazyllhttp() {
const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
let mod;
let useWasmSIMD = process.arch !== "ppc64";
if (process.env.UNDICI_NO_WASM_SIMD === "1") useWasmSIMD = true;
else if (process.env.UNDICI_NO_WASM_SIMD === "0") useWasmSIMD = false;
if (useWasmSIMD) try {
mod = new WebAssembly.Module(require_llhttp_simd_wasm());
} catch {}
if (!mod) mod = new WebAssembly.Module(llhttpWasmData || require_llhttp_wasm());
return new WebAssembly.Instance(mod, { env: {
wasm_on_url: (p$1, at, len) => {
return 0;
},
wasm_on_status: (p$1, at, len) => {
assert$24(currentParser.ptr === p$1);
const start = at - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
},
wasm_on_message_begin: (p$1) => {
assert$24(currentParser.ptr === p$1);
return currentParser.onMessageBegin();
},
wasm_on_header_field: (p$1, at, len) => {
assert$24(currentParser.ptr === p$1);
const start = at - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
},
wasm_on_header_value: (p$1, at, len) => {
assert$24(currentParser.ptr === p$1);
const start = at - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
},
wasm_on_headers_complete: (p$1, statusCode, upgrade$1, shouldKeepAlive) => {
assert$24(currentParser.ptr === p$1);
return currentParser.onHeadersComplete(statusCode, upgrade$1 === 1, shouldKeepAlive === 1);
},
wasm_on_body: (p$1, at, len) => {
assert$24(currentParser.ptr === p$1);
const start = at - currentBufferPtr + currentBufferRef.byteOffset;
return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
},
wasm_on_message_complete: (p$1) => {
assert$24(currentParser.ptr === p$1);
return currentParser.onMessageComplete();
}
} });
}
let llhttpInstance = null;
/**
* @type {Parser|null}
*/
let currentParser = null;
let currentBufferRef = null;
/**
* @type {number}
*/
let currentBufferSize = 0;
let currentBufferPtr = null;
const USE_NATIVE_TIMER = 0;
const USE_FAST_TIMER = 1;
const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER;
const TIMEOUT_BODY = 4 | USE_FAST_TIMER;
const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER;
var Parser$1 = class {
/**
* @param {import('./client.js')} client
* @param {import('net').Socket} socket
* @param {*} llhttp
*/
constructor(client, socket, { exports: exports$1 }) {
this.llhttp = exports$1;
this.ptr = this.llhttp.llhttp_alloc(constants$4.TYPE.RESPONSE);
this.client = client;
/**
* @type {import('net').Socket}
*/
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$1];
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$1];
}
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;
assert$24(this.ptr != null);
assert$24(currentParser === null);
this.llhttp.llhttp_resume(this.ptr);
assert$24(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) {
assert$24(currentParser === null);
assert$24(this.ptr != null);
assert$24(!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);
} finally {
currentParser = null;
currentBufferRef = null;
}
if (ret !== constants$4.ERROR.OK) {
const data$1 = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
if (ret === constants$4.ERROR.PAUSED_UPGRADE) this.onUpgrade(data$1);
else if (ret === constants$4.ERROR.PAUSED) {
this.paused = true;
socket.unshift(data$1);
} 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, constants$4.ERROR[ret], data$1);
}
}
} catch (err) {
util$23.destroy(socket, err);
}
}
destroy() {
assert$24(currentParser === null);
assert$24(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 request$2 = client[kQueue$3][client[kRunningIdx$2]];
if (!request$2) return -1;
request$2.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 = util$23.bufferToLowerCasedHeaderName(key);
if (headerName === "keep-alive") this.keepAlive += buf.toString();
else if (headerName === "connection") this.connection += buf.toString();
} else if (key.length === 14 && util$23.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) util$23.destroy(this.socket, new HeadersOverflowError());
}
/**
* @param {Buffer} head
*/
onUpgrade(head) {
const { upgrade: upgrade$1, client, socket, headers, statusCode } = this;
assert$24(upgrade$1);
assert$24(client[kSocket$1] === socket);
assert$24(!socket.destroyed);
assert$24(!this.paused);
assert$24((headers.length & 1) === 0);
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
assert$24(request$2);
assert$24(request$2.upgrade || request$2.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$3] = null;
socket[kError$2] = null;
removeAllListeners(socket);
client[kSocket$1] = null;
client[kHTTPContext$2] = null;
client[kQueue$3][client[kRunningIdx$2]++] = null;
client.emit("disconnect", client[kUrl$7], [client], new InformationalError$3("upgrade"));
try {
request$2.onUpgrade(statusCode, headers, socket);
} catch (err) {
util$23.destroy(socket, err);
}
client[kResume$3]();
}
/**
* @param {number} statusCode
* @param {boolean} upgrade
* @param {boolean} shouldKeepAlive
* @returns {number}
*/
onHeadersComplete(statusCode, upgrade$1, shouldKeepAlive) {
const { client, socket, headers, statusText } = this;
if (socket.destroyed) return -1;
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
if (!request$2) return -1;
assert$24(!this.upgrade);
assert$24(this.statusCode < 200);
if (statusCode === 100) {
util$23.destroy(socket, new SocketError$3("bad response", util$23.getSocketInfo(socket)));
return -1;
}
if (upgrade$1 && !request$2.upgrade) {
util$23.destroy(socket, new SocketError$3("bad upgrade", util$23.getSocketInfo(socket)));
return -1;
}
assert$24(this.timeoutType === TIMEOUT_HEADERS);
this.statusCode = statusCode;
this.shouldKeepAlive = shouldKeepAlive || request$2.method === "HEAD" && !socket[kReset$1] && this.connection.toLowerCase() === "keep-alive";
if (this.statusCode >= 200) {
const bodyTimeout = request$2.bodyTimeout != null ? request$2.bodyTimeout : client[kBodyTimeout$2];
this.setTimeout(bodyTimeout, TIMEOUT_BODY);
} else if (this.timeout) {
if (this.timeout.refresh) this.timeout.refresh();
}
if (request$2.method === "CONNECT") {
assert$24(client[kRunning$4] === 1);
this.upgrade = true;
return 2;
}
if (upgrade$1) {
assert$24(client[kRunning$4] === 1);
this.upgrade = true;
return 2;
}
assert$24((this.headers.length & 1) === 0);
this.headers = [];
this.headersSize = 0;
if (this.shouldKeepAlive && client[kPipelining$1]) {
const keepAliveTimeout = this.keepAlive ? util$23.parseKeepAliveTimeout(this.keepAlive) : null;
if (keepAliveTimeout != null) {
const timeout$1 = Math.min(keepAliveTimeout - client[kKeepAliveTimeoutThreshold$1], client[kKeepAliveMaxTimeout$1]);
if (timeout$1 <= 0) socket[kReset$1] = true;
else client[kKeepAliveTimeoutValue$1] = timeout$1;
} else client[kKeepAliveTimeoutValue$1] = client[kKeepAliveDefaultTimeout$1];
} else socket[kReset$1] = true;
const pause = request$2.onHeaders(statusCode, headers, this.resume, statusText) === false;
if (request$2.aborted) return -1;
if (request$2.method === "HEAD") return 1;
if (statusCode < 200) return 1;
if (socket[kBlocking]) {
socket[kBlocking] = false;
client[kResume$3]();
}
return pause ? constants$4.ERROR.PAUSED : 0;
}
/**
* @param {Buffer} buf
* @returns {number}
*/
onBody(buf) {
const { client, socket, statusCode, maxResponseSize } = this;
if (socket.destroyed) return -1;
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
assert$24(request$2);
assert$24(this.timeoutType === TIMEOUT_BODY);
if (this.timeout) {
if (this.timeout.refresh) this.timeout.refresh();
}
assert$24(statusCode >= 200);
if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
util$23.destroy(socket, new ResponseExceededMaxSizeError());
return -1;
}
this.bytesRead += buf.length;
if (request$2.onData(buf) === false) return constants$4.ERROR.PAUSED;
return 0;
}
/**
* @returns {number}
*/
onMessageComplete() {
const { client, socket, statusCode, upgrade: upgrade$1, headers, contentLength, bytesRead, shouldKeepAlive } = this;
if (socket.destroyed && (!statusCode || shouldKeepAlive)) return -1;
if (upgrade$1) return 0;
assert$24(statusCode >= 100);
assert$24((this.headers.length & 1) === 0);
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
assert$24(request$2);
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 (request$2.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
util$23.destroy(socket, new ResponseContentLengthMismatchError());
return -1;
}
request$2.onComplete(headers);
client[kQueue$3][client[kRunningIdx$2]++] = null;
if (socket[kWriting]) {
assert$24(client[kRunning$4] === 0);
util$23.destroy(socket, new InformationalError$3("reset"));
return constants$4.ERROR.PAUSED;
} else if (!shouldKeepAlive) {
util$23.destroy(socket, new InformationalError$3("reset"));
return constants$4.ERROR.PAUSED;
} else if (socket[kReset$1] && client[kRunning$4] === 0) {
util$23.destroy(socket, new InformationalError$3("reset"));
return constants$4.ERROR.PAUSED;
} else if (client[kPipelining$1] == null || client[kPipelining$1] === 1) setImmediate(client[kResume$3]);
else client[kResume$3]();
return 0;
}
};
function onParserTimeout(parserWeakRef) {
const parser = parserWeakRef.deref();
if (!parser) return;
const { socket, timeoutType, client, paused } = parser;
if (timeoutType === TIMEOUT_HEADERS) {
if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning$4] > 1) {
assert$24(!paused, "cannot be paused while waiting for headers");
util$23.destroy(socket, new HeadersTimeoutError());
}
} else if (timeoutType === TIMEOUT_BODY) {
if (!paused) util$23.destroy(socket, new BodyTimeoutError());
} else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
assert$24(client[kRunning$4] === 0 && client[kKeepAliveTimeoutValue$1]);
util$23.destroy(socket, new InformationalError$3("socket idle timeout"));
}
}
/**
* @param {import ('./client.js')} client
* @param {import('net').Socket} socket
* @returns
*/
function connectH1$1(client, socket) {
client[kSocket$1] = socket;
if (!llhttpInstance) llhttpInstance = lazyllhttp();
if (socket.errored) throw socket.errored;
if (socket.destroyed) throw new SocketError$3("destroyed");
socket[kNoRef] = false;
socket[kWriting] = false;
socket[kReset$1] = false;
socket[kBlocking] = false;
socket[kParser] = new Parser$1(client, socket, llhttpInstance);
util$23.addListener(socket, "error", onHttpSocketError);
util$23.addListener(socket, "readable", onHttpSocketReadable);
util$23.addListener(socket, "end", onHttpSocketEnd);
util$23.addListener(socket, "close", onHttpSocketClose);
socket[kClosed$2] = false;
socket.on("close", onSocketClose$1);
return {
version: "h1",
defaultPipelining: 1,
write(request$2) {
return writeH1(client, request$2);
},
resume() {
resumeH1(client);
},
destroy(err, callback$1) {
if (socket[kClosed$2]) queueMicrotask(callback$1);
else {
socket.on("close", callback$1);
socket.destroy(err);
}
},
get destroyed() {
return socket.destroyed;
},
busy(request$2) {
if (socket[kWriting] || socket[kReset$1] || socket[kBlocking]) return true;
if (request$2) {
if (client[kRunning$4] > 0 && !request$2.idempotent) return true;
if (client[kRunning$4] > 0 && (request$2.upgrade || request$2.method === "CONNECT")) return true;
if (client[kRunning$4] > 0 && util$23.bodyLength(request$2.body) !== 0 && (util$23.isStream(request$2.body) || util$23.isAsyncIterable(request$2.body) || util$23.isFormDataLike(request$2.body))) return true;
}
return false;
}
};
}
function onHttpSocketError(err) {
assert$24(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
const parser = this[kParser];
if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
parser.onMessageComplete();
return;
}
this[kError$2] = err;
this[kClient$3][kOnError$2](err);
}
function onHttpSocketReadable() {
this[kParser]?.readMore();
}
function onHttpSocketEnd() {
const parser = this[kParser];
if (parser.statusCode && !parser.shouldKeepAlive) {
parser.onMessageComplete();
return;
}
util$23.destroy(this, new SocketError$3("other side closed", util$23.getSocketInfo(this)));
}
function onHttpSocketClose() {
const parser = this[kParser];
if (parser) {
if (!this[kError$2] && parser.statusCode && !parser.shouldKeepAlive) parser.onMessageComplete();
this[kParser].destroy();
this[kParser] = null;
}
const err = this[kError$2] || new SocketError$3("closed", util$23.getSocketInfo(this));
const client = this[kClient$3];
client[kSocket$1] = null;
client[kHTTPContext$2] = null;
if (client.destroyed) {
assert$24(client[kPending$3] === 0);
const requests = client[kQueue$3].splice(client[kRunningIdx$2]);
for (let i$1 = 0; i$1 < requests.length; i$1++) {
const request$2 = requests[i$1];
util$23.errorRequest(client, request$2, err);
}
} else if (client[kRunning$4] > 0 && err.code !== "UND_ERR_INFO") {
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
client[kQueue$3][client[kRunningIdx$2]++] = null;
util$23.errorRequest(client, request$2, err);
}
client[kPendingIdx$2] = client[kRunningIdx$2];
assert$24(client[kRunning$4] === 0);
client.emit("disconnect", client[kUrl$7], [client], err);
client[kResume$3]();
}
function onSocketClose$1() {
this[kClosed$2] = true;
}
/**
* @param {import('./client.js')} client
*/
function resumeH1(client) {
const socket = client[kSocket$1];
if (socket && !socket.destroyed) {
if (client[kSize$4] === 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$4] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) socket[kParser].setTimeout(client[kKeepAliveTimeoutValue$1], TIMEOUT_KEEP_ALIVE);
} else if (client[kRunning$4] > 0 && socket[kParser].statusCode < 200) {
if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
const request$2 = client[kQueue$3][client[kRunningIdx$2]];
const headersTimeout = request$2.headersTimeout != null ? request$2.headersTimeout : client[kHeadersTimeout$1];
socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
}
}
}
}
function shouldSendContentLength$1(method) {
return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
}
/**
* @param {import('./client.js')} client
* @param {import('../core/request.js')} request
* @returns
*/
function writeH1(client, request$2) {
const { method, path: path$2, host, upgrade: upgrade$1, blocking, reset } = request$2;
let { body, headers, contentLength } = request$2;
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
if (util$23.isFormDataLike(body)) {
if (!extractBody$4) extractBody$4 = require_body().extractBody;
const [bodyStream, contentType] = extractBody$4(body);
if (request$2.contentType == null) headers.push("content-type", contentType);
body = bodyStream.stream;
contentLength = bodyStream.length;
} else if (util$23.isBlobLike(body) && request$2.contentType == null && body.type) headers.push("content-type", body.type);
if (body && typeof body.read === "function") body.read(0);
const bodyLength$1 = util$23.bodyLength(body);
contentLength = bodyLength$1 ?? contentLength;
if (contentLength === null) contentLength = request$2.contentLength;
if (contentLength === 0 && !expectsPayload) contentLength = null;
if (shouldSendContentLength$1(method) && contentLength > 0 && request$2.contentLength !== null && request$2.contentLength !== contentLength) {
if (client[kStrictContentLength$2]) {
util$23.errorRequest(client, request$2, new RequestContentLengthMismatchError$1());
return false;
}
process.emitWarning(new RequestContentLengthMismatchError$1());
}
const socket = client[kSocket$1];
/**
* @param {Error} [err]
* @returns {void}
*/
const abort$1 = (err) => {
if (request$2.aborted || request$2.completed) return;
util$23.errorRequest(client, request$2, err || new RequestAbortedError$8());
util$23.destroy(body);
util$23.destroy(socket, new InformationalError$3("aborted"));
};
try {
request$2.onConnect(abort$1);
} catch (err) {
util$23.errorRequest(client, request$2, err);
}
if (request$2.aborted) return false;
if (method === "HEAD") socket[kReset$1] = true;
if (upgrade$1 || method === "CONNECT") socket[kReset$1] = true;
if (reset != null) socket[kReset$1] = reset;
if (client[kMaxRequests$1] && socket[kCounter$1]++ >= client[kMaxRequests$1]) socket[kReset$1] = true;
if (blocking) socket[kBlocking] = true;
if (socket.setTypeOfService) socket.setTypeOfService(request$2.typeOfService);
let header = `${method} ${path$2} HTTP/1.1\r\n`;
if (typeof host === "string") header += `host: ${host}\r\n`;
else header += client[kHostHeader$1];
if (upgrade$1) header += `connection: upgrade\r\nupgrade: ${upgrade$1}\r\n`;
else if (client[kPipelining$1] && !socket[kReset$1]) header += "connection: keep-alive\r\n";
else header += "connection: close\r\n";
if (Array.isArray(headers)) for (let n$1 = 0; n$1 < headers.length; n$1 += 2) {
const key = headers[n$1 + 0];
const val = headers[n$1 + 1];
if (Array.isArray(val)) for (let i$1 = 0; i$1 < val.length; i$1++) header += `${key}: ${val[i$1]}\r\n`;
else header += `${key}: ${val}\r\n`;
}
if (channels$5.sendHeaders.hasSubscribers) channels$5.sendHeaders.publish({
request: request$2,
headers: header,
socket
});
if (!body || bodyLength$1 === 0) writeBuffer$1(abort$1, null, client, request$2, socket, contentLength, header, expectsPayload);
else if (util$23.isBuffer(body)) writeBuffer$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload);
else if (util$23.isBlobLike(body)) if (typeof body.stream === "function") writeIterable$1(abort$1, body.stream(), client, request$2, socket, contentLength, header, expectsPayload);
else writeBlob$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload);
else if (util$23.isStream(body)) writeStream$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload);
else if (util$23.isIterable(body)) writeIterable$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload);
else assert$24(false);
return true;
}
/**
* @param {AbortCallback} abort
* @param {import('stream').Stream} body
* @param {import('./client.js')} client
* @param {import('../core/request.js')} request
* @param {import('net').Socket} socket
* @param {number} contentLength
* @param {string} header
* @param {boolean} expectsPayload
*/
function writeStream$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload) {
assert$24(contentLength !== 0 || client[kRunning$4] === 0, "stream body cannot be pipelined");
let finished$2 = false;
const writer = new AsyncWriter({
abort: abort$1,
socket,
request: request$2,
contentLength,
client,
expectsPayload,
header
});
/**
* @param {Buffer} chunk
* @returns {void}
*/
const onData = function(chunk) {
if (finished$2) return;
try {
if (!writer.write(chunk) && this.pause) this.pause();
} catch (err) {
util$23.destroy(this, err);
}
};
/**
* @returns {void}
*/
const onDrain = function() {
if (finished$2) return;
if (body.resume) body.resume();
};
/**
* @returns {void}
*/
const onClose = function() {
queueMicrotask(() => {
body.removeListener("error", onFinished);
});
if (!finished$2) {
const err = new RequestAbortedError$8();
queueMicrotask(() => onFinished(err));
}
};
/**
* @param {Error} [err]
* @returns
*/
const onFinished = function(err) {
if (finished$2) return;
finished$2 = true;
assert$24(socket.destroyed || socket[kWriting] && client[kRunning$4] <= 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")) util$23.destroy(body, err);
else util$23.destroy(body);
};
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);
}
/**
* @typedef AbortCallback
* @type {Function}
* @param {Error} [err]
* @returns {void}
*/
/**
* @param {AbortCallback} abort
* @param {Uint8Array|null} body
* @param {import('./client.js')} client
* @param {import('../core/request.js')} request
* @param {import('net').Socket} socket
* @param {number} contentLength
* @param {string} header
* @param {boolean} expectsPayload
* @returns {void}
*/
function writeBuffer$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload) {
try {
if (!body) if (contentLength === 0) socket.write(`${header}content-length: 0\r\n\r\n`, "latin1");
else {
assert$24(contentLength === null, "no body must not have content length");
socket.write(`${header}\r\n`, "latin1");
}
else if (util$23.isBuffer(body)) {
assert$24(contentLength === body.byteLength, "buffer body must have content length");
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, "latin1");
socket.write(body);
socket.uncork();
request$2.onBodySent(body);
if (!expectsPayload && request$2.reset !== false) socket[kReset$1] = true;
}
request$2.onRequestSent();
client[kResume$3]();
} catch (err) {
abort$1(err);
}
}
/**
* @param {AbortCallback} abort
* @param {Blob} body
* @param {import('./client.js')} client
* @param {import('../core/request.js')} request
* @param {import('net').Socket} socket
* @param {number} contentLength
* @param {string} header
* @param {boolean} expectsPayload
* @returns {Promise<void>}
*/
async function writeBlob$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload) {
assert$24(contentLength === body.size, "blob body must have content length");
try {
if (contentLength != null && contentLength !== body.size) throw new RequestContentLengthMismatchError$1();
const buffer$1 = Buffer.from(await body.arrayBuffer());
socket.cork();
socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, "latin1");
socket.write(buffer$1);
socket.uncork();
request$2.onBodySent(buffer$1);
request$2.onRequestSent();
if (!expectsPayload && request$2.reset !== false) socket[kReset$1] = true;
client[kResume$3]();
} catch (err) {
abort$1(err);
}
}
/**
* @param {AbortCallback} abort
* @param {Iterable} body
* @param {import('./client.js')} client
* @param {import('../core/request.js')} request
* @param {import('net').Socket} socket
* @param {number} contentLength
* @param {string} header
* @param {boolean} expectsPayload
* @returns {Promise<void>}
*/
async function writeIterable$1(abort$1, body, client, request$2, socket, contentLength, header, expectsPayload) {
assert$24(contentLength !== 0 || client[kRunning$4] === 0, "iterator body cannot be pipelined");
let callback$1 = null;
function onDrain() {
if (callback$1) {
const cb = callback$1;
callback$1 = null;
cb();
}
}
const waitForDrain = () => new Promise((resolve$4, reject) => {
assert$24(callback$1 === null);
if (socket[kError$2]) reject(socket[kError$2]);
else callback$1 = resolve$4;
});
socket.on("close", onDrain).on("drain", onDrain);
const writer = new AsyncWriter({
abort: abort$1,
socket,
request: request$2,
contentLength,
client,
expectsPayload,
header
});
try {
for await (const chunk of body) {
if (socket[kError$2]) throw socket[kError$2];
if (!writer.write(chunk)) await waitForDrain();
}
writer.end();
} catch (err) {
writer.destroy(err);
} finally {
socket.off("close", onDrain).off("drain", onDrain);
}
}
var AsyncWriter = class {
/**
*
* @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: abort$1, socket, request: request$2, contentLength, client, expectsPayload, header }) {
this.socket = socket;
this.request = request$2;
this.contentLength = contentLength;
this.client = client;
this.bytesWritten = 0;
this.expectsPayload = expectsPayload;
this.header = header;
this.abort = abort$1;
socket[kWriting] = true;
}
/**
* @param {Buffer} chunk
* @returns
*/
write(chunk) {
const { socket, request: request$2, contentLength, client, bytesWritten, expectsPayload, header } = this;
if (socket[kError$2]) throw socket[kError$2];
if (socket.destroyed) return false;
const len = Buffer.byteLength(chunk);
if (!len) return true;
if (contentLength !== null && bytesWritten + len > contentLength) {
if (client[kStrictContentLength$2]) throw new RequestContentLengthMismatchError$1();
process.emitWarning(new RequestContentLengthMismatchError$1());
}
socket.cork();
if (bytesWritten === 0) {
if (!expectsPayload && request$2.reset !== false) socket[kReset$1] = true;
if (contentLength === null) socket.write(`${header}transfer-encoding: chunked\r\n`, "latin1");
else socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, "latin1");
}
if (contentLength === null) socket.write(`\r\n${len.toString(16)}\r\n`, "latin1");
this.bytesWritten += len;
const ret = socket.write(chunk);
socket.uncork();
request$2.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: request$2 } = this;
request$2.onRequestSent();
socket[kWriting] = false;
if (socket[kError$2]) throw socket[kError$2];
if (socket.destroyed) return;
if (bytesWritten === 0) if (expectsPayload) socket.write(`${header}content-length: 0\r\n\r\n`, "latin1");
else socket.write(`${header}\r\n`, "latin1");
else if (contentLength === null) socket.write("\r\n0\r\n\r\n", "latin1");
if (contentLength !== null && bytesWritten !== contentLength) if (client[kStrictContentLength$2]) throw new RequestContentLengthMismatchError$1();
else process.emitWarning(new RequestContentLengthMismatchError$1());
if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
if (socket[kParser].timeout.refresh) socket[kParser].timeout.refresh();
}
client[kResume$3]();
}
/**
* @param {Error} [err]
* @returns {void}
*/
destroy(err) {
const { socket, client, abort: abort$1 } = this;
socket[kWriting] = false;
if (err) {
assert$24(client[kRunning$4] <= 1, "pipeline should only contain this request");
abort$1(err);
}
}
};
module.exports = connectH1$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client-h2.js": ((exports, module) => {
const assert$23 = __require$2("node:assert");
const { pipeline: pipeline$4 } = __require$2("node:stream");
const util$22 = require_util$5();
const { RequestContentLengthMismatchError, RequestAbortedError: RequestAbortedError$7, SocketError: SocketError$2, InformationalError: InformationalError$2, InvalidArgumentError: InvalidArgumentError$30 } = require_errors();
const { kUrl: kUrl$6, kReset, kClient: kClient$2, kRunning: kRunning$3, kPending: kPending$2, kQueue: kQueue$2, kPendingIdx: kPendingIdx$1, kRunningIdx: kRunningIdx$1, kError: kError$1, kSocket, kStrictContentLength: kStrictContentLength$1, kOnError: kOnError$1, kMaxConcurrentStreams: kMaxConcurrentStreams$1, kPingInterval: kPingInterval$1, kHTTP2Session, kHTTP2InitialWindowSize: kHTTP2InitialWindowSize$1, kHTTP2ConnectionWindowSize: kHTTP2ConnectionWindowSize$1, kResume: kResume$2, kSize: kSize$3, kHTTPContext: kHTTPContext$1, kClosed: kClosed$1, kBodyTimeout: kBodyTimeout$1, kEnableConnectProtocol, kRemoteSettings, kHTTP2Stream: kHTTP2Stream$1, kHTTP2SessionState } = require_symbols();
const { channels: channels$4 } = require_diagnostics();
const kOpenStreams = Symbol("open streams");
let extractBody$3;
/** @type {import('http2')} */
let http2;
try {
http2 = __require$2("node:http2");
} catch {
http2 = { constants: {} };
}
const { constants: { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_SCHEME, HTTP2_HEADER_CONTENT_LENGTH, HTTP2_HEADER_EXPECT, HTTP2_HEADER_STATUS, HTTP2_HEADER_PROTOCOL, NGHTTP2_REFUSED_STREAM, NGHTTP2_CANCEL } } = http2;
function parseH2Headers(headers) {
const result = [];
for (const [name, value] of Object.entries(headers)) if (Array.isArray(value)) for (const subvalue of value) result.push(Buffer.from(name), Buffer.from(subvalue));
else result.push(Buffer.from(name), Buffer.from(value));
return result;
}
function connectH2$1(client, socket) {
client[kSocket] = socket;
const http2InitialWindowSize = client[kHTTP2InitialWindowSize$1];
const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize$1];
const session = http2.connect(client[kUrl$6], {
createConnection: () => socket,
peerMaxConcurrentStreams: client[kMaxConcurrentStreams$1],
settings: {
enablePush: false,
...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
}
});
client[kSocket] = socket;
session[kOpenStreams] = 0;
session[kClient$2] = client;
session[kSocket] = socket;
session[kHTTP2SessionState] = { ping: { interval: client[kPingInterval$1] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval$1], session).unref() } };
session[kEnableConnectProtocol] = false;
session[kRemoteSettings] = false;
if (http2ConnectionWindowSize) util$22.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
util$22.addListener(session, "error", onHttp2SessionError);
util$22.addListener(session, "frameError", onHttp2FrameError);
util$22.addListener(session, "end", onHttp2SessionEnd);
util$22.addListener(session, "goaway", onHttp2SessionGoAway);
util$22.addListener(session, "close", onHttp2SessionClose);
util$22.addListener(session, "remoteSettings", onHttp2RemoteSettings);
session.unref();
client[kHTTP2Session] = session;
socket[kHTTP2Session] = session;
util$22.addListener(socket, "error", onHttp2SocketError);
util$22.addListener(socket, "end", onHttp2SocketEnd);
util$22.addListener(socket, "close", onHttp2SocketClose);
socket[kClosed$1] = false;
socket.on("close", onSocketClose);
return {
version: "h2",
defaultPipelining: Infinity,
write(request$2) {
return writeH2(client, request$2);
},
resume() {
resumeH2(client);
},
destroy(err, callback$1) {
if (socket[kClosed$1]) queueMicrotask(callback$1);
else socket.destroy(err).on("close", callback$1);
},
get destroyed() {
return socket.destroyed;
},
busy(request$2) {
if (request$2 != null) if (client[kRunning$3] > 0) {
if (request$2.idempotent === false) return true;
if ((request$2.upgrade === "websocket" || request$2.method === "CONNECT") && session[kRemoteSettings] === false) return true;
if (util$22.bodyLength(request$2.body) !== 0 && (util$22.isStream(request$2.body) || util$22.isAsyncIterable(request$2.body) || util$22.isFormDataLike(request$2.body))) return true;
} else return (request$2.upgrade === "websocket" || request$2.method === "CONNECT") && session[kRemoteSettings] === false;
return false;
}
};
}
function resumeH2(client) {
const socket = client[kSocket];
if (socket?.destroyed === false) if (client[kSize$3] === 0 || client[kMaxConcurrentStreams$1] === 0) {
socket.unref();
client[kHTTP2Session].unref();
} else {
socket.ref();
client[kHTTP2Session].ref();
}
}
function applyConnectionWindowSize(connectionWindowSize) {
try {
if (typeof this.setLocalWindowSize === "function") this.setLocalWindowSize(connectionWindowSize);
} catch {}
}
function onHttp2RemoteSettings(settings) {
this[kClient$2][kMaxConcurrentStreams$1] = settings.maxConcurrentStreams ?? this[kClient$2][kMaxConcurrentStreams$1];
/**
* From RFC-8441
* A sender MUST NOT send a SETTINGS_ENABLE_CONNECT_PROTOCOL parameter
* with the value of 0 after previously sending a value of 1.
*/
if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
const err = new InformationalError$2("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441");
this[kSocket][kError$1] = err;
this[kClient$2][kOnError$1](err);
return;
}
this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol];
this[kRemoteSettings] = true;
this[kClient$2][kResume$2]();
}
function onHttp2SendPing(session) {
const state = session[kHTTP2SessionState];
if ((session.closed || session.destroyed) && state.ping.interval != null) {
clearInterval(state.ping.interval);
state.ping.interval = null;
return;
}
session.ping(onPing.bind(session));
function onPing(err, duration) {
const client = this[kClient$2];
const socket = this[kClient$2];
if (err != null) {
const error = new InformationalError$2(`HTTP/2: "PING" errored - type ${err.message}`);
socket[kError$1] = error;
client[kOnError$1](error);
} else client.emit("ping", duration);
}
}
function onHttp2SessionError(err) {
assert$23(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
this[kSocket][kError$1] = err;
this[kClient$2][kOnError$1](err);
}
function onHttp2FrameError(type, code, id) {
if (id === 0) {
const err = new InformationalError$2(`HTTP/2: "frameError" received - type ${type}, code ${code}`);
this[kSocket][kError$1] = err;
this[kClient$2][kOnError$1](err);
}
}
function onHttp2SessionEnd() {
const err = new SocketError$2("other side closed", util$22.getSocketInfo(this[kSocket]));
this.destroy(err);
util$22.destroy(this[kSocket], err);
}
/**
* This is the root cause of #3011
* We need to handle GOAWAY frames properly, and trigger the session close
* along with the socket right away
*
* @this {import('http2').ClientHttp2Session}
* @param {number} errorCode
*/
function onHttp2SessionGoAway(errorCode) {
const err = this[kError$1] || new SocketError$2(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util$22.getSocketInfo(this[kSocket]));
const client = this[kClient$2];
client[kSocket] = null;
client[kHTTPContext$1] = null;
this.close();
this[kHTTP2Session] = null;
util$22.destroy(this[kSocket], err);
if (client[kRunningIdx$1] < client[kQueue$2].length) {
const request$2 = client[kQueue$2][client[kRunningIdx$1]];
client[kQueue$2][client[kRunningIdx$1]++] = null;
util$22.errorRequest(client, request$2, err);
client[kPendingIdx$1] = client[kRunningIdx$1];
}
assert$23(client[kRunning$3] === 0);
client.emit("disconnect", client[kUrl$6], [client], err);
client.emit("connectionError", client[kUrl$6], [client], err);
client[kResume$2]();
}
function onHttp2SessionClose() {
const { [kClient$2]: client, [kHTTP2SessionState]: state } = this;
const { [kSocket]: socket } = client;
const err = this[kSocket][kError$1] || this[kError$1] || new SocketError$2("closed", util$22.getSocketInfo(socket));
client[kSocket] = null;
client[kHTTPContext$1] = null;
if (state.ping.interval != null) {
clearInterval(state.ping.interval);
state.ping.interval = null;
}
if (client.destroyed) {
assert$23(client[kPending$2] === 0);
const requests = client[kQueue$2].splice(client[kRunningIdx$1]);
for (let i$1 = 0; i$1 < requests.length; i$1++) {
const request$2 = requests[i$1];
util$22.errorRequest(client, request$2, err);
}
}
}
function onHttp2SocketClose() {
const err = this[kError$1] || new SocketError$2("closed", util$22.getSocketInfo(this));
const client = this[kHTTP2Session][kClient$2];
client[kSocket] = null;
client[kHTTPContext$1] = null;
if (this[kHTTP2Session] !== null) this[kHTTP2Session].destroy(err);
client[kPendingIdx$1] = client[kRunningIdx$1];
assert$23(client[kRunning$3] === 0);
client.emit("disconnect", client[kUrl$6], [client], err);
client[kResume$2]();
}
function onHttp2SocketError(err) {
assert$23(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
this[kError$1] = err;
this[kClient$2][kOnError$1](err);
}
function onHttp2SocketEnd() {
util$22.destroy(this, new SocketError$2("other side closed", util$22.getSocketInfo(this)));
}
function onSocketClose() {
this[kClosed$1] = true;
}
function shouldSendContentLength(method) {
return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
}
function writeH2(client, request$2) {
const requestTimeout = request$2.bodyTimeout ?? client[kBodyTimeout$1];
const session = client[kHTTP2Session];
const { method, path: path$2, host, upgrade: upgrade$1, expectContinue, signal, protocol, headers: reqHeaders } = request$2;
let { body } = request$2;
if (upgrade$1 != null && upgrade$1 !== "websocket") {
util$22.errorRequest(client, request$2, new InvalidArgumentError$30(`Custom upgrade "${upgrade$1}" not supported over HTTP/2`));
return false;
}
const headers = {};
for (let n$1 = 0; n$1 < reqHeaders.length; n$1 += 2) {
const key = reqHeaders[n$1 + 0];
const val = reqHeaders[n$1 + 1];
if (key === "cookie") {
if (headers[key] != null) headers[key] = Array.isArray(headers[key]) ? (headers[key].push(val), headers[key]) : [headers[key], val];
else headers[key] = val;
continue;
}
if (Array.isArray(val)) for (let i$1 = 0; i$1 < val.length; i$1++) if (headers[key]) headers[key] += `, ${val[i$1]}`;
else headers[key] = val[i$1];
else if (headers[key]) headers[key] += `, ${val}`;
else headers[key] = val;
}
/** @type {import('node:http2').ClientHttp2Stream} */
let stream$2 = null;
const { hostname, port } = client[kUrl$6];
headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`;
headers[HTTP2_HEADER_METHOD] = method;
const abort$1 = (err) => {
if (request$2.aborted || request$2.completed) return;
err = err || new RequestAbortedError$7();
util$22.errorRequest(client, request$2, err);
if (stream$2 != null) {
stream$2.removeAllListeners("data");
stream$2.close();
client[kOnError$1](err);
client[kResume$2]();
}
util$22.destroy(body, err);
};
try {
request$2.onConnect(abort$1);
} catch (err) {
util$22.errorRequest(client, request$2, err);
}
if (request$2.aborted) return false;
if (upgrade$1 || method === "CONNECT") {
session.ref();
if (upgrade$1 === "websocket") {
if (session[kEnableConnectProtocol] === false) {
util$22.errorRequest(client, request$2, new InformationalError$2("HTTP/2: Extended CONNECT protocol not supported by server"));
session.unref();
return false;
}
headers[HTTP2_HEADER_METHOD] = "CONNECT";
headers[HTTP2_HEADER_PROTOCOL] = "websocket";
headers[HTTP2_HEADER_PATH] = path$2;
if (protocol === "ws:" || protocol === "wss:") headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
else headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
stream$2 = session.request(headers, {
endStream: false,
signal
});
stream$2[kHTTP2Stream$1] = true;
stream$2.once("response", (headers$1, _flags) => {
const { [HTTP2_HEADER_STATUS]: statusCode,...realHeaders } = headers$1;
request$2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream$2);
++session[kOpenStreams];
client[kQueue$2][client[kRunningIdx$1]++] = null;
});
stream$2.on("error", () => {
if (stream$2.rstCode === NGHTTP2_REFUSED_STREAM || stream$2.rstCode === NGHTTP2_CANCEL) abort$1(new InformationalError$2(`HTTP/2: "stream error" received - code ${stream$2.rstCode}`));
});
stream$2.once("close", () => {
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream$2.setTimeout(requestTimeout);
return true;
}
stream$2 = session.request(headers, {
endStream: false,
signal
});
stream$2[kHTTP2Stream$1] = true;
stream$2.on("response", (headers$1) => {
const { [HTTP2_HEADER_STATUS]: statusCode,...realHeaders } = headers$1;
request$2.onUpgrade(statusCode, parseH2Headers(realHeaders), stream$2);
++session[kOpenStreams];
client[kQueue$2][client[kRunningIdx$1]++] = null;
});
stream$2.once("close", () => {
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream$2.setTimeout(requestTimeout);
return true;
}
headers[HTTP2_HEADER_PATH] = path$2;
headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
if (body && typeof body.read === "function") body.read(0);
let contentLength = util$22.bodyLength(body);
if (util$22.isFormDataLike(body)) {
extractBody$3 ??= require_body().extractBody;
const [bodyStream, contentType] = extractBody$3(body);
headers["content-type"] = contentType;
body = bodyStream.stream;
contentLength = bodyStream.length;
}
if (contentLength == null) contentLength = request$2.contentLength;
if (!expectsPayload) contentLength = null;
if (shouldSendContentLength(method) && contentLength > 0 && request$2.contentLength != null && request$2.contentLength !== contentLength) {
if (client[kStrictContentLength$1]) {
util$22.errorRequest(client, request$2, new RequestContentLengthMismatchError());
return false;
}
process.emitWarning(new RequestContentLengthMismatchError());
}
if (contentLength != null) {
assert$23(body || contentLength === 0, "no body must not have content length");
headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
}
session.ref();
if (channels$4.sendHeaders.hasSubscribers) {
let header = "";
for (const key in headers) header += `${key}: ${headers[key]}\r\n`;
channels$4.sendHeaders.publish({
request: request$2,
headers: header,
socket: session[kSocket]
});
}
const shouldEndStream = method === "GET" || method === "HEAD" || body === null;
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = "100-continue";
stream$2 = session.request(headers, {
endStream: shouldEndStream,
signal
});
stream$2[kHTTP2Stream$1] = true;
stream$2.once("continue", writeBodyH2);
} else {
stream$2 = session.request(headers, {
endStream: shouldEndStream,
signal
});
stream$2[kHTTP2Stream$1] = true;
writeBodyH2();
}
++session[kOpenStreams];
stream$2.setTimeout(requestTimeout);
let responseReceived = false;
stream$2.once("response", (headers$1) => {
const { [HTTP2_HEADER_STATUS]: statusCode,...realHeaders } = headers$1;
request$2.onResponseStarted();
responseReceived = true;
if (request$2.aborted) {
stream$2.removeAllListeners("data");
return;
}
if (request$2.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream$2.resume.bind(stream$2), "") === false) stream$2.pause();
stream$2.on("data", (chunk) => {
if (request$2.aborted || request$2.completed) return;
if (request$2.onData(chunk) === false) stream$2.pause();
});
});
stream$2.once("end", () => {
stream$2.removeAllListeners("data");
if (responseReceived) {
if (!request$2.aborted && !request$2.completed) request$2.onComplete({});
client[kQueue$2][client[kRunningIdx$1]++] = null;
client[kResume$2]();
} else {
abort$1(new InformationalError$2("HTTP/2: stream half-closed (remote)"));
client[kQueue$2][client[kRunningIdx$1]++] = null;
client[kPendingIdx$1] = client[kRunningIdx$1];
client[kResume$2]();
}
});
stream$2.once("close", () => {
stream$2.removeAllListeners("data");
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
});
stream$2.once("error", function(err) {
stream$2.removeAllListeners("data");
abort$1(err);
});
stream$2.once("frameError", (type, code) => {
stream$2.removeAllListeners("data");
abort$1(new InformationalError$2(`HTTP/2: "frameError" received - type ${type}, code ${code}`));
});
stream$2.on("aborted", () => {
stream$2.removeAllListeners("data");
});
stream$2.on("timeout", () => {
const err = new InformationalError$2(`HTTP/2: "stream timeout after ${requestTimeout}"`);
stream$2.removeAllListeners("data");
session[kOpenStreams] -= 1;
if (session[kOpenStreams] === 0) session.unref();
abort$1(err);
});
stream$2.once("trailers", (trailers) => {
if (request$2.aborted || request$2.completed) return;
stream$2.removeAllListeners("data");
request$2.onComplete(trailers);
});
return true;
function writeBodyH2() {
if (!body || contentLength === 0) writeBuffer(abort$1, stream$2, null, client, request$2, client[kSocket], contentLength, expectsPayload);
else if (util$22.isBuffer(body)) writeBuffer(abort$1, stream$2, body, client, request$2, client[kSocket], contentLength, expectsPayload);
else if (util$22.isBlobLike(body)) if (typeof body.stream === "function") writeIterable(abort$1, stream$2, body.stream(), client, request$2, client[kSocket], contentLength, expectsPayload);
else writeBlob(abort$1, stream$2, body, client, request$2, client[kSocket], contentLength, expectsPayload);
else if (util$22.isStream(body)) writeStream(abort$1, client[kSocket], expectsPayload, stream$2, body, client, request$2, contentLength);
else if (util$22.isIterable(body)) writeIterable(abort$1, stream$2, body, client, request$2, client[kSocket], contentLength, expectsPayload);
else assert$23(false);
}
}
function writeBuffer(abort$1, h2stream, body, client, request$2, socket, contentLength, expectsPayload) {
try {
if (body != null && util$22.isBuffer(body)) {
assert$23(contentLength === body.byteLength, "buffer body must have content length");
h2stream.cork();
h2stream.write(body);
h2stream.uncork();
h2stream.end();
request$2.onBodySent(body);
}
if (!expectsPayload) socket[kReset] = true;
request$2.onRequestSent();
client[kResume$2]();
} catch (error) {
abort$1(error);
}
}
function writeStream(abort$1, socket, expectsPayload, h2stream, body, client, request$2, contentLength) {
assert$23(contentLength !== 0 || client[kRunning$3] === 0, "stream body cannot be pipelined");
const pipe = pipeline$4(body, h2stream, (err) => {
if (err) {
util$22.destroy(pipe, err);
abort$1(err);
} else {
util$22.removeAllListeners(pipe);
request$2.onRequestSent();
if (!expectsPayload) socket[kReset] = true;
client[kResume$2]();
}
});
util$22.addListener(pipe, "data", onPipeData);
function onPipeData(chunk) {
request$2.onBodySent(chunk);
}
}
async function writeBlob(abort$1, h2stream, body, client, request$2, socket, contentLength, expectsPayload) {
assert$23(contentLength === body.size, "blob body must have content length");
try {
if (contentLength != null && contentLength !== body.size) throw new RequestContentLengthMismatchError();
const buffer$1 = Buffer.from(await body.arrayBuffer());
h2stream.cork();
h2stream.write(buffer$1);
h2stream.uncork();
h2stream.end();
request$2.onBodySent(buffer$1);
request$2.onRequestSent();
if (!expectsPayload) socket[kReset] = true;
client[kResume$2]();
} catch (err) {
abort$1(err);
}
}
async function writeIterable(abort$1, h2stream, body, client, request$2, socket, contentLength, expectsPayload) {
assert$23(contentLength !== 0 || client[kRunning$3] === 0, "iterator body cannot be pipelined");
let callback$1 = null;
function onDrain() {
if (callback$1) {
const cb = callback$1;
callback$1 = null;
cb();
}
}
const waitForDrain = () => new Promise((resolve$4, reject) => {
assert$23(callback$1 === null);
if (socket[kError$1]) reject(socket[kError$1]);
else callback$1 = resolve$4;
});
h2stream.on("close", onDrain).on("drain", onDrain);
try {
for await (const chunk of body) {
if (socket[kError$1]) throw socket[kError$1];
const res = h2stream.write(chunk);
request$2.onBodySent(chunk);
if (!res) await waitForDrain();
}
h2stream.end();
request$2.onRequestSent();
if (!expectsPayload) socket[kReset] = true;
client[kResume$2]();
} catch (err) {
abort$1(err);
} finally {
h2stream.off("close", onDrain).off("drain", onDrain);
}
}
module.exports = connectH2$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client.js
var require_client = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/client.js": ((exports, module) => {
const assert$22 = __require$2("node:assert");
const net$3 = __require$2("node:net");
const http = __require$2("node:http");
const util$21 = require_util$5();
const { ClientStats } = require_stats();
const { channels: channels$3 } = require_diagnostics();
const Request$5 = require_request$1();
const DispatcherBase$5 = require_dispatcher_base();
const { InvalidArgumentError: InvalidArgumentError$29, InformationalError: InformationalError$1, ClientDestroyedError } = require_errors();
const buildConnector$5 = require_connect();
const { kUrl: kUrl$5, kServerName, kClient: kClient$1, kBusy: kBusy$1, kConnect, kResuming, kRunning: kRunning$2, kPending: kPending$1, kSize: kSize$2, kQueue: kQueue$1, kConnected: kConnected$3, kConnecting, kNeedDrain: kNeedDrain$4, kKeepAliveDefaultTimeout, kHostHeader, kPendingIdx, kRunningIdx, kError, kPipelining, kKeepAliveTimeoutValue, kMaxHeadersSize, kKeepAliveMaxTimeout, kKeepAliveTimeoutThreshold, kHeadersTimeout, kBodyTimeout, kStrictContentLength, kConnector: kConnector$1, kMaxRequests, kCounter, kClose: kClose$7, kDestroy: kDestroy$5, kDispatch: kDispatch$5, kLocalAddress, kMaxResponseSize, kOnError, kHTTPContext, kMaxConcurrentStreams, kHTTP2InitialWindowSize, kHTTP2ConnectionWindowSize, kResume: kResume$1, kPingInterval } = require_symbols();
const connectH1 = require_client_h1();
const connectH2 = require_client_h2();
const kClosedResolve$1 = Symbol("kClosedResolve");
const getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
throw new InvalidArgumentError$29("http module not available or http.maxHeaderSize invalid");
};
const noop$7 = () => {};
function getPipelining(client) {
return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
}
/**
* @type {import('../../types/client.js').default}
*/
var Client$7 = class extends DispatcherBase$5 {
/**
*
* @param {string|URL} url
* @param {import('../../types/client.js').Client.Options} options
*/
constructor(url, { maxHeaderSize, headersTimeout, socketTimeout, requestTimeout, connectTimeout, bodyTimeout, idleTimeout, keepAlive, keepAliveTimeout, maxKeepAliveTimeout, keepAliveMaxTimeout, keepAliveTimeoutThreshold, socketPath, pipelining, tls: tls$2, strictContentLength, maxCachedSessions, connect: connect$2, maxRequestsPerClient, localAddress, maxResponseSize, autoSelectFamily, autoSelectFamilyAttemptTimeout, maxConcurrentStreams, allowH2, useH2c, initialWindowSize, connectionWindowSize, pingInterval } = {}) {
if (keepAlive !== void 0) throw new InvalidArgumentError$29("unsupported keepAlive, use pipelining=0 instead");
if (socketTimeout !== void 0) throw new InvalidArgumentError$29("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
if (requestTimeout !== void 0) throw new InvalidArgumentError$29("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
if (idleTimeout !== void 0) throw new InvalidArgumentError$29("unsupported idleTimeout, use keepAliveTimeout instead");
if (maxKeepAliveTimeout !== void 0) throw new InvalidArgumentError$29("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
if (maxHeaderSize != null) {
if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) throw new InvalidArgumentError$29("invalid maxHeaderSize");
} else maxHeaderSize = getDefaultNodeMaxHeaderSize();
if (socketPath != null && typeof socketPath !== "string") throw new InvalidArgumentError$29("invalid socketPath");
if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) throw new InvalidArgumentError$29("invalid connectTimeout");
if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) throw new InvalidArgumentError$29("invalid keepAliveTimeout");
if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) throw new InvalidArgumentError$29("invalid keepAliveMaxTimeout");
if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) throw new InvalidArgumentError$29("invalid keepAliveTimeoutThreshold");
if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) throw new InvalidArgumentError$29("headersTimeout must be a positive integer or zero");
if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) throw new InvalidArgumentError$29("bodyTimeout must be a positive integer or zero");
if (connect$2 != null && typeof connect$2 !== "function" && typeof connect$2 !== "object") throw new InvalidArgumentError$29("connect must be a function or an object");
if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) throw new InvalidArgumentError$29("maxRequestsPerClient must be a positive number");
if (localAddress != null && (typeof localAddress !== "string" || net$3.isIP(localAddress) === 0)) throw new InvalidArgumentError$29("localAddress must be valid string IP address");
if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) throw new InvalidArgumentError$29("maxResponseSize must be a positive number");
if (autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)) throw new InvalidArgumentError$29("autoSelectFamilyAttemptTimeout must be a positive number");
if (allowH2 != null && typeof allowH2 !== "boolean") throw new InvalidArgumentError$29("allowH2 must be a valid boolean value");
if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) throw new InvalidArgumentError$29("maxConcurrentStreams must be a positive integer, greater than 0");
if (useH2c != null && typeof useH2c !== "boolean") throw new InvalidArgumentError$29("useH2c must be a valid boolean value");
if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) throw new InvalidArgumentError$29("initialWindowSize must be a positive integer, greater than 0");
if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) throw new InvalidArgumentError$29("connectionWindowSize must be a positive integer, greater than 0");
if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) throw new InvalidArgumentError$29("pingInterval must be a positive integer, greater or equal to 0");
super();
if (typeof connect$2 !== "function") connect$2 = buildConnector$5({
...tls$2,
maxCachedSessions,
allowH2,
useH2c,
socketPath,
timeout: connectTimeout,
...typeof autoSelectFamily === "boolean" ? {
autoSelectFamily,
autoSelectFamilyAttemptTimeout
} : void 0,
...connect$2
});
else if (socketPath != null) {
const customConnect = connect$2;
connect$2 = (opts, callback$1) => customConnect({
...opts,
socketPath
}, callback$1);
}
this[kUrl$5] = util$21.parseOrigin(url);
this[kConnector$1] = connect$2;
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$4] = 0;
this[kHostHeader] = `host: ${this[kUrl$5].hostname}${this[kUrl$5].port ? `:${this[kUrl$5].port}` : ""}\r\n`;
this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5;
this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5;
this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
this[kMaxRequests] = maxRequestsPerClient;
this[kClosedResolve$1] = null;
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
this[kHTTPContext] = null;
this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144;
this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288;
this[kPingInterval] = pingInterval != null ? pingInterval : 6e4;
this[kQueue$1] = [];
this[kRunningIdx] = 0;
this[kPendingIdx] = 0;
this[kResume$1] = (sync$1) => resume(this, sync$1);
this[kOnError] = (err) => onError(this, err);
}
get pipelining() {
return this[kPipelining];
}
set pipelining(value) {
this[kPipelining] = value;
this[kResume$1](true);
}
get stats() {
return new ClientStats(this);
}
get [kPending$1]() {
return this[kQueue$1].length - this[kPendingIdx];
}
get [kRunning$2]() {
return this[kPendingIdx] - this[kRunningIdx];
}
get [kSize$2]() {
return this[kQueue$1].length - this[kRunningIdx];
}
get [kConnected$3]() {
return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed;
}
get [kBusy$1]() {
return Boolean(this[kHTTPContext]?.busy(null) || this[kSize$2] >= (getPipelining(this) || 1) || this[kPending$1] > 0);
}
[kConnect](cb) {
connect$1(this);
this.once("connect", cb);
}
[kDispatch$5](opts, handler) {
const request$2 = new Request$5(this[kUrl$5].origin, opts, handler);
this[kQueue$1].push(request$2);
if (this[kResuming]) {} else if (util$21.bodyLength(request$2.body) == null && util$21.isIterable(request$2.body)) {
this[kResuming] = 1;
queueMicrotask(() => resume(this));
} else this[kResume$1](true);
if (this[kResuming] && this[kNeedDrain$4] !== 2 && this[kBusy$1]) this[kNeedDrain$4] = 2;
return this[kNeedDrain$4] < 2;
}
[kClose$7]() {
return new Promise((resolve$4) => {
if (this[kSize$2]) this[kClosedResolve$1] = resolve$4;
else resolve$4(null);
});
}
[kDestroy$5](err) {
return new Promise((resolve$4) => {
const requests = this[kQueue$1].splice(this[kPendingIdx]);
for (let i$1 = 0; i$1 < requests.length; i$1++) {
const request$2 = requests[i$1];
util$21.errorRequest(this, request$2, err);
}
const callback$1 = () => {
if (this[kClosedResolve$1]) {
this[kClosedResolve$1]();
this[kClosedResolve$1] = null;
}
resolve$4(null);
};
if (this[kHTTPContext]) {
this[kHTTPContext].destroy(err, callback$1);
this[kHTTPContext] = null;
} else queueMicrotask(callback$1);
this[kResume$1]();
});
}
};
function onError(client, err) {
if (client[kRunning$2] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
assert$22(client[kPendingIdx] === client[kRunningIdx]);
const requests = client[kQueue$1].splice(client[kRunningIdx]);
for (let i$1 = 0; i$1 < requests.length; i$1++) {
const request$2 = requests[i$1];
util$21.errorRequest(client, request$2, err);
}
assert$22(client[kSize$2] === 0);
}
}
/**
* @param {Client} client
* @returns {void}
*/
function connect$1(client) {
assert$22(!client[kConnecting]);
assert$22(!client[kHTTPContext]);
let { host, hostname, protocol, port } = client[kUrl$5];
if (hostname[0] === "[") {
const idx = hostname.indexOf("]");
assert$22(idx !== -1);
const ip = hostname.substring(1, idx);
assert$22(net$3.isIPv6(ip));
hostname = ip;
}
client[kConnecting] = true;
if (channels$3.beforeConnect.hasSubscribers) channels$3.beforeConnect.publish({
connectParams: {
host,
hostname,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector$1]
});
try {
client[kConnector$1]({
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
}, (err, socket) => {
if (err) {
handleConnectError(client, err, {
host,
hostname,
protocol,
port
});
client[kResume$1]();
return;
}
if (client.destroyed) {
util$21.destroy(socket.on("error", noop$7), new ClientDestroyedError());
client[kResume$1]();
return;
}
assert$22(socket);
try {
client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
} catch (err$1) {
socket.destroy().on("error", noop$7);
handleConnectError(client, err$1, {
host,
hostname,
protocol,
port
});
client[kResume$1]();
return;
}
client[kConnecting] = false;
socket[kCounter] = 0;
socket[kMaxRequests] = client[kMaxRequests];
socket[kClient$1] = client;
socket[kError] = null;
if (channels$3.connected.hasSubscribers) channels$3.connected.publish({
connectParams: {
host,
hostname,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector$1],
socket
});
client.emit("connect", client[kUrl$5], [client]);
client[kResume$1]();
});
} catch (err) {
handleConnectError(client, err, {
host,
hostname,
protocol,
port
});
client[kResume$1]();
}
}
function handleConnectError(client, err, { host, hostname, protocol, port }) {
if (client.destroyed) return;
client[kConnecting] = false;
if (channels$3.connectError.hasSubscribers) channels$3.connectError.publish({
connectParams: {
host,
hostname,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector$1],
error: err
});
if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
assert$22(client[kRunning$2] === 0);
while (client[kPending$1] > 0 && client[kQueue$1][client[kPendingIdx]].servername === client[kServerName]) {
const request$2 = client[kQueue$1][client[kPendingIdx]++];
util$21.errorRequest(client, request$2, err);
}
} else onError(client, err);
client.emit("connectionError", client[kUrl$5], [client], err);
}
function emitDrain(client) {
client[kNeedDrain$4] = 0;
client.emit("drain", client[kUrl$5], [client]);
}
function resume(client, sync$1) {
if (client[kResuming] === 2) return;
client[kResuming] = 2;
_resume(client, sync$1);
client[kResuming] = 0;
if (client[kRunningIdx] > 256) {
client[kQueue$1].splice(0, client[kRunningIdx]);
client[kPendingIdx] -= client[kRunningIdx];
client[kRunningIdx] = 0;
}
}
function _resume(client, sync$1) {
while (true) {
if (client.destroyed) {
assert$22(client[kPending$1] === 0);
return;
}
if (client[kClosedResolve$1] && !client[kSize$2]) {
client[kClosedResolve$1]();
client[kClosedResolve$1] = null;
return;
}
if (client[kHTTPContext]) client[kHTTPContext].resume();
if (client[kBusy$1]) client[kNeedDrain$4] = 2;
else if (client[kNeedDrain$4] === 2) {
if (sync$1) {
client[kNeedDrain$4] = 1;
queueMicrotask(() => emitDrain(client));
} else emitDrain(client);
continue;
}
if (client[kPending$1] === 0) return;
if (client[kRunning$2] >= (getPipelining(client) || 1)) return;
const request$2 = client[kQueue$1][client[kPendingIdx]];
if (request$2 === null) return;
if (client[kUrl$5].protocol === "https:" && client[kServerName] !== request$2.servername) {
if (client[kRunning$2] > 0) return;
client[kServerName] = request$2.servername;
client[kHTTPContext]?.destroy(new InformationalError$1("servername changed"), () => {
client[kHTTPContext] = null;
resume(client);
});
}
if (client[kConnecting]) return;
if (!client[kHTTPContext]) {
connect$1(client);
return;
}
if (client[kHTTPContext].destroyed) return;
if (client[kHTTPContext].busy(request$2)) return;
if (!request$2.aborted && client[kHTTPContext].write(request$2)) client[kPendingIdx]++;
else client[kQueue$1].splice(client[kPendingIdx], 1);
}
}
module.exports = Client$7;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/fixed-queue.js": ((exports, module) => {
const kSize$1 = 2048;
const kMask = kSize$1 - 1;
/**
* @type {FixedCircularBuffer}
* @template T
*/
var FixedCircularBuffer = class {
/** @type {number} */
bottom = 0;
/** @type {number} */
top = 0;
/** @type {Array<T|undefined>} */
list = new Array(kSize$1).fill(void 0);
/** @type {T|null} */
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$1) {
this.list[this.top] = data$1;
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;
}
};
/**
* @template T
*/
module.exports = class FixedQueue$2 {
constructor() {
/** @type {FixedCircularBuffer<T>} */
this.head = this.tail = new FixedCircularBuffer();
}
/** @returns {boolean} */
isEmpty() {
return this.head.isEmpty();
}
/** @param {T} data */
push(data$1) {
if (this.head.isFull()) this.head = this.head.next = new FixedCircularBuffer();
this.head.push(data$1);
}
/** @returns {T|null} */
shift() {
const tail$1 = this.tail;
const next = tail$1.shift();
if (tail$1.isEmpty() && tail$1.next !== null) {
this.tail = tail$1.next;
tail$1.next = null;
}
return next;
}
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/pool-base.js": ((exports, module) => {
const { PoolStats } = require_stats();
const DispatcherBase$4 = require_dispatcher_base();
const FixedQueue$1 = require_fixed_queue();
const { kConnected: kConnected$2, kSize, kRunning: kRunning$1, kPending, kQueued, kBusy, kFree, kUrl: kUrl$4, kClose: kClose$6, kDestroy: kDestroy$4, kDispatch: kDispatch$4 } = require_symbols();
const kClients$5 = Symbol("clients");
const kNeedDrain$3 = Symbol("needDrain");
const kQueue = Symbol("queue");
const kClosedResolve = Symbol("closed resolve");
const kOnDrain$1 = Symbol("onDrain");
const kOnConnect$1 = Symbol("onConnect");
const kOnDisconnect$1 = Symbol("onDisconnect");
const kOnConnectionError$1 = Symbol("onConnectionError");
const kGetDispatcher$3 = Symbol("get dispatcher");
const kAddClient$3 = Symbol("add client");
const kRemoveClient$3 = Symbol("remove client");
var PoolBase$3 = class extends DispatcherBase$4 {
[kQueue] = new FixedQueue$1();
[kQueued] = 0;
[kClients$5] = [];
[kNeedDrain$3] = false;
[kOnDrain$1](client, origin, targets) {
const queue = this[kQueue];
let needDrain = false;
while (!needDrain) {
const item = queue.shift();
if (!item) break;
this[kQueued]--;
needDrain = !client.dispatch(item.opts, item.handler);
}
client[kNeedDrain$3] = needDrain;
if (!needDrain && this[kNeedDrain$3]) {
this[kNeedDrain$3] = false;
this.emit("drain", origin, [this, ...targets]);
}
if (this[kClosedResolve] && queue.isEmpty()) {
const closeAll = [];
for (let i$1 = 0; i$1 < this[kClients$5].length; i$1++) {
const client$1 = this[kClients$5][i$1];
if (!client$1.destroyed) closeAll.push(client$1.close());
}
return Promise.all(closeAll).then(this[kClosedResolve]);
}
}
[kOnConnect$1] = (origin, targets) => {
this.emit("connect", origin, [this, ...targets]);
};
[kOnDisconnect$1] = (origin, targets, err) => {
this.emit("disconnect", origin, [this, ...targets], err);
};
[kOnConnectionError$1] = (origin, targets, err) => {
this.emit("connectionError", origin, [this, ...targets], err);
};
get [kBusy]() {
return this[kNeedDrain$3];
}
get [kConnected$2]() {
let ret = 0;
for (const { [kConnected$2]: connected } of this[kClients$5]) ret += connected;
return ret;
}
get [kFree]() {
let ret = 0;
for (const { [kConnected$2]: connected, [kNeedDrain$3]: needDrain } of this[kClients$5]) ret += connected && !needDrain;
return ret;
}
get [kPending]() {
let ret = this[kQueued];
for (const { [kPending]: pending } of this[kClients$5]) ret += pending;
return ret;
}
get [kRunning$1]() {
let ret = 0;
for (const { [kRunning$1]: running } of this[kClients$5]) ret += running;
return ret;
}
get [kSize]() {
let ret = this[kQueued];
for (const { [kSize]: size } of this[kClients$5]) ret += size;
return ret;
}
get stats() {
return new PoolStats(this);
}
[kClose$6]() {
if (this[kQueue].isEmpty()) {
const closeAll = [];
for (let i$1 = 0; i$1 < this[kClients$5].length; i$1++) {
const client = this[kClients$5][i$1];
if (!client.destroyed) closeAll.push(client.close());
}
return Promise.all(closeAll);
} else return new Promise((resolve$4) => {
this[kClosedResolve] = resolve$4;
});
}
[kDestroy$4](err) {
while (true) {
const item = this[kQueue].shift();
if (!item) break;
item.handler.onError(err);
}
const destroyAll = new Array(this[kClients$5].length);
for (let i$1 = 0; i$1 < this[kClients$5].length; i$1++) destroyAll[i$1] = this[kClients$5][i$1].destroy(err);
return Promise.all(destroyAll);
}
[kDispatch$4](opts, handler) {
const dispatcher = this[kGetDispatcher$3]();
if (!dispatcher) {
this[kNeedDrain$3] = true;
this[kQueue].push({
opts,
handler
});
this[kQueued]++;
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain$3] = true;
this[kNeedDrain$3] = !this[kGetDispatcher$3]();
}
return !this[kNeedDrain$3];
}
[kAddClient$3](client) {
client.on("drain", this[kOnDrain$1].bind(this, client)).on("connect", this[kOnConnect$1]).on("disconnect", this[kOnDisconnect$1]).on("connectionError", this[kOnConnectionError$1]);
this[kClients$5].push(client);
if (this[kNeedDrain$3]) queueMicrotask(() => {
if (this[kNeedDrain$3]) this[kOnDrain$1](client, client[kUrl$4], [client, this]);
});
return this;
}
[kRemoveClient$3](client) {
client.close(() => {
const idx = this[kClients$5].indexOf(client);
if (idx !== -1) this[kClients$5].splice(idx, 1);
});
this[kNeedDrain$3] = this[kClients$5].some((dispatcher) => !dispatcher[kNeedDrain$3] && dispatcher.closed !== true && dispatcher.destroyed !== true);
}
};
module.exports = {
PoolBase: PoolBase$3,
kClients: kClients$5,
kNeedDrain: kNeedDrain$3,
kAddClient: kAddClient$3,
kRemoveClient: kRemoveClient$3,
kGetDispatcher: kGetDispatcher$3
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/pool.js
var require_pool = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/pool.js": ((exports, module) => {
const { PoolBase: PoolBase$2, kClients: kClients$4, kNeedDrain: kNeedDrain$2, kAddClient: kAddClient$2, kGetDispatcher: kGetDispatcher$2, kRemoveClient: kRemoveClient$2 } = require_pool_base();
const Client$6 = require_client();
const { InvalidArgumentError: InvalidArgumentError$28 } = require_errors();
const util$20 = require_util$5();
const { kUrl: kUrl$3 } = require_symbols();
const buildConnector$4 = require_connect();
const kOptions$4 = Symbol("options");
const kConnections$1 = Symbol("connections");
const kFactory$4 = Symbol("factory");
function defaultFactory$4(origin, opts) {
return new Client$6(origin, opts);
}
var Pool$6 = class extends PoolBase$2 {
constructor(origin, { connections, factory: factory$1 = defaultFactory$4, connect: connect$2, connectTimeout, tls: tls$2, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, clientTtl,...options } = {}) {
if (connections != null && (!Number.isFinite(connections) || connections < 0)) throw new InvalidArgumentError$28("invalid connections");
if (typeof factory$1 !== "function") throw new InvalidArgumentError$28("factory must be a function.");
if (connect$2 != null && typeof connect$2 !== "function" && typeof connect$2 !== "object") throw new InvalidArgumentError$28("connect must be a function or an object");
if (typeof connect$2 !== "function") connect$2 = buildConnector$4({
...tls$2,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...typeof autoSelectFamily === "boolean" ? {
autoSelectFamily,
autoSelectFamilyAttemptTimeout
} : void 0,
...connect$2
});
super();
this[kConnections$1] = connections || null;
this[kUrl$3] = util$20.parseOrigin(origin);
this[kOptions$4] = {
...util$20.deepClone(options),
connect: connect$2,
allowH2,
clientTtl,
socketPath
};
this[kOptions$4].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
this[kFactory$4] = factory$1;
this.on("connect", (origin$1, targets) => {
if (clientTtl != null && clientTtl > 0) for (const target$1 of targets) Object.assign(target$1, { ttl: Date.now() });
});
this.on("connectionError", (origin$1, targets, error) => {
for (const target$1 of targets) {
const idx = this[kClients$4].indexOf(target$1);
if (idx !== -1) this[kClients$4].splice(idx, 1);
}
});
}
[kGetDispatcher$2]() {
const clientTtlOption = this[kOptions$4].clientTtl;
for (const client of this[kClients$4]) if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) this[kRemoveClient$2](client);
else if (!client[kNeedDrain$2]) return client;
if (!this[kConnections$1] || this[kClients$4].length < this[kConnections$1]) {
const dispatcher = this[kFactory$4](this[kUrl$3], this[kOptions$4]);
this[kAddClient$2](dispatcher);
return dispatcher;
}
}
};
module.exports = Pool$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/balanced-pool.js": ((exports, module) => {
const { BalancedPoolMissingUpstreamError, InvalidArgumentError: InvalidArgumentError$27 } = require_errors();
const { PoolBase: PoolBase$1, kClients: kClients$3, kNeedDrain: kNeedDrain$1, kAddClient: kAddClient$1, kRemoveClient: kRemoveClient$1, kGetDispatcher: kGetDispatcher$1 } = require_pool_base();
const Pool$5 = require_pool();
const { kUrl: kUrl$2 } = require_symbols();
const util$19 = require_util$5();
const kFactory$3 = Symbol("factory");
const kOptions$3 = Symbol("options");
const kGreatestCommonDivisor = Symbol("kGreatestCommonDivisor");
const kCurrentWeight = Symbol("kCurrentWeight");
const kIndex$1 = Symbol("kIndex");
const kWeight = Symbol("kWeight");
const kMaxWeightPerServer = Symbol("kMaxWeightPerServer");
const kErrorPenalty = Symbol("kErrorPenalty");
/**
* Calculate the greatest common divisor of two numbers by
* using the Euclidean algorithm.
*
* @param {number} a
* @param {number} b
* @returns {number}
*/
function getGreatestCommonDivisor(a, b) {
if (a === 0) return b;
while (b !== 0) {
const t$5 = b;
b = a % b;
a = t$5;
}
return a;
}
function defaultFactory$3(origin, opts) {
return new Pool$5(origin, opts);
}
var BalancedPool$1 = class extends PoolBase$1 {
constructor(upstreams = [], { factory: factory$1 = defaultFactory$3,...opts } = {}) {
if (typeof factory$1 !== "function") throw new InvalidArgumentError$27("factory must be a function.");
super();
this[kOptions$3] = { ...util$19.deepClone(opts) };
this[kOptions$3].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
this[kIndex$1] = -1;
this[kCurrentWeight] = 0;
this[kMaxWeightPerServer] = this[kOptions$3].maxWeightPerServer || 100;
this[kErrorPenalty] = this[kOptions$3].errorPenalty || 15;
if (!Array.isArray(upstreams)) upstreams = [upstreams];
this[kFactory$3] = factory$1;
for (const upstream of upstreams) this.addUpstream(upstream);
this._updateBalancedPoolStats();
}
addUpstream(upstream) {
const upstreamOrigin = util$19.parseOrigin(upstream).origin;
if (this[kClients$3].find((pool$1) => pool$1[kUrl$2].origin === upstreamOrigin && pool$1.closed !== true && pool$1.destroyed !== true)) return this;
const pool = this[kFactory$3](upstreamOrigin, this[kOptions$3]);
this[kAddClient$1](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$3]) client[kWeight] = this[kMaxWeightPerServer];
this._updateBalancedPoolStats();
return this;
}
_updateBalancedPoolStats() {
let result = 0;
for (let i$1 = 0; i$1 < this[kClients$3].length; i$1++) result = getGreatestCommonDivisor(this[kClients$3][i$1][kWeight], result);
this[kGreatestCommonDivisor] = result;
}
removeUpstream(upstream) {
const upstreamOrigin = util$19.parseOrigin(upstream).origin;
const pool = this[kClients$3].find((pool$1) => pool$1[kUrl$2].origin === upstreamOrigin && pool$1.closed !== true && pool$1.destroyed !== true);
if (pool) this[kRemoveClient$1](pool);
return this;
}
getUpstream(upstream) {
const upstreamOrigin = util$19.parseOrigin(upstream).origin;
return this[kClients$3].find((pool) => pool[kUrl$2].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true);
}
get upstreams() {
return this[kClients$3].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p$1) => p$1[kUrl$2].origin);
}
[kGetDispatcher$1]() {
if (this[kClients$3].length === 0) throw new BalancedPoolMissingUpstreamError();
if (!this[kClients$3].find((dispatcher) => !dispatcher[kNeedDrain$1] && dispatcher.closed !== true && dispatcher.destroyed !== true)) return;
if (this[kClients$3].map((pool) => pool[kNeedDrain$1]).reduce((a, b) => a && b, true)) return;
let counter = 0;
let maxWeightIndex = this[kClients$3].findIndex((pool) => !pool[kNeedDrain$1]);
while (counter++ < this[kClients$3].length) {
this[kIndex$1] = (this[kIndex$1] + 1) % this[kClients$3].length;
const pool = this[kClients$3][this[kIndex$1]];
if (pool[kWeight] > this[kClients$3][maxWeightIndex][kWeight] && !pool[kNeedDrain$1]) maxWeightIndex = this[kIndex$1];
if (this[kIndex$1] === 0) {
this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
if (this[kCurrentWeight] <= 0) this[kCurrentWeight] = this[kMaxWeightPerServer];
}
if (pool[kWeight] >= this[kCurrentWeight] && !pool[kNeedDrain$1]) return pool;
}
this[kCurrentWeight] = this[kClients$3][maxWeightIndex][kWeight];
this[kIndex$1] = maxWeightIndex;
return this[kClients$3][maxWeightIndex];
}
};
module.exports = BalancedPool$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/round-robin-pool.js
var require_round_robin_pool = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/round-robin-pool.js": ((exports, module) => {
const { PoolBase, kClients: kClients$2, kNeedDrain, kAddClient, kGetDispatcher, kRemoveClient } = require_pool_base();
const Client$5 = require_client();
const { InvalidArgumentError: InvalidArgumentError$26 } = require_errors();
const util$18 = require_util$5();
const { kUrl: kUrl$1 } = require_symbols();
const buildConnector$3 = require_connect();
const kOptions$2 = Symbol("options");
const kConnections = Symbol("connections");
const kFactory$2 = Symbol("factory");
const kIndex = Symbol("index");
function defaultFactory$2(origin, opts) {
return new Client$5(origin, opts);
}
var RoundRobinPool$1 = class extends PoolBase {
constructor(origin, { connections, factory: factory$1 = defaultFactory$2, connect: connect$2, connectTimeout, tls: tls$2, maxCachedSessions, socketPath, autoSelectFamily, autoSelectFamilyAttemptTimeout, allowH2, clientTtl,...options } = {}) {
if (connections != null && (!Number.isFinite(connections) || connections < 0)) throw new InvalidArgumentError$26("invalid connections");
if (typeof factory$1 !== "function") throw new InvalidArgumentError$26("factory must be a function.");
if (connect$2 != null && typeof connect$2 !== "function" && typeof connect$2 !== "object") throw new InvalidArgumentError$26("connect must be a function or an object");
if (typeof connect$2 !== "function") connect$2 = buildConnector$3({
...tls$2,
maxCachedSessions,
allowH2,
socketPath,
timeout: connectTimeout,
...typeof autoSelectFamily === "boolean" ? {
autoSelectFamily,
autoSelectFamilyAttemptTimeout
} : void 0,
...connect$2
});
super();
this[kConnections] = connections || null;
this[kUrl$1] = util$18.parseOrigin(origin);
this[kOptions$2] = {
...util$18.deepClone(options),
connect: connect$2,
allowH2,
clientTtl,
socketPath
};
this[kOptions$2].interceptors = options.interceptors ? { ...options.interceptors } : void 0;
this[kFactory$2] = factory$1;
this[kIndex] = -1;
this.on("connect", (origin$1, targets) => {
if (clientTtl != null && clientTtl > 0) for (const target$1 of targets) Object.assign(target$1, { ttl: Date.now() });
});
this.on("connectionError", (origin$1, targets, error) => {
for (const target$1 of targets) {
const idx = this[kClients$2].indexOf(target$1);
if (idx !== -1) this[kClients$2].splice(idx, 1);
}
});
}
[kGetDispatcher]() {
const clientTtlOption = this[kOptions$2].clientTtl;
const clientsLength = this[kClients$2].length;
if (clientsLength === 0) {
const dispatcher = this[kFactory$2](this[kUrl$1], this[kOptions$2]);
this[kAddClient](dispatcher);
return dispatcher;
}
let checked = 0;
while (checked < clientsLength) {
this[kIndex] = (this[kIndex] + 1) % clientsLength;
const client = this[kClients$2][this[kIndex]];
if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
this[kRemoveClient](client);
checked++;
continue;
}
if (!client[kNeedDrain]) return client;
checked++;
}
if (!this[kConnections] || clientsLength < this[kConnections]) {
const dispatcher = this[kFactory$2](this[kUrl$1], this[kOptions$2]);
this[kAddClient](dispatcher);
return dispatcher;
}
}
};
module.exports = RoundRobinPool$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/agent.js
var require_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/agent.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$25, MaxOriginsReachedError } = require_errors();
const { kClients: kClients$1, kRunning, kClose: kClose$5, kDestroy: kDestroy$3, kDispatch: kDispatch$3, kUrl } = require_symbols();
const DispatcherBase$3 = require_dispatcher_base();
const Pool$4 = require_pool();
const Client$4 = require_client();
const util$17 = require_util$5();
const kOnConnect = Symbol("onConnect");
const kOnDisconnect = Symbol("onDisconnect");
const kOnConnectionError = Symbol("onConnectionError");
const kOnDrain = Symbol("onDrain");
const kFactory$1 = Symbol("factory");
const kOptions$1 = Symbol("options");
const kOrigins = Symbol("origins");
function defaultFactory$1(origin, opts) {
return opts && opts.connections === 1 ? new Client$4(origin, opts) : new Pool$4(origin, opts);
}
var Agent$6 = class extends DispatcherBase$3 {
constructor({ factory: factory$1 = defaultFactory$1, maxOrigins = Infinity, connect: connect$2,...options } = {}) {
if (typeof factory$1 !== "function") throw new InvalidArgumentError$25("factory must be a function.");
if (connect$2 != null && typeof connect$2 !== "function" && typeof connect$2 !== "object") throw new InvalidArgumentError$25("connect must be a function or an object");
if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) throw new InvalidArgumentError$25("maxOrigins must be a number greater than 0");
super();
if (connect$2 && typeof connect$2 !== "function") connect$2 = { ...connect$2 };
this[kOptions$1] = {
...util$17.deepClone(options),
maxOrigins,
connect: connect$2
};
this[kFactory$1] = factory$1;
this[kClients$1] = /* @__PURE__ */ new Map();
this[kOrigins] = /* @__PURE__ */ new Set();
this[kOnDrain] = (origin, targets) => {
this.emit("drain", origin, [this, ...targets]);
};
this[kOnConnect] = (origin, targets) => {
this.emit("connect", origin, [this, ...targets]);
};
this[kOnDisconnect] = (origin, targets, err) => {
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$1].values()) ret += dispatcher[kRunning];
return ret;
}
[kDispatch$3](opts, handler) {
let key;
if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) key = String(opts.origin);
else throw new InvalidArgumentError$25("opts.origin must be a non-empty string or URL.");
if (this[kOrigins].size >= this[kOptions$1].maxOrigins && !this[kOrigins].has(key)) throw new MaxOriginsReachedError();
const result = this[kClients$1].get(key);
let dispatcher = result && result.dispatcher;
if (!dispatcher) {
const closeClientIfUnused = (connected) => {
const result$1 = this[kClients$1].get(key);
if (result$1) {
if (connected) result$1.count -= 1;
if (result$1.count <= 0) {
this[kClients$1].delete(key);
if (!result$1.dispatcher.destroyed) result$1.dispatcher.close();
}
this[kOrigins].delete(key);
}
};
dispatcher = this[kFactory$1](opts.origin, this[kOptions$1]).on("drain", this[kOnDrain]).on("connect", (origin, targets) => {
const result$1 = this[kClients$1].get(key);
if (result$1) result$1.count += 1;
this[kOnConnect](origin, targets);
}).on("disconnect", (origin, targets, err) => {
closeClientIfUnused(true);
this[kOnDisconnect](origin, targets, err);
}).on("connectionError", (origin, targets, err) => {
closeClientIfUnused(false);
this[kOnConnectionError](origin, targets, err);
});
this[kClients$1].set(key, {
count: 0,
dispatcher
});
this[kOrigins].add(key);
}
return dispatcher.dispatch(opts, handler);
}
[kClose$5]() {
const closePromises = [];
for (const { dispatcher } of this[kClients$1].values()) closePromises.push(dispatcher.close());
this[kClients$1].clear();
return Promise.all(closePromises);
}
[kDestroy$3](err) {
const destroyPromises = [];
for (const { dispatcher } of this[kClients$1].values()) destroyPromises.push(dispatcher.destroy(err));
this[kClients$1].clear();
return Promise.all(destroyPromises);
}
get stats() {
const allClientStats = {};
for (const { dispatcher } of this[kClients$1].values()) if (dispatcher.stats) allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
return allClientStats;
}
};
module.exports = Agent$6;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/socks5-utils.js
var require_socks5_utils = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/socks5-utils.js": ((exports, module) => {
const { Buffer: Buffer$3 } = __require$2("node:buffer");
const net$2 = __require$2("node:net");
const { InvalidArgumentError: InvalidArgumentError$24 } = require_errors();
/**
* Parse an address and determine its type
* @param {string} address - The address to parse
* @returns {{type: number, buffer: Buffer}} Address type and buffer
*/
function parseAddress$1(address) {
if (net$2.isIPv4(address)) {
const parts = address.split(".").map(Number);
return {
type: 1,
buffer: Buffer$3.from(parts)
};
}
if (net$2.isIPv6(address)) return {
type: 4,
buffer: parseIPv6(address)
};
const domainBuffer = Buffer$3.from(address, "utf8");
if (domainBuffer.length > 255) throw new InvalidArgumentError$24("Domain name too long (max 255 bytes)");
return {
type: 3,
buffer: Buffer$3.concat([Buffer$3.from([domainBuffer.length]), domainBuffer])
};
}
/**
* Parse IPv6 address to buffer
* @param {string} address - IPv6 address string
* @returns {Buffer} 16-byte buffer
*/
function parseIPv6(address) {
const buffer$1 = Buffer$3.alloc(16);
const parts = address.split(":");
let partIndex = 0;
let bufferIndex = 0;
const doubleColonIndex = address.indexOf("::");
if (doubleColonIndex !== -1) {
const skipParts = 8 - parts.filter((p$1) => p$1.length > 0).length;
for (let i$1 = 0; i$1 < parts.length; i$1++) if (parts[i$1] === "" && i$1 === doubleColonIndex / 3) bufferIndex += skipParts * 2;
else if (parts[i$1] !== "") {
const value = parseInt(parts[i$1], 16);
buffer$1.writeUInt16BE(value, bufferIndex);
bufferIndex += 2;
}
} else for (const part of parts) {
if (part === "") continue;
const value = parseInt(part, 16);
buffer$1.writeUInt16BE(value, partIndex * 2);
partIndex++;
}
return buffer$1;
}
/**
* Build a SOCKS5 address buffer
* @param {number} type - Address type (1=IPv4, 3=Domain, 4=IPv6)
* @param {Buffer} addressBuffer - The address data
* @param {number} port - Port number
* @returns {Buffer} Complete address buffer including type, address, and port
*/
function buildAddressBuffer(type, addressBuffer, port) {
const portBuffer = Buffer$3.allocUnsafe(2);
portBuffer.writeUInt16BE(port, 0);
return Buffer$3.concat([
Buffer$3.from([type]),
addressBuffer,
portBuffer
]);
}
/**
* Parse address from SOCKS5 response
* @param {Buffer} buffer - Buffer containing the address
* @param {number} offset - Starting offset in buffer
* @returns {{address: string, port: number, bytesRead: number}}
*/
function parseResponseAddress(buffer$1, offset = 0) {
if (buffer$1.length < offset + 1) throw new InvalidArgumentError$24("Buffer too small to contain address type");
const addressType = buffer$1[offset];
let address;
let currentOffset = offset + 1;
switch (addressType) {
case 1:
if (buffer$1.length < currentOffset + 6) throw new InvalidArgumentError$24("Buffer too small for IPv4 address");
address = Array.from(buffer$1.subarray(currentOffset, currentOffset + 4)).join(".");
currentOffset += 4;
break;
case 3: {
if (buffer$1.length < currentOffset + 1) throw new InvalidArgumentError$24("Buffer too small for domain length");
const domainLength = buffer$1[currentOffset];
currentOffset += 1;
if (buffer$1.length < currentOffset + domainLength + 2) throw new InvalidArgumentError$24("Buffer too small for domain address");
address = buffer$1.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
currentOffset += domainLength;
break;
}
case 4: {
if (buffer$1.length < currentOffset + 18) throw new InvalidArgumentError$24("Buffer too small for IPv6 address");
const parts = [];
for (let i$1 = 0; i$1 < 8; i$1++) {
const value = buffer$1.readUInt16BE(currentOffset + i$1 * 2);
parts.push(value.toString(16));
}
address = parts.join(":");
currentOffset += 16;
break;
}
default: throw new InvalidArgumentError$24(`Invalid address type: ${addressType}`);
}
if (buffer$1.length < currentOffset + 2) throw new InvalidArgumentError$24("Buffer too small for port");
const port = buffer$1.readUInt16BE(currentOffset);
currentOffset += 2;
return {
address,
port,
bytesRead: currentOffset - offset
};
}
/**
* Create error for SOCKS5 reply code
* @param {number} replyCode - SOCKS5 reply code
* @returns {Error} Appropriate error object
*/
function createReplyError(replyCode) {
const message = {
1: "General SOCKS server failure",
2: "Connection not allowed by ruleset",
3: "Network unreachable",
4: "Host unreachable",
5: "Connection refused",
6: "TTL expired",
7: "Command not supported",
8: "Address type not supported"
}[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
const error = new Error(message);
error.code = `SOCKS5_${replyCode}`;
return error;
}
module.exports = {
parseAddress: parseAddress$1,
parseIPv6,
buildAddressBuffer,
parseResponseAddress,
createReplyError
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/socks5-client.js
var require_socks5_client = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/core/socks5-client.js": ((exports, module) => {
const { EventEmitter: EventEmitter$1 } = __require$2("node:events");
const { Buffer: Buffer$2 } = __require$2("node:buffer");
const { InvalidArgumentError: InvalidArgumentError$23, Socks5ProxyError } = require_errors();
const { debuglog: debuglog$2 } = __require$2("node:util");
const { parseAddress } = require_socks5_utils();
const debug$1 = debuglog$2("undici:socks5");
const SOCKS_VERSION = 5;
const AUTH_METHODS = {
NO_AUTH: 0,
GSSAPI: 1,
USERNAME_PASSWORD: 2,
NO_ACCEPTABLE: 255
};
const COMMANDS = {
CONNECT: 1,
BIND: 2,
UDP_ASSOCIATE: 3
};
const ADDRESS_TYPES = {
IPV4: 1,
DOMAIN: 3,
IPV6: 4
};
const REPLY_CODES = {
SUCCEEDED: 0,
GENERAL_FAILURE: 1,
CONNECTION_NOT_ALLOWED: 2,
NETWORK_UNREACHABLE: 3,
HOST_UNREACHABLE: 4,
CONNECTION_REFUSED: 5,
TTL_EXPIRED: 6,
COMMAND_NOT_SUPPORTED: 7,
ADDRESS_TYPE_NOT_SUPPORTED: 8
};
const STATES = {
INITIAL: "initial",
HANDSHAKING: "handshaking",
AUTHENTICATING: "authenticating",
CONNECTING: "connecting",
CONNECTED: "connected",
ERROR: "error",
CLOSED: "closed"
};
/**
* SOCKS5 client implementation
* Handles SOCKS5 protocol negotiation and connection establishment
*/
var Socks5Client$1 = class extends EventEmitter$1 {
constructor(socket, options = {}) {
super();
if (!socket) throw new InvalidArgumentError$23("socket is required");
this.socket = socket;
this.options = options;
this.state = STATES.INITIAL;
this.buffer = Buffer$2.alloc(0);
this.authMethods = [];
if (options.username && options.password) this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
this.authMethods.push(AUTH_METHODS.NO_AUTH);
this.socket.on("data", this.onData.bind(this));
this.socket.on("error", this.onError.bind(this));
this.socket.on("close", this.onClose.bind(this));
}
/**
* Handle incoming data from the socket
*/
onData(data$1) {
debug$1("received data", data$1.length, "bytes in state", this.state);
this.buffer = Buffer$2.concat([this.buffer, data$1]);
try {
switch (this.state) {
case STATES.HANDSHAKING:
this.handleHandshakeResponse();
break;
case STATES.AUTHENTICATING:
this.handleAuthResponse();
break;
case STATES.CONNECTING:
this.handleConnectResponse();
break;
}
} catch (err) {
this.onError(err);
}
}
/**
* Handle socket errors
*/
onError(err) {
debug$1("socket error", err);
this.state = STATES.ERROR;
this.emit("error", err);
this.destroy();
}
/**
* Handle socket close
*/
onClose() {
debug$1("socket closed");
this.state = STATES.CLOSED;
this.emit("close");
}
/**
* Destroy the client and underlying socket
*/
destroy() {
if (this.socket && !this.socket.destroyed) this.socket.destroy();
}
/**
* Start the SOCKS5 handshake
*/
handshake() {
if (this.state !== STATES.INITIAL) throw new InvalidArgumentError$23("Handshake already started");
debug$1("starting handshake with", this.authMethods.length, "auth methods");
this.state = STATES.HANDSHAKING;
const request$2 = Buffer$2.alloc(2 + this.authMethods.length);
request$2[0] = SOCKS_VERSION;
request$2[1] = this.authMethods.length;
this.authMethods.forEach((method, i$1) => {
request$2[2 + i$1] = method;
});
this.socket.write(request$2);
}
/**
* Handle handshake response from server
*/
handleHandshakeResponse() {
if (this.buffer.length < 2) return;
const version$2 = this.buffer[0];
const method = this.buffer[1];
if (version$2 !== SOCKS_VERSION) throw new Socks5ProxyError(`Invalid SOCKS version: ${version$2}`, "UND_ERR_SOCKS5_VERSION");
if (method === AUTH_METHODS.NO_ACCEPTABLE) throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
this.buffer = this.buffer.subarray(2);
debug$1("server selected auth method", method);
if (method === AUTH_METHODS.NO_AUTH) this.emit("authenticated");
else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
this.state = STATES.AUTHENTICATING;
this.sendAuthRequest();
} else throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
}
/**
* Send username/password authentication request
*/
sendAuthRequest() {
const { username, password } = this.options;
if (!username || !password) throw new InvalidArgumentError$23("Username and password required for authentication");
debug$1("sending username/password auth");
const usernameBuffer = Buffer$2.from(username);
const passwordBuffer = Buffer$2.from(password);
if (usernameBuffer.length > 255 || passwordBuffer.length > 255) throw new InvalidArgumentError$23("Username or password too long");
const request$2 = Buffer$2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
request$2[0] = 1;
request$2[1] = usernameBuffer.length;
usernameBuffer.copy(request$2, 2);
request$2[2 + usernameBuffer.length] = passwordBuffer.length;
passwordBuffer.copy(request$2, 3 + usernameBuffer.length);
this.socket.write(request$2);
}
/**
* Handle authentication response
*/
handleAuthResponse() {
if (this.buffer.length < 2) return;
const version$2 = this.buffer[0];
const status = this.buffer[1];
if (version$2 !== 1) throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version$2}`, "UND_ERR_SOCKS5_AUTH_VERSION");
if (status !== 0) throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
this.buffer = this.buffer.subarray(2);
debug$1("authentication successful");
this.emit("authenticated");
}
/**
* Send CONNECT command
* @param {string} address - Target address (IP or domain)
* @param {number} port - Target port
*/
connect(address, port) {
if (this.state === STATES.CONNECTED) throw new InvalidArgumentError$23("Already connected");
debug$1("connecting to", address, port);
this.state = STATES.CONNECTING;
const request$2 = this.buildConnectRequest(COMMANDS.CONNECT, address, port);
this.socket.write(request$2);
}
/**
* Build a SOCKS5 request
*/
buildConnectRequest(command, address, port) {
const { type: addressType, buffer: addressBuffer } = parseAddress(address);
const request$2 = Buffer$2.alloc(4 + addressBuffer.length + 2);
request$2[0] = SOCKS_VERSION;
request$2[1] = command;
request$2[2] = 0;
request$2[3] = addressType;
addressBuffer.copy(request$2, 4);
request$2.writeUInt16BE(port, 4 + addressBuffer.length);
return request$2;
}
/**
* Handle CONNECT response
*/
handleConnectResponse() {
if (this.buffer.length < 4) return;
const version$2 = this.buffer[0];
const reply = this.buffer[1];
const addressType = this.buffer[3];
if (version$2 !== SOCKS_VERSION) throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version$2}`, "UND_ERR_SOCKS5_REPLY_VERSION");
let responseLength = 4;
if (addressType === ADDRESS_TYPES.IPV4) responseLength += 6;
else if (addressType === ADDRESS_TYPES.DOMAIN) {
if (this.buffer.length < 5) return;
responseLength += 1 + this.buffer[4] + 2;
} else if (addressType === ADDRESS_TYPES.IPV6) responseLength += 18;
else throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
if (this.buffer.length < responseLength) return;
if (reply !== REPLY_CODES.SUCCEEDED) throw new Socks5ProxyError(`SOCKS5 connection failed: ${this.getReplyErrorMessage(reply)}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
let boundAddress;
let offset = 4;
if (addressType === ADDRESS_TYPES.IPV4) {
boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
offset += 4;
} else if (addressType === ADDRESS_TYPES.DOMAIN) {
const domainLength = this.buffer[offset];
offset += 1;
boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
offset += domainLength;
} else if (addressType === ADDRESS_TYPES.IPV6) {
const parts = [];
for (let i$1 = 0; i$1 < 8; i$1++) {
const value = this.buffer.readUInt16BE(offset + i$1 * 2);
parts.push(value.toString(16));
}
boundAddress = parts.join(":");
offset += 16;
}
const boundPort = this.buffer.readUInt16BE(offset);
this.buffer = this.buffer.subarray(responseLength);
this.state = STATES.CONNECTED;
debug$1("connected, bound address:", boundAddress, "port:", boundPort);
this.emit("connected", {
address: boundAddress,
port: boundPort
});
}
/**
* Get human-readable error message for reply code
*/
getReplyErrorMessage(reply) {
switch (reply) {
case REPLY_CODES.GENERAL_FAILURE: return "General SOCKS server failure";
case REPLY_CODES.CONNECTION_NOT_ALLOWED: return "Connection not allowed by ruleset";
case REPLY_CODES.NETWORK_UNREACHABLE: return "Network unreachable";
case REPLY_CODES.HOST_UNREACHABLE: return "Host unreachable";
case REPLY_CODES.CONNECTION_REFUSED: return "Connection refused";
case REPLY_CODES.TTL_EXPIRED: return "TTL expired";
case REPLY_CODES.COMMAND_NOT_SUPPORTED: return "Command not supported";
case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED: return "Address type not supported";
default: return `Unknown error code: ${reply}`;
}
}
};
module.exports = {
Socks5Client: Socks5Client$1,
AUTH_METHODS,
COMMANDS,
ADDRESS_TYPES,
REPLY_CODES,
STATES
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
var require_socks5_proxy_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/socks5-proxy-agent.js": ((exports, module) => {
const net$1 = __require$2("node:net");
const { URL: URL$2 } = __require$2("node:url");
let tls;
const DispatcherBase$2 = require_dispatcher_base();
const { InvalidArgumentError: InvalidArgumentError$22 } = require_errors();
const { Socks5Client } = require_socks5_client();
const { kDispatch: kDispatch$2, kClose: kClose$4, kDestroy: kDestroy$2 } = require_symbols();
const Pool$3 = require_pool();
const buildConnector$2 = require_connect();
const { debuglog: debuglog$1 } = __require$2("node:util");
const debug = debuglog$1("undici:socks5-proxy");
const kProxyUrl = Symbol("proxy url");
const kProxyHeaders$1 = Symbol("proxy headers");
const kProxyAuth = Symbol("proxy auth");
const kPool = Symbol("pool");
const kConnector = Symbol("connector");
let experimentalWarningEmitted = false;
/**
* SOCKS5 proxy agent for dispatching requests through a SOCKS5 proxy
*/
var Socks5ProxyAgent$2 = class extends DispatcherBase$2 {
constructor(proxyUrl, options = {}) {
super();
if (!experimentalWarningEmitted) {
process.emitWarning("SOCKS5 proxy support is experimental and subject to change", "ExperimentalWarning");
experimentalWarningEmitted = true;
}
if (!proxyUrl) throw new InvalidArgumentError$22("Proxy URL is mandatory");
const url = typeof proxyUrl === "string" ? new URL$2(proxyUrl) : proxyUrl;
if (url.protocol !== "socks5:" && url.protocol !== "socks:") throw new InvalidArgumentError$22("Proxy URL must use socks5:// or socks:// protocol");
this[kProxyUrl] = url;
this[kProxyHeaders$1] = options.headers || {};
this[kProxyAuth] = {
username: options.username || (url.username ? decodeURIComponent(url.username) : null),
password: options.password || (url.password ? decodeURIComponent(url.password) : null)
};
this[kConnector] = options.connect || buildConnector$2({
...options.proxyTls,
servername: options.proxyTls?.servername || url.hostname
});
this[kPool] = null;
}
/**
* Create a SOCKS5 connection to the proxy
*/
async createSocks5Connection(targetHost, targetPort) {
const proxyHost = this[kProxyUrl].hostname;
const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
debug("creating SOCKS5 connection to", proxyHost, proxyPort);
const socket = await new Promise((resolve$4, reject) => {
const onConnect = () => {
socket$1.removeListener("error", onError$1);
resolve$4(socket$1);
};
const onError$1 = (err) => {
socket$1.removeListener("connect", onConnect);
reject(err);
};
const socket$1 = net$1.connect({
host: proxyHost,
port: proxyPort
});
socket$1.once("connect", onConnect);
socket$1.once("error", onError$1);
});
const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
socks5Client.on("error", (err) => {
debug("SOCKS5 error:", err);
socket.destroy();
});
await socks5Client.handshake();
await new Promise((resolve$4, reject) => {
const timeout$1 = setTimeout(() => {
reject(/* @__PURE__ */ new Error("SOCKS5 authentication timeout"));
}, 5e3);
const onAuthenticated = () => {
clearTimeout(timeout$1);
socks5Client.removeListener("error", onError$1);
resolve$4();
};
const onError$1 = (err) => {
clearTimeout(timeout$1);
socks5Client.removeListener("authenticated", onAuthenticated);
reject(err);
};
if (socks5Client.state === "authenticated") {
clearTimeout(timeout$1);
resolve$4();
} else {
socks5Client.once("authenticated", onAuthenticated);
socks5Client.once("error", onError$1);
}
});
await socks5Client.connect(targetHost, targetPort);
await new Promise((resolve$4, reject) => {
const timeout$1 = setTimeout(() => {
reject(/* @__PURE__ */ new Error("SOCKS5 connection timeout"));
}, 5e3);
const onConnected = (info) => {
debug("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
clearTimeout(timeout$1);
socks5Client.removeListener("error", onError$1);
resolve$4();
};
const onError$1 = (err) => {
clearTimeout(timeout$1);
socks5Client.removeListener("connected", onConnected);
reject(err);
};
socks5Client.once("connected", onConnected);
socks5Client.once("error", onError$1);
});
return socket;
}
/**
* Dispatch a request through the SOCKS5 proxy
*/
async [kDispatch$2](opts, handler) {
const { origin } = opts;
debug("dispatching request to", origin, "via SOCKS5");
try {
if (!this[kPool] || this[kPool].destroyed || this[kPool].closed) this[kPool] = new Pool$3(origin, {
pipelining: opts.pipelining,
connections: opts.connections,
connect: async (connectOpts, callback$1) => {
try {
const url = new URL$2(origin);
const targetHost = url.hostname;
const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
debug("establishing SOCKS5 connection to", targetHost, targetPort);
const socket = await this.createSocks5Connection(targetHost, targetPort);
let finalSocket = socket;
if (url.protocol === "https:") {
if (!tls) tls = __require$2("node:tls");
debug("upgrading to TLS");
finalSocket = tls.connect({
socket,
servername: targetHost,
...connectOpts.tls || {}
});
await new Promise((resolve$4, reject) => {
finalSocket.once("secureConnect", resolve$4);
finalSocket.once("error", reject);
});
}
callback$1(null, finalSocket);
} catch (err) {
debug("SOCKS5 connection error:", err);
callback$1(err);
}
}
});
return this[kPool][kDispatch$2](opts, handler);
} catch (err) {
debug("dispatch error:", err);
if (typeof handler.onError === "function") handler.onError(err);
else throw err;
}
}
async [kClose$4]() {
if (this[kPool]) await this[kPool].close();
}
async [kDestroy$2](err) {
if (this[kPool]) await this[kPool].destroy(err);
}
};
module.exports = Socks5ProxyAgent$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/proxy-agent.js": ((exports, module) => {
const { kProxy, kClose: kClose$3, kDestroy: kDestroy$1, kDispatch: kDispatch$1 } = require_symbols();
const Agent$5 = require_agent();
const Pool$2 = require_pool();
const DispatcherBase$1 = require_dispatcher_base();
const { InvalidArgumentError: InvalidArgumentError$21, RequestAbortedError: RequestAbortedError$6, SecureProxyConnectionError } = require_errors();
const buildConnector$1 = require_connect();
const Client$3 = require_client();
const { channels: channels$2 } = require_diagnostics();
const Socks5ProxyAgent$1 = require_socks5_proxy_agent();
const kAgent$1 = Symbol("proxy agent");
const kClient = Symbol("proxy client");
const kProxyHeaders = Symbol("proxy headers");
const kRequestTls = Symbol("request tls settings");
const kProxyTls = Symbol("proxy tls settings");
const kConnectEndpoint = Symbol("connect endpoint function");
const kTunnelProxy = Symbol("tunnel proxy");
function defaultProtocolPort(protocol) {
return protocol === "https:" ? 443 : 80;
}
function defaultFactory(origin, opts) {
return new Pool$2(origin, opts);
}
const noop$6 = () => {};
function defaultAgentFactory(origin, opts) {
if (opts.connections === 1) return new Client$3(origin, opts);
return new Pool$2(origin, opts);
}
var Http1ProxyWrapper = class extends DispatcherBase$1 {
#client;
constructor(proxyUrl, { headers = {}, connect: connect$2, factory: factory$1 }) {
if (!proxyUrl) throw new InvalidArgumentError$21("Proxy URL is mandatory");
super();
this[kProxyHeaders] = headers;
if (factory$1) this.#client = factory$1(proxyUrl, { connect: connect$2 });
else this.#client = new Client$3(proxyUrl, { connect: connect$2 });
}
[kDispatch$1](opts, handler) {
const onHeaders = handler.onHeaders;
handler.onHeaders = function(statusCode, data$1, resume$1) {
if (statusCode === 407) {
if (typeof handler.onError === "function") handler.onError(new InvalidArgumentError$21("Proxy Authentication Required (407)"));
return;
}
if (onHeaders) onHeaders.call(this, statusCode, data$1, resume$1);
};
const { origin, path: path$2 = "/", headers = {} } = opts;
opts.path = origin + path$2;
if (!("host" in headers) && !("Host" in headers)) {
const { host } = new URL(origin);
headers.host = host;
}
opts.headers = {
...this[kProxyHeaders],
...headers
};
return this.#client[kDispatch$1](opts, handler);
}
[kClose$3]() {
return this.#client.close();
}
[kDestroy$1](err) {
return this.#client.destroy(err);
}
};
var ProxyAgent$2 = class extends DispatcherBase$1 {
constructor(opts) {
if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) throw new InvalidArgumentError$21("Proxy uri is mandatory");
const { clientFactory = defaultFactory } = opts;
if (typeof clientFactory !== "function") throw new InvalidArgumentError$21("Proxy opts.clientFactory must be a function.");
const { proxyTunnel = true } = opts;
super();
const url = this.#getUrl(opts);
const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url;
this[kProxy] = {
uri: href,
protocol
};
this[kRequestTls] = opts.requestTls;
this[kProxyTls] = opts.proxyTls;
this[kProxyHeaders] = opts.headers || {};
this[kTunnelProxy] = proxyTunnel;
if (opts.auth && opts.token) throw new InvalidArgumentError$21("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 connect$2 = buildConnector$1({ ...opts.proxyTls });
this[kConnectEndpoint] = buildConnector$1({ ...opts.requestTls });
const agentFactory = opts.factory || defaultAgentFactory;
const factory$1 = (origin$1, options) => {
const { protocol: protocol$1 } = new URL(origin$1);
if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") return new Socks5ProxyAgent$1(this[kProxy].uri, {
headers: this[kProxyHeaders],
connect: connect$2,
factory: agentFactory,
username: opts.username || username,
password: opts.password || password,
proxyTls: opts.proxyTls
});
if (!this[kTunnelProxy] && protocol$1 === "http:" && this[kProxy].protocol === "http:") return new Http1ProxyWrapper(this[kProxy].uri, {
headers: this[kProxyHeaders],
connect: connect$2,
factory: agentFactory
});
return agentFactory(origin$1, options);
};
if (protocol === "socks5:" || protocol === "socks:") this[kClient] = null;
else this[kClient] = clientFactory(url, { connect: connect$2 });
this[kAgent$1] = new Agent$5({
...opts,
factory: factory$1,
connect: async (opts$1, callback$1) => {
if (!this[kClient]) {
callback$1(new InvalidArgumentError$21("Cannot establish tunnel connection without a proxy client"));
return;
}
let requestedPath = opts$1.host;
if (!opts$1.port) requestedPath += `:${defaultProtocolPort(opts$1.protocol)}`;
try {
const connectParams = {
origin,
port,
path: requestedPath,
signal: opts$1.signal,
headers: {
...this[kProxyHeaders],
host: opts$1.host,
...opts$1.connections == null || opts$1.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
},
servername: this[kProxyTls]?.servername || proxyHostname
};
const { socket, statusCode } = await this[kClient].connect(connectParams);
if (statusCode !== 200) {
socket.on("error", noop$6).destroy();
callback$1(new RequestAbortedError$6(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
return;
}
if (channels$2.proxyConnected.hasSubscribers) channels$2.proxyConnected.publish({
socket,
connectParams
});
if (opts$1.protocol !== "https:") {
callback$1(null, socket);
return;
}
let servername;
if (this[kRequestTls]) servername = this[kRequestTls].servername;
else servername = opts$1.servername;
this[kConnectEndpoint]({
...opts$1,
servername,
httpSocket: socket
}, callback$1);
} catch (err) {
if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") callback$1(new SecureProxyConnectionError(err));
else callback$1(err);
}
}
});
}
dispatch(opts, handler) {
const headers = buildHeaders(opts.headers);
throwIfProxyAuthIsSent(headers);
if (headers && !("host" in headers) && !("Host" in headers)) {
const { host } = new URL(opts.origin);
headers.host = host;
}
return this[kAgent$1].dispatch({
...opts,
headers
}, handler);
}
/**
* @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
* @returns {URL}
*/
#getUrl(opts) {
if (typeof opts === "string") return new URL(opts);
else if (opts instanceof URL) return opts;
else return new URL(opts.uri);
}
[kClose$3]() {
const promises$1 = [this[kAgent$1].close()];
if (this[kClient]) promises$1.push(this[kClient].close());
return Promise.all(promises$1);
}
[kDestroy$1]() {
const promises$1 = [this[kAgent$1].destroy()];
if (this[kClient]) promises$1.push(this[kClient].destroy());
return Promise.all(promises$1);
}
};
/**
* @param {string[] | Record<string, string>} headers
* @returns {Record<string, string>}
*/
function buildHeaders(headers) {
if (Array.isArray(headers)) {
/** @type {Record<string, string>} */
const headersPair = {};
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) headersPair[headers[i$1]] = headers[i$1 + 1];
return headersPair;
}
return headers;
}
/**
* @param {Record<string, string>} headers
*
* Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
* Nevertheless, it was changed and to avoid a security vulnerability by end users
* this check was created.
* It should be removed in the next major version for performance reasons
*/
function throwIfProxyAuthIsSent(headers) {
if (headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization")) throw new InvalidArgumentError$21("Proxy-Authorization should be sent in ProxyAgent constructor");
}
module.exports = ProxyAgent$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js": ((exports, module) => {
const DispatcherBase = require_dispatcher_base();
const { kClose: kClose$2, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
const ProxyAgent$1 = require_proxy_agent();
const Agent$4 = require_agent();
const DEFAULT_PORTS = {
"http:": 80,
"https:": 443
};
var EnvHttpProxyAgent$1 = class extends DispatcherBase {
#noProxyValue = null;
#noProxyEntries = null;
#opts = null;
constructor(opts = {}) {
super();
this.#opts = opts;
const { httpProxy, httpsProxy, noProxy,...agentOpts } = opts;
this[kNoProxyAgent] = new Agent$4(agentOpts);
const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
if (HTTP_PROXY) this[kHttpProxyAgent] = new ProxyAgent$1({
...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 ProxyAgent$1({
...agentOpts,
uri: HTTPS_PROXY
});
else this[kHttpsProxyAgent] = this[kHttpProxyAgent];
this.#parseNoProxy();
}
[kDispatch](opts, handler) {
const url = new URL(opts.origin);
return this.#getProxyAgentForUrl(url).dispatch(opts, handler);
}
[kClose$2]() {
return Promise.all([
this[kNoProxyAgent].close(),
!this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(),
!this[kHttpsProxyAgent][kClosed] && this[kHttpsProxyAgent].close()
]);
}
[kDestroy](err) {
return Promise.all([
this[kNoProxyAgent].destroy(err),
!this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err),
!this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err)
]);
}
#getProxyAgentForUrl(url) {
let { protocol, host: hostname, port } = url;
hostname = hostname.replace(/:\d*$/, "").toLowerCase();
port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
if (!this.#shouldProxy(hostname, port)) return this[kNoProxyAgent];
if (protocol === "https:") return this[kHttpsProxyAgent];
return this[kHttpProxyAgent];
}
#shouldProxy(hostname, port) {
if (this.#noProxyChanged) this.#parseNoProxy();
if (this.#noProxyEntries.length === 0) return true;
if (this.#noProxyValue === "*") return false;
for (let i$1 = 0; i$1 < this.#noProxyEntries.length; i$1++) {
const entry = this.#noProxyEntries[i$1];
if (entry.port && entry.port !== port) continue;
if (hostname === entry.hostname) return false;
if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) return false;
}
return true;
}
#parseNoProxy() {
const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
const noProxySplit = noProxyValue.split(/[,\s]/);
const noProxyEntries = [];
for (let i$1 = 0; i$1 < noProxySplit.length; i$1++) {
const entry = noProxySplit[i$1];
if (!entry) continue;
const parsed = entry.match(/^(.+):(\d+)$/);
noProxyEntries.push({
hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").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 ?? "";
}
};
module.exports = EnvHttpProxyAgent$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/retry-handler.js": ((exports, module) => {
const assert$21 = __require$2("node:assert");
const { kRetryHandlerDefaultRetry } = require_symbols();
const { RequestRetryError } = require_errors();
const WrapHandler$2 = require_wrap_handler();
const { isDisturbed: isDisturbed$1, parseRangeHeader, wrapRequestBody } = require_util$5();
function calculateRetryAfterHeader(retryAfter) {
const retryTime = new Date(retryAfter).getTime();
return isNaN(retryTime) ? 0 : retryTime - Date.now();
}
var RetryHandler$3 = class RetryHandler$3 {
constructor(opts, { dispatch, handler }) {
const { retryOptions,...dispatchOpts } = opts;
const { retry: retryFn, maxRetries, maxTimeout, minTimeout, timeoutFactor, methods, errorCodes, retryAfter, statusCodes, throwOnError } = retryOptions ?? {};
this.error = null;
this.dispatch = dispatch;
this.handler = WrapHandler$2.wrap(handler);
this.opts = {
...dispatchOpts,
body: wrapRequestBody(opts.body)
};
this.retryOpts = {
throwOnError: throwOnError ?? true,
retry: retryFn ?? RetryHandler$3[kRetryHandlerDefaultRetry],
retryAfter: retryAfter ?? true,
maxTimeout: maxTimeout ?? 30 * 1e3,
minTimeout: minTimeout ?? 500,
timeoutFactor: timeoutFactor ?? 2,
maxRetries: maxRetries ?? 5,
methods: methods ?? [
"GET",
"HEAD",
"OPTIONS",
"PUT",
"DELETE",
"TRACE"
],
statusCodes: statusCodes ?? [
500,
502,
503,
504,
429
],
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$1(this.opts.body)) {
this.headersSent = true;
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
return;
}
function shouldRetry(passedErr) {
if (passedErr) {
this.headersSent = true;
this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
controller.resume();
return;
}
this.error = err;
controller.resume();
}
controller.pause();
this.retryOpts.retry(err, {
state: { counter: this.retryCount },
opts: {
retryOptions: this.retryOpts,
...this.opts
}
}, shouldRetry.bind(this));
}
onRequestStart(controller, context) {
if (!this.headersSent) this.handler.onRequestStart?.(controller, context);
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
const { statusCode, code, headers } = err;
const { method, retryOptions } = opts;
const { maxRetries, minTimeout, maxTimeout, timeoutFactor, statusCodes, errorCodes, methods } = retryOptions;
const { counter } = state;
if (code && code !== "UND_ERR_REQ_RETRY" && !errorCodes.includes(code)) {
cb(err);
return;
}
if (Array.isArray(methods) && !methods.includes(method)) {
cb(err);
return;
}
if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
cb(err);
return;
}
if (counter > maxRetries) {
cb(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(() => cb(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;
assert$21(this.start === start, "content-range mismatch");
assert$21(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;
assert$21(start != null && Number.isFinite(start), "content-range mismatch");
assert$21(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;
}
assert$21(Number.isFinite(this.start));
assert$21(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$1(this.opts.body)) {
this.handler.onResponseError?.(controller, err);
return;
}
function shouldRetry(returnedErr) {
if (!returnedErr) {
this.retry(controller);
return;
}
this.handler?.onResponseError?.(controller, returnedErr);
}
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));
}
};
module.exports = RetryHandler$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/retry-agent.js": ((exports, module) => {
const Dispatcher$2 = require_dispatcher();
const RetryHandler$2 = require_retry_handler();
var RetryAgent$1 = class extends Dispatcher$2 {
#agent = null;
#options = null;
constructor(agent, options = {}) {
super(options);
this.#agent = agent;
this.#options = options;
}
dispatch(opts, handler) {
const retry = new RetryHandler$2({
...opts,
retryOptions: this.#options
}, {
dispatch: this.#agent.dispatch.bind(this.#agent),
handler
});
return this.#agent.dispatch(opts, retry);
}
close() {
return this.#agent.close();
}
destroy() {
return this.#agent.destroy();
}
};
module.exports = RetryAgent$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/h2c-client.js
var require_h2c_client = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/dispatcher/h2c-client.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$20 } = require_errors();
const Client$2 = require_client();
var H2CClient$1 = class extends Client$2 {
constructor(origin, clientOpts) {
if (typeof origin === "string") origin = new URL(origin);
if (origin.protocol !== "http:") throw new InvalidArgumentError$20("h2c-client: Only h2c protocol is supported");
const { connect: connect$2, 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$20("h2c-client: pipelining cannot be greater than maxConcurrentStreams");
super(origin, {
...opts,
maxConcurrentStreams: defaultMaxConcurrentStreams,
pipelining: defaultPipelining,
allowH2: true,
useH2c: true
});
}
};
module.exports = H2CClient$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/readable.js
var require_readable = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/readable.js": ((exports, module) => {
const assert$20 = __require$2("node:assert");
const { Readable: Readable$4 } = __require$2("node:stream");
const { RequestAbortedError: RequestAbortedError$5, NotSupportedError, InvalidArgumentError: InvalidArgumentError$19, AbortError: AbortError$1 } = require_errors();
const util$16 = require_util$5();
const { ReadableStreamFrom } = require_util$5();
const kConsume = Symbol("kConsume");
const kReading = Symbol("kReading");
const kBody$1 = Symbol("kBody");
const kAbort = Symbol("kAbort");
const kContentType = Symbol("kContentType");
const kContentLength$1 = Symbol("kContentLength");
const kUsed = Symbol("kUsed");
const kBytesRead = Symbol("kBytesRead");
const noop$5 = () => {};
/**
* @class
* @extends {Readable}
* @see https://fetch.spec.whatwg.org/#body
*/
var BodyReadable = class extends Readable$4 {
/**
* @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: resume$1, abort: abort$1, contentType = "", contentLength, highWaterMark = 64 * 1024 }) {
super({
autoDestroy: true,
read: resume$1,
highWaterMark
});
this._readableState.dataEmitted = false;
this[kAbort] = abort$1;
/** @type {Consume | null} */
this[kConsume] = null;
/** @type {number} */
this[kBytesRead] = 0;
/** @type {ReadableStream|null} */
this[kBody$1] = null;
/** @type {boolean} */
this[kUsed] = false;
/** @type {string} */
this[kContentType] = contentType;
/** @type {number|null} */
this[kContentLength$1] = Number.isFinite(contentLength) ? contentLength : null;
/**
* Is stream being consumed through Readable API?
* This is an optimization so that we avoid checking
* for 'data' and 'readable' listeners in the hot path
* inside push().
*
* @type {boolean}
*/
this[kReading] = false;
}
/**
* @param {Error|null} err
* @param {(error:(Error|null)) => void} callback
* @returns {void}
*/
_destroy(err, callback$1) {
if (!err && !this._readableState.endEmitted) err = new RequestAbortedError$5();
if (err) this[kAbort]();
if (!this[kUsed]) setImmediate(callback$1, err);
else callback$1(err);
}
/**
* @param {string|symbol} 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|symbol} 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) {
if (chunk) {
this[kBytesRead] += chunk.length;
if (this[kConsume]) {
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 util$16.isDisturbed(this);
}
/**
* @see https://fetch.spec.whatwg.org/#dom-body-body
* @readonly
* @returns {ReadableStream}
*/
get body() {
if (!this[kBody$1]) {
this[kBody$1] = ReadableStreamFrom(this);
if (this[kConsume]) {
this[kBody$1].getReader();
assert$20(this[kBody$1].locked);
}
}
return this[kBody$1];
}
/**
* 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>}
*/
dump(opts) {
const signal = opts?.signal;
if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) return Promise.reject(new InvalidArgumentError$19("signal must be an AbortSignal"));
const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024;
if (signal?.aborted) return Promise.reject(signal.reason ?? new AbortError$1());
if (this._readableState.closeEmitted) return Promise.resolve(null);
return new Promise((resolve$4, reject) => {
if (this[kContentLength$1] && this[kContentLength$1] > limit || this[kBytesRead] > limit) this.destroy(new AbortError$1());
if (signal) {
const onAbort = () => {
this.destroy(signal.reason ?? new AbortError$1());
};
signal.addEventListener("abort", onAbort);
this.on("close", function() {
signal.removeEventListener("abort", onAbort);
if (signal.aborted) reject(signal.reason ?? new AbortError$1());
else resolve$4(null);
});
} else this.on("close", resolve$4);
this.on("error", noop$5).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;
}
};
/**
* @see https://streams.spec.whatwg.org/#readablestream-locked
* @param {BodyReadable} bodyReadable
* @returns {boolean}
*/
function isLocked(bodyReadable) {
return bodyReadable[kBody$1]?.locked === true || bodyReadable[kConsume] !== null;
}
/**
* @see https://fetch.spec.whatwg.org/#body-unusable
* @param {BodyReadable} bodyReadable
* @returns {boolean}
*/
function isUnusable(bodyReadable) {
return util$16.isDisturbed(bodyReadable) || isLocked(bodyReadable);
}
/**
* @typedef {'text' | 'json' | 'blob' | 'bytes' | 'arrayBuffer'} ConsumeType
*/
/**
* @template {ConsumeType} T
* @typedef {T extends 'text' ? string :
* T extends 'json' ? unknown :
* T extends 'blob' ? Blob :
* T extends 'arrayBuffer' ? ArrayBuffer :
* T extends 'bytes' ? Uint8Array :
* never
* } ConsumeReturnType
*/
/**
* @typedef {object} Consume
* @property {ConsumeType} type
* @property {BodyReadable} stream
* @property {((value?: any) => void)} resolve
* @property {((err: Error) => void)} reject
* @property {number} length
* @property {Buffer[]} body
*/
/**
* @template {ConsumeType} T
* @param {BodyReadable} stream
* @param {T} type
* @returns {Promise<ConsumeReturnType<T>>}
*/
function consume(stream$2, type) {
assert$20(!stream$2[kConsume]);
return new Promise((resolve$4, reject) => {
if (isUnusable(stream$2)) {
const rState = stream$2._readableState;
if (rState.destroyed && rState.closeEmitted === false) stream$2.on("error", reject).on("close", () => {
reject(/* @__PURE__ */ new TypeError("unusable"));
});
else reject(rState.errored ?? /* @__PURE__ */ new TypeError("unusable"));
} else queueMicrotask(() => {
stream$2[kConsume] = {
type,
stream: stream$2,
resolve: resolve$4,
reject,
length: 0,
body: []
};
stream$2.on("error", function(err) {
consumeFinish(this[kConsume], err);
}).on("close", function() {
if (this[kConsume].body !== null) consumeFinish(this[kConsume], new RequestAbortedError$5());
});
consumeStart(stream$2[kConsume]);
});
});
}
/**
* @param {Consume} consume
* @returns {void}
*/
function consumeStart(consume$1) {
if (consume$1.body === null) return;
const { _readableState: state } = consume$1.stream;
if (state.bufferIndex) {
const start = state.bufferIndex;
const end = state.buffer.length;
for (let n$1 = start; n$1 < end; n$1++) consumePush(consume$1, state.buffer[n$1]);
} else for (const chunk of state.buffer) consumePush(consume$1, chunk);
if (state.endEmitted) consumeEnd(this[kConsume], this._readableState.encoding);
else consume$1.stream.on("end", function() {
consumeEnd(this[kConsume], this._readableState.encoding);
});
consume$1.stream.resume();
while (consume$1.stream.read() != null);
}
/**
* @param {Buffer[]} chunks
* @param {number} length
* @param {BufferEncoding} [encoding='utf8']
* @returns {string}
*/
function chunksDecode(chunks, length, encoding) {
if (chunks.length === 0 || length === 0) return "";
const buffer$1 = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length);
const bufferLength = buffer$1.length;
const start = bufferLength > 2 && buffer$1[0] === 239 && buffer$1[1] === 187 && buffer$1[2] === 191 ? 3 : 0;
if (!encoding || encoding === "utf8" || encoding === "utf-8") return buffer$1.utf8Slice(start, bufferLength);
else return buffer$1.subarray(start, bufferLength).toString(encoding);
}
/**
* @param {Buffer[]} chunks
* @param {number} length
* @returns {Uint8Array}
*/
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$1 = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
let offset = 0;
for (let i$1 = 0; i$1 < chunks.length; ++i$1) {
const chunk = chunks[i$1];
buffer$1.set(chunk, offset);
offset += chunk.length;
}
return buffer$1;
}
/**
* @param {Consume} consume
* @param {BufferEncoding} encoding
* @returns {void}
*/
function consumeEnd(consume$1, encoding) {
const { type, body, resolve: resolve$4, stream: stream$2, length } = consume$1;
try {
if (type === "text") resolve$4(chunksDecode(body, length, encoding));
else if (type === "json") resolve$4(JSON.parse(chunksDecode(body, length, encoding)));
else if (type === "arrayBuffer") resolve$4(chunksConcat(body, length).buffer);
else if (type === "blob") resolve$4(new Blob(body, { type: stream$2[kContentType] }));
else if (type === "bytes") resolve$4(chunksConcat(body, length));
consumeFinish(consume$1);
} catch (err) {
stream$2.destroy(err);
}
}
/**
* @param {Consume} consume
* @param {Buffer} chunk
* @returns {void}
*/
function consumePush(consume$1, chunk) {
consume$1.length += chunk.length;
consume$1.body.push(chunk);
}
/**
* @param {Consume} consume
* @param {Error} [err]
* @returns {void}
*/
function consumeFinish(consume$1, err) {
if (consume$1.body === null) return;
if (err) consume$1.reject(err);
else consume$1.resolve();
consume$1.type = null;
consume$1.stream = null;
consume$1.resolve = null;
consume$1.reject = null;
consume$1.length = 0;
consume$1.body = null;
}
module.exports = {
Readable: BodyReadable,
chunksDecode
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-request.js
var require_api_request = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-request.js": ((exports, module) => {
const assert$19 = __require$2("node:assert");
const { AsyncResource: AsyncResource$4 } = __require$2("node:async_hooks");
const { Readable: Readable$3 } = require_readable();
const { InvalidArgumentError: InvalidArgumentError$18, RequestAbortedError: RequestAbortedError$4 } = require_errors();
const util$15 = require_util$5();
function noop$4() {}
var RequestHandler = class extends AsyncResource$4 {
constructor(opts, callback$1) {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$18("invalid opts");
const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
try {
if (typeof callback$1 !== "function") throw new InvalidArgumentError$18("invalid callback");
if (highWaterMark && (typeof highWaterMark !== "number" || highWaterMark < 0)) throw new InvalidArgumentError$18("invalid highWaterMark");
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") throw new InvalidArgumentError$18("signal must be an EventEmitter or EventTarget");
if (method === "CONNECT") throw new InvalidArgumentError$18("invalid method");
if (onInfo && typeof onInfo !== "function") throw new InvalidArgumentError$18("invalid onInfo callback");
super("UNDICI_REQUEST");
} catch (err) {
if (util$15.isStream(body)) util$15.destroy(body.on("error", noop$4), err);
throw err;
}
this.method = method;
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback$1;
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$4();
else if (signal) this.removeAbortListener = util$15.addAbortListener(signal, () => {
this.reason = signal.reason ?? new RequestAbortedError$4();
if (this.res) util$15.destroy(this.res.on("error", noop$4), this.reason);
else if (this.abort) this.abort(this.reason);
});
}
onConnect(abort$1, context) {
if (this.reason) {
abort$1(this.reason);
return;
}
assert$19(this.callback);
this.abort = abort$1;
this.context = context;
}
onHeaders(statusCode, rawHeaders, resume$1, statusMessage) {
const { callback: callback$1, opaque, abort: abort$1, context, responseHeaders, highWaterMark } = this;
const headers = responseHeaders === "raw" ? util$15.parseRawHeaders(rawHeaders) : util$15.parseHeaders(rawHeaders);
if (statusCode < 200) {
if (this.onInfo) this.onInfo({
statusCode,
headers
});
return;
}
const parsedHeaders = responseHeaders === "raw" ? util$15.parseHeaders(rawHeaders) : headers;
const contentType = parsedHeaders["content-type"];
const contentLength = parsedHeaders["content-length"];
const res = new Readable$3({
resume: resume$1,
abort: abort$1,
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$1 !== null) try {
this.runInAsyncScope(callback$1, null, null, {
statusCode,
statusText: statusMessage,
headers,
trailers: this.trailers,
opaque,
body: res,
context
});
} catch (err) {
this.res = null;
util$15.destroy(res.on("error", noop$4), err);
queueMicrotask(() => {
throw err;
});
}
}
onData(chunk) {
return this.res.push(chunk);
}
onComplete(trailers) {
util$15.parseHeaders(trailers, this.trailers);
this.res.push(null);
}
onError(err) {
const { res, callback: callback$1, body, opaque } = this;
if (callback$1) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback$1, null, err, { opaque });
});
}
if (res) {
this.res = null;
queueMicrotask(() => {
util$15.destroy(res.on("error", noop$4), err);
});
}
if (body) {
this.body = null;
if (util$15.isStream(body)) {
body.on("error", noop$4);
util$15.destroy(body, err);
}
}
if (this.removeAbortListener) {
this.removeAbortListener();
this.removeAbortListener = null;
}
}
};
function request$1(opts, callback$1) {
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
request$1.call(this, opts, (err, data$1) => {
return err ? reject(err) : resolve$4(data$1);
});
});
try {
const handler = new RequestHandler(opts, callback$1);
this.dispatch(opts, handler);
} catch (err) {
if (typeof callback$1 !== "function") throw err;
const opaque = opts?.opaque;
queueMicrotask(() => callback$1(err, { opaque }));
}
}
module.exports = request$1;
module.exports.RequestHandler = RequestHandler;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/abort-signal.js": ((exports, module) => {
const { addAbortListener: addAbortListener$1 } = require_util$5();
const { RequestAbortedError: RequestAbortedError$3 } = require_errors();
const kListener = Symbol("kListener");
const kSignal = Symbol("kSignal");
function abort(self) {
if (self.abort) self.abort(self[kSignal]?.reason);
else self.reason = self[kSignal]?.reason ?? new RequestAbortedError$3();
removeSignal$4(self);
}
function addSignal$4(self, signal) {
self.reason = null;
self[kSignal] = null;
self[kListener] = null;
if (!signal) return;
if (signal.aborted) {
abort(self);
return;
}
self[kSignal] = signal;
self[kListener] = () => {
abort(self);
};
addAbortListener$1(self[kSignal], self[kListener]);
}
function removeSignal$4(self) {
if (!self[kSignal]) return;
if ("removeEventListener" in self[kSignal]) self[kSignal].removeEventListener("abort", self[kListener]);
else self[kSignal].removeListener("abort", self[kListener]);
self[kSignal] = null;
self[kListener] = null;
}
module.exports = {
addSignal: addSignal$4,
removeSignal: removeSignal$4
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-stream.js
var require_api_stream = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-stream.js": ((exports, module) => {
const assert$18 = __require$2("node:assert");
const { finished: finished$1 } = __require$2("node:stream");
const { AsyncResource: AsyncResource$3 } = __require$2("node:async_hooks");
const { InvalidArgumentError: InvalidArgumentError$17, InvalidReturnValueError: InvalidReturnValueError$1 } = require_errors();
const util$14 = require_util$5();
const { addSignal: addSignal$3, removeSignal: removeSignal$3 } = require_abort_signal();
function noop$3() {}
var StreamHandler = class extends AsyncResource$3 {
constructor(opts, factory$1, callback$1) {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$17("invalid opts");
const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
try {
if (typeof callback$1 !== "function") throw new InvalidArgumentError$17("invalid callback");
if (typeof factory$1 !== "function") throw new InvalidArgumentError$17("invalid factory");
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") throw new InvalidArgumentError$17("signal must be an EventEmitter or EventTarget");
if (method === "CONNECT") throw new InvalidArgumentError$17("invalid method");
if (onInfo && typeof onInfo !== "function") throw new InvalidArgumentError$17("invalid onInfo callback");
super("UNDICI_STREAM");
} catch (err) {
if (util$14.isStream(body)) util$14.destroy(body.on("error", noop$3), err);
throw err;
}
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.factory = factory$1;
this.callback = callback$1;
this.res = null;
this.abort = null;
this.context = null;
this.trailers = null;
this.body = body;
this.onInfo = onInfo || null;
if (util$14.isStream(body)) body.on("error", (err) => {
this.onError(err);
});
addSignal$3(this, signal);
}
onConnect(abort$1, context) {
if (this.reason) {
abort$1(this.reason);
return;
}
assert$18(this.callback);
this.abort = abort$1;
this.context = context;
}
onHeaders(statusCode, rawHeaders, resume$1, statusMessage) {
const { factory: factory$1, opaque, context, responseHeaders } = this;
const headers = responseHeaders === "raw" ? util$14.parseRawHeaders(rawHeaders) : util$14.parseHeaders(rawHeaders);
if (statusCode < 200) {
if (this.onInfo) this.onInfo({
statusCode,
headers
});
return;
}
this.factory = null;
if (factory$1 === null) return;
const res = this.runInAsyncScope(factory$1, null, {
statusCode,
headers,
opaque,
context
});
if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") throw new InvalidReturnValueError$1("expected Writable");
finished$1(res, { readable: false }, (err) => {
const { callback: callback$1, res: res$1, opaque: opaque$1, trailers, abort: abort$1 } = this;
this.res = null;
if (err || !res$1?.readable) util$14.destroy(res$1, err);
this.callback = null;
this.runInAsyncScope(callback$1, null, err || null, {
opaque: opaque$1,
trailers
});
if (err) abort$1();
});
res.on("drain", resume$1);
this.res = res;
return (res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain) !== true;
}
onData(chunk) {
const { res } = this;
return res ? res.write(chunk) : true;
}
onComplete(trailers) {
const { res } = this;
removeSignal$3(this);
if (!res) return;
this.trailers = util$14.parseHeaders(trailers);
res.end();
}
onError(err) {
const { res, callback: callback$1, opaque, body } = this;
removeSignal$3(this);
this.factory = null;
if (res) {
this.res = null;
util$14.destroy(res, err);
} else if (callback$1) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback$1, null, err, { opaque });
});
}
if (body) {
this.body = null;
util$14.destroy(body, err);
}
}
};
function stream(opts, factory$1, callback$1) {
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
stream.call(this, opts, factory$1, (err, data$1) => {
return err ? reject(err) : resolve$4(data$1);
});
});
try {
const handler = new StreamHandler(opts, factory$1, callback$1);
this.dispatch(opts, handler);
} catch (err) {
if (typeof callback$1 !== "function") throw err;
const opaque = opts?.opaque;
queueMicrotask(() => callback$1(err, { opaque }));
}
}
module.exports = stream;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-pipeline.js": ((exports, module) => {
const { Readable: Readable$2, Duplex, PassThrough } = __require$2("node:stream");
const assert$17 = __require$2("node:assert");
const { AsyncResource: AsyncResource$2 } = __require$2("node:async_hooks");
const { InvalidArgumentError: InvalidArgumentError$16, InvalidReturnValueError, RequestAbortedError: RequestAbortedError$2 } = require_errors();
const util$13 = require_util$5();
const { addSignal: addSignal$2, removeSignal: removeSignal$2 } = require_abort_signal();
function noop$2() {}
const kResume = Symbol("resume");
var PipelineRequest = class extends Readable$2 {
constructor() {
super({ autoDestroy: true });
this[kResume] = null;
}
_read() {
const { [kResume]: resume$1 } = this;
if (resume$1) {
this[kResume] = null;
resume$1();
}
}
_destroy(err, callback$1) {
this._read();
callback$1(err);
}
};
var PipelineResponse = class extends Readable$2 {
constructor(resume$1) {
super({ autoDestroy: true });
this[kResume] = resume$1;
}
_read() {
this[kResume]();
}
_destroy(err, callback$1) {
if (!err && !this._readableState.endEmitted) err = new RequestAbortedError$2();
callback$1(err);
}
};
var PipelineHandler = class extends AsyncResource$2 {
constructor(opts, handler) {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$16("invalid opts");
if (typeof handler !== "function") throw new InvalidArgumentError$16("invalid handler");
const { signal, method, opaque, onInfo, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") throw new InvalidArgumentError$16("signal must be an EventEmitter or EventTarget");
if (method === "CONNECT") throw new InvalidArgumentError$16("invalid method");
if (onInfo && typeof onInfo !== "function") throw new InvalidArgumentError$16("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$2);
this.ret = new Duplex({
readableObjectMode: opts.objectMode,
autoDestroy: true,
read: () => {
const { body } = this;
if (body?.resume) body.resume();
},
write: (chunk, encoding, callback$1) => {
const { req } = this;
if (req.push(chunk, encoding) || req._readableState.destroyed) callback$1();
else req[kResume] = callback$1;
},
destroy: (err, callback$1) => {
const { body, req, res, ret, abort: abort$1 } = this;
if (!err && !ret._readableState.endEmitted) err = new RequestAbortedError$2();
if (abort$1 && err) abort$1();
util$13.destroy(body, err);
util$13.destroy(req, err);
util$13.destroy(res, err);
removeSignal$2(this);
callback$1(err);
}
}).on("prefinish", () => {
const { req } = this;
req.push(null);
});
this.res = null;
addSignal$2(this, signal);
}
onConnect(abort$1, context) {
const { res } = this;
if (this.reason) {
abort$1(this.reason);
return;
}
assert$17(!res, "pipeline cannot be retried");
this.abort = abort$1;
this.context = context;
}
onHeaders(statusCode, rawHeaders, resume$1) {
const { opaque, handler, context } = this;
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === "raw" ? util$13.parseRawHeaders(rawHeaders) : util$13.parseHeaders(rawHeaders);
this.onInfo({
statusCode,
headers
});
}
return;
}
this.res = new PipelineResponse(resume$1);
let body;
try {
this.handler = null;
const headers = this.responseHeaders === "raw" ? util$13.parseRawHeaders(rawHeaders) : util$13.parseHeaders(rawHeaders);
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
opaque,
body: this.res,
context
});
} catch (err) {
this.res.on("error", noop$2);
throw err;
}
if (!body || typeof body.on !== "function") throw new InvalidReturnValueError("expected Readable");
body.on("data", (chunk) => {
const { ret, body: body$1 } = this;
if (!ret.push(chunk) && body$1.pause) body$1.pause();
}).on("error", (err) => {
const { ret } = this;
util$13.destroy(ret, err);
}).on("end", () => {
const { ret } = this;
ret.push(null);
}).on("close", () => {
const { ret } = this;
if (!ret._readableState.ended) util$13.destroy(ret, new RequestAbortedError$2());
});
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;
util$13.destroy(ret, err);
}
};
function pipeline$3(opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler);
this.dispatch({
...opts,
body: pipelineHandler.req
}, pipelineHandler);
return pipelineHandler.ret;
} catch (err) {
return new PassThrough().destroy(err);
}
}
module.exports = pipeline$3;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-upgrade.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$15, SocketError: SocketError$1 } = require_errors();
const { AsyncResource: AsyncResource$1 } = __require$2("node:async_hooks");
const assert$16 = __require$2("node:assert");
const util$12 = require_util$5();
const { kHTTP2Stream } = require_symbols();
const { addSignal: addSignal$1, removeSignal: removeSignal$1 } = require_abort_signal();
var UpgradeHandler = class extends AsyncResource$1 {
constructor(opts, callback$1) {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$15("invalid opts");
if (typeof callback$1 !== "function") throw new InvalidArgumentError$15("invalid callback");
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") throw new InvalidArgumentError$15("signal must be an EventEmitter or EventTarget");
super("UNDICI_UPGRADE");
this.responseHeaders = responseHeaders || null;
this.opaque = opaque || null;
this.callback = callback$1;
this.abort = null;
this.context = null;
addSignal$1(this, signal);
}
onConnect(abort$1, context) {
if (this.reason) {
abort$1(this.reason);
return;
}
assert$16(this.callback);
this.abort = abort$1;
this.context = null;
}
onHeaders() {
throw new SocketError$1("bad upgrade", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
assert$16(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101);
const { callback: callback$1, opaque, context } = this;
removeSignal$1(this);
this.callback = null;
const headers = this.responseHeaders === "raw" ? util$12.parseRawHeaders(rawHeaders) : util$12.parseHeaders(rawHeaders);
this.runInAsyncScope(callback$1, null, null, {
headers,
socket,
opaque,
context
});
}
onError(err) {
const { callback: callback$1, opaque } = this;
removeSignal$1(this);
if (callback$1) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback$1, null, err, { opaque });
});
}
}
};
function upgrade(opts, callback$1) {
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
upgrade.call(this, opts, (err, data$1) => {
return err ? reject(err) : resolve$4(data$1);
});
});
try {
const upgradeHandler = new UpgradeHandler(opts, callback$1);
const upgradeOpts = {
...opts,
method: opts.method || "GET",
upgrade: opts.protocol || "Websocket"
};
this.dispatch(upgradeOpts, upgradeHandler);
} catch (err) {
if (typeof callback$1 !== "function") throw err;
const opaque = opts?.opaque;
queueMicrotask(() => callback$1(err, { opaque }));
}
}
module.exports = upgrade;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-connect.js
var require_api_connect = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/api-connect.js": ((exports, module) => {
const assert$15 = __require$2("node:assert");
const { AsyncResource } = __require$2("node:async_hooks");
const { InvalidArgumentError: InvalidArgumentError$14, SocketError } = require_errors();
const util$11 = require_util$5();
const { addSignal, removeSignal } = require_abort_signal();
var ConnectHandler = class extends AsyncResource {
constructor(opts, callback$1) {
if (!opts || typeof opts !== "object") throw new InvalidArgumentError$14("invalid opts");
if (typeof callback$1 !== "function") throw new InvalidArgumentError$14("invalid callback");
const { signal, opaque, responseHeaders } = opts;
if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") throw new InvalidArgumentError$14("signal must be an EventEmitter or EventTarget");
super("UNDICI_CONNECT");
this.opaque = opaque || null;
this.responseHeaders = responseHeaders || null;
this.callback = callback$1;
this.abort = null;
addSignal(this, signal);
}
onConnect(abort$1, context) {
if (this.reason) {
abort$1(this.reason);
return;
}
assert$15(this.callback);
this.abort = abort$1;
this.context = context;
}
onHeaders() {
throw new SocketError("bad connect", null);
}
onUpgrade(statusCode, rawHeaders, socket) {
const { callback: callback$1, opaque, context } = this;
removeSignal(this);
this.callback = null;
let headers = rawHeaders;
if (headers != null) headers = this.responseHeaders === "raw" ? util$11.parseRawHeaders(rawHeaders) : util$11.parseHeaders(rawHeaders);
this.runInAsyncScope(callback$1, null, null, {
statusCode,
headers,
socket,
opaque,
context
});
}
onError(err) {
const { callback: callback$1, opaque } = this;
removeSignal(this);
if (callback$1) {
this.callback = null;
queueMicrotask(() => {
this.runInAsyncScope(callback$1, null, err, { opaque });
});
}
}
};
function connect(opts, callback$1) {
if (callback$1 === void 0) return new Promise((resolve$4, reject) => {
connect.call(this, opts, (err, data$1) => {
return err ? reject(err) : resolve$4(data$1);
});
});
try {
const connectHandler = new ConnectHandler(opts, callback$1);
const connectOptions = {
...opts,
method: "CONNECT"
};
this.dispatch(connectOptions, connectHandler);
} catch (err) {
if (typeof callback$1 !== "function") throw err;
const opaque = opts?.opaque;
queueMicrotask(() => callback$1(err, { opaque }));
}
}
module.exports = connect;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/index.js
var require_api = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/api/index.js": ((exports, module) => {
module.exports.request = require_api_request();
module.exports.stream = require_api_stream();
module.exports.pipeline = require_api_pipeline();
module.exports.upgrade = require_api_upgrade();
module.exports.connect = require_api_connect();
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-errors.js": ((exports, module) => {
const { UndiciError: UndiciError$3 } = require_errors();
const kMockNotMatchedError = Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
/**
* The request does not match any registered mock dispatches.
*/
var MockNotMatchedError$1 = class extends UndiciError$3 {
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";
}
static [Symbol.hasInstance](instance$1) {
return instance$1 && instance$1[kMockNotMatchedError] === true;
}
get [kMockNotMatchedError]() {
return true;
}
};
module.exports = { MockNotMatchedError: MockNotMatchedError$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-symbols.js": ((exports, module) => {
module.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"),
kTotalDispatchCount: Symbol("total dispatch count")
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-utils.js": ((exports, module) => {
const { MockNotMatchedError } = require_mock_errors();
const { kDispatches: kDispatches$4, kMockAgent: kMockAgent$2, kOriginalDispatch: kOriginalDispatch$2, kOrigin: kOrigin$2, kGetNetConnect: kGetNetConnect$1, kTotalDispatchCount } = require_mock_symbols();
const { serializePathWithQuery: serializePathWithQuery$2 } = require_util$5();
const { STATUS_CODES: STATUS_CODES$1 } = __require$2("node:http");
const { types: { isPromise } } = __require$2("node:util");
const { InvalidArgumentError: InvalidArgumentError$13 } = require_errors();
function matchValue$1(match, value) {
if (typeof match === "string") return match === value;
if (match instanceof RegExp) return match.test(value);
if (typeof match === "function") return match(value) === true;
return false;
}
function lowerCaseEntries(headers) {
return Object.fromEntries(Object.entries(headers).map(([headerName, headerValue]) => {
return [headerName.toLocaleLowerCase(), headerValue];
}));
}
/**
* @param {import('../../index').Headers|string[]|Record<string, string>} headers
* @param {string} key
*/
function getHeaderByName(headers, key) {
if (Array.isArray(headers)) {
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) if (headers[i$1].toLocaleLowerCase() === key.toLocaleLowerCase()) return headers[i$1 + 1];
return;
} else if (typeof headers.get === "function") return headers.get(key);
else return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
}
/** @param {string[]} headers */
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);
}
function matchHeaders(mockDispatch$1, headers) {
if (typeof mockDispatch$1.headers === "function") {
if (Array.isArray(headers)) headers = buildHeadersFromArray(headers);
return mockDispatch$1.headers(headers ? lowerCaseEntries(headers) : {});
}
if (typeof mockDispatch$1.headers === "undefined") return true;
if (typeof headers !== "object" || typeof mockDispatch$1.headers !== "object") return false;
for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch$1.headers)) if (!matchValue$1(matchHeaderValue, getHeaderByName(headers, matchHeaderName))) return false;
return true;
}
function normalizeSearchParams$1(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("[]", "");
if (/^(['"]).*\1$/.test(value)) {
normalizedQp.append(key, value);
continue;
}
if (value.includes(",")) {
const values = value.split(",");
for (const v of values) normalizedQp.append(key, v);
continue;
}
normalizedQp.append(key, value);
}
return normalizedQp;
}
function safeUrl(path$2) {
if (typeof path$2 !== "string") return path$2;
const pathSegments = path$2.split("?", 3);
if (pathSegments.length !== 2) return path$2;
const qp = new URLSearchParams(pathSegments.pop());
qp.sort();
return [...pathSegments, qp.toString()].join("?");
}
function matchKey(mockDispatch$1, { path: path$2, method, body, headers }) {
const pathMatch = matchValue$1(mockDispatch$1.path, path$2);
const methodMatch = matchValue$1(mockDispatch$1.method, method);
const bodyMatch = typeof mockDispatch$1.body !== "undefined" ? matchValue$1(mockDispatch$1.body, body) : true;
const headersMatch = matchHeaders(mockDispatch$1, headers);
return pathMatch && methodMatch && bodyMatch && headersMatch;
}
function getResponseData$1(data$1) {
if (Buffer.isBuffer(data$1)) return data$1;
else if (data$1 instanceof Uint8Array) return data$1;
else if (data$1 instanceof ArrayBuffer) return data$1;
else if (typeof data$1 === "object") return JSON.stringify(data$1);
else if (data$1) return data$1.toString();
else return "";
}
function getMockDispatch(mockDispatches, key) {
const basePath = key.query ? serializePathWithQuery$2(key.path, key.query) : key.path;
const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path$2, ignoreTrailingSlash }) => {
return ignoreTrailingSlash ? matchValue$1(removeTrailingSlash(safeUrl(path$2)), resolvedPathWithoutTrailingSlash) : matchValue$1(safeUrl(path$2), resolvedPath);
});
if (matchedMockDispatches.length === 0) throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue$1(method, key.method));
if (matchedMockDispatches.length === 0) throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`);
matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue$1(body, key.body) : true);
if (matchedMockDispatches.length === 0) throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`);
matchedMockDispatches = matchedMockDispatches.filter((mockDispatch$1) => matchHeaders(mockDispatch$1, key.headers));
if (matchedMockDispatches.length === 0) throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers}' on path '${resolvedPath}'`);
return matchedMockDispatches[0];
}
function addMockDispatch$1(mockDispatches, key, data$1, opts) {
const baseData = {
timesInvoked: 0,
times: 1,
persist: false,
consumed: false,
...opts
};
const replyData = typeof data$1 === "function" ? { callback: data$1 } : { ...data$1 };
const newMockDispatch = {
...baseData,
...key,
pending: true,
data: {
error: null,
...replyData
}
};
mockDispatches.push(newMockDispatch);
mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1;
return newMockDispatch;
}
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);
}
/**
* @param {string} path Path to remove trailing slash from
*/
function removeTrailingSlash(path$2) {
while (path$2.endsWith("/")) path$2 = path$2.slice(0, -1);
if (path$2.length === 0) path$2 = "/";
return path$2;
}
function buildKey$1(opts) {
const { path: path$2, method, body, headers, query } = opts;
return {
path: path$2,
method,
body,
headers,
query
};
}
function generateKeyValues(data$1) {
const keys = Object.keys(data$1);
const result = [];
for (let i$1 = 0; i$1 < keys.length; ++i$1) {
const key = keys[i$1];
const value = data$1[key];
const name = Buffer.from(`${key}`);
if (Array.isArray(value)) for (let j = 0; j < value.length; ++j) result.push(name, Buffer.from(`${value[j]}`));
else result.push(name, Buffer.from(`${value}`));
}
return result;
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
* @param {number} statusCode
*/
function getStatusText(statusCode) {
return STATUS_CODES$1[statusCode] || "unknown";
}
async function getResponse(body) {
const buffers = [];
for await (const data$1 of body) buffers.push(data$1);
return Buffer.concat(buffers).toString("utf8");
}
/**
* Mock dispatch function used to simulate undici dispatches
*/
function mockDispatch(opts, handler) {
const key = buildKey$1(opts);
const mockDispatch$1 = getMockDispatch(this[kDispatches$4], key);
mockDispatch$1.timesInvoked++;
if (mockDispatch$1.data.callback) mockDispatch$1.data = {
...mockDispatch$1.data,
...mockDispatch$1.data.callback(opts)
};
const { data: { statusCode, data: data$1, headers, trailers, error }, delay, persist } = mockDispatch$1;
const { timesInvoked, times } = mockDispatch$1;
mockDispatch$1.consumed = !persist && timesInvoked >= times;
mockDispatch$1.pending = timesInvoked < times;
if (error !== null) {
deleteMockDispatch(this[kDispatches$4], key);
handler.onError(error);
return true;
}
let aborted = false;
let timer = null;
function abort$1(err) {
if (aborted) return;
aborted = true;
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
handler.onError(err);
}
handler.onConnect?.(abort$1, null);
if (typeof delay === "number" && delay > 0) timer = setTimeout(() => {
timer = null;
handleReply(this[kDispatches$4]);
}, delay);
else handleReply(this[kDispatches$4]);
function handleReply(mockDispatches, _data = data$1) {
if (aborted) return;
const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
const body = typeof _data === "function" ? _data({
...opts,
headers: optsHeaders
}) : _data;
if (isPromise(body)) return body.then((newData) => handleReply(mockDispatches, newData));
if (aborted) return;
const responseData = getResponseData$1(body);
const responseHeaders = generateKeyValues(headers);
const responseTrailers = generateKeyValues(trailers);
handler.onHeaders?.(statusCode, responseHeaders, resume$1, getStatusText(statusCode));
handler.onData?.(Buffer.from(responseData));
handler.onComplete?.(responseTrailers);
deleteMockDispatch(mockDispatches, key);
}
function resume$1() {}
return true;
}
function buildMockDispatch$2() {
const agent = this[kMockAgent$2];
const origin = this[kOrigin$2];
const originalDispatch = this[kOriginalDispatch$2];
return function dispatch(opts, handler) {
if (agent.isMockActive) try {
mockDispatch.call(this, opts, handler);
} catch (error) {
if (error.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
const netConnect = agent[kGetNetConnect$1]();
const totalInterceptsCount = this[kDispatches$4][kTotalDispatchCount] || this[kDispatches$4].length;
const interceptsMessage = `, ${this[kDispatches$4].filter(({ consumed }) => !consumed).length} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
if (netConnect === false) throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
if (checkNetConnect(netConnect, origin)) originalDispatch.call(this, opts, handler);
else throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
} else throw error;
}
else originalDispatch.call(this, opts, handler);
};
}
function checkNetConnect(netConnect, origin) {
const url = new URL(origin);
if (netConnect === true) return true;
else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue$1(matcher, url.host))) return true;
return false;
}
function normalizeOrigin$1(origin) {
if (typeof origin !== "string" && !(origin instanceof URL)) return origin;
if (origin instanceof URL) return origin.origin;
return origin.toLowerCase();
}
function buildAndValidateMockOptions$1(opts) {
const { agent,...mockOptions } = opts;
if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") throw new InvalidArgumentError$13("options.enableCallHistory must to be a boolean");
if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") throw new InvalidArgumentError$13("options.acceptNonStandardSearchParameters must to be a boolean");
if ("ignoreTrailingSlash" in mockOptions && typeof mockOptions.ignoreTrailingSlash !== "boolean") throw new InvalidArgumentError$13("options.ignoreTrailingSlash must to be a boolean");
return mockOptions;
}
module.exports = {
getResponseData: getResponseData$1,
getMockDispatch,
addMockDispatch: addMockDispatch$1,
deleteMockDispatch,
buildKey: buildKey$1,
generateKeyValues,
matchValue: matchValue$1,
getResponse,
getStatusText,
mockDispatch,
buildMockDispatch: buildMockDispatch$2,
checkNetConnect,
buildAndValidateMockOptions: buildAndValidateMockOptions$1,
getHeaderByName,
buildHeadersFromArray,
normalizeSearchParams: normalizeSearchParams$1,
normalizeOrigin: normalizeOrigin$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-interceptor.js": ((exports, module) => {
const { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
const { kDispatches: kDispatches$3, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch, kIgnoreTrailingSlash: kIgnoreTrailingSlash$3 } = require_mock_symbols();
const { InvalidArgumentError: InvalidArgumentError$12 } = require_errors();
const { serializePathWithQuery: serializePathWithQuery$1 } = require_util$5();
/**
* Defines the scope API for an interceptor reply
*/
var MockScope = class {
constructor(mockDispatch$1) {
this[kMockDispatch] = mockDispatch$1;
}
/**
* Delay a reply by a set amount in ms.
*/
delay(waitInMs) {
if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) throw new InvalidArgumentError$12("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$12("repeatTimes must be a valid integer > 0");
this[kMockDispatch].times = repeatTimes;
return this;
}
};
/**
* Defines an interceptor for a Mock
*/
var MockInterceptor$2 = class {
constructor(opts, mockDispatches) {
if (typeof opts !== "object") throw new InvalidArgumentError$12("opts must be an object");
if (typeof opts.path === "undefined") throw new InvalidArgumentError$12("opts.path must be defined");
if (typeof opts.method === "undefined") opts.method = "GET";
if (typeof opts.path === "string") if (opts.query) opts.path = serializePathWithQuery$1(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$3] = mockDispatches;
this[kIgnoreTrailingSlash$3] = opts.ignoreTrailingSlash ?? false;
this[kDefaultHeaders] = {};
this[kDefaultTrailers] = {};
this[kContentLength] = false;
}
createMockScopeDispatchData({ statusCode, data: data$1, responseOptions }) {
const responseData = getResponseData(data$1);
const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
return {
statusCode,
data: data$1,
headers: {
...this[kDefaultHeaders],
...contentLength,
...responseOptions.headers
},
trailers: {
...this[kDefaultTrailers],
...responseOptions.trailers
}
};
}
validateReplyParameters(replyParameters) {
if (typeof replyParameters.statusCode === "undefined") throw new InvalidArgumentError$12("statusCode must be defined");
if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) throw new InvalidArgumentError$12("responseOptions must be an object");
}
/**
* Mock an undici request with a defined reply.
*/
reply(replyOptionsCallbackOrStatusCode) {
if (typeof replyOptionsCallbackOrStatusCode === "function") {
const wrappedDefaultsCallback = (opts) => {
const resolvedData = replyOptionsCallbackOrStatusCode(opts);
if (typeof resolvedData !== "object" || resolvedData === null) throw new InvalidArgumentError$12("reply options callback must return an object");
const replyParameters$1 = {
data: "",
responseOptions: {},
...resolvedData
};
this.validateReplyParameters(replyParameters$1);
return { ...this.createMockScopeDispatchData(replyParameters$1) };
};
return new MockScope(addMockDispatch(this[kDispatches$3], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash$3] }));
}
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);
return new MockScope(addMockDispatch(this[kDispatches$3], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash$3] }));
}
/**
* Mock an undici request with a defined error.
*/
replyWithError(error) {
if (typeof error === "undefined") throw new InvalidArgumentError$12("error must be defined");
return new MockScope(addMockDispatch(this[kDispatches$3], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash$3] }));
}
/**
* Set default reply headers on the interceptor for subsequent replies
*/
defaultReplyHeaders(headers) {
if (typeof headers === "undefined") throw new InvalidArgumentError$12("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$12("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;
}
};
module.exports.MockInterceptor = MockInterceptor$2;
module.exports.MockScope = MockScope;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-client.js
var require_mock_client = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-client.js": ((exports, module) => {
const { promisify: promisify$2 } = __require$2("node:util");
const Client$1 = require_client();
const { buildMockDispatch: buildMockDispatch$1 } = require_mock_utils();
const { kDispatches: kDispatches$2, kMockAgent: kMockAgent$1, kClose: kClose$1, kOriginalClose: kOriginalClose$1, kOrigin: kOrigin$1, kOriginalDispatch: kOriginalDispatch$1, kConnected: kConnected$1, kIgnoreTrailingSlash: kIgnoreTrailingSlash$2 } = require_mock_symbols();
const { MockInterceptor: MockInterceptor$1 } = require_mock_interceptor();
const Symbols$1 = require_symbols();
const { InvalidArgumentError: InvalidArgumentError$11 } = require_errors();
/**
* MockClient provides an API that extends the Client to influence the mockDispatches.
*/
var MockClient$2 = class extends Client$1 {
constructor(origin, opts) {
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") throw new InvalidArgumentError$11("Argument opts.agent must implement Agent");
super(origin, opts);
this[kMockAgent$1] = opts.agent;
this[kOrigin$1] = origin;
this[kIgnoreTrailingSlash$2] = opts.ignoreTrailingSlash ?? false;
this[kDispatches$2] = [];
this[kConnected$1] = 1;
this[kOriginalDispatch$1] = this.dispatch;
this[kOriginalClose$1] = this.close.bind(this);
this.dispatch = buildMockDispatch$1.call(this);
this.close = this[kClose$1];
}
get [Symbols$1.kConnected]() {
return this[kConnected$1];
}
/**
* Sets up the base interceptor for mocking replies from undici.
*/
intercept(opts) {
return new MockInterceptor$1(opts && {
ignoreTrailingSlash: this[kIgnoreTrailingSlash$2],
...opts
}, this[kDispatches$2]);
}
cleanMocks() {
this[kDispatches$2] = [];
}
async [kClose$1]() {
await promisify$2(this[kOriginalClose$1])();
this[kConnected$1] = 0;
this[kMockAgent$1][Symbols$1.kClients].delete(this[kOrigin$1]);
}
};
module.exports = MockClient$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-call-history.js
var require_mock_call_history = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-call-history.js": ((exports, module) => {
const { kMockCallHistoryAddLog: kMockCallHistoryAddLog$1 } = require_mock_symbols();
const { InvalidArgumentError: InvalidArgumentError$10 } = 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$10("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
}
}
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$10("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
return {
...finalOptions,
operator: options.operator.toUpperCase()
};
}
return finalOptions;
}
function makeFilterCalls(parameterName) {
return (parameterValue) => {
if (typeof parameterValue === "string" || parameterValue == null) return this.logs.filter((log$1) => {
return log$1[parameterName] === parameterValue;
});
if (parameterValue instanceof RegExp) return this.logs.filter((log$1) => {
return parameterValue.test(log$1[parameterName]);
});
throw new InvalidArgumentError$10(`${parameterName} parameter should be one of string, regexp, undefined or null`);
};
}
function computeUrlWithMaybeSearchParameters(requestInit) {
try {
const url = new URL(requestInit.path, requestInit.origin);
if (url.search.length !== 0) return url;
url.search = new URLSearchParams(requestInit.query).toString();
return url;
} catch (error) {
throw new InvalidArgumentError$10("An error occurred when computing MockCallHistoryLog.url", { cause: error });
}
}
var MockCallHistoryLog$1 = class {
constructor(requestInit = {}) {
this.body = requestInit.body;
this.headers = requestInit.headers;
this.method = requestInit.method;
const url = computeUrlWithMaybeSearchParameters(requestInit);
this.fullUrl = url.toString();
this.origin = url.origin;
this.path = url.pathname;
this.searchParams = Object.fromEntries(url.searchParams);
this.protocol = url.protocol;
this.host = url.host;
this.port = url.port;
this.hash = url.hash;
}
toMap() {
return 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$2 = class {
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$10("nthCall must be called with a number");
if (!Number.isInteger(number)) throw new InvalidArgumentError$10("nthCall must be called with an integer");
if (Math.sign(number) !== 1) throw new InvalidArgumentError$10("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((log$1) => {
return criteria.test(log$1.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);
return [...new Set(maybeDuplicatedLogsFiltered)];
}
throw new InvalidArgumentError$10("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$1](requestInit) {
const log$1 = new MockCallHistoryLog$1(requestInit);
this.logs.push(log$1);
return log$1;
}
*[Symbol.iterator]() {
for (const log$1 of this.calls()) yield log$1;
}
};
module.exports.MockCallHistory = MockCallHistory$2;
module.exports.MockCallHistoryLog = MockCallHistoryLog$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-pool.js": ((exports, module) => {
const { promisify: promisify$1 } = __require$2("node:util");
const Pool$1 = require_pool();
const { buildMockDispatch } = require_mock_utils();
const { kDispatches: kDispatches$1, kMockAgent, kClose, kOriginalClose, kOrigin, kOriginalDispatch, kConnected, kIgnoreTrailingSlash: kIgnoreTrailingSlash$1 } = require_mock_symbols();
const { MockInterceptor } = require_mock_interceptor();
const Symbols = require_symbols();
const { InvalidArgumentError: InvalidArgumentError$9 } = require_errors();
/**
* MockPool provides an API that extends the Pool to influence the mockDispatches.
*/
var MockPool$2 = class extends Pool$1 {
constructor(origin, opts) {
if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") throw new InvalidArgumentError$9("Argument opts.agent must implement Agent");
super(origin, opts);
this[kMockAgent] = opts.agent;
this[kOrigin] = origin;
this[kIgnoreTrailingSlash$1] = opts.ignoreTrailingSlash ?? false;
this[kDispatches$1] = [];
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$1],
...opts
}, this[kDispatches$1]);
}
cleanMocks() {
this[kDispatches$1] = [];
}
async [kClose]() {
await promisify$1(this[kOriginalClose])();
this[kConnected] = 0;
this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
}
};
module.exports = MockPool$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/pending-interceptors-formatter.js": ((exports, module) => {
const { Transform: Transform$1 } = __require$2("node:stream");
const { Console } = __require$2("node:console");
const PERSISTENT = process.versions.icu ? "✅" : "Y ";
const NOT_PERSISTENT = process.versions.icu ? "❌" : "N ";
/**
* Gets the output of `console.table(…)` as a string.
*/
module.exports = class PendingInterceptorsFormatter$1 {
constructor({ disableColors } = {}) {
this.transform = new Transform$1({ transform(chunk, _enc, cb) {
cb(null, chunk);
} });
this.logger = new Console({
stdout: this.transform,
inspectOptions: { colors: !disableColors && !process.env.CI }
});
}
format(pendingInterceptors) {
const withPrettyHeaders = pendingInterceptors.map(({ method, path: path$2, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
Method: method,
Origin: origin,
Path: path$2,
"Status code": statusCode,
Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
Invocations: timesInvoked,
Remaining: persist ? Infinity : times - timesInvoked
}));
this.logger.table(withPrettyHeaders);
return this.transform.read().toString();
}
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/mock-agent.js": ((exports, module) => {
const { kClients } = require_symbols();
const Agent$3 = require_agent();
const { kAgent, kMockAgentSet, kMockAgentGet, kDispatches, kIsMockActive, kNetConnect, kGetNetConnect, kOptions, kFactory, kMockAgentRegisterCallHistory, kMockAgentIsCallHistoryEnabled, kMockAgentAddCallHistoryLog, kMockAgentMockCallHistoryInstance, kMockAgentAcceptsNonStandardSearchParameters, kMockCallHistoryAddLog, kIgnoreTrailingSlash } = require_mock_symbols();
const MockClient$1 = require_mock_client();
const MockPool$1 = require_mock_pool();
const { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils();
const { InvalidArgumentError: InvalidArgumentError$8, UndiciError: UndiciError$2 } = require_errors();
const Dispatcher$1 = require_dispatcher();
const PendingInterceptorsFormatter = require_pending_interceptors_formatter();
const { MockCallHistory: MockCallHistory$1 } = require_mock_call_history();
var MockAgent$2 = class extends Dispatcher$1 {
constructor(opts = {}) {
super(opts);
const mockOptions = buildAndValidateMockOptions(opts);
this[kNetConnect] = true;
this[kIsMockActive] = true;
this[kMockAgentIsCallHistoryEnabled] = mockOptions.enableCallHistory ?? false;
this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions.acceptNonStandardSearchParameters ?? false;
this[kIgnoreTrailingSlash] = mockOptions.ignoreTrailingSlash ?? false;
if (opts?.agent && typeof opts.agent.dispatch !== "function") throw new InvalidArgumentError$8("Argument opts.agent must implement Agent");
const agent = opts?.agent ? opts.agent : new Agent$3(opts);
this[kAgent] = agent;
this[kClients] = agent[kClients];
this[kOptions] = mockOptions;
if (this[kMockAgentIsCallHistoryEnabled]) this[kMockAgentRegisterCallHistory]();
}
get(origin) {
const normalizedOrigin = normalizeOrigin(origin);
const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin;
let dispatcher = this[kMockAgentGet](originKey);
if (!dispatcher) {
dispatcher = this[kFactory](originKey);
this[kMockAgentSet](originKey, dispatcher);
}
return dispatcher;
}
dispatch(opts, handler) {
opts.origin = normalizeOrigin(opts.origin);
this.get(opts.origin);
this[kMockAgentAddCallHistoryLog](opts);
const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
const dispatchOpts = { ...opts };
if (acceptNonStandardSearchParameters && dispatchOpts.path) {
const [path$2, searchParams] = dispatchOpts.path.split("?");
dispatchOpts.path = `${path$2}?${normalizeSearchParams(searchParams, acceptNonStandardSearchParameters)}`;
}
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$8("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();
}
get isMockActive() {
return this[kIsMockActive];
}
[kMockAgentRegisterCallHistory]() {
if (this[kMockAgentMockCallHistoryInstance] === void 0) this[kMockAgentMockCallHistoryInstance] = new MockCallHistory$1();
}
[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$1(origin, mockOptions) : new MockPool$1(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, result$1] of Array.from(this[kClients])) if (result$1 && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
const dispatcher = this[kFactory](origin);
this[kMockAgentSet](origin, dispatcher);
dispatcher[kDispatches] = result$1.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$2(pending.length === 1 ? `1 interceptor is pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:\n\n${pendingInterceptorsFormatter.format(pending)}`.trim());
}
};
module.exports = MockAgent$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-utils.js
var require_snapshot_utils = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-utils.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$7 } = require_errors();
const { runtimeFeatures: runtimeFeatures$5 } = require_runtime_features();
/**
* @typedef {Object} HeaderFilters
* @property {Set<string>} ignore - Set of headers to ignore for matching
* @property {Set<string>} exclude - Set of headers to exclude from matching
* @property {Set<string>} match - Set of headers to match (empty means match
*/
/**
* Creates cached header sets for performance
*
* @param {import('./snapshot-recorder').SnapshotRecorderMatchOptions} matchOptions - Matching options for headers
* @returns {HeaderFilters} - Cached sets for ignore, exclude, and match headers
*/
function createHeaderFilters$1(matchOptions = {}) {
const { ignoreHeaders = [], excludeHeaders = [], matchHeaders: matchHeaders$1 = [], caseSensitive = false } = matchOptions;
return {
ignore: new Set(ignoreHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
exclude: new Set(excludeHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
match: new Set(matchHeaders$1.map((header) => caseSensitive ? header : header.toLowerCase()))
};
}
const crypto$2 = runtimeFeatures$5.has("crypto") ? __require$2("node:crypto") : null;
/**
* @callback HashIdFunction
* @param {string} value - The value to hash
* @returns {string} - The base64url encoded hash of the value
*/
/**
* Generates a hash for a given value
* @type {HashIdFunction}
*/
const hashId$1 = crypto$2?.hash ? (value) => crypto$2.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
/**
* @typedef {(url: string) => boolean} IsUrlExcluded Checks if a URL matches any of the exclude patterns
*/
/** @typedef {{[key: Lowercase<string>]: string}} NormalizedHeaders */
/** @typedef {Array<string>} UndiciHeaders */
/** @typedef {Record<string, string|string[]>} Headers */
/**
* @param {*} headers
* @returns {headers is UndiciHeaders}
*/
function isUndiciHeaders(headers) {
return Array.isArray(headers) && (headers.length & 1) === 0;
}
/**
* Factory function to create a URL exclusion checker
* @param {Array<string| RegExp>} [excludePatterns=[]] - Array of patterns to exclude
* @returns {IsUrlExcluded} - A function that checks if a URL matches any of the exclude patterns
*/
function isUrlExcludedFactory$1(excludePatterns = []) {
if (excludePatterns.length === 0) return () => false;
return function isUrlExcluded(url) {
let urlLowerCased;
for (const pattern of excludePatterns) if (typeof pattern === "string") {
if (!urlLowerCased) urlLowerCased = url.toLowerCase();
if (urlLowerCased.includes(pattern.toLowerCase())) return true;
} else if (pattern instanceof RegExp) {
if (pattern.test(url)) return true;
}
return false;
};
}
/**
* Normalizes headers for consistent comparison
*
* @param {Object|UndiciHeaders} headers - Headers to normalize
* @returns {NormalizedHeaders} - Normalized headers as a lowercase object
*/
function normalizeHeaders$5(headers) {
/** @type {NormalizedHeaders} */
const normalizedHeaders = {};
if (!headers) return normalizedHeaders;
if (isUndiciHeaders(headers)) {
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) {
const key = headers[i$1];
const value = headers[i$1 + 1];
if (key && value !== void 0) {
const keyStr = Buffer.isBuffer(key) ? key.toString() : key;
const valueStr = Buffer.isBuffer(value) ? value.toString() : value;
normalizedHeaders[keyStr.toLowerCase()] = valueStr;
}
}
return normalizedHeaders;
}
if (headers && typeof headers === "object") {
for (const [key, value] of Object.entries(headers)) if (key && typeof key === "string") normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
}
return normalizedHeaders;
}
const validSnapshotModes = [
"record",
"playback",
"update"
];
/** @typedef {typeof validSnapshotModes[number]} SnapshotMode */
/**
* @param {*} mode - The snapshot mode to validate
* @returns {asserts mode is SnapshotMode}
*/
function validateSnapshotMode$1(mode) {
if (!validSnapshotModes.includes(mode)) throw new InvalidArgumentError$7(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`);
}
module.exports = {
createHeaderFilters: createHeaderFilters$1,
hashId: hashId$1,
isUndiciHeaders,
normalizeHeaders: normalizeHeaders$5,
isUrlExcludedFactory: isUrlExcludedFactory$1,
validateSnapshotMode: validateSnapshotMode$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-recorder.js
var require_snapshot_recorder = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-recorder.js": ((exports, module) => {
const { writeFile, readFile, mkdir } = __require$2("node:fs/promises");
const { dirname: dirname$2, resolve: resolve$3 } = __require$2("node:path");
const { setTimeout: setTimeout$1, clearTimeout: clearTimeout$1 } = __require$2("node:timers");
const { InvalidArgumentError: InvalidArgumentError$6, UndiciError: UndiciError$1 } = require_errors();
const { hashId, isUrlExcludedFactory, normalizeHeaders: normalizeHeaders$4, createHeaderFilters } = require_snapshot_utils();
/**
* @typedef {Object} SnapshotRequestOptions
* @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
* @property {string} path - Request path
* @property {string} origin - Request origin (base URL)
* @property {import('./snapshot-utils').Headers|import('./snapshot-utils').UndiciHeaders} headers - Request headers
* @property {import('./snapshot-utils').NormalizedHeaders} _normalizedHeaders - Request headers as a lowercase object
* @property {string|Buffer} [body] - Request body (optional)
*/
/**
* @typedef {Object} SnapshotEntryRequest
* @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
* @property {string} url - Full URL of the request
* @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object
* @property {string|Buffer} [body] - Request body (optional)
*/
/**
* @typedef {Object} SnapshotEntryResponse
* @property {number} statusCode - HTTP status code of the response
* @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized response headers as a lowercase object
* @property {string} body - Response body as a base64url encoded string
* @property {Object} [trailers] - Optional response trailers
*/
/**
* @typedef {Object} SnapshotEntry
* @property {SnapshotEntryRequest} request - The request object
* @property {Array<SnapshotEntryResponse>} responses - Array of response objects
* @property {number} callCount - Number of times this snapshot has been called
* @property {string} timestamp - ISO timestamp of when the snapshot was created
*/
/**
* @typedef {Object} SnapshotRecorderMatchOptions
* @property {Array<string>} [matchHeaders=[]] - Headers to match (empty array means match all headers)
* @property {Array<string>} [ignoreHeaders=[]] - Headers to ignore for matching
* @property {Array<string>} [excludeHeaders=[]] - Headers to exclude from matching
* @property {boolean} [matchBody=true] - Whether to match request body
* @property {boolean} [matchQuery=true] - Whether to match query properties
* @property {boolean} [caseSensitive=false] - Whether header matching is case-sensitive
*/
/**
* @typedef {Object} SnapshotRecorderOptions
* @property {string} [snapshotPath] - Path to save/load snapshots
* @property {import('./snapshot-utils').SnapshotMode} [mode='record'] - Mode: 'record' or 'playback'
* @property {number} [maxSnapshots=Infinity] - Maximum number of snapshots to keep
* @property {boolean} [autoFlush=false] - Whether to automatically flush snapshots to disk
* @property {number} [flushInterval=30000] - Auto-flush interval in milliseconds (default: 30 seconds)
* @property {Array<string|RegExp>} [excludeUrls=[]] - URLs to exclude from recording
* @property {function} [shouldRecord=null] - Function to filter requests for recording
* @property {function} [shouldPlayback=null] - Function to filter requests
*/
/**
* @typedef {Object} SnapshotFormattedRequest
* @property {string} method - HTTP method (e.g. 'GET', 'POST', etc.)
* @property {string} url - Full URL of the request (with query parameters if matchQuery is true)
* @property {import('./snapshot-utils').NormalizedHeaders} headers - Normalized headers as a lowercase object
* @property {string} body - Request body (optional, only if matchBody is true)
*/
/**
* @typedef {Object} SnapshotInfo
* @property {string} hash - Hash key for the snapshot
* @property {SnapshotEntryRequest} request - The request object
* @property {number} responseCount - Number of responses recorded for this request
* @property {number} callCount - Number of times this snapshot has been called
* @property {string} timestamp - ISO timestamp of when the snapshot was created
*/
/**
* Formats a request for consistent snapshot storage
* Caches normalized headers to avoid repeated processing
*
* @param {SnapshotRequestOptions} opts - Request options
* @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached header sets for performance
* @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers and body
* @returns {SnapshotFormattedRequest} - Formatted request object
*/
function formatRequestKey(opts, headerFilters, matchOptions = {}) {
const url = new URL(opts.path, opts.origin);
const normalized = opts._normalizedHeaders || normalizeHeaders$4(opts.headers);
if (!opts._normalizedHeaders) opts._normalizedHeaders = normalized;
return {
method: opts.method || "GET",
url: matchOptions.matchQuery !== false ? url.toString() : `${url.origin}${url.pathname}`,
headers: filterHeadersForMatching(normalized, headerFilters, matchOptions),
body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : ""
};
}
/**
* Filters headers based on matching configuration
*
* @param {import('./snapshot-utils').Headers} headers - Headers to filter
* @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers
* @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers
*/
function filterHeadersForMatching(headers, headerFilters, matchOptions = {}) {
if (!headers || typeof headers !== "object") return {};
const { caseSensitive = false } = matchOptions;
const filtered = {};
const { ignore: ignore$1, exclude, match } = headerFilters;
for (const [key, value] of Object.entries(headers)) {
const headerKey = caseSensitive ? key : key.toLowerCase();
if (exclude.has(headerKey)) continue;
if (ignore$1.has(headerKey)) continue;
if (match.size !== 0) {
if (!match.has(headerKey)) continue;
}
filtered[headerKey] = value;
}
return filtered;
}
/**
* Filters headers for storage (only excludes sensitive headers)
*
* @param {import('./snapshot-utils').Headers} headers - Headers to filter
* @param {import('./snapshot-utils').HeaderFilters} headerFilters - Cached sets for ignore, exclude, and match headers
* @param {SnapshotRecorderMatchOptions} [matchOptions] - Matching options for headers
*/
function filterHeadersForStorage(headers, headerFilters, matchOptions = {}) {
if (!headers || typeof headers !== "object") return {};
const { caseSensitive = false } = matchOptions;
const filtered = {};
const { exclude: excludeSet } = headerFilters;
for (const [key, value] of Object.entries(headers)) {
const headerKey = caseSensitive ? key : key.toLowerCase();
if (excludeSet.has(headerKey)) continue;
filtered[headerKey] = value;
}
return filtered;
}
/**
* Creates a hash key for request matching
* Properly orders headers to avoid conflicts and uses crypto hashing when available
*
* @param {SnapshotFormattedRequest} formattedRequest - Request object
* @returns {string} - Base64url encoded hash of the request
*/
function createRequestHash(formattedRequest) {
const parts = [formattedRequest.method, formattedRequest.url];
if (formattedRequest.headers && typeof formattedRequest.headers === "object") {
const headerKeys = Object.keys(formattedRequest.headers).sort();
for (const key of headerKeys) {
const values = Array.isArray(formattedRequest.headers[key]) ? formattedRequest.headers[key] : [formattedRequest.headers[key]];
parts.push(key);
for (const value of values.sort()) parts.push(String(value));
}
}
parts.push(formattedRequest.body);
return hashId(parts.join("|"));
}
var SnapshotRecorder$1 = class {
/** @type {NodeJS.Timeout | null} */
#flushTimeout;
/** @type {import('./snapshot-utils').IsUrlExcluded} */
#isUrlExcluded;
/** @type {Map<string, SnapshotEntry>} */
#snapshots = /* @__PURE__ */ new Map();
/** @type {string|undefined} */
#snapshotPath;
/** @type {number} */
#maxSnapshots = Infinity;
/** @type {boolean} */
#autoFlush = false;
/** @type {import('./snapshot-utils').HeaderFilters} */
#headerFilters;
/**
* Creates a new SnapshotRecorder instance
* @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder
*/
constructor(options = {}) {
this.#snapshotPath = options.snapshotPath;
this.#maxSnapshots = options.maxSnapshots || Infinity;
this.#autoFlush = options.autoFlush || false;
this.flushInterval = options.flushInterval || 3e4;
this._flushTimer = null;
/** @type {Required<SnapshotRecorderMatchOptions>} */
this.matchOptions = {
matchHeaders: options.matchHeaders || [],
ignoreHeaders: options.ignoreHeaders || [],
excludeHeaders: options.excludeHeaders || [],
matchBody: options.matchBody !== false,
matchQuery: options.matchQuery !== false,
caseSensitive: options.caseSensitive || false
};
this.#headerFilters = createHeaderFilters(this.matchOptions);
this.shouldRecord = options.shouldRecord || (() => true);
this.shouldPlayback = options.shouldPlayback || (() => true);
this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls);
if (this.#autoFlush && this.#snapshotPath) this.#startAutoFlush();
}
/**
* Records a request-response interaction
* @param {SnapshotRequestOptions} requestOpts - Request options
* @param {SnapshotEntryResponse} response - Response data to record
* @return {Promise<void>} - Resolves when the recording is complete
*/
async record(requestOpts, response) {
if (!this.shouldRecord(requestOpts)) return;
if (this.isUrlExcluded(requestOpts)) return;
const request$2 = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
const hash = createRequestHash(request$2);
const normalizedHeaders = normalizeHeaders$4(response.headers);
/** @type {SnapshotEntryResponse} */
const responseData = {
statusCode: response.statusCode,
headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions),
body: Buffer.isBuffer(response.body) ? response.body.toString("base64") : Buffer.from(String(response.body || "")).toString("base64"),
trailers: response.trailers
};
if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) {
const oldestKey = this.#snapshots.keys().next().value;
this.#snapshots.delete(oldestKey);
}
const existingSnapshot = this.#snapshots.get(hash);
if (existingSnapshot && existingSnapshot.responses) {
existingSnapshot.responses.push(responseData);
existingSnapshot.timestamp = (/* @__PURE__ */ new Date()).toISOString();
} else this.#snapshots.set(hash, {
request: request$2,
responses: [responseData],
callCount: 0,
timestamp: (/* @__PURE__ */ new Date()).toISOString()
});
if (this.#autoFlush && this.#snapshotPath) this.#scheduleFlush();
}
/**
* Checks if a URL should be excluded from recording/playback
* @param {SnapshotRequestOptions} requestOpts - Request options to check
* @returns {boolean} - True if URL is excluded
*/
isUrlExcluded(requestOpts) {
const url = new URL(requestOpts.path, requestOpts.origin).toString();
return this.#isUrlExcluded(url);
}
/**
* Finds a matching snapshot for the given request
* Returns the appropriate response based on call count for sequential responses
*
* @param {SnapshotRequestOptions} requestOpts - Request options to match
* @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found
*/
findSnapshot(requestOpts) {
if (!this.shouldPlayback(requestOpts)) return;
if (this.isUrlExcluded(requestOpts)) return;
const hash = createRequestHash(formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions));
const snapshot = this.#snapshots.get(hash);
if (!snapshot) return void 0;
const currentCallCount = snapshot.callCount || 0;
const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1);
snapshot.callCount = currentCallCount + 1;
return {
...snapshot,
response: snapshot.responses[responseIndex]
};
}
/**
* Loads snapshots from file
* @param {string} [filePath] - Optional file path to load snapshots from
* @return {Promise<void>} - Resolves when snapshots are loaded
*/
async loadSnapshots(filePath) {
const path$2 = filePath || this.#snapshotPath;
if (!path$2) throw new InvalidArgumentError$6("Snapshot path is required");
try {
const data$1 = await readFile(resolve$3(path$2), "utf8");
const parsed = JSON.parse(data$1);
if (Array.isArray(parsed)) {
this.#snapshots.clear();
for (const { hash, snapshot } of parsed) this.#snapshots.set(hash, snapshot);
} else this.#snapshots = new Map(Object.entries(parsed));
} catch (error) {
if (error.code === "ENOENT") this.#snapshots.clear();
else throw new UndiciError$1(`Failed to load snapshots from ${path$2}`, { cause: error });
}
}
/**
* Saves snapshots to file
*
* @param {string} [filePath] - Optional file path to save snapshots
* @returns {Promise<void>} - Resolves when snapshots are saved
*/
async saveSnapshots(filePath) {
const path$2 = filePath || this.#snapshotPath;
if (!path$2) throw new InvalidArgumentError$6("Snapshot path is required");
const resolvedPath = resolve$3(path$2);
await mkdir(dirname$2(resolvedPath), { recursive: true });
const data$1 = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
hash,
snapshot
}));
await writeFile(resolvedPath, JSON.stringify(data$1, null, 2), { flush: true });
}
/**
* Clears all recorded snapshots
* @returns {void}
*/
clear() {
this.#snapshots.clear();
}
/**
* Gets all recorded snapshots
* @return {Array<SnapshotEntry>} - Array of all recorded snapshots
*/
getSnapshots() {
return Array.from(this.#snapshots.values());
}
/**
* Gets snapshot count
* @return {number} - Number of recorded snapshots
*/
size() {
return this.#snapshots.size;
}
/**
* Resets call counts for all snapshots (useful for test cleanup)
* @returns {void}
*/
resetCallCounts() {
for (const snapshot of this.#snapshots.values()) snapshot.callCount = 0;
}
/**
* Deletes a specific snapshot by request options
* @param {SnapshotRequestOptions} requestOpts - Request options to match
* @returns {boolean} - True if snapshot was deleted, false if not found
*/
deleteSnapshot(requestOpts) {
const hash = createRequestHash(formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions));
return this.#snapshots.delete(hash);
}
/**
* Gets information about a specific snapshot
* @param {SnapshotRequestOptions} requestOpts - Request options to match
* @returns {SnapshotInfo|null} - Snapshot information or null if not found
*/
getSnapshotInfo(requestOpts) {
const hash = createRequestHash(formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions));
const snapshot = this.#snapshots.get(hash);
if (!snapshot) return null;
return {
hash,
request: snapshot.request,
responseCount: snapshot.responses ? snapshot.responses.length : snapshot.response ? 1 : 0,
callCount: snapshot.callCount || 0,
timestamp: snapshot.timestamp
};
}
/**
* Replaces all snapshots with new data (full replacement)
* @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record<string, SnapshotEntry>} snapshotData - New snapshot data to replace existing ones
* @returns {void}
*/
replaceSnapshots(snapshotData) {
this.#snapshots.clear();
if (Array.isArray(snapshotData)) for (const { hash, snapshot } of snapshotData) this.#snapshots.set(hash, snapshot);
else if (snapshotData && typeof snapshotData === "object") this.#snapshots = new Map(Object.entries(snapshotData));
}
/**
* Starts the auto-flush timer
* @returns {void}
*/
#startAutoFlush() {
return this.#scheduleFlush();
}
/**
* Stops the auto-flush timer
* @returns {void}
*/
#stopAutoFlush() {
if (this.#flushTimeout) {
clearTimeout$1(this.#flushTimeout);
this.saveSnapshots().catch(() => {});
this.#flushTimeout = null;
}
}
/**
* Schedules a flush (debounced to avoid excessive writes)
*/
#scheduleFlush() {
this.#flushTimeout = setTimeout$1(() => {
this.saveSnapshots().catch(() => {});
if (this.#autoFlush) this.#flushTimeout?.refresh();
else this.#flushTimeout = null;
}, 1e3);
}
/**
* Cleanup method to stop timers
* @returns {void}
*/
destroy() {
this.#stopAutoFlush();
if (this.#flushTimeout) {
clearTimeout$1(this.#flushTimeout);
this.#flushTimeout = null;
}
}
/**
* Async close method that saves all recordings and performs cleanup
* @returns {Promise<void>}
*/
async close() {
if (this.#snapshotPath && this.#snapshots.size !== 0) await this.saveSnapshots();
this.destroy();
}
};
module.exports = {
SnapshotRecorder: SnapshotRecorder$1,
formatRequestKey,
createRequestHash,
filterHeadersForMatching,
filterHeadersForStorage,
createHeaderFilters
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-agent.js
var require_snapshot_agent = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/mock/snapshot-agent.js": ((exports, module) => {
const Agent$2 = require_agent();
const MockAgent$1 = require_mock_agent();
const { SnapshotRecorder } = require_snapshot_recorder();
const WrapHandler$1 = require_wrap_handler();
const { InvalidArgumentError: InvalidArgumentError$5, UndiciError } = require_errors();
const { validateSnapshotMode } = require_snapshot_utils();
const kSnapshotRecorder = Symbol("kSnapshotRecorder");
const kSnapshotMode = Symbol("kSnapshotMode");
const kSnapshotPath = Symbol("kSnapshotPath");
const kSnapshotLoaded = Symbol("kSnapshotLoaded");
const kRealAgent = Symbol("kRealAgent");
let warningEmitted$2 = false;
var SnapshotAgent$1 = class extends MockAgent$1 {
constructor(opts = {}) {
if (!warningEmitted$2) {
process.emitWarning("SnapshotAgent is experimental and subject to change", "ExperimentalWarning");
warningEmitted$2 = true;
}
const { mode = "record", snapshotPath = null,...mockAgentOpts } = opts;
super(mockAgentOpts);
validateSnapshotMode(mode);
if ((mode === "playback" || mode === "update") && !snapshotPath) throw new InvalidArgumentError$5(`snapshotPath is required when mode is '${mode}'`);
this[kSnapshotMode] = mode;
this[kSnapshotPath] = snapshotPath;
this[kSnapshotRecorder] = new SnapshotRecorder({
snapshotPath: this[kSnapshotPath],
mode: this[kSnapshotMode],
maxSnapshots: opts.maxSnapshots,
autoFlush: opts.autoFlush,
flushInterval: opts.flushInterval,
matchHeaders: opts.matchHeaders,
ignoreHeaders: opts.ignoreHeaders,
excludeHeaders: opts.excludeHeaders,
matchBody: opts.matchBody,
matchQuery: opts.matchQuery,
caseSensitive: opts.caseSensitive,
shouldRecord: opts.shouldRecord,
shouldPlayback: opts.shouldPlayback,
excludeUrls: opts.excludeUrls
});
this[kSnapshotLoaded] = false;
if (this[kSnapshotMode] === "record" || this[kSnapshotMode] === "update" || this[kSnapshotMode] === "playback" && opts.excludeUrls && opts.excludeUrls.length > 0) this[kRealAgent] = new Agent$2(opts);
if ((this[kSnapshotMode] === "playback" || this[kSnapshotMode] === "update") && this[kSnapshotPath]) this.loadSnapshots().catch(() => {});
}
dispatch(opts, handler) {
handler = WrapHandler$1.wrap(handler);
const mode = this[kSnapshotMode];
if (this[kSnapshotRecorder].isUrlExcluded(opts)) return this[kRealAgent].dispatch(opts, handler);
if (mode === "playback" || mode === "update") {
if (!this[kSnapshotLoaded]) return this.#asyncDispatch(opts, handler);
const snapshot = this[kSnapshotRecorder].findSnapshot(opts);
if (snapshot) return this.#replaySnapshot(snapshot, handler);
else if (mode === "update") return this.#recordAndReplay(opts, handler);
else {
const error = new UndiciError(`No snapshot found for ${opts.method || "GET"} ${opts.path}`);
if (handler.onError) {
handler.onError(error);
return;
}
throw error;
}
} else if (mode === "record") return this.#recordAndReplay(opts, handler);
}
/**
* Async version of dispatch for when we need to load snapshots first
*/
async #asyncDispatch(opts, handler) {
await this.loadSnapshots();
return this.dispatch(opts, handler);
}
/**
* Records a real request and replays the response
*/
#recordAndReplay(opts, handler) {
const responseData = {
statusCode: null,
headers: {},
trailers: {},
body: []
};
const self = this;
return this[kRealAgent].dispatch(opts, {
onRequestStart(controller, context) {
return handler.onRequestStart(controller, {
...context,
history: this.history
});
},
onRequestUpgrade(controller, statusCode, headers, socket) {
return handler.onRequestUpgrade(controller, statusCode, headers, socket);
},
onResponseStart(controller, statusCode, headers, statusMessage) {
responseData.statusCode = statusCode;
responseData.headers = headers;
return handler.onResponseStart(controller, statusCode, headers, statusMessage);
},
onResponseData(controller, chunk) {
responseData.body.push(chunk);
return handler.onResponseData(controller, chunk);
},
onResponseEnd(controller, trailers) {
responseData.trailers = trailers;
const responseBody = Buffer.concat(responseData.body);
self[kSnapshotRecorder].record(opts, {
statusCode: responseData.statusCode,
headers: responseData.headers,
body: responseBody,
trailers: responseData.trailers
}).then(() => handler.onResponseEnd(controller, trailers)).catch((error) => handler.onResponseError(controller, error));
}
});
}
/**
* Replays a recorded response
*
* @param {Object} snapshot - The recorded snapshot to replay.
* @param {Object} handler - The handler to call with the response data.
* @returns {void}
*/
#replaySnapshot(snapshot, handler) {
try {
const { response } = snapshot;
const controller = {
pause() {},
resume() {},
abort(reason) {
this.aborted = true;
this.reason = reason;
},
aborted: false,
paused: false
};
handler.onRequestStart(controller);
handler.onResponseStart(controller, response.statusCode, response.headers);
const body = Buffer.from(response.body, "base64");
handler.onResponseData(controller, body);
handler.onResponseEnd(controller, response.trailers);
} catch (error) {
handler.onError?.(error);
}
}
/**
* Loads snapshots from file
*
* @param {string} [filePath] - Optional file path to load snapshots from.
* @returns {Promise<void>} - Resolves when snapshots are loaded.
*/
async loadSnapshots(filePath) {
await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]);
this[kSnapshotLoaded] = true;
if (this[kSnapshotMode] === "playback") this.#setupMockInterceptors();
}
/**
* Saves snapshots to file
*
* @param {string} [filePath] - Optional file path to save snapshots to.
* @returns {Promise<void>} - Resolves when snapshots are saved.
*/
async saveSnapshots(filePath) {
return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]);
}
/**
* Sets up MockAgent interceptors based on recorded snapshots.
*
* This method creates MockAgent interceptors for each recorded snapshot,
* allowing the SnapshotAgent to fall back to MockAgent's standard intercept
* mechanism in playback mode. Each interceptor is configured to persist
* (remain active for multiple requests) and responds with the recorded
* response data.
*
* Called automatically when loading snapshots in playback mode.
*
* @returns {void}
*/
#setupMockInterceptors() {
for (const snapshot of this[kSnapshotRecorder].getSnapshots()) {
const { request: request$2, responses, response } = snapshot;
const url = new URL(request$2.url);
const mockPool = this.get(url.origin);
const responseData = responses ? responses[0] : response;
if (!responseData) continue;
mockPool.intercept({
path: url.pathname + url.search,
method: request$2.method,
headers: request$2.headers,
body: request$2.body
}).reply(responseData.statusCode, responseData.body, {
headers: responseData.headers,
trailers: responseData.trailers
}).persist();
}
}
/**
* Gets the snapshot recorder
* @return {SnapshotRecorder} - The snapshot recorder instance
*/
getRecorder() {
return this[kSnapshotRecorder];
}
/**
* Gets the current mode
* @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode
*/
getMode() {
return this[kSnapshotMode];
}
/**
* Clears all snapshots
* @returns {void}
*/
clearSnapshots() {
this[kSnapshotRecorder].clear();
}
/**
* Resets call counts for all snapshots (useful for test cleanup)
* @returns {void}
*/
resetCallCounts() {
this[kSnapshotRecorder].resetCallCounts();
}
/**
* Deletes a specific snapshot by request options
* @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot
* @return {Promise<boolean>} - Returns true if the snapshot was deleted, false if not found
*/
deleteSnapshot(requestOpts) {
return this[kSnapshotRecorder].deleteSnapshot(requestOpts);
}
/**
* Gets information about a specific snapshot
* @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found
*/
getSnapshotInfo(requestOpts) {
return this[kSnapshotRecorder].getSnapshotInfo(requestOpts);
}
/**
* Replaces all snapshots with new data (full replacement)
* @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record<string, import('./snapshot-recorder').SnapshotEntry>} snapshotData - New snapshot data to replace existing snapshots
* @returns {void}
*/
replaceSnapshots(snapshotData) {
this[kSnapshotRecorder].replaceSnapshots(snapshotData);
}
/**
* Closes the agent, saving snapshots and cleaning up resources.
*
* @returns {Promise<void>}
*/
async close() {
await this[kSnapshotRecorder].close();
await this[kRealAgent]?.close();
await super.close();
}
};
module.exports = SnapshotAgent$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/global.js
var require_global = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/global.js": ((exports, module) => {
const globalDispatcher = Symbol.for("undici.globalDispatcher.1");
const { InvalidArgumentError: InvalidArgumentError$4 } = require_errors();
const Agent$1 = require_agent();
if (getGlobalDispatcher$3() === void 0) setGlobalDispatcher$1(new Agent$1());
function setGlobalDispatcher$1(agent) {
if (!agent || typeof agent.dispatch !== "function") throw new InvalidArgumentError$4("Argument agent must implement Agent");
Object.defineProperty(globalThis, globalDispatcher, {
value: agent,
writable: true,
enumerable: false,
configurable: false
});
}
function getGlobalDispatcher$3() {
return globalThis[globalDispatcher];
}
const installedExports = [
"fetch",
"Headers",
"Response",
"Request",
"FormData",
"WebSocket",
"CloseEvent",
"ErrorEvent",
"MessageEvent",
"EventSource"
];
module.exports = {
setGlobalDispatcher: setGlobalDispatcher$1,
getGlobalDispatcher: getGlobalDispatcher$3,
installedExports
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/decorator-handler.js": ((exports, module) => {
const assert$14 = __require$2("node:assert");
const WrapHandler = require_wrap_handler();
/**
* @deprecated
*/
module.exports = class DecoratorHandler$5 {
#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) {
assert$14(!this.#onCompleteCalled);
assert$14(!this.#onErrorCalled);
return this.#handler.onRequestUpgrade?.(...args);
}
onResponseStart(...args) {
assert$14(!this.#onCompleteCalled);
assert$14(!this.#onErrorCalled);
assert$14(!this.#onResponseStartCalled);
this.#onResponseStartCalled = true;
return this.#handler.onResponseStart?.(...args);
}
onResponseData(...args) {
assert$14(!this.#onCompleteCalled);
assert$14(!this.#onErrorCalled);
return this.#handler.onResponseData?.(...args);
}
onResponseEnd(...args) {
assert$14(!this.#onCompleteCalled);
assert$14(!this.#onErrorCalled);
this.#onCompleteCalled = true;
return this.#handler.onResponseEnd?.(...args);
}
onResponseError(...args) {
this.#onErrorCalled = true;
return this.#handler.onResponseError?.(...args);
}
/**
* @deprecated
*/
onBodySent() {}
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/redirect-handler.js": ((exports, module) => {
const util$10 = require_util$5();
const { kBodyUsed } = require_symbols();
const assert$13 = __require$2("node:assert");
const { InvalidArgumentError: InvalidArgumentError$3 } = require_errors();
const EE$1 = __require$2("node:events");
const redirectableStatusCodes = [
300,
301,
302,
303,
307,
308
];
const kBody = Symbol("body");
const noop$1 = () => {};
var BodyAsyncIterable = class {
constructor(body) {
this[kBody] = body;
this[kBodyUsed] = false;
}
async *[Symbol.asyncIterator]() {
assert$13(!this[kBodyUsed], "disturbed");
this[kBodyUsed] = true;
yield* this[kBody];
}
};
var RedirectHandler$2 = class RedirectHandler$2 {
static buildDispatch(dispatcher, maxRedirections) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) throw new InvalidArgumentError$3("maxRedirections must be a positive number");
const dispatch = dispatcher.dispatch.bind(dispatcher);
return (opts, originalHandler) => dispatch(opts, new RedirectHandler$2(dispatch, maxRedirections, opts, originalHandler));
}
constructor(dispatch, maxRedirections, opts, handler) {
if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) throw new InvalidArgumentError$3("maxRedirections must be a positive number");
this.dispatch = dispatch;
this.location = null;
const { maxRedirections: _,...cleanOpts } = opts;
this.opts = cleanOpts;
this.maxRedirections = maxRedirections;
this.handler = handler;
this.history = [];
if (util$10.isStream(this.opts.body)) {
if (util$10.bodyLength(this.opts.body) === 0) this.opts.body.on("data", function() {
assert$13(false);
});
if (typeof this.opts.body.readableDidRead !== "boolean") {
this.opts.body[kBodyUsed] = false;
EE$1.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) && util$10.isIterable(this.opts.body) && !util$10.isFormDataLike(this.opts.body)) this.opts.body = new BodyAsyncIterable(this.opts.body);
}
onRequestStart(controller, context) {
this.handler.onRequestStart?.(controller, {
...context,
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 (util$10.isStream(this.opts.body)) util$10.destroy(this.opts.body.on("error", noop$1));
this.opts.body = null;
}
if (statusCode === 303 && this.opts.method !== "HEAD") {
this.opts.method = "GET";
if (util$10.isStream(this.opts.body)) util$10.destroy(this.opts.body.on("error", noop$1));
this.opts.body = null;
}
this.location = this.history.length >= this.maxRedirections || util$10.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 } = util$10.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
const path$2 = search ? `${pathname}${search}` : pathname;
const redirectUrlString = `${origin}${path$2}`;
for (const historyUrl of this.history) if (historyUrl.toString() === redirectUrlString) throw new InvalidArgumentError$3(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
this.opts.path = path$2;
this.opts.origin = origin;
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, error) {
this.handler.onResponseError?.(controller, error);
}
};
function shouldRemoveHeader(header, removeContent, unknownOrigin) {
if (header.length === 4) return util$10.headerNameToString(header) === "host";
if (removeContent && util$10.headerNameToString(header).startsWith("content-")) return true;
if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
const name = util$10.headerNameToString(header);
return name === "authorization" || name === "cookie" || name === "proxy-authorization";
}
return false;
}
function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
const ret = [];
if (Array.isArray(headers)) {
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) if (!shouldRemoveHeader(headers[i$1], removeContent, unknownOrigin)) ret.push(headers[i$1], headers[i$1 + 1]);
} else if (headers && typeof headers === "object") {
const entries = util$10.hasSafeIterator(headers) ? headers : Object.entries(headers);
for (const [key, value] of entries) if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) ret.push(key, value);
} else assert$13(headers == null, "headers must be an object or an array");
return ret;
}
module.exports = RedirectHandler$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/redirect.js
var require_redirect = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/redirect.js": ((exports, module) => {
const RedirectHandler$1 = require_redirect_handler();
function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) {
return (dispatch) => {
return function Intercept(opts, handler) {
const { maxRedirections = defaultMaxRedirections,...rest } = opts;
if (maxRedirections == null || maxRedirections === 0) return dispatch(opts, handler);
const dispatchOpts = { ...rest };
return dispatch(dispatchOpts, new RedirectHandler$1(dispatch, maxRedirections, dispatchOpts, handler));
};
};
}
module.exports = createRedirectInterceptor;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/response-error.js
var require_response_error = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/response-error.js": ((exports, module) => {
const DecoratorHandler$4 = require_decorator_handler();
const { ResponseError } = require_errors();
var ResponseErrorHandler = class extends DecoratorHandler$4 {
#statusCode;
#contentType;
#decoder;
#headers;
#body;
constructor(_opts, { handler }) {
super(handler);
}
#checkContentType(contentType) {
return (this.#contentType ?? "").indexOf(contentType) === 0;
}
onRequestStart(controller, context) {
this.#statusCode = 0;
this.#contentType = null;
this.#decoder = null;
this.#headers = null;
this.#body = "";
return super.onRequestStart(controller, context);
}
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);
}
};
module.exports = () => {
return (dispatch) => {
return function Intercept(opts, handler) {
return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
};
};
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/retry.js
var require_retry = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/retry.js": ((exports, module) => {
const RetryHandler$1 = require_retry_handler();
module.exports = (globalOpts) => {
return (dispatch) => {
return function retryInterceptor(opts, handler) {
return dispatch(opts, new RetryHandler$1({
...opts,
retryOptions: {
...globalOpts,
...opts.retryOptions
}
}, {
handler,
dispatch
}));
};
};
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/dump.js
var require_dump = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/dump.js": ((exports, module) => {
const { InvalidArgumentError: InvalidArgumentError$2, RequestAbortedError: RequestAbortedError$1 } = require_errors();
const DecoratorHandler$3 = require_decorator_handler();
var DumpHandler = class extends DecoratorHandler$3 {
#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$2("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, context) {
controller.abort = this.#abort.bind(this);
this.#controller = controller;
return super.onRequestStart(controller, context);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
const contentLength = headers["content-length"];
if (contentLength != null && contentLength > this.#maxSize) throw new RequestAbortedError$1(`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 function Intercept(opts, handler) {
const { dumpMaxSize = defaultMaxSize } = opts;
return dispatch(opts, new DumpHandler({
maxSize: dumpMaxSize,
signal: opts.signal
}, handler));
};
};
}
module.exports = createDumpInterceptor;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/dns.js
var require_dns = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/dns.js": ((exports, module) => {
const { isIP } = __require$2("node:net");
const { lookup } = __require$2("node:dns");
const DecoratorHandler$2 = require_decorator_handler();
const { InvalidArgumentError: InvalidArgumentError$1, InformationalError } = require_errors();
const maxInt = Math.pow(2, 31) - 1;
function hasSafeIterator$1(headers) {
const prototype = Object.getPrototypeOf(headers);
return Object.prototype.hasOwnProperty.call(headers, Symbol.iterator) || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
}
function isHostHeader(key) {
return typeof key === "string" && key.toLowerCase() === "host";
}
function normalizeHeaders$3(headers) {
if (headers == null) return null;
if (Array.isArray(headers)) {
if (headers.length === 0 || !Array.isArray(headers[0])) return headers;
const normalized = [];
for (const header of headers) if (Array.isArray(header) && header.length === 2) normalized.push(header[0], header[1]);
else normalized.push(header);
return normalized;
}
if (typeof headers === "object" && hasSafeIterator$1(headers)) {
const normalized = [];
for (const header of headers) if (Array.isArray(header) && header.length === 2) normalized.push(header[0], header[1]);
else normalized.push(header);
return normalized;
}
return headers;
}
function hasHostHeader(headers) {
if (headers == null) return false;
if (Array.isArray(headers)) {
if (headers.length === 0) return false;
for (let i$1 = 0; i$1 < headers.length; i$1 += 2) if (isHostHeader(headers[i$1])) return true;
return false;
}
if (typeof headers === "object") {
for (const key in headers) if (isHostHeader(key)) return true;
}
return false;
}
function withHostHeader(host, headers) {
const normalizedHeaders = normalizeHeaders$3(headers);
if (hasHostHeader(normalizedHeaders)) return normalizedHeaders;
if (Array.isArray(normalizedHeaders)) return [
"host",
host,
...normalizedHeaders
];
if (normalizedHeaders && typeof normalizedHeaders === "object") return {
host,
...normalizedHeaders
};
return { host };
}
var DNSStorage = class {
#maxItems = 0;
#records = /* @__PURE__ */ new Map();
constructor(opts) {
this.#maxItems = opts.maxItems;
}
get size() {
return this.#records.size;
}
get(hostname) {
return this.#records.get(hostname) ?? null;
}
set(hostname, records) {
this.#records.set(hostname, records);
}
delete(hostname) {
this.#records.delete(hostname);
}
full() {
return this.size >= this.#maxItems;
}
};
var DNSInstance = class {
#maxTTL = 0;
#maxItems = 0;
dualStack = true;
affinity = null;
lookup = null;
pick = null;
storage = 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;
this.storage = opts.storage ?? new DNSStorage(opts);
}
runLookup(origin, opts, cb) {
const ips = this.storage.get(origin.hostname);
if (ips == null && this.storage.full()) {
cb(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) {
cb(err ?? new InformationalError("No DNS entries found"));
return;
}
this.setRecords(origin, addresses);
const records = this.storage.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 = "";
cb(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.storage.delete(origin.hostname);
this.runLookup(origin, opts, cb);
return;
}
let port;
if (typeof ip.port === "number") port = `:${ip.port}`;
else if (origin.port !== "") port = `:${origin.port}`;
else port = "";
cb(null, new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`));
}
}
#defaultLookup(origin, opts, cb) {
lookup(origin.hostname, {
all: true,
family: this.dualStack === false ? this.affinity : 0,
order: "ipv4first"
}, (err, addresses) => {
if (err) return cb(err);
const results = /* @__PURE__ */ new Map();
for (const addr of addresses) results.set(`${addr.address}:${addr.family}`, addr);
cb(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.storage.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
} };
let minTTL = this.#maxTTL;
for (const record of addresses) {
record.timestamp = timestamp;
if (typeof record.ttl === "number") {
record.ttl = Math.min(record.ttl, this.#maxTTL);
minTTL = Math.min(minTTL, record.ttl);
} else record.ttl = this.#maxTTL;
const familyRecords = records.records[record.family] ?? { ips: [] };
familyRecords.ips.push(record);
records.records[record.family] = familyRecords;
}
this.storage.set(origin.hostname, records, { ttl: minTTL });
}
deleteRecords(origin) {
this.storage.delete(origin.hostname);
}
getHandler(meta, opts) {
return new DNSDispatchHandler(this, meta, opts);
}
};
var DNSDispatchHandler = class extends DecoratorHandler$2 {
#state = null;
#opts = null;
#dispatch = null;
#origin = null;
#controller = null;
#newOrigin = null;
#firstTry = true;
constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
super(handler);
this.#origin = origin;
this.#newOrigin = newOrigin;
this.#opts = { ...opts };
this.#state = state;
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}`,
headers: withHostHeader(this.#origin.host, this.#opts.headers)
};
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;
}
}
};
module.exports = (interceptorOpts) => {
if (interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== "number" || interceptorOpts?.maxTTL < 0)) throw new InvalidArgumentError$1("Invalid maxTTL. Must be a positive number");
if (interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== "number" || interceptorOpts?.maxItems < 1)) throw new InvalidArgumentError$1("Invalid maxItems. Must be a positive number and greater than zero");
if (interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6) throw new InvalidArgumentError$1("Invalid affinity. Must be either 4 or 6");
if (interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== "boolean") throw new InvalidArgumentError$1("Invalid dualStack. Must be a boolean");
if (interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== "function") throw new InvalidArgumentError$1("Invalid lookup. Must be a function");
if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") throw new InvalidArgumentError$1("Invalid pick. Must be a function");
if (interceptorOpts?.storage != null && (typeof interceptorOpts?.storage?.get !== "function" || typeof interceptorOpts?.storage?.set !== "function" || typeof interceptorOpts?.storage?.full !== "function" || typeof interceptorOpts?.storage?.delete !== "function")) throw new InvalidArgumentError$1("Invalid storage. Must be a object with methods: { get, set, full, delete }");
const dualStack = interceptorOpts?.dualStack ?? true;
let affinity;
if (dualStack) affinity = interceptorOpts?.affinity ?? null;
else affinity = interceptorOpts?.affinity ?? 4;
const instance$1 = new DNSInstance({
maxTTL: interceptorOpts?.maxTTL ?? 1e4,
lookup: interceptorOpts?.lookup ?? null,
pick: interceptorOpts?.pick ?? null,
dualStack,
affinity,
maxItems: interceptorOpts?.maxItems ?? Infinity,
storage: interceptorOpts?.storage
});
return (dispatch) => {
return 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$1.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
if (err) return handler.onResponseError(null, err);
dispatch({
...origDispatchOpts,
servername: origin.hostname,
origin: newOrigin.origin,
headers: withHostHeader(origin.host, origDispatchOpts.headers)
}, instance$1.getHandler({
origin,
dispatch,
handler,
newOrigin
}, origDispatchOpts));
});
return true;
};
};
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/cache.js
var require_cache$2 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/cache.js": ((exports, module) => {
const { safeHTTPMethods, pathHasQueryOrFragment, hasSafeIterator } = require_util$5();
const { serializePathWithQuery } = require_util$5();
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchOptions} opts
*/
function makeCacheKey$2(opts) {
if (!opts.origin) throw new Error("opts.origin is undefined");
let fullPath = opts.path || "/";
if (opts.query && !pathHasQueryOrFragment(opts.path)) fullPath = serializePathWithQuery(fullPath, opts.query);
return {
origin: opts.origin.toString(),
method: opts.method,
path: fullPath,
headers: opts.headers
};
}
/**
* @param {Record<string, string[] | string>}
* @returns {Record<string, string[] | string>}
*/
function normalizeHeaders$2(opts) {
let headers;
if (opts.headers == null) headers = {};
else if (typeof opts.headers === "object") {
headers = {};
if (hasSafeIterator(opts.headers)) for (const x of opts.headers) {
if (!Array.isArray(x)) throw new Error("opts.headers is not a valid header map");
const [key, val] = x;
if (typeof key !== "string" || typeof val !== "string") throw new Error("opts.headers is not a valid header map");
headers[key.toLowerCase()] = val;
}
else 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;
}
/**
* @param {any} key
*/
function assertCacheKey$2(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}`);
}
/**
* @param {any} value
*/
function assertCacheValue$2(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}`);
}
/**
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-cache-control
* @see https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml
* @param {string | string[]} header
* @returns {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives}
*/
function parseCacheControlHeader$2(header) {
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives}
*/
const output = {};
let directives;
if (Array.isArray(header)) {
directives = [];
for (const directive of header) directives.push(...directive.split(","));
} else directives = header.split(",");
for (let i$1 = 0; i$1 < directives.length; i$1++) {
const directive = directives[i$1].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 j = i$1 + 1; j < directives.length; j++) {
const nextPart = directives[j];
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;
}
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;
}
/**
* @param {string | string[]} varyHeader Vary header from the server
* @param {Record<string, string | string[]>} headers Request headers
* @returns {Record<string, string | string[]>}
*/
function parseVaryHeader$1(varyHeader, headers) {
if (typeof varyHeader === "string" && varyHeader.includes("*")) return headers;
const output = {};
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;
}
/**
* Note: this deviates from the spec a little. Empty etags ("", W/"") are valid,
* however, including them in cached resposnes serves little to no purpose.
*
* @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag
*
* @param {string} etag
* @returns {boolean}
*/
function isEtagUsable$1(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;
}
/**
* @param {unknown} store
* @returns {asserts store is import('../../types/cache-interceptor.d.ts').default.CacheStore}
*/
function assertCacheStore$1(store, name = "CacheStore") {
if (typeof store !== "object" || store === null) throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? "null" : typeof store}`);
for (const fn of [
"get",
"createWriteStream",
"delete"
]) if (typeof store[fn] !== "function") throw new TypeError(`${name} needs to have a \`${fn}()\` function`);
}
/**
* @param {unknown} methods
* @returns {asserts methods is import('../../types/cache-interceptor.d.ts').default.CacheMethods[]}
*/
function assertCacheMethods$1(methods, name = "CacheMethods") {
if (!Array.isArray(methods)) throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? "null" : typeof methods}`);
if (methods.length === 0) throw new TypeError(`${name} needs to have at least one method`);
for (const method of methods) if (!safeHTTPMethods.includes(method)) throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
}
/**
* Creates a string key for request deduplication purposes.
* This key is used to identify in-flight requests that can be shared.
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {Set<string>} [excludeHeaders] Set of lowercase header names to exclude from the key
* @returns {string}
*/
function makeDeduplicationKey$1(cacheKey, excludeHeaders) {
let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
if (cacheKey.headers) {
const sortedHeaders = Object.keys(cacheKey.headers).sort();
for (const header of sortedHeaders) {
if (excludeHeaders?.has(header.toLowerCase())) continue;
const value = cacheKey.headers[header];
key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
}
}
return key;
}
module.exports = {
makeCacheKey: makeCacheKey$2,
normalizeHeaders: normalizeHeaders$2,
assertCacheKey: assertCacheKey$2,
assertCacheValue: assertCacheValue$2,
parseCacheControlHeader: parseCacheControlHeader$2,
parseVaryHeader: parseVaryHeader$1,
isEtagUsable: isEtagUsable$1,
assertCacheMethods: assertCacheMethods$1,
assertCacheStore: assertCacheStore$1,
makeDeduplicationKey: makeDeduplicationKey$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/date.js
var require_date = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/util/date.js": ((exports, module) => {
/**
* @see https://www.rfc-editor.org/rfc/rfc9110.html#name-date-time-formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseHttpDate$1(date) {
switch (date[3]) {
case ",": return parseImfDate(date);
case " ": return parseAscTimeDate(date);
default: return parseRfc850Date(date);
}
}
/**
* @see https://httpwg.org/specs/rfc9110.html#preferred.date.format
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseImfDate(date) {
if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") return;
let weekday = -1;
if (date[0] === "S" && date[1] === "u" && date[2] === "n") weekday = 0;
else if (date[0] === "M" && date[1] === "o" && date[2] === "n") weekday = 1;
else if (date[0] === "T" && date[1] === "u" && date[2] === "e") weekday = 2;
else if (date[0] === "W" && date[1] === "e" && date[2] === "d") weekday = 3;
else if (date[0] === "T" && date[1] === "h" && date[2] === "u") weekday = 4;
else if (date[0] === "F" && date[1] === "r" && date[2] === "i") weekday = 5;
else if (date[0] === "S" && date[1] === "a" && date[2] === "t") weekday = 6;
else return;
let day = 0;
if (date[5] === "0") {
const code = date.charCodeAt(6);
if (code < 49 || code > 57) return;
day = code - 48;
} else {
const code1 = date.charCodeAt(5);
if (code1 < 49 || code1 > 51) return;
const code2 = date.charCodeAt(6);
if (code2 < 48 || code2 > 57) return;
day = (code1 - 48) * 10 + (code2 - 48);
}
let monthIdx = -1;
if (date[8] === "J" && date[9] === "a" && date[10] === "n") monthIdx = 0;
else if (date[8] === "F" && date[9] === "e" && date[10] === "b") monthIdx = 1;
else if (date[8] === "M" && date[9] === "a") if (date[10] === "r") monthIdx = 2;
else if (date[10] === "y") monthIdx = 4;
else return;
else if (date[8] === "J") if (date[9] === "a" && date[10] === "n") monthIdx = 0;
else if (date[9] === "u") if (date[10] === "n") monthIdx = 5;
else if (date[10] === "l") monthIdx = 6;
else return;
else return;
else if (date[8] === "A") if (date[9] === "p" && date[10] === "r") monthIdx = 3;
else if (date[9] === "u" && date[10] === "g") monthIdx = 7;
else return;
else if (date[8] === "S" && date[9] === "e" && date[10] === "p") monthIdx = 8;
else if (date[8] === "O" && date[9] === "c" && date[10] === "t") monthIdx = 9;
else if (date[8] === "N" && date[9] === "o" && date[10] === "v") monthIdx = 10;
else if (date[8] === "D" && date[9] === "e" && date[10] === "c") monthIdx = 11;
else return;
const yearDigit1 = date.charCodeAt(12);
if (yearDigit1 < 48 || yearDigit1 > 57) return;
const yearDigit2 = date.charCodeAt(13);
if (yearDigit2 < 48 || yearDigit2 > 57) return;
const yearDigit3 = date.charCodeAt(14);
if (yearDigit3 < 48 || yearDigit3 > 57) return;
const yearDigit4 = date.charCodeAt(15);
if (yearDigit4 < 48 || yearDigit4 > 57) return;
const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
let hour = 0;
if (date[17] === "0") {
const code = date.charCodeAt(18);
if (code < 48 || code > 57) return;
hour = code - 48;
} else {
const code1 = date.charCodeAt(17);
if (code1 < 48 || code1 > 50) return;
const code2 = date.charCodeAt(18);
if (code2 < 48 || code2 > 57) return;
if (code1 === 50 && code2 > 51) return;
hour = (code1 - 48) * 10 + (code2 - 48);
}
let minute = 0;
if (date[20] === "0") {
const code = date.charCodeAt(21);
if (code < 48 || code > 57) return;
minute = code - 48;
} else {
const code1 = date.charCodeAt(20);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(21);
if (code2 < 48 || code2 > 57) return;
minute = (code1 - 48) * 10 + (code2 - 48);
}
let second = 0;
if (date[23] === "0") {
const code = date.charCodeAt(24);
if (code < 48 || code > 57) return;
second = code - 48;
} else {
const code1 = date.charCodeAt(23);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(24);
if (code2 < 48 || code2 > 57) return;
second = (code1 - 48) * 10 + (code2 - 48);
}
const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
return result.getUTCDay() === weekday ? result : void 0;
}
/**
* @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseAscTimeDate(date) {
if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") return;
let weekday = -1;
if (date[0] === "S" && date[1] === "u" && date[2] === "n") weekday = 0;
else if (date[0] === "M" && date[1] === "o" && date[2] === "n") weekday = 1;
else if (date[0] === "T" && date[1] === "u" && date[2] === "e") weekday = 2;
else if (date[0] === "W" && date[1] === "e" && date[2] === "d") weekday = 3;
else if (date[0] === "T" && date[1] === "h" && date[2] === "u") weekday = 4;
else if (date[0] === "F" && date[1] === "r" && date[2] === "i") weekday = 5;
else if (date[0] === "S" && date[1] === "a" && date[2] === "t") weekday = 6;
else return;
let monthIdx = -1;
if (date[4] === "J" && date[5] === "a" && date[6] === "n") monthIdx = 0;
else if (date[4] === "F" && date[5] === "e" && date[6] === "b") monthIdx = 1;
else if (date[4] === "M" && date[5] === "a") if (date[6] === "r") monthIdx = 2;
else if (date[6] === "y") monthIdx = 4;
else return;
else if (date[4] === "J") if (date[5] === "a" && date[6] === "n") monthIdx = 0;
else if (date[5] === "u") if (date[6] === "n") monthIdx = 5;
else if (date[6] === "l") monthIdx = 6;
else return;
else return;
else if (date[4] === "A") if (date[5] === "p" && date[6] === "r") monthIdx = 3;
else if (date[5] === "u" && date[6] === "g") monthIdx = 7;
else return;
else if (date[4] === "S" && date[5] === "e" && date[6] === "p") monthIdx = 8;
else if (date[4] === "O" && date[5] === "c" && date[6] === "t") monthIdx = 9;
else if (date[4] === "N" && date[5] === "o" && date[6] === "v") monthIdx = 10;
else if (date[4] === "D" && date[5] === "e" && date[6] === "c") monthIdx = 11;
else return;
let day = 0;
if (date[8] === " ") {
const code = date.charCodeAt(9);
if (code < 49 || code > 57) return;
day = code - 48;
} else {
const code1 = date.charCodeAt(8);
if (code1 < 49 || code1 > 51) return;
const code2 = date.charCodeAt(9);
if (code2 < 48 || code2 > 57) return;
day = (code1 - 48) * 10 + (code2 - 48);
}
let hour = 0;
if (date[11] === "0") {
const code = date.charCodeAt(12);
if (code < 48 || code > 57) return;
hour = code - 48;
} else {
const code1 = date.charCodeAt(11);
if (code1 < 48 || code1 > 50) return;
const code2 = date.charCodeAt(12);
if (code2 < 48 || code2 > 57) return;
if (code1 === 50 && code2 > 51) return;
hour = (code1 - 48) * 10 + (code2 - 48);
}
let minute = 0;
if (date[14] === "0") {
const code = date.charCodeAt(15);
if (code < 48 || code > 57) return;
minute = code - 48;
} else {
const code1 = date.charCodeAt(14);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(15);
if (code2 < 48 || code2 > 57) return;
minute = (code1 - 48) * 10 + (code2 - 48);
}
let second = 0;
if (date[17] === "0") {
const code = date.charCodeAt(18);
if (code < 48 || code > 57) return;
second = code - 48;
} else {
const code1 = date.charCodeAt(17);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(18);
if (code2 < 48 || code2 > 57) return;
second = (code1 - 48) * 10 + (code2 - 48);
}
const yearDigit1 = date.charCodeAt(20);
if (yearDigit1 < 48 || yearDigit1 > 57) return;
const yearDigit2 = date.charCodeAt(21);
if (yearDigit2 < 48 || yearDigit2 > 57) return;
const yearDigit3 = date.charCodeAt(22);
if (yearDigit3 < 48 || yearDigit3 > 57) return;
const yearDigit4 = date.charCodeAt(23);
if (yearDigit4 < 48 || yearDigit4 > 57) return;
const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
return result.getUTCDay() === weekday ? result : void 0;
}
/**
* @see https://httpwg.org/specs/rfc9110.html#obsolete.date.formats
*
* @param {string} date
* @returns {Date | undefined}
*/
function parseRfc850Date(date) {
let commaIndex = -1;
let weekday = -1;
if (date[0] === "S") {
if (date[1] === "u" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
weekday = 0;
commaIndex = 6;
} else if (date[1] === "a" && date[2] === "t" && date[3] === "u" && date[4] === "r" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
weekday = 6;
commaIndex = 8;
}
} else if (date[0] === "M" && date[1] === "o" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
weekday = 1;
commaIndex = 6;
} else if (date[0] === "T") {
if (date[1] === "u" && date[2] === "e" && date[3] === "s" && date[4] === "d" && date[5] === "a" && date[6] === "y") {
weekday = 2;
commaIndex = 7;
} else if (date[1] === "h" && date[2] === "u" && date[3] === "r" && date[4] === "s" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
weekday = 4;
commaIndex = 8;
}
} else if (date[0] === "W" && date[1] === "e" && date[2] === "d" && date[3] === "n" && date[4] === "e" && date[5] === "s" && date[6] === "d" && date[7] === "a" && date[8] === "y") {
weekday = 3;
commaIndex = 9;
} else if (date[0] === "F" && date[1] === "r" && date[2] === "i" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
weekday = 5;
commaIndex = 6;
} else return;
if (date[commaIndex] !== "," || date.length - commaIndex - 1 !== 23 || date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " " || date[commaIndex + 21] !== "G" || date[commaIndex + 22] !== "M" || date[commaIndex + 23] !== "T") return;
let day = 0;
if (date[commaIndex + 2] === "0") {
const code = date.charCodeAt(commaIndex + 3);
if (code < 49 || code > 57) return;
day = code - 48;
} else {
const code1 = date.charCodeAt(commaIndex + 2);
if (code1 < 49 || code1 > 51) return;
const code2 = date.charCodeAt(commaIndex + 3);
if (code2 < 48 || code2 > 57) return;
day = (code1 - 48) * 10 + (code2 - 48);
}
let monthIdx = -1;
if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "n") monthIdx = 0;
else if (date[commaIndex + 5] === "F" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "b") monthIdx = 1;
else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "r") monthIdx = 2;
else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "p" && date[commaIndex + 7] === "r") monthIdx = 3;
else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "y") monthIdx = 4;
else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "n") monthIdx = 5;
else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "l") monthIdx = 6;
else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "g") monthIdx = 7;
else if (date[commaIndex + 5] === "S" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "p") monthIdx = 8;
else if (date[commaIndex + 5] === "O" && date[commaIndex + 6] === "c" && date[commaIndex + 7] === "t") monthIdx = 9;
else if (date[commaIndex + 5] === "N" && date[commaIndex + 6] === "o" && date[commaIndex + 7] === "v") monthIdx = 10;
else if (date[commaIndex + 5] === "D" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "c") monthIdx = 11;
else return;
const yearDigit1 = date.charCodeAt(commaIndex + 9);
if (yearDigit1 < 48 || yearDigit1 > 57) return;
const yearDigit2 = date.charCodeAt(commaIndex + 10);
if (yearDigit2 < 48 || yearDigit2 > 57) return;
let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48);
year += year < 70 ? 2e3 : 1900;
let hour = 0;
if (date[commaIndex + 12] === "0") {
const code = date.charCodeAt(commaIndex + 13);
if (code < 48 || code > 57) return;
hour = code - 48;
} else {
const code1 = date.charCodeAt(commaIndex + 12);
if (code1 < 48 || code1 > 50) return;
const code2 = date.charCodeAt(commaIndex + 13);
if (code2 < 48 || code2 > 57) return;
if (code1 === 50 && code2 > 51) return;
hour = (code1 - 48) * 10 + (code2 - 48);
}
let minute = 0;
if (date[commaIndex + 15] === "0") {
const code = date.charCodeAt(commaIndex + 16);
if (code < 48 || code > 57) return;
minute = code - 48;
} else {
const code1 = date.charCodeAt(commaIndex + 15);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(commaIndex + 16);
if (code2 < 48 || code2 > 57) return;
minute = (code1 - 48) * 10 + (code2 - 48);
}
let second = 0;
if (date[commaIndex + 18] === "0") {
const code = date.charCodeAt(commaIndex + 19);
if (code < 48 || code > 57) return;
second = code - 48;
} else {
const code1 = date.charCodeAt(commaIndex + 18);
if (code1 < 48 || code1 > 53) return;
const code2 = date.charCodeAt(commaIndex + 19);
if (code2 < 48 || code2 > 57) return;
second = (code1 - 48) * 10 + (code2 - 48);
}
const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
return result.getUTCDay() === weekday ? result : void 0;
}
module.exports = { parseHttpDate: parseHttpDate$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/cache-handler.js
var require_cache_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/cache-handler.js": ((exports, module) => {
const util$9 = require_util$5();
const { parseCacheControlHeader: parseCacheControlHeader$1, parseVaryHeader, isEtagUsable } = require_cache$2();
const { parseHttpDate } = require_date();
function noop() {}
const HEURISTICALLY_CACHEABLE_STATUS_CODES = [
200,
203,
204,
206,
300,
301,
308,
404,
405,
410,
414,
501
];
const NOT_UNDERSTOOD_STATUS_CODES = [206];
const MAX_RESPONSE_AGE = 2147483647e3;
/**
* @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler
*
* @implements {DispatchHandler}
*/
var CacheHandler$1 = class {
/**
* @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, context) {
this.#writeStream?.destroy();
this.#writeStream = void 0;
this.#handler.onRequestStart?.(controller, context);
}
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 = () => this.#handler.onResponseStart?.(controller, statusCode, resHeaders, statusMessage);
const handler = this;
if (!util$9.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$1(cacheControlHeader) : {};
if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) 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);
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const value = {
statusCode,
statusMessage,
headers: strippedHeaders,
vary: varyDirectives,
cacheControlDirectives,
cachedAt: resAge ? now - resAge : now,
staleAt: absoluteStaleAt,
deleteAt
};
if (statusCode === 304) {
const handle304 = (cachedValue) => {
if (!cachedValue) return downstreamOnHeaders();
value.statusCode = cachedValue.statusCode;
value.statusMessage = cachedValue.statusMessage;
value.etag = cachedValue.etag;
value.headers = {
...cachedValue.headers,
...strippedHeaders
};
downstreamOnHeaders();
this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
if (!this.#writeStream || !cachedValue?.body) return;
if (typeof cachedValue.body.values === "function") {
const bodyIterator = cachedValue.body.values();
const streamCachedBody = () => {
for (const chunk of bodyIterator) {
const full = this.#writeStream.write(chunk) === false;
this.#handler.onResponseData?.(controller, chunk);
if (full) break;
}
};
this.#writeStream.on("error", function() {
handler.#writeStream = void 0;
handler.#store.delete(handler.#cacheKey);
}).on("drain", () => {
streamCachedBody();
}).on("close", function() {
if (handler.#writeStream === this) handler.#writeStream = void 0;
});
streamCachedBody();
} else if (typeof cachedValue.body.on === "function") {
cachedValue.body.on("data", (chunk) => {
this.#writeStream.write(chunk);
this.#handler.onResponseData?.(controller, chunk);
}).on("end", () => {
this.#writeStream.end();
}).on("error", () => {
this.#writeStream = void 0;
this.#store.delete(this.#cacheKey);
});
this.#writeStream.on("error", function() {
handler.#writeStream = void 0;
handler.#store.delete(handler.#cacheKey);
}).on("close", function() {
if (handler.#writeStream === this) handler.#writeStream = void 0;
});
}
};
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheValue}
*/
const result = this.#store.get(this.#cacheKey);
if (result && typeof result.then === "function") result.then(handle304);
else handle304(result);
} else {
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();
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();
});
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);
}
};
/**
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
*
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} [reqHeaders]
*/
function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) return false;
if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) return false;
if (cacheControlDirectives["no-store"]) return false;
if (cacheType === "shared" && cacheControlDirectives.private === true) return false;
if (resHeaders.vary?.includes("*")) return false;
if (reqHeaders?.authorization) {
if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) return false;
if (typeof reqHeaders.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;
}
/**
* @param {string | string[]} ageHeader
* @returns {number | undefined}
*/
function getAge(ageHeader) {
const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
return isNaN(age) ? void 0 : age * 1e3;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions['type']} cacheType
* @param {number} now
* @param {number | undefined} age
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {Date | undefined} responseDate
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
*
* @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached
*/
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;
if (responseDate) {
if (responseDate >= expiresDate) return;
if (age !== void 0 && age > expiresDate - responseDate) return;
}
return expiresDate.getTime() - now;
}
}
if (typeof resHeaders["last-modified"] === "string") {
const lastModified = new Date(resHeaders["last-modified"]);
if (isValidDate(lastModified)) {
if (lastModified.getTime() >= now) return;
return (now - lastModified.getTime()) * .1;
}
}
if (cacheControlDirectives.immutable) return 31536e3;
}
/**
* @param {number} now
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {number} staleAt
*/
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 (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) immutable = now + 31536e6;
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) return staleAt + (staleAt - now);
return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
}
/**
* Strips headers required to be removed in cached responses
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @returns {Record<string, string | string []>}
*/
function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
const headersToRemove = [
"connection",
"proxy-authenticate",
"proxy-authentication-info",
"proxy-authorization",
"proxy-connection",
"te",
"transfer-encoding",
"upgrade",
"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;
}
/**
* @param {Date} date
* @returns {boolean}
*/
function isValidDate(date) {
return date instanceof Date && Number.isFinite(date.valueOf());
}
module.exports = CacheHandler$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/cache/memory-cache-store.js
var require_memory_cache_store = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/cache/memory-cache-store.js": ((exports, module) => {
const { Writable: Writable$2 } = __require$2("node:stream");
const { EventEmitter } = __require$2("node:events");
const { assertCacheKey: assertCacheKey$1, assertCacheValue: assertCacheValue$1 } = require_cache$2();
/**
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheKey} CacheKey
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheValue} CacheValue
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
* @typedef {import('../../types/cache-interceptor.d.ts').default.GetResult} GetResult
*/
/**
* @implements {CacheStore}
* @extends {EventEmitter}
*/
var MemoryCacheStore$1 = class extends EventEmitter {
#maxCount = 1024;
#maxSize = 104857600;
#maxEntrySize = 5242880;
#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$1(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, val) {
assertCacheKey$1(key);
assertCacheValue$1(val);
const topLevelKey = `${key.origin}:${key.path}`;
const store = this;
const entry = {
...key,
...val,
body: [],
size: 0
};
return new Writable$2({
write(chunk, encoding, callback$1) {
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$1(null);
},
final(callback$1) {
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 [key$1, entries$1] of store.#entries) {
for (const entry$1 of entries$1.splice(0, entries$1.length / 2)) {
store.#size -= entry$1.size;
store.#count -= 1;
}
if (entries$1.length === 0) store.#entries.delete(key$1);
}
if (store.#size < store.#maxSize && store.#count < store.#maxCount) store.#hasEmittedMaxSizeEvent = false;
}
callback$1(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];
})));
}
module.exports = MemoryCacheStore$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/cache-revalidation-handler.js
var require_cache_revalidation_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/cache-revalidation-handler.js": ((exports, module) => {
const assert$12 = __require$2("node:assert");
/**
* This takes care of revalidation requests we send to the origin. If we get
* a response indicating that what we have is cached (via a HTTP 304), we can
* continue using the cached value. Otherwise, we'll receive the new response
* here, which we then just pass on to the next handler (most likely a
* CacheHandler). Note that this assumes the proper headers were already
* included in the request to tell the origin that we want to revalidate the
* response (i.e. if-modified-since or if-none-match).
*
* @see https://www.rfc-editor.org/rfc/rfc9111.html#name-validation
*
* @implements {import('../../types/dispatcher.d.ts').default.DispatchHandler}
*/
var CacheRevalidationHandler$1 = class {
#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$1, handler, allowErrorStatusCodes) {
if (typeof callback$1 !== "function") throw new TypeError("callback must be a function");
this.#callback = callback$1;
this.#handler = handler;
this.#allowErrorStatusCodes = allowErrorStatusCodes;
}
onRequestStart(_, context) {
this.#successful = false;
this.#context = context;
}
onRequestUpgrade(controller, statusCode, headers, socket) {
this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
onResponseStart(controller, statusCode, headers, statusMessage) {
assert$12(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;
}
};
module.exports = CacheRevalidationHandler$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/cache.js
var require_cache$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/cache.js": ((exports, module) => {
const assert$11 = __require$2("node:assert");
const { Readable: Readable$1 } = __require$2("node:stream");
const util$8 = require_util$5();
const CacheHandler = require_cache_handler();
const MemoryCacheStore = require_memory_cache_store();
const CacheRevalidationHandler = require_cache_revalidation_handler();
const { assertCacheStore, assertCacheMethods, makeCacheKey: makeCacheKey$1, normalizeHeaders: normalizeHeaders$1, parseCacheControlHeader } = require_cache$2();
const { AbortError } = require_errors();
/**
* @param {(string | RegExp)[] | undefined} origins
* @param {string} name
*/
function assertCacheOrigins(origins, name) {
if (origins === void 0) return;
if (!Array.isArray(origins)) throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
for (let i$1 = 0; i$1 < origins.length; i$1++) {
const origin = origins[i$1];
if (typeof origin !== "string" && !(origin instanceof RegExp)) throw new TypeError(`expected ${name}[${i$1}] to be a string or RegExp, got ${typeof origin}`);
}
}
const nop = () => {};
/**
* @typedef {(options: import('../../types/dispatcher.d.ts').default.DispatchOptions, handler: import('../../types/dispatcher.d.ts').default.DispatchHandler) => void} DispatchFn
*/
/**
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives
* @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts
* @returns {boolean}
*/
function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
if (cacheControlDirectives?.["no-cache"]) return true;
if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) return true;
if (headers["if-modified-since"] || headers["if-none-match"]) return true;
return false;
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives
* @returns {boolean}
*/
function isStale(result, cacheControlDirectives) {
const now = Date.now();
if (now > result.staleAt) {
if (cacheControlDirectives?.["max-stale"]) return now > result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
return true;
}
if (cacheControlDirectives?.["min-fresh"]) return result.staleAt - now <= cacheControlDirectives["min-fresh"] * 1e3;
return false;
}
/**
* Check if we're within the stale-while-revalidate window for a stale response
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
* @returns {boolean}
*/
function withinStaleWhileRevalidateWindow(result) {
const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
if (!staleWhileRevalidate) return false;
return Date.now() <= result.staleAt + staleWhileRevalidate * 1e3;
}
/**
* @param {DispatchFn} dispatch
* @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
* @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl
*/
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, [], nop, "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));
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
* @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
* @param {number} age
* @param {any} context
* @param {boolean} isStale
*/
function sendCachedValue(handler, opts, result, age, context, isStale$1) {
const stream$2 = util$8.isStream(result.body) ? result.body : Readable$1.from(result.body ?? []);
assert$11(!stream$2.destroyed, "stream should not be destroyed");
assert$11(!stream$2.readableDidRead, "stream should not be readableDidRead");
const controller = {
resume() {
stream$2.resume();
},
pause() {
stream$2.pause();
},
get paused() {
return stream$2.isPaused();
},
get aborted() {
return stream$2.destroyed;
},
get reason() {
return stream$2.errored;
},
abort(reason) {
stream$2.destroy(reason ?? new AbortError());
}
};
stream$2.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, context);
if (stream$2.destroyed) return;
const headers = {
...result.headers,
age: String(age)
};
if (isStale$1) headers.warning = "110 - \"response is stale\"";
handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
if (opts.method === "HEAD") stream$2.destroy();
else stream$2.on("data", function(chunk) {
handler.onResponseData?.(controller, chunk);
});
}
/**
* @param {DispatchFn} dispatch
* @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} globalOpts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
* @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
* @param {import('../../types/dispatcher.d.ts').default.RequestOptions} opts
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} reqCacheControl
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined} result
*/
function handleResult$2(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);
const stale = isStale(result, reqCacheControl);
const revalidate = needsRevalidation(result, reqCacheControl, opts);
if (stale || revalidate) {
if (util$8.isStream(opts.body) && util$8.bodyLength(opts.body) !== 0) return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
sendCachedValue(handler, opts, result, age, null, true);
queueMicrotask(() => {
const headers$1 = {
...opts.headers,
"if-modified-since": new Date(result.cachedAt).toUTCString()
};
if (result.etag) headers$1["if-none-match"] = result.etag;
if (result.vary) {
for (const key in result.vary) if (result.vary[key] != null) headers$1[key] = result.vary[key];
}
dispatch({
...opts,
headers: headers$1
}, new CacheHandler(globalOpts, cacheKey, {
onRequestStart() {},
onRequestUpgrade() {},
onResponseStart() {},
onResponseData() {},
onResponseEnd() {},
onResponseError() {}
}));
});
return true;
}
let withinStaleIfErrorThreshold = false;
const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
if (staleIfErrorExpiry) withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
const headers = {
...opts.headers,
"if-modified-since": new Date(result.cachedAt).toUTCString()
};
if (result.etag) headers["if-none-match"] = result.etag;
if (result.vary) {
for (const key in result.vary) if (result.vary[key] != null) headers[key] = result.vary[key];
}
return dispatch({
...opts,
headers
}, new CacheRevalidationHandler((success, context) => {
if (success) sendCachedValue(handler, opts, result, age, context, stale);
else if (util$8.isStream(result.body)) result.body.on("error", nop).destroy();
}, new CacheHandler(globalOpts, cacheKey, handler), withinStaleIfErrorThreshold));
}
if (util$8.isStream(opts.body)) opts.body.on("error", nop).destroy();
sendCachedValue(handler, opts, result, age, null, false);
}
/**
* @param {import('../../types/cache-interceptor.d.ts').default.CacheOptions} [opts]
* @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor}
*/
module.exports = (opts = {}) => {
const { store = new MemoryCacheStore(), methods = ["GET"], cacheByDefault = void 0, type = "shared", origins = void 0 } = 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");
assertCacheOrigins(origins, "opts.origins");
if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
if (typeof type !== "undefined" && type !== "shared" && type !== "private") throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`);
const globalOpts = {
store,
methods,
cacheByDefault,
type
};
const safeMethodsToNotCache = util$8.safeHTTPMethods.filter((method) => methods.includes(method) === false);
return (dispatch) => {
return (opts$1, handler) => {
if (!opts$1.origin || safeMethodsToNotCache.includes(opts$1.method)) return dispatch(opts$1, handler);
if (origins !== void 0) {
const requestOrigin = opts$1.origin.toString().toLowerCase();
let isAllowed = false;
for (let i$1 = 0; i$1 < origins.length; i$1++) {
const allowed = origins[i$1];
if (typeof allowed === "string") {
if (allowed.toLowerCase() === requestOrigin) {
isAllowed = true;
break;
}
} else if (allowed.test(requestOrigin)) {
isAllowed = true;
break;
}
}
if (!isAllowed) return dispatch(opts$1, handler);
}
opts$1 = {
...opts$1,
headers: normalizeHeaders$1(opts$1)
};
const reqCacheControl = opts$1.headers?.["cache-control"] ? parseCacheControlHeader(opts$1.headers["cache-control"]) : void 0;
if (reqCacheControl?.["no-store"]) return dispatch(opts$1, handler);
/**
* @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
*/
const cacheKey = makeCacheKey$1(opts$1);
const result = store.get(cacheKey);
if (result && typeof result.then === "function") return result.then((result$1) => handleResult$2(dispatch, globalOpts, cacheKey, handler, opts$1, reqCacheControl, result$1));
else return handleResult$2(dispatch, globalOpts, cacheKey, handler, opts$1, reqCacheControl, result);
};
};
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/decompress.js
var require_decompress = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/decompress.js": ((exports, module) => {
const { createInflate: createInflate$1, createGunzip, createBrotliDecompress, createZstdDecompress } = __require$2("node:zlib");
const { pipeline: pipeline$2 } = __require$2("node:stream");
const DecoratorHandler$1 = require_decorator_handler();
const { runtimeFeatures: runtimeFeatures$4 } = require_runtime_features();
/** @typedef {import('node:stream').Transform} Transform */
/** @typedef {import('node:stream').Transform} Controller */
/** @typedef {Transform&import('node:zlib').Zlib} DecompressorStream */
/** @type {Record<string, () => DecompressorStream>} */
const supportedEncodings = {
gzip: createGunzip,
"x-gzip": createGunzip,
br: createBrotliDecompress,
deflate: createInflate$1,
compress: createInflate$1,
"x-compress": createInflate$1,
...runtimeFeatures$4.has("zstd") ? { zstd: createZstdDecompress } : {}
};
const defaultSkipStatusCodes = [204, 304];
let warningEmitted$1 = false;
/**
* @typedef {Object} DecompressHandlerOptions
* @property {number[]|Readonly<number[]>} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for
* @property {boolean} [skipErrorResponses] - Whether to skip decompression for error responses (status codes >= 400)
*/
var DecompressHandler = class extends DecoratorHandler$1 {
/** @type {Transform[]} */
#decompressors = [];
/** @type {Readonly<number[]>} */
#skipStatusCodes;
/** @type {boolean} */
#skipErrorResponses;
constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
super(handler);
this.#skipStatusCodes = skipStatusCodes;
this.#skipErrorResponses = skipErrorResponses;
}
/**
* Determines if decompression should be skipped based on encoding and status code
* @param {string} contentEncoding - Content-Encoding header value
* @param {number} statusCode - HTTP status code of the response
* @returns {boolean} - True if decompression should be skipped
*/
#shouldSkipDecompression(contentEncoding, statusCode) {
if (!contentEncoding || statusCode < 200) return true;
if (this.#skipStatusCodes.includes(statusCode)) return true;
if (this.#skipErrorResponses && statusCode >= 400) return true;
return false;
}
/**
* Creates a chain of decompressors for multiple content encodings
*
* @param {string} encodings - Comma-separated list of content encodings
* @returns {Array<DecompressorStream>} - Array of decompressor streams
* @throws {Error} - If the number of content-encodings exceeds the maximum allowed
*/
#createDecompressionChain(encodings) {
const parts = encodings.split(",");
const maxContentEncodings = 5;
if (parts.length > maxContentEncodings) throw new Error(`too many content-encodings in response: ${parts.length}, maximum allowed is ${maxContentEncodings}`);
/** @type {DecompressorStream[]} */
const decompressors = [];
for (let i$1 = parts.length - 1; i$1 >= 0; i$1--) {
const encoding = parts[i$1].trim();
if (!encoding) continue;
if (!supportedEncodings[encoding]) {
decompressors.length = 0;
return decompressors;
}
decompressors.push(supportedEncodings[encoding]());
}
return decompressors;
}
/**
* Sets up event handlers for a decompressor stream using readable events
* @param {DecompressorStream} decompressor - The decompressor stream
* @param {Controller} controller - The controller to coordinate with
* @returns {void}
*/
#setupDecompressorEvents(decompressor, controller) {
decompressor.on("readable", () => {
let chunk;
while ((chunk = decompressor.read()) !== null) if (super.onResponseData(controller, chunk) === false) break;
});
decompressor.on("error", (error) => {
super.onResponseError(controller, error);
});
}
/**
* Sets up event handling for a single decompressor
* @param {Controller} controller - The controller to handle events
* @returns {void}
*/
#setupSingleDecompressor(controller) {
const decompressor = this.#decompressors[0];
this.#setupDecompressorEvents(decompressor, controller);
decompressor.on("end", () => {
super.onResponseEnd(controller, {});
});
}
/**
* Sets up event handling for multiple chained decompressors using pipeline
* @param {Controller} controller - The controller to handle events
* @returns {void}
*/
#setupMultipleDecompressors(controller) {
const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
this.#setupDecompressorEvents(lastDecompressor, controller);
pipeline$2(this.#decompressors, (err) => {
if (err) {
super.onResponseError(controller, err);
return;
}
super.onResponseEnd(controller, {});
});
}
/**
* Cleans up decompressor references to prevent memory leaks
* @returns {void}
*/
#cleanupDecompressors() {
this.#decompressors.length = 0;
}
/**
* @param {Controller} controller
* @param {number} statusCode
* @param {Record<string, string | string[] | undefined>} headers
* @param {string} statusMessage
* @returns {void}
*/
onResponseStart(controller, statusCode, headers, statusMessage) {
const contentEncoding = headers["content-encoding"];
if (this.#shouldSkipDecompression(contentEncoding, statusCode)) return super.onResponseStart(controller, statusCode, headers, statusMessage);
const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase());
if (decompressors.length === 0) {
this.#cleanupDecompressors();
return super.onResponseStart(controller, statusCode, headers, statusMessage);
}
this.#decompressors = decompressors;
const { "content-encoding": _, "content-length": __,...newHeaders } = headers;
if (this.#decompressors.length === 1) this.#setupSingleDecompressor(controller);
else this.#setupMultipleDecompressors(controller);
return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
}
/**
* @param {Controller} controller
* @param {Buffer} chunk
* @returns {void}
*/
onResponseData(controller, chunk) {
if (this.#decompressors.length > 0) {
this.#decompressors[0].write(chunk);
return;
}
super.onResponseData(controller, chunk);
}
/**
* @param {Controller} controller
* @param {Record<string, string | string[]> | undefined} trailers
* @returns {void}
*/
onResponseEnd(controller, trailers) {
if (this.#decompressors.length > 0) {
this.#decompressors[0].end();
this.#cleanupDecompressors();
return;
}
super.onResponseEnd(controller, trailers);
}
/**
* @param {Controller} controller
* @param {Error} err
* @returns {void}
*/
onResponseError(controller, err) {
if (this.#decompressors.length > 0) {
for (const decompressor of this.#decompressors) decompressor.destroy(err);
this.#cleanupDecompressors();
}
super.onResponseError(controller, err);
}
};
/**
* Creates a decompression interceptor for HTTP responses
* @param {DecompressHandlerOptions} [options] - Options for the interceptor
* @returns {Function} - Interceptor function
*/
function createDecompressInterceptor(options = {}) {
if (!warningEmitted$1) {
process.emitWarning("DecompressInterceptor is experimental and subject to change", "ExperimentalWarning");
warningEmitted$1 = true;
}
return (dispatch) => {
return (opts, handler) => {
return dispatch(opts, new DecompressHandler(handler, options));
};
};
}
module.exports = createDecompressInterceptor;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/deduplication-handler.js
var require_deduplication_handler = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/handler/deduplication-handler.js": ((exports, module) => {
const { RequestAbortedError } = require_errors();
/**
* @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler
*/
const DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
/**
* @typedef {Object} WaitingHandler
* @property {DispatchHandler} handler
* @property {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @property {Buffer[]} bufferedChunks
* @property {number} bufferedBytes
* @property {object | null} pendingTrailers
* @property {boolean} done
*/
/**
* Handler that forwards response events to multiple waiting handlers.
* Used for request deduplication.
*
* @implements {DispatchHandler}
*/
var DeduplicationHandler$1 = class {
/**
* @type {DispatchHandler}
*/
#primaryHandler;
/**
* @type {WaitingHandler[]}
*/
#waitingHandlers = [];
/**
* @type {number}
*/
#maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
/**
* @type {number}
*/
#statusCode = 0;
/**
* @type {Record<string, string | string[]>}
*/
#headers = {};
/**
* @type {string}
*/
#statusMessage = "";
/**
* @type {boolean}
*/
#aborted = false;
/**
* @type {boolean}
*/
#responseStarted = false;
/**
* @type {boolean}
*/
#responseDataStarted = false;
/**
* @type {boolean}
*/
#completed = false;
/**
* @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
*/
#controller = null;
/**
* @type {(() => void) | null}
*/
#onComplete = null;
/**
* @param {DispatchHandler} primaryHandler The primary handler
* @param {() => void} onComplete Callback when request completes
* @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
*/
constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
this.#primaryHandler = primaryHandler;
this.#onComplete = onComplete;
this.#maxBufferSize = maxBufferSize;
}
/**
* Add a waiting handler that will receive response events.
* Returns false if deduplication can no longer safely attach this handler.
*
* @param {DispatchHandler} handler
* @returns {boolean}
*/
addWaitingHandler(handler) {
if (this.#completed || this.#responseDataStarted) return false;
const waitingHandler = this.#createWaitingHandler(handler);
const waitingController = waitingHandler.controller;
try {
handler.onRequestStart?.(waitingController, null);
if (waitingController.aborted) {
waitingHandler.done = true;
return true;
}
if (this.#responseStarted) handler.onResponseStart?.(waitingController, this.#statusCode, this.#headers, this.#statusMessage);
} catch {
waitingHandler.done = true;
return true;
}
if (!waitingController.aborted) this.#waitingHandlers.push(waitingHandler);
return true;
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {any} context
*/
onRequestStart(controller, context) {
this.#controller = controller;
this.#primaryHandler.onRequestStart?.(controller, context);
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers
* @param {Socket} socket
*/
onRequestUpgrade(controller, statusCode, headers, socket) {
this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket);
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {number} statusCode
* @param {Record<string, string | string[]>} headers
* @param {string} statusMessage
*/
onResponseStart(controller, statusCode, headers, statusMessage) {
this.#responseStarted = true;
this.#statusCode = statusCode;
this.#headers = headers;
this.#statusMessage = statusMessage;
this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
for (const waitingHandler of this.#waitingHandlers) {
const { handler, controller: waitingController } = waitingHandler;
if (waitingHandler.done || waitingController.aborted) {
waitingHandler.done = true;
continue;
}
try {
handler.onResponseStart?.(waitingController, statusCode, headers, statusMessage);
} catch {}
if (waitingController.aborted) waitingHandler.done = true;
}
this.#pruneDoneWaitingHandlers();
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {Buffer} chunk
*/
onResponseData(controller, chunk) {
if (this.#aborted || this.#completed) return;
this.#responseDataStarted = true;
this.#primaryHandler.onResponseData?.(controller, chunk);
for (const waitingHandler of this.#waitingHandlers) {
const { handler, controller: waitingController } = waitingHandler;
if (waitingHandler.done || waitingController.aborted) {
waitingHandler.done = true;
continue;
}
if (waitingController.paused) {
this.#bufferWaitingChunk(waitingHandler, chunk);
continue;
}
try {
handler.onResponseData?.(waitingController, chunk);
} catch {}
if (waitingController.aborted) {
waitingHandler.done = true;
waitingHandler.bufferedChunks = [];
waitingHandler.bufferedBytes = 0;
}
}
this.#pruneDoneWaitingHandlers();
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {object} trailers
*/
onResponseEnd(controller, trailers) {
if (this.#aborted || this.#completed) return;
this.#completed = true;
this.#primaryHandler.onResponseEnd?.(controller, trailers);
for (const waitingHandler of this.#waitingHandlers) {
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true;
continue;
}
this.#flushWaitingHandler(waitingHandler);
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true;
continue;
}
if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
waitingHandler.pendingTrailers = trailers;
continue;
}
try {
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
} catch {}
waitingHandler.done = true;
}
this.#pruneDoneWaitingHandlers();
this.#onComplete?.();
}
/**
* @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
* @param {Error} err
*/
onResponseError(controller, err) {
if (this.#completed) return;
this.#aborted = true;
this.#completed = true;
this.#primaryHandler.onResponseError?.(controller, err);
for (const waitingHandler of this.#waitingHandlers) this.#errorWaitingHandler(waitingHandler, err);
this.#waitingHandlers = [];
this.#onComplete?.();
}
/**
* @param {DispatchHandler} handler
* @returns {WaitingHandler}
*/
#createWaitingHandler(handler) {
/** @type {WaitingHandler} */
const waitingHandler = {
handler,
controller: null,
bufferedChunks: [],
bufferedBytes: 0,
pendingTrailers: null,
done: false
};
const state = {
aborted: false,
paused: false,
reason: null
};
waitingHandler.controller = {
resume: () => {
if (state.aborted) return;
state.paused = false;
this.#flushWaitingHandler(waitingHandler);
if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
try {
waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
} catch {}
waitingHandler.pendingTrailers = null;
waitingHandler.done = true;
}
this.#pruneDoneWaitingHandlers();
},
pause: () => {
if (!state.aborted) state.paused = true;
},
get paused() {
return state.paused;
},
get aborted() {
return state.aborted;
},
get reason() {
return state.reason;
},
abort: (reason) => {
state.aborted = true;
state.reason = reason ?? null;
waitingHandler.done = true;
waitingHandler.pendingTrailers = null;
waitingHandler.bufferedChunks = [];
waitingHandler.bufferedBytes = 0;
}
};
return waitingHandler;
}
/**
* @param {WaitingHandler} waitingHandler
* @param {Buffer} chunk
*/
#bufferWaitingChunk(waitingHandler, chunk) {
if (waitingHandler.done || waitingHandler.controller.aborted) {
waitingHandler.done = true;
waitingHandler.bufferedChunks = [];
waitingHandler.bufferedBytes = 0;
return;
}
const bufferedChunk = Buffer.from(chunk);
waitingHandler.bufferedChunks.push(bufferedChunk);
waitingHandler.bufferedBytes += bufferedChunk.length;
if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
this.#errorWaitingHandler(waitingHandler, err);
}
}
/**
* @param {WaitingHandler} waitingHandler
*/
#flushWaitingHandler(waitingHandler) {
const { handler, controller } = waitingHandler;
while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
const bufferedChunk = waitingHandler.bufferedChunks.shift();
waitingHandler.bufferedBytes -= bufferedChunk.length;
try {
handler.onResponseData?.(controller, bufferedChunk);
} catch {}
if (controller.aborted) {
waitingHandler.done = true;
waitingHandler.pendingTrailers = null;
waitingHandler.bufferedChunks = [];
waitingHandler.bufferedBytes = 0;
break;
}
}
}
/**
* @param {WaitingHandler} waitingHandler
* @param {Error} err
*/
#errorWaitingHandler(waitingHandler, err) {
if (waitingHandler.done) return;
waitingHandler.done = true;
waitingHandler.pendingTrailers = null;
waitingHandler.bufferedChunks = [];
waitingHandler.bufferedBytes = 0;
try {
waitingHandler.controller.abort(err);
waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
} catch {}
}
#pruneDoneWaitingHandlers() {
this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
}
};
module.exports = DeduplicationHandler$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/deduplicate.js
var require_deduplicate = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/interceptor/deduplicate.js": ((exports, module) => {
const diagnosticsChannel = __require$2("node:diagnostics_channel");
const util$7 = require_util$5();
const DeduplicationHandler = require_deduplication_handler();
const { normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require_cache$2();
const pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests");
/**
* @param {import('../../types/interceptors.d.ts').default.DeduplicateInterceptorOpts} [opts]
* @returns {import('../../types/dispatcher.d.ts').default.DispatcherComposeInterceptor}
*/
module.exports = (opts = {}) => {
const { methods = ["GET"], skipHeaderNames = [], excludeHeaderNames = [], maxBufferSize = 5 * 1024 * 1024 } = opts;
if (typeof opts !== "object" || opts === null) throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
if (!Array.isArray(methods)) throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`);
for (const method of methods) if (!util$7.safeHTTPMethods.includes(method)) throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`);
if (!Array.isArray(skipHeaderNames)) throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);
if (!Array.isArray(excludeHeaderNames)) throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
/**
* Map of pending requests for deduplication
* @type {Map<string, DeduplicationHandler>}
*/
const pendingRequests = /* @__PURE__ */ new Map();
return (dispatch) => {
return (opts$1, handler) => {
if (!opts$1.origin || methods.includes(opts$1.method) === false) return dispatch(opts$1, handler);
opts$1 = {
...opts$1,
headers: normalizeHeaders(opts$1)
};
if (skipHeaderNamesSet.size > 0) {
for (const headerName of Object.keys(opts$1.headers)) if (skipHeaderNamesSet.has(headerName.toLowerCase())) return dispatch(opts$1, handler);
}
const dedupeKey = makeDeduplicationKey(makeCacheKey(opts$1), excludeHeaderNamesSet);
const pendingHandler = pendingRequests.get(dedupeKey);
if (pendingHandler) {
if (pendingHandler.addWaitingHandler(handler)) return true;
return dispatch(opts$1, handler);
}
const deduplicationHandler = new DeduplicationHandler(handler, () => {
pendingRequests.delete(dedupeKey);
if (pendingRequestsChannel.hasSubscribers) pendingRequestsChannel.publish({
size: pendingRequests.size,
key: dedupeKey,
type: "removed"
});
}, maxBufferSize);
pendingRequests.set(dedupeKey, deduplicationHandler);
if (pendingRequestsChannel.hasSubscribers) pendingRequestsChannel.publish({
size: pendingRequests.size,
key: dedupeKey,
type: "added"
});
return dispatch(opts$1, deduplicationHandler);
};
};
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/cache/sqlite-cache-store.js
var require_sqlite_cache_store = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/cache/sqlite-cache-store.js": ((exports, module) => {
const { Writable: Writable$1 } = __require$2("node:stream");
const { assertCacheKey, assertCacheValue } = require_cache$2();
let DatabaseSync;
const VERSION = 3;
const MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
/**
* @typedef {import('../../types/cache-interceptor.d.ts').default.CacheStore} CacheStore
* @implements {CacheStore}
*
* @typedef {{
* id: Readonly<number>,
* body?: Uint8Array
* statusCode: number
* statusMessage: string
* headers?: string
* vary?: string
* etag?: string
* cacheControlDirectives?: string
* cachedAt: number
* staleAt: number
* deleteAt: number
* }} SqliteStoreValue
*/
module.exports = class SqliteCacheStore$1 {
#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$2("node: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 url = 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(url, 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;
/**
* @type {Buffer[] | null}
*/
const body = [];
const store = this;
return new Writable$1({
decodeStrings: true,
write(chunk, encoding, callback$1) {
size += chunk.byteLength;
if (size < store.#maxEntrySize) body.push(chunk);
else this.destroy();
callback$1();
},
final(callback$1) {
store.set(key, {
...value,
body
});
callback$1();
}
});
}
/**
* @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 * .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 url = this.#makeValueUrl(key);
const { headers, method } = key;
/**
* @type {SqliteStoreValue[]}
*/
const values = this.#getValuesQuery.all(url, method);
if (values.length === 0) return;
const now = Date.now();
for (const value of values) {
if (now >= value.deleteAt && !canBeExpired) return;
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;
}
}
};
/**
* @param {string|string[]|null|undefined} lhs
* @param {string|string[]|null|undefined} rhs
* @returns {boolean}
*/
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((x, i$1) => x === rhs[i$1]);
}
return lhs === rhs;
}
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/headers.js
var require_headers = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/headers.js": ((exports, module) => {
const { kConstruct: kConstruct$7 } = require_symbols();
const { kEnumerableProperty: kEnumerableProperty$9 } = require_util$5();
const { iteratorMixin, isValidHeaderName: isValidHeaderName$1, isValidHeaderValue } = require_util$4();
const { webidl: webidl$11 } = require_webidl();
const assert$10 = __require$2("node:assert");
const util$6 = __require$2("node:util");
/**
* @param {number} code
* @returns {code is (0x0a | 0x0d | 0x09 | 0x20)}
*/
function isHTTPWhiteSpaceCharCode(code) {
return code === 10 || code === 13 || code === 9 || code === 32;
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
* @param {string} potentialValue
* @returns {string}
*/
function headerValueNormalize(potentialValue) {
let i$1 = 0;
let j = potentialValue.length;
while (j > i$1 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j;
while (j > i$1 && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i$1))) ++i$1;
return i$1 === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i$1, j);
}
/**
* @param {Headers} headers
* @param {Array|Object} object
*/
function fill$1(headers, object) {
if (Array.isArray(object)) for (let i$1 = 0; i$1 < object.length; ++i$1) {
const header = object[i$1];
if (header.length !== 2) throw webidl$11.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 i$1 = 0; i$1 < keys.length; ++i$1) appendHeader(headers, keys[i$1], object[keys[i$1]]);
} else throw webidl$11.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
}
/**
* @see https://fetch.spec.whatwg.org/#concept-headers-append
* @param {Headers} headers
* @param {string} name
* @param {string} value
*/
function appendHeader(headers, name, value) {
value = headerValueNormalize(value);
if (!isValidHeaderName$1(name)) throw webidl$11.errors.invalidArgument({
prefix: "Headers.append",
value: name,
type: "header name"
});
else if (!isValidHeaderValue(value)) throw webidl$11.errors.invalidArgument({
prefix: "Headers.append",
value,
type: "header value"
});
if (getHeadersGuard$2(headers) === "immutable") throw new TypeError("immutable");
return getHeadersList$2(headers).append(name, value, false);
}
/**
* @param {Headers} target
*/
function headersListSortAndCombine(target$1) {
const headersList = getHeadersList$2(target$1);
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 i$1 = 0; i$1 < names.length; ++i$1) {
const { 0: name, 1: value } = names[i$1];
if (name === "set-cookie") for (let j = 0; j < cookies.length; ++j) headers.push([name, cookies[j]]);
else headers.push([name, value]);
}
return headersList.sortedMap = headers;
}
function compareHeaderName(a, b) {
return a[0] < b[0] ? -1 : 1;
}
var HeadersList$3 = class HeadersList$3 {
/** @type {[string, string][]|null} */
cookies = null;
sortedMap;
headersMap;
constructor(init) {
if (init instanceof HeadersList$3) {
this.headersMap = new Map(init.headersMap);
this.sortedMap = init.sortedMap;
this.cookies = init.cookies === null ? null : [...init.cookies];
} else {
this.headersMap = new Map(init);
this.sortedMap = null;
}
}
/**
* @see https://fetch.spec.whatwg.org/#header-list-contains
* @param {string} name
* @param {boolean} isLowerCase
*/
contains(name, isLowerCase) {
return this.headersMap.has(isLowerCase ? name : name.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(name, value, isLowerCase) {
this.sortedMap = null;
const lowercaseName = isLowerCase ? name : name.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,
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(name, value, isLowerCase) {
this.sortedMap = null;
const lowercaseName = isLowerCase ? name : name.toLowerCase();
if (lowercaseName === "set-cookie") this.cookies = [value];
this.headersMap.set(lowercaseName, {
name,
value
});
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-delete
* @param {string} name
* @param {boolean} isLowerCase
*/
delete(name, isLowerCase) {
this.sortedMap = null;
if (!isLowerCase) name = name.toLowerCase();
if (name === "set-cookie") this.cookies = null;
this.headersMap.delete(name);
}
/**
* @see https://fetch.spec.whatwg.org/#concept-header-list-get
* @param {string} name
* @param {boolean} isLowerCase
* @returns {string | null}
*/
get(name, isLowerCase) {
return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null;
}
*[Symbol.iterator]() {
for (const { 0: name, 1: { value } } of this.headersMap) yield [name, value];
}
get entries() {
const headers = {};
if (this.headersMap.size !== 0) for (const { name, value } of this.headersMap.values()) headers[name] = value;
return headers;
}
rawValues() {
return this.headersMap.values();
}
get entriesList() {
const headers = [];
if (this.headersMap.size !== 0) for (const { 0: lowerName, 1: { name, value } } of this.headersMap) if (lowerName === "set-cookie") for (const cookie of this.cookies) headers.push([name, cookie]);
else headers.push([name, value]);
return headers;
}
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];
assert$10(firstValue[1].value !== null);
for (let i$1 = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i$1 < size; ++i$1) {
value = iterator.next().value;
x = array[i$1] = [value[0], value[1].value];
assert$10(x[1] !== null);
left = 0;
right = i$1;
while (left < right) {
pivot = left + (right - left >> 1);
if (array[pivot][0] <= x[0]) left = pivot + 1;
else right = pivot;
}
if (i$1 !== pivot) {
j = i$1;
while (j > left) array[j] = array[--j];
array[left] = x;
}
}
/* c8 ignore next 4 */
if (!iterator.next().done) throw new TypeError("Unreachable");
return array;
} else {
let i$1 = 0;
for (const { 0: name, 1: { value } } of this.headersMap) {
array[i$1++] = [name, value];
assert$10(value !== null);
}
return array.sort(compareHeaderName);
}
}
};
var Headers$5 = class Headers$5 {
#guard;
/**
* @type {HeadersList}
*/
#headersList;
/**
* @param {HeadersInit|Symbol} [init]
* @returns
*/
constructor(init = void 0) {
webidl$11.util.markAsUncloneable(this);
if (init === kConstruct$7) return;
this.#headersList = new HeadersList$3();
this.#guard = "none";
if (init !== void 0) {
init = webidl$11.converters.HeadersInit(init, "Headers constructor", "init");
fill$1(this, init);
}
}
append(name, value) {
webidl$11.brandCheck(this, Headers$5);
webidl$11.argumentLengthCheck(arguments, 2, "Headers.append");
const prefix = "Headers.append";
name = webidl$11.converters.ByteString(name, prefix, "name");
value = webidl$11.converters.ByteString(value, prefix, "value");
return appendHeader(this, name, value);
}
delete(name) {
webidl$11.brandCheck(this, Headers$5);
webidl$11.argumentLengthCheck(arguments, 1, "Headers.delete");
name = webidl$11.converters.ByteString(name, "Headers.delete", "name");
if (!isValidHeaderName$1(name)) throw webidl$11.errors.invalidArgument({
prefix: "Headers.delete",
value: name,
type: "header name"
});
if (this.#guard === "immutable") throw new TypeError("immutable");
if (!this.#headersList.contains(name, false)) return;
this.#headersList.delete(name, false);
}
get(name) {
webidl$11.brandCheck(this, Headers$5);
webidl$11.argumentLengthCheck(arguments, 1, "Headers.get");
const prefix = "Headers.get";
name = webidl$11.converters.ByteString(name, prefix, "name");
if (!isValidHeaderName$1(name)) throw webidl$11.errors.invalidArgument({
prefix,
value: name,
type: "header name"
});
return this.#headersList.get(name, false);
}
has(name) {
webidl$11.brandCheck(this, Headers$5);
webidl$11.argumentLengthCheck(arguments, 1, "Headers.has");
const prefix = "Headers.has";
name = webidl$11.converters.ByteString(name, prefix, "name");
if (!isValidHeaderName$1(name)) throw webidl$11.errors.invalidArgument({
prefix,
value: name,
type: "header name"
});
return this.#headersList.contains(name, false);
}
set(name, value) {
webidl$11.brandCheck(this, Headers$5);
webidl$11.argumentLengthCheck(arguments, 2, "Headers.set");
const prefix = "Headers.set";
name = webidl$11.converters.ByteString(name, prefix, "name");
value = webidl$11.converters.ByteString(value, prefix, "value");
value = headerValueNormalize(value);
if (!isValidHeaderName$1(name)) throw webidl$11.errors.invalidArgument({
prefix,
value: name,
type: "header name"
});
else if (!isValidHeaderValue(value)) throw webidl$11.errors.invalidArgument({
prefix,
value,
type: "header value"
});
if (this.#guard === "immutable") throw new TypeError("immutable");
this.#headersList.set(name, value, false);
}
getSetCookie() {
webidl$11.brandCheck(this, Headers$5);
const list$1 = this.#headersList.cookies;
if (list$1) return [...list$1];
return [];
}
[util$6.inspect.custom](depth$1, options) {
options.depth ??= depth$1;
return `Headers ${util$6.formatWithOptions(options, this.#headersList.entries)}`;
}
static getHeadersGuard(o) {
return o.#guard;
}
static setHeadersGuard(o, guard) {
o.#guard = guard;
}
/**
* @param {Headers} o
*/
static getHeadersList(o) {
return o.#headersList;
}
/**
* @param {Headers} target
* @param {HeadersList} list
*/
static setHeadersList(target$1, list$1) {
target$1.#headersList = list$1;
}
};
const { getHeadersGuard: getHeadersGuard$2, setHeadersGuard: setHeadersGuard$2, getHeadersList: getHeadersList$2, setHeadersList: setHeadersList$2 } = Headers$5;
Reflect.deleteProperty(Headers$5, "getHeadersGuard");
Reflect.deleteProperty(Headers$5, "setHeadersGuard");
Reflect.deleteProperty(Headers$5, "getHeadersList");
Reflect.deleteProperty(Headers$5, "setHeadersList");
iteratorMixin("Headers", Headers$5, headersListSortAndCombine, 0, 1);
Object.defineProperties(Headers$5.prototype, {
append: kEnumerableProperty$9,
delete: kEnumerableProperty$9,
get: kEnumerableProperty$9,
has: kEnumerableProperty$9,
set: kEnumerableProperty$9,
getSetCookie: kEnumerableProperty$9,
[Symbol.toStringTag]: {
value: "Headers",
configurable: true
},
[util$6.inspect.custom]: { enumerable: false }
});
webidl$11.converters.HeadersInit = function(V, prefix, argument) {
if (webidl$11.util.Type(V) === webidl$11.util.Types.OBJECT) {
const iterator = Reflect.get(V, Symbol.iterator);
if (!util$6.types.isProxy(V) && iterator === Headers$5.prototype.entries) try {
return getHeadersList$2(V).entriesList;
} catch {}
if (typeof iterator === "function") return webidl$11.converters["sequence<sequence<ByteString>>"](V, prefix, argument, iterator.bind(V));
return webidl$11.converters["record<ByteString, ByteString>"](V, prefix, argument);
}
throw webidl$11.errors.conversionFailed({
prefix: "Headers constructor",
argument: "Argument 1",
types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
});
};
module.exports = {
fill: fill$1,
compareHeaderName,
Headers: Headers$5,
HeadersList: HeadersList$3,
getHeadersGuard: getHeadersGuard$2,
setHeadersGuard: setHeadersGuard$2,
setHeadersList: setHeadersList$2,
getHeadersList: getHeadersList$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/response.js
var require_response = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/response.js": ((exports, module) => {
const { Headers: Headers$4, HeadersList: HeadersList$2, fill, getHeadersGuard: getHeadersGuard$1, setHeadersGuard: setHeadersGuard$1, setHeadersList: setHeadersList$1 } = require_headers();
const { extractBody: extractBody$2, cloneBody: cloneBody$1, mixinBody: mixinBody$1, streamRegistry, bodyUnusable: bodyUnusable$1 } = require_body();
const util$5 = require_util$5();
const nodeUtil$1 = __require$2("node:util");
const { kEnumerableProperty: kEnumerableProperty$8 } = util$5;
const { isValidReasonPhrase, isCancelled: isCancelled$1, isAborted: isAborted$3, isErrorLike: isErrorLike$1, environmentSettingsObject: relevantRealm } = require_util$4();
const { redirectStatusSet: redirectStatusSet$1, nullBodyStatus: nullBodyStatus$1 } = require_constants$3();
const { webidl: webidl$10 } = require_webidl();
const { URLSerializer: URLSerializer$3 } = require_data_url();
const { kConstruct: kConstruct$6 } = require_symbols();
const assert$9 = __require$2("node:assert");
const { isomorphicEncode: isomorphicEncode$1, serializeJavascriptValueToJSONString } = require_infra();
const textEncoder = new TextEncoder("utf-8");
var Response$2 = class Response$2 {
/** @type {Headers} */
#headers;
#state;
static error() {
return fromInnerResponse$2(makeNetworkError$1(), "immutable");
}
static json(data$1, init = void 0) {
webidl$10.argumentLengthCheck(arguments, 1, "Response.json");
if (init !== null) init = webidl$10.converters.ResponseInit(init);
const body = extractBody$2(textEncoder.encode(serializeJavascriptValueToJSONString(data$1)));
const responseObject = fromInnerResponse$2(makeResponse$1({}), "response");
initializeResponse(responseObject, init, {
body: body[0],
type: "application/json"
});
return responseObject;
}
static redirect(url, status = 302) {
webidl$10.argumentLengthCheck(arguments, 1, "Response.redirect");
url = webidl$10.converters.USVString(url);
status = webidl$10.converters["unsigned short"](status);
let parsedURL;
try {
parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl);
} catch (err) {
throw new TypeError(`Failed to parse URL from ${url}`, { cause: err });
}
if (!redirectStatusSet$1.has(status)) throw new RangeError(`Invalid status code ${status}`);
const responseObject = fromInnerResponse$2(makeResponse$1({}), "immutable");
responseObject.#state.status = status;
const value = isomorphicEncode$1(URLSerializer$3(parsedURL));
responseObject.#state.headersList.append("location", value, true);
return responseObject;
}
constructor(body = null, init = void 0) {
webidl$10.util.markAsUncloneable(this);
if (body === kConstruct$6) return;
if (body !== null) body = webidl$10.converters.BodyInit(body, "Response", "body");
init = webidl$10.converters.ResponseInit(init);
this.#state = makeResponse$1({});
this.#headers = new Headers$4(kConstruct$6);
setHeadersGuard$1(this.#headers, "response");
setHeadersList$1(this.#headers, this.#state.headersList);
let bodyWithType = null;
if (body != null) {
const [extractedBody, type] = extractBody$2(body);
bodyWithType = {
body: extractedBody,
type
};
}
initializeResponse(this, init, bodyWithType);
}
get type() {
webidl$10.brandCheck(this, Response$2);
return this.#state.type;
}
get url() {
webidl$10.brandCheck(this, Response$2);
const urlList = this.#state.urlList;
const url = urlList[urlList.length - 1] ?? null;
if (url === null) return "";
return URLSerializer$3(url, true);
}
get redirected() {
webidl$10.brandCheck(this, Response$2);
return this.#state.urlList.length > 1;
}
get status() {
webidl$10.brandCheck(this, Response$2);
return this.#state.status;
}
get ok() {
webidl$10.brandCheck(this, Response$2);
return this.#state.status >= 200 && this.#state.status <= 299;
}
get statusText() {
webidl$10.brandCheck(this, Response$2);
return this.#state.statusText;
}
get headers() {
webidl$10.brandCheck(this, Response$2);
return this.#headers;
}
get body() {
webidl$10.brandCheck(this, Response$2);
return this.#state.body ? this.#state.body.stream : null;
}
get bodyUsed() {
webidl$10.brandCheck(this, Response$2);
return !!this.#state.body && util$5.isDisturbed(this.#state.body.stream);
}
clone() {
webidl$10.brandCheck(this, Response$2);
if (bodyUnusable$1(this.#state)) throw webidl$10.errors.exception({
header: "Response.clone",
message: "Body has already been consumed."
});
const clonedResponse = cloneResponse$1(this.#state);
if (this.#state.urlList.length !== 0 && this.#state.body?.stream) streamRegistry.register(this, new WeakRef(this.#state.body.stream));
return fromInnerResponse$2(clonedResponse, getHeadersGuard$1(this.#headers));
}
[nodeUtil$1.inspect.custom](depth$1, 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$1.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;
}
};
const { getResponseHeaders, setResponseHeaders, getResponseState: getResponseState$2, setResponseState } = Response$2;
Reflect.deleteProperty(Response$2, "getResponseHeaders");
Reflect.deleteProperty(Response$2, "setResponseHeaders");
Reflect.deleteProperty(Response$2, "getResponseState");
Reflect.deleteProperty(Response$2, "setResponseState");
mixinBody$1(Response$2, getResponseState$2);
Object.defineProperties(Response$2.prototype, {
type: kEnumerableProperty$8,
url: kEnumerableProperty$8,
status: kEnumerableProperty$8,
ok: kEnumerableProperty$8,
redirected: kEnumerableProperty$8,
statusText: kEnumerableProperty$8,
headers: kEnumerableProperty$8,
clone: kEnumerableProperty$8,
body: kEnumerableProperty$8,
bodyUsed: kEnumerableProperty$8,
[Symbol.toStringTag]: {
value: "Response",
configurable: true
}
});
Object.defineProperties(Response$2, {
json: kEnumerableProperty$8,
redirect: kEnumerableProperty$8,
error: kEnumerableProperty$8
});
function cloneResponse$1(response) {
if (response.internalResponse) return filterResponse$1(cloneResponse$1(response.internalResponse), response.type);
const newResponse = makeResponse$1({
...response,
body: null
});
if (response.body != null) newResponse.body = cloneBody$1(response.body);
return newResponse;
}
function makeResponse$1(init) {
return {
aborted: false,
rangeRequested: false,
timingAllowPassed: false,
requestIncludesCredentials: false,
type: "default",
status: 200,
timingInfo: null,
cacheState: "",
statusText: "",
...init,
headersList: init?.headersList ? new HeadersList$2(init?.headersList) : new HeadersList$2(),
urlList: init?.urlList ? [...init.urlList] : []
};
}
function makeNetworkError$1(reason) {
return makeResponse$1({
type: "error",
status: 0,
error: isErrorLike$1(reason) ? reason : new Error(reason ? String(reason) : reason),
aborted: reason && reason.name === "AbortError"
});
}
function isNetworkError$1(response) {
return response.type === "error" && response.status === 0;
}
function makeFilteredResponse(response, state) {
state = {
internalResponse: response,
...state
};
return new Proxy(response, {
get(target$1, p$1) {
return p$1 in state ? state[p$1] : target$1[p$1];
},
set(target$1, p$1, value) {
assert$9(!(p$1 in state));
target$1[p$1] = value;
return true;
}
});
}
function filterResponse$1(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: [],
status: 0,
statusText: "",
body: null
});
else if (type === "opaqueredirect") return makeFilteredResponse(response, {
type: "opaqueredirect",
status: 0,
statusText: "",
headersList: [],
body: null
});
else assert$9(false);
}
function makeAppropriateNetworkError$1(fetchParams, err = null) {
assert$9(isCancelled$1(fetchParams));
return isAborted$3(fetchParams) ? makeNetworkError$1(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err })) : makeNetworkError$1(Object.assign(new DOMException("Request was cancelled."), { cause: err }));
}
function initializeResponse(response, init, body) {
if (init.status !== null && (init.status < 200 || init.status > 599)) throw new RangeError("init[\"status\"] must be in the range of 200 to 599, inclusive.");
if ("statusText" in init && init.statusText != null) {
if (!isValidReasonPhrase(String(init.statusText))) throw new TypeError("Invalid statusText");
}
if ("status" in init && init.status != null) getResponseState$2(response).status = init.status;
if ("statusText" in init && init.statusText != null) getResponseState$2(response).statusText = init.statusText;
if ("headers" in init && init.headers != null) fill(getResponseHeaders(response), init.headers);
if (body) {
if (nullBodyStatus$1.includes(response.status)) throw webidl$10.errors.exception({
header: "Response constructor",
message: `Invalid response status code ${response.status}`
});
getResponseState$2(response).body = body.body;
if (body.type != null && !getResponseState$2(response).headersList.contains("content-type", true)) getResponseState$2(response).headersList.append("content-type", body.type, true);
}
}
/**
* @see https://fetch.spec.whatwg.org/#response-create
* @param {any} innerResponse
* @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
* @returns {Response}
*/
function fromInnerResponse$2(innerResponse, guard) {
const response = new Response$2(kConstruct$6);
setResponseState(response, innerResponse);
const headers = new Headers$4(kConstruct$6);
setResponseHeaders(response, headers);
setHeadersList$1(headers, innerResponse.headersList);
setHeadersGuard$1(headers, guard);
if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
return response;
}
webidl$10.converters.XMLHttpRequestBodyInit = function(V, prefix, name) {
if (typeof V === "string") return webidl$10.converters.USVString(V, prefix, name);
if (webidl$10.is.Blob(V)) return V;
if (webidl$10.is.BufferSource(V)) return V;
if (webidl$10.is.FormData(V)) return V;
if (webidl$10.is.URLSearchParams(V)) return V;
return webidl$10.converters.DOMString(V, prefix, name);
};
webidl$10.converters.BodyInit = function(V, prefix, argument) {
if (webidl$10.is.ReadableStream(V)) return V;
if (V?.[Symbol.asyncIterator]) return V;
return webidl$10.converters.XMLHttpRequestBodyInit(V, prefix, argument);
};
webidl$10.converters.ResponseInit = webidl$10.dictionaryConverter([
{
key: "status",
converter: webidl$10.converters["unsigned short"],
defaultValue: () => 200
},
{
key: "statusText",
converter: webidl$10.converters.ByteString,
defaultValue: () => ""
},
{
key: "headers",
converter: webidl$10.converters.HeadersInit
}
]);
webidl$10.is.Response = webidl$10.util.MakeTypeAssertion(Response$2);
module.exports = {
isNetworkError: isNetworkError$1,
makeNetworkError: makeNetworkError$1,
makeResponse: makeResponse$1,
makeAppropriateNetworkError: makeAppropriateNetworkError$1,
filterResponse: filterResponse$1,
Response: Response$2,
cloneResponse: cloneResponse$1,
fromInnerResponse: fromInnerResponse$2,
getResponseState: getResponseState$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/request.js
var require_request = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/request.js": ((exports, module) => {
const { extractBody: extractBody$1, mixinBody, cloneBody, bodyUnusable } = require_body();
const { Headers: Headers$3, fill: fillHeaders, HeadersList: HeadersList$1, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList: getHeadersList$1 } = require_headers();
const util$4 = require_util$5();
const nodeUtil = __require$2("node:util");
const { isValidHTTPToken, sameOrigin: sameOrigin$1, environmentSettingsObject: environmentSettingsObject$3 } = require_util$4();
const { forbiddenMethodsSet, corsSafeListedMethodsSet, referrerPolicy, requestRedirect, requestMode, requestCredentials, requestCache, requestDuplex } = require_constants$3();
const { kEnumerableProperty: kEnumerableProperty$7, normalizedMethodRecordsBase, normalizedMethodRecords } = util$4;
const { webidl: webidl$9 } = require_webidl();
const { URLSerializer: URLSerializer$2 } = require_data_url();
const { kConstruct: kConstruct$5 } = require_symbols();
const assert$8 = __require$2("node:assert");
const { getMaxListeners, setMaxListeners, defaultMaxListeners } = __require$2("node:events");
const kAbortController = Symbol("abortController");
const requestFinalizer = new FinalizationRegistry(({ signal, abort: abort$1 }) => {
signal.removeEventListener("abort", abort$1);
});
const dependentControllerMap = /* @__PURE__ */ new WeakMap();
let abortSignalHasEventHandlerLeakWarning;
try {
abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0;
} catch {
abortSignalHasEventHandlerLeakWarning = false;
}
function buildAbort(acRef) {
return abort$1;
function abort$1() {
const ac = acRef.deref();
if (ac !== void 0) {
requestFinalizer.unregister(abort$1);
this.removeEventListener("abort", abort$1);
ac.abort(this.reason);
const controllerList = dependentControllerMap.get(ac.signal);
if (controllerList !== void 0) {
if (controllerList.size !== 0) {
for (const ref$1 of controllerList) {
const ctrl = ref$1.deref();
if (ctrl !== void 0) ctrl.abort(this.reason);
}
controllerList.clear();
}
dependentControllerMap.delete(ac.signal);
}
}
}
}
let patchMethodWarning = false;
var Request$4 = class Request$4 {
/** @type {AbortSignal} */
#signal;
/** @type {import('../../dispatcher/dispatcher')} */
#dispatcher;
/** @type {Headers} */
#headers;
#state;
constructor(input, init = void 0) {
webidl$9.util.markAsUncloneable(this);
if (input === kConstruct$5) return;
webidl$9.argumentLengthCheck(arguments, 1, "Request constructor");
input = webidl$9.converters.RequestInfo(input);
init = webidl$9.converters.RequestInit(init);
let request$2 = null;
let fallbackMode = null;
const baseUrl = environmentSettingsObject$3.settingsObject.baseUrl;
let signal = null;
if (typeof input === "string") {
this.#dispatcher = init.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);
request$2 = makeRequest$2({ urlList: [parsedURL] });
fallbackMode = "cors";
} else {
assert$8(webidl$9.is.Request(input));
request$2 = input.#state;
signal = input.#signal;
this.#dispatcher = init.dispatcher || input.#dispatcher;
}
const origin = environmentSettingsObject$3.settingsObject.origin;
let window = "client";
if (request$2.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin$1(request$2.window, origin)) window = request$2.window;
if (init.window != null) throw new TypeError(`'window' option '${window}' must be null`);
if ("window" in init) window = "no-window";
request$2 = makeRequest$2({
method: request$2.method,
headersList: request$2.headersList,
unsafeRequest: request$2.unsafeRequest,
client: environmentSettingsObject$3.settingsObject,
window,
priority: request$2.priority,
origin: request$2.origin,
referrer: request$2.referrer,
referrerPolicy: request$2.referrerPolicy,
mode: request$2.mode,
credentials: request$2.credentials,
cache: request$2.cache,
redirect: request$2.redirect,
integrity: request$2.integrity,
keepalive: request$2.keepalive,
reloadNavigation: request$2.reloadNavigation,
historyNavigation: request$2.historyNavigation,
urlList: [...request$2.urlList]
});
const initHasKey = Object.keys(init).length !== 0;
if (initHasKey) {
if (request$2.mode === "navigate") request$2.mode = "same-origin";
request$2.reloadNavigation = false;
request$2.historyNavigation = false;
request$2.origin = "client";
request$2.referrer = "client";
request$2.referrerPolicy = "";
request$2.url = request$2.urlList[request$2.urlList.length - 1];
request$2.urlList = [request$2.url];
}
if (init.referrer !== void 0) {
const referrer = init.referrer;
if (referrer === "") request$2.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$1(parsedReferrer, environmentSettingsObject$3.settingsObject.baseUrl)) request$2.referrer = "client";
else request$2.referrer = parsedReferrer;
}
}
if (init.referrerPolicy !== void 0) request$2.referrerPolicy = init.referrerPolicy;
let mode;
if (init.mode !== void 0) mode = init.mode;
else mode = fallbackMode;
if (mode === "navigate") throw webidl$9.errors.exception({
header: "Request constructor",
message: "invalid request mode navigate."
});
if (mode != null) request$2.mode = mode;
if (init.credentials !== void 0) request$2.credentials = init.credentials;
if (init.cache !== void 0) request$2.cache = init.cache;
if (request$2.cache === "only-if-cached" && request$2.mode !== "same-origin") throw new TypeError("'only-if-cached' can be set only with 'same-origin' mode");
if (init.redirect !== void 0) request$2.redirect = init.redirect;
if (init.integrity != null) request$2.integrity = String(init.integrity);
if (init.keepalive !== void 0) request$2.keepalive = Boolean(init.keepalive);
if (init.method !== void 0) {
let method = init.method;
const mayBeNormalized = normalizedMethodRecords[method];
if (mayBeNormalized !== void 0) request$2.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;
request$2.method = method;
}
if (!patchMethodWarning && request$2.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 (init.signal !== void 0) signal = init.signal;
this.#state = request$2;
const ac = new AbortController();
this.#signal = ac.signal;
if (signal != null) if (signal.aborted) ac.abort(signal.reason);
else {
this[kAbortController] = ac;
const abort$1 = buildAbort(new WeakRef(ac));
if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) setMaxListeners(1500, signal);
util$4.addAbortListener(signal, abort$1);
requestFinalizer.register(ac, {
signal,
abort: abort$1
}, abort$1);
}
this.#headers = new Headers$3(kConstruct$5);
setHeadersList(this.#headers, request$2.headersList);
setHeadersGuard(this.#headers, "request");
if (mode === "no-cors") {
if (!corsSafeListedMethodsSet.has(request$2.method)) throw new TypeError(`'${request$2.method} is unsupported in no-cors mode.`);
setHeadersGuard(this.#headers, "request-no-cors");
}
if (initHasKey) {
/** @type {HeadersList} */
const headersList = getHeadersList$1(this.#headers);
const headers = init.headers !== void 0 ? init.headers : new HeadersList$1(headersList);
headersList.clear();
if (headers instanceof HeadersList$1) {
for (const { name, value } of headers.rawValues()) headersList.append(name, value, false);
headersList.cookies = headers.cookies;
} else fillHeaders(this.#headers, headers);
}
const inputBody = webidl$9.is.Request(input) ? input.#state.body : null;
if ((init.body != null || inputBody != null) && (request$2.method === "GET" || request$2.method === "HEAD")) throw new TypeError("Request with GET/HEAD method cannot have body.");
let initBody = null;
if (init.body != null) {
const [extractedBody, contentType] = extractBody$1(init.body, request$2.keepalive);
initBody = extractedBody;
if (contentType && !getHeadersList$1(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 && init.duplex == null) throw new TypeError("RequestInit: duplex option is required when sending a body.");
if (request$2.mode !== "same-origin" && request$2.mode !== "cors") throw new TypeError("If request is made from ReadableStream, mode should be \"same-origin\" or \"cors\"");
request$2.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;
}
get method() {
webidl$9.brandCheck(this, Request$4);
return this.#state.method;
}
get url() {
webidl$9.brandCheck(this, Request$4);
return URLSerializer$2(this.#state.url);
}
get headers() {
webidl$9.brandCheck(this, Request$4);
return this.#headers;
}
get destination() {
webidl$9.brandCheck(this, Request$4);
return this.#state.destination;
}
get referrer() {
webidl$9.brandCheck(this, Request$4);
if (this.#state.referrer === "no-referrer") return "";
if (this.#state.referrer === "client") return "about:client";
return this.#state.referrer.toString();
}
get referrerPolicy() {
webidl$9.brandCheck(this, Request$4);
return this.#state.referrerPolicy;
}
get mode() {
webidl$9.brandCheck(this, Request$4);
return this.#state.mode;
}
get credentials() {
webidl$9.brandCheck(this, Request$4);
return this.#state.credentials;
}
get cache() {
webidl$9.brandCheck(this, Request$4);
return this.#state.cache;
}
get redirect() {
webidl$9.brandCheck(this, Request$4);
return this.#state.redirect;
}
get integrity() {
webidl$9.brandCheck(this, Request$4);
return this.#state.integrity;
}
get keepalive() {
webidl$9.brandCheck(this, Request$4);
return this.#state.keepalive;
}
get isReloadNavigation() {
webidl$9.brandCheck(this, Request$4);
return this.#state.reloadNavigation;
}
get isHistoryNavigation() {
webidl$9.brandCheck(this, Request$4);
return this.#state.historyNavigation;
}
get signal() {
webidl$9.brandCheck(this, Request$4);
return this.#signal;
}
get body() {
webidl$9.brandCheck(this, Request$4);
return this.#state.body ? this.#state.body.stream : null;
}
get bodyUsed() {
webidl$9.brandCheck(this, Request$4);
return !!this.#state.body && util$4.isDisturbed(this.#state.body.stream);
}
get duplex() {
webidl$9.brandCheck(this, Request$4);
return "half";
}
clone() {
webidl$9.brandCheck(this, Request$4);
if (bodyUnusable(this.#state)) throw new TypeError("unusable");
const clonedRequest = cloneRequest$1(this.#state);
const ac = new AbortController();
if (this.signal.aborted) ac.abort(this.signal.reason);
else {
let list$1 = dependentControllerMap.get(this.signal);
if (list$1 === void 0) {
list$1 = /* @__PURE__ */ new Set();
dependentControllerMap.set(this.signal, list$1);
}
const acRef = new WeakRef(ac);
list$1.add(acRef);
util$4.addAbortListener(ac.signal, buildAbort(acRef));
}
return fromInnerRequest$1(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers));
}
[nodeUtil.inspect.custom](depth$1, 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(request$2, newSignal) {
request$2.#signal = newSignal;
return request$2;
}
/**
* @param {Request} request
*/
static getRequestDispatcher(request$2) {
return request$2.#dispatcher;
}
/**
* @param {Request} request
* @param {import('../../dispatcher/dispatcher')} newDispatcher
*/
static setRequestDispatcher(request$2, newDispatcher) {
request$2.#dispatcher = newDispatcher;
}
/**
* @param {Request} request
* @param {Headers} newHeaders
*/
static setRequestHeaders(request$2, newHeaders) {
request$2.#headers = newHeaders;
}
/**
* @param {Request} request
*/
static getRequestState(request$2) {
return request$2.#state;
}
/**
* @param {Request} request
* @param {any} newState
*/
static setRequestState(request$2, newState) {
request$2.#state = newState;
}
};
const { setRequestSignal, getRequestDispatcher: getRequestDispatcher$1, setRequestDispatcher, setRequestHeaders, getRequestState: getRequestState$2, setRequestState } = Request$4;
Reflect.deleteProperty(Request$4, "setRequestSignal");
Reflect.deleteProperty(Request$4, "getRequestDispatcher");
Reflect.deleteProperty(Request$4, "setRequestDispatcher");
Reflect.deleteProperty(Request$4, "setRequestHeaders");
Reflect.deleteProperty(Request$4, "getRequestState");
Reflect.deleteProperty(Request$4, "setRequestState");
mixinBody(Request$4, getRequestState$2);
function makeRequest$2(init) {
return {
method: init.method ?? "GET",
localURLsOnly: init.localURLsOnly ?? false,
unsafeRequest: init.unsafeRequest ?? false,
body: init.body ?? null,
client: init.client ?? null,
reservedClient: init.reservedClient ?? null,
replacesClientId: init.replacesClientId ?? "",
window: init.window ?? "client",
keepalive: init.keepalive ?? false,
serviceWorkers: init.serviceWorkers ?? "all",
initiator: init.initiator ?? "",
destination: init.destination ?? "",
priority: init.priority ?? null,
origin: init.origin ?? "client",
policyContainer: init.policyContainer ?? "client",
referrer: init.referrer ?? "client",
referrerPolicy: init.referrerPolicy ?? "",
mode: init.mode ?? "no-cors",
useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
credentials: init.credentials ?? "same-origin",
useCredentials: init.useCredentials ?? false,
cache: init.cache ?? "default",
redirect: init.redirect ?? "follow",
integrity: init.integrity ?? "",
cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? "",
parserMetadata: init.parserMetadata ?? "",
reloadNavigation: init.reloadNavigation ?? false,
historyNavigation: init.historyNavigation ?? false,
userActivation: init.userActivation ?? false,
taintedOrigin: init.taintedOrigin ?? false,
redirectCount: init.redirectCount ?? 0,
responseTainting: init.responseTainting ?? "basic",
preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
done: init.done ?? false,
timingAllowFailed: init.timingAllowFailed ?? false,
useURLCredentials: init.useURLCredentials ?? void 0,
traversableForUserPrompts: init.traversableForUserPrompts ?? "client",
urlList: init.urlList,
url: init.urlList[0],
headersList: init.headersList ? new HeadersList$1(init.headersList) : new HeadersList$1()
};
}
function cloneRequest$1(request$2) {
const newRequest = makeRequest$2({
...request$2,
body: null
});
if (request$2.body != null) newRequest.body = cloneBody(request$2.body);
return newRequest;
}
/**
* @see https://fetch.spec.whatwg.org/#request-create
* @param {any} innerRequest
* @param {import('../../dispatcher/agent')} dispatcher
* @param {AbortSignal} signal
* @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
* @returns {Request}
*/
function fromInnerRequest$1(innerRequest, dispatcher, signal, guard) {
const request$2 = new Request$4(kConstruct$5);
setRequestState(request$2, innerRequest);
setRequestDispatcher(request$2, dispatcher);
setRequestSignal(request$2, signal);
const headers = new Headers$3(kConstruct$5);
setRequestHeaders(request$2, headers);
setHeadersList(headers, innerRequest.headersList);
setHeadersGuard(headers, guard);
return request$2;
}
Object.defineProperties(Request$4.prototype, {
method: kEnumerableProperty$7,
url: kEnumerableProperty$7,
headers: kEnumerableProperty$7,
redirect: kEnumerableProperty$7,
clone: kEnumerableProperty$7,
signal: kEnumerableProperty$7,
duplex: kEnumerableProperty$7,
destination: kEnumerableProperty$7,
body: kEnumerableProperty$7,
bodyUsed: kEnumerableProperty$7,
isHistoryNavigation: kEnumerableProperty$7,
isReloadNavigation: kEnumerableProperty$7,
keepalive: kEnumerableProperty$7,
integrity: kEnumerableProperty$7,
cache: kEnumerableProperty$7,
credentials: kEnumerableProperty$7,
attribute: kEnumerableProperty$7,
referrerPolicy: kEnumerableProperty$7,
referrer: kEnumerableProperty$7,
mode: kEnumerableProperty$7,
[Symbol.toStringTag]: {
value: "Request",
configurable: true
}
});
webidl$9.is.Request = webidl$9.util.MakeTypeAssertion(Request$4);
/**
* @param {*} V
* @returns {import('../../../types/fetch').Request|string}
*
* @see https://fetch.spec.whatwg.org/#requestinfo
*/
webidl$9.converters.RequestInfo = function(V) {
if (typeof V === "string") return webidl$9.converters.USVString(V);
if (webidl$9.is.Request(V)) return V;
return webidl$9.converters.USVString(V);
};
/**
* @param {*} V
* @returns {import('../../../types/fetch').RequestInit}
* @see https://fetch.spec.whatwg.org/#requestinit
*/
webidl$9.converters.RequestInit = webidl$9.dictionaryConverter([
{
key: "method",
converter: webidl$9.converters.ByteString
},
{
key: "headers",
converter: webidl$9.converters.HeadersInit
},
{
key: "body",
converter: webidl$9.nullableConverter(webidl$9.converters.BodyInit)
},
{
key: "referrer",
converter: webidl$9.converters.USVString
},
{
key: "referrerPolicy",
converter: webidl$9.converters.DOMString,
allowedValues: referrerPolicy
},
{
key: "mode",
converter: webidl$9.converters.DOMString,
allowedValues: requestMode
},
{
key: "credentials",
converter: webidl$9.converters.DOMString,
allowedValues: requestCredentials
},
{
key: "cache",
converter: webidl$9.converters.DOMString,
allowedValues: requestCache
},
{
key: "redirect",
converter: webidl$9.converters.DOMString,
allowedValues: requestRedirect
},
{
key: "integrity",
converter: webidl$9.converters.DOMString
},
{
key: "keepalive",
converter: webidl$9.converters.boolean
},
{
key: "signal",
converter: webidl$9.nullableConverter((signal) => webidl$9.converters.AbortSignal(signal, "RequestInit", "signal"))
},
{
key: "window",
converter: webidl$9.converters.any
},
{
key: "duplex",
converter: webidl$9.converters.DOMString,
allowedValues: requestDuplex
},
{
key: "dispatcher",
converter: webidl$9.converters.any
},
{
key: "priority",
converter: webidl$9.converters.DOMString,
allowedValues: [
"high",
"low",
"auto"
],
defaultValue: () => "auto"
}
]);
module.exports = {
Request: Request$4,
makeRequest: makeRequest$2,
fromInnerRequest: fromInnerRequest$1,
cloneRequest: cloneRequest$1,
getRequestDispatcher: getRequestDispatcher$1,
getRequestState: getRequestState$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js
var require_subresource_integrity = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js": ((exports, module) => {
const assert$7 = __require$2("node:assert");
const { runtimeFeatures: runtimeFeatures$3 } = require_runtime_features();
/**
* @typedef {object} Metadata
* @property {SRIHashAlgorithm} alg - The algorithm used for the hash.
* @property {string} val - The base64-encoded hash value.
*/
/**
* @typedef {Metadata[]} MetadataList
*/
/**
* @typedef {('sha256' | 'sha384' | 'sha512')} SRIHashAlgorithm
*/
/**
* @type {Map<SRIHashAlgorithm, number>}
*
* The valid SRI hash algorithm token set is the ordered set « "sha256",
* "sha384", "sha512" » (corresponding to SHA-256, SHA-384, and SHA-512
* respectively). The ordering of this set is meaningful, with stronger
* algorithms appearing later in the set.
*
* @see https://w3c.github.io/webappsec-subresource-integrity/#valid-sri-hash-algorithm-token-set
*/
const validSRIHashAlgorithmTokenSet = new Map([
["sha256", 0],
["sha384", 1],
["sha512", 2]
]);
/** @type {import('node:crypto')} */
let crypto$1;
if (runtimeFeatures$3.has("crypto")) {
crypto$1 = __require$2("node:crypto");
const cryptoHashes = crypto$1.getHashes();
if (cryptoHashes.length === 0) validSRIHashAlgorithmTokenSet.clear();
for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) if (cryptoHashes.includes(algorithm) === false) validSRIHashAlgorithmTokenSet.delete(algorithm);
} else validSRIHashAlgorithmTokenSet.clear();
/**
* @typedef GetSRIHashAlgorithmIndex
* @type {(algorithm: SRIHashAlgorithm) => number}
* @param {SRIHashAlgorithm} algorithm
* @returns {number} The index of the algorithm in the valid SRI hash algorithm
* token set.
*/
const getSRIHashAlgorithmIndex = Map.prototype.get.bind(validSRIHashAlgorithmTokenSet);
/**
* @typedef IsValidSRIHashAlgorithm
* @type {(algorithm: string) => algorithm is SRIHashAlgorithm}
* @param {*} algorithm
* @returns {algorithm is SRIHashAlgorithm}
*/
const isValidSRIHashAlgorithm = Map.prototype.has.bind(validSRIHashAlgorithmTokenSet);
/**
* @param {Uint8Array} bytes
* @param {string} metadataList
* @returns {boolean}
*
* @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
*/
const bytesMatch$1 = runtimeFeatures$3.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => {
const parsedMetadata = parseMetadata(metadataList);
if (parsedMetadata.length === 0) return true;
const metadata = getStrongestMetadata(parsedMetadata);
for (const item of metadata) {
const algorithm = item.alg;
const expectedValue = item.val;
if (caseSensitiveMatch(applyAlgorithmToBytes(algorithm, bytes), expectedValue)) return true;
}
return false;
};
/**
* @param {MetadataList} metadataList
* @returns {MetadataList} The strongest hash algorithm from the metadata list.
*/
function getStrongestMetadata(metadataList) {
const result = [];
/** @type {Metadata|null} */
let strongest = null;
for (const item of metadataList) {
assert$7(isValidSRIHashAlgorithm(item.alg), "Invalid SRI hash algorithm token");
if (result.length === 0) {
result.push(item);
strongest = item;
continue;
}
const currentAlgorithm = strongest.alg;
const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm);
const newAlgorithm = item.alg;
const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm);
if (newAlgorithmIndex < currentAlgorithmIndex) continue;
else if (newAlgorithmIndex > currentAlgorithmIndex) {
strongest = item;
result[0] = item;
result.length = 1;
} else result.push(item);
}
return result;
}
/**
* @param {string} metadata
* @returns {MetadataList}
*
* @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
*/
function parseMetadata(metadata) {
/** @type {MetadataList} */
const result = [];
for (const item of metadata.split(" ")) {
const algorithmExpression = item.split("?", 1)[0];
let base64Value = "";
const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)];
const algorithm = algorithmAndValue[0];
if (!isValidSRIHashAlgorithm(algorithm)) continue;
if (algorithmAndValue[1]) base64Value = algorithmAndValue[1];
const metadata$1 = {
alg: algorithm,
val: base64Value
};
result.push(metadata$1);
}
return result;
}
/**
* Applies the specified hash algorithm to the given bytes
*
* @typedef {(algorithm: SRIHashAlgorithm, bytes: Uint8Array) => string} ApplyAlgorithmToBytes
* @param {SRIHashAlgorithm} algorithm
* @param {Uint8Array} bytes
* @returns {string}
*/
const applyAlgorithmToBytes = (algorithm, bytes) => {
return crypto$1.hash(algorithm, bytes, "base64");
};
/**
* Compares two base64 strings, allowing for base64url
* in the second string.
*
* @param {string} actualValue base64 encoded string
* @param {string} expectedValue base64 or base64url encoded string
* @returns {boolean}
*/
function caseSensitiveMatch(actualValue, expectedValue) {
let actualValueLength = actualValue.length;
if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") actualValueLength -= 1;
if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") actualValueLength -= 1;
let expectedValueLength = expectedValue.length;
if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") expectedValueLength -= 1;
if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") expectedValueLength -= 1;
if (actualValueLength !== expectedValueLength) return false;
for (let i$1 = 0; i$1 < actualValueLength; ++i$1) {
if (actualValue[i$1] === expectedValue[i$1] || actualValue[i$1] === "+" && expectedValue[i$1] === "-" || actualValue[i$1] === "/" && expectedValue[i$1] === "_") continue;
return false;
}
return true;
}
module.exports = {
applyAlgorithmToBytes,
bytesMatch: bytesMatch$1,
caseSensitiveMatch,
isValidSRIHashAlgorithm,
getStrongestMetadata,
parseMetadata
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/index.js
var require_fetch = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/fetch/index.js": ((exports, module) => {
const { makeNetworkError, makeAppropriateNetworkError, filterResponse, makeResponse, fromInnerResponse: fromInnerResponse$1, getResponseState: getResponseState$1 } = require_response();
const { HeadersList } = require_headers();
const { Request: Request$3, cloneRequest, getRequestDispatcher, getRequestState: getRequestState$1 } = require_request();
const zlib = __require$2("node:zlib");
const { makePolicyContainer, clonePolicyContainer, requestBadPort, TAOCheck, appendRequestOriginHeader, responseLocationURL, requestCurrentURL, setRequestReferrerPolicyOnRedirect, tryUpgradeRequestToAPotentiallyTrustworthyURL, createOpaqueTimingInfo, appendFetchMetadata, corsCheck, crossOriginResourcePolicyCheck, determineRequestsReferrer, coarsenedSharedCurrentTime, sameOrigin, isCancelled, isAborted: isAborted$2, isErrorLike, fullyReadBody, readableStreamClose, urlIsLocal, urlIsHttpHttpsScheme: urlIsHttpHttpsScheme$1, urlHasHttpsScheme, clampAndCoarsenConnectionTimingInfo, simpleRangeHeaderValue, buildContentRange, createInflate, extractMimeType, hasAuthenticationEntry, includesCredentials, isTraversableNavigable } = require_util$4();
const assert$6 = __require$2("node:assert");
const { safelyExtractBody, extractBody } = require_body();
const { redirectStatusSet, nullBodyStatus, safeMethodsSet, requestBodyHeader, subresourceSet } = require_constants$3();
const EE = __require$2("node:events");
const { Readable, pipeline: pipeline$1, finished, isErrored, isReadable } = __require$2("node:stream");
const { addAbortListener, bufferToLowerCasedHeaderName } = require_util$5();
const { dataURLProcessor, serializeAMimeType: serializeAMimeType$1, minimizeSupportedMimeType } = require_data_url();
const { getGlobalDispatcher: getGlobalDispatcher$2 } = require_global();
const { webidl: webidl$8 } = require_webidl();
const { STATUS_CODES } = __require$2("node:http");
const { bytesMatch } = require_subresource_integrity();
const { createDeferredPromise: createDeferredPromise$2 } = require_promise();
const { isomorphicEncode } = require_infra();
const { runtimeFeatures: runtimeFeatures$2 } = require_runtime_features();
const hasZstd = runtimeFeatures$2.has("zstd");
const GET_OR_HEAD = ["GET", "HEAD"];
const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
/** @type {import('buffer').resolveObjectURL} */
let resolveObjectURL;
var Fetch = class extends EE {
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);
}
abort(error) {
if (this.state !== "ongoing") return;
this.state = "aborted";
if (!error) error = new DOMException("The operation was aborted.", "AbortError");
this.serializedAbortReason = error;
this.connection?.destroy(error);
this.emit("terminated", error);
}
};
function handleFetchDone(response) {
finalizeAndReportTiming(response, "fetch");
}
function fetch$2(input, init = void 0) {
webidl$8.argumentLengthCheck(arguments, 1, "globalThis.fetch");
let p$1 = createDeferredPromise$2();
let requestObject;
try {
requestObject = new Request$3(input, init);
} catch (e) {
p$1.reject(e);
return p$1.promise;
}
const request$2 = getRequestState$1(requestObject);
if (requestObject.signal.aborted) {
abortFetch(p$1, request$2, null, requestObject.signal.reason, null);
return p$1.promise;
}
if (request$2.client.globalObject?.constructor?.name === "ServiceWorkerGlobalScope") request$2.serviceWorkers = "none";
let responseObject = null;
let locallyAborted = false;
let controller = null;
addAbortListener(requestObject.signal, () => {
locallyAborted = true;
assert$6(controller != null);
controller.abort(requestObject.signal.reason);
const realResponse = responseObject?.deref();
abortFetch(p$1, request$2, realResponse, requestObject.signal.reason, controller.controller);
});
const processResponse = (response) => {
if (locallyAborted) return;
if (response.aborted) {
abortFetch(p$1, request$2, responseObject, controller.serializedAbortReason, controller.controller);
return;
}
if (response.type === "error") {
p$1.reject(new TypeError("fetch failed", { cause: response.error }));
return;
}
responseObject = new WeakRef(fromInnerResponse$1(response, "immutable"));
p$1.resolve(responseObject.deref());
p$1 = null;
};
controller = fetching$3({
request: request$2,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: getRequestDispatcher(requestObject),
requestObject
});
return p$1.promise;
}
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$1(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, "", response.status);
}
const markResourceTiming = performance.markResourceTiming;
function abortFetch(p$1, request$2, responseObject, error, controller) {
if (p$1) p$1.reject(error);
if (request$2.body?.stream != null && isReadable(request$2.body.stream)) request$2.body.stream.cancel(error).catch((err) => {
if (err.code === "ERR_INVALID_STATE") return;
throw err;
});
if (responseObject == null) return;
const response = getResponseState$1(responseObject);
if (response.body?.stream != null && isReadable(response.body.stream)) controller.error(error);
}
function fetching$3({ request: request$2, processRequestBodyChunkLength, processRequestEndOfBody, processResponse, processResponseEndOfBody, processResponseConsumeBody, useParallelQueue = false, dispatcher = getGlobalDispatcher$2(), requestObject = null }) {
assert$6(dispatcher);
let taskDestination = null;
let crossOriginIsolatedCapability = false;
if (request$2.client != null) {
taskDestination = request$2.client.globalObject;
crossOriginIsolatedCapability = request$2.client.crossOriginIsolatedCapability;
}
const timingInfo = createOpaqueTimingInfo({ startTime: coarsenedSharedCurrentTime(crossOriginIsolatedCapability) });
const fetchParams = {
controller: new Fetch(dispatcher),
request: request$2,
timingInfo,
processRequestBodyChunkLength,
processRequestEndOfBody,
processResponse,
processResponseConsumeBody,
processResponseEndOfBody,
taskDestination,
crossOriginIsolatedCapability,
requestObject
};
assert$6(!request$2.body || request$2.body.stream);
if (request$2.window === "client") request$2.window = request$2.client?.globalObject?.constructor?.name === "Window" ? request$2.client : "no-window";
if (request$2.origin === "client") request$2.origin = request$2.client.origin;
if (request$2.policyContainer === "client") if (request$2.client != null) request$2.policyContainer = clonePolicyContainer(request$2.client.policyContainer);
else request$2.policyContainer = makePolicyContainer();
if (!request$2.headersList.contains("accept", true)) request$2.headersList.append("accept", "*/*", true);
if (!request$2.headersList.contains("accept-language", true)) request$2.headersList.append("accept-language", "*", true);
if (request$2.priority === null) {}
if (subresourceSet.has(request$2.destination)) {}
mainFetch(fetchParams, false);
return fetchParams.controller;
}
async function mainFetch(fetchParams, recursive) {
try {
const request$2 = fetchParams.request;
let response = null;
if (request$2.localURLsOnly && !urlIsLocal(requestCurrentURL(request$2))) response = makeNetworkError("local URLs only");
tryUpgradeRequestToAPotentiallyTrustworthyURL(request$2);
if (requestBadPort(request$2) === "blocked") response = makeNetworkError("bad port");
if (request$2.referrerPolicy === "") request$2.referrerPolicy = request$2.policyContainer.referrerPolicy;
if (request$2.referrer !== "no-referrer") request$2.referrer = determineRequestsReferrer(request$2);
if (response === null) {
const currentURL = requestCurrentURL(request$2);
if (sameOrigin(currentURL, request$2.url) && request$2.responseTainting === "basic" || currentURL.protocol === "data:" || request$2.mode === "navigate" || request$2.mode === "websocket") {
request$2.responseTainting = "basic";
response = await schemeFetch(fetchParams);
} else if (request$2.mode === "same-origin") response = makeNetworkError("request mode cannot be \"same-origin\"");
else if (request$2.mode === "no-cors") if (request$2.redirect !== "follow") response = makeNetworkError("redirect mode cannot be \"follow\" for \"no-cors\" request");
else {
request$2.responseTainting = "opaque";
response = await schemeFetch(fetchParams);
}
else if (!urlIsHttpHttpsScheme$1(requestCurrentURL(request$2))) response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
else {
request$2.responseTainting = "cors";
response = await httpFetch(fetchParams);
}
}
if (recursive) return response;
if (response.status !== 0 && !response.internalResponse) {
if (request$2.responseTainting === "cors") {}
if (request$2.responseTainting === "basic") response = filterResponse(response, "basic");
else if (request$2.responseTainting === "cors") response = filterResponse(response, "cors");
else if (request$2.responseTainting === "opaque") response = filterResponse(response, "opaque");
else assert$6(false);
}
let internalResponse = response.status === 0 ? response : response.internalResponse;
if (internalResponse.urlList.length === 0) internalResponse.urlList.push(...request$2.urlList);
if (!request$2.timingAllowFailed) response.timingAllowPassed = true;
if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request$2.headers.contains("range", true)) response = internalResponse = makeNetworkError();
if (response.status !== 0 && (request$2.method === "HEAD" || request$2.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
internalResponse.body = null;
fetchParams.controller.dump = true;
}
if (request$2.integrity) {
const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason));
if (request$2.responseTainting === "opaque" || response.body == null) {
processBodyError(response.error);
return;
}
const processBody = (bytes) => {
if (!bytesMatch(bytes, request$2.integrity)) {
processBodyError("integrity mismatch");
return;
}
response.body = safelyExtractBody(bytes)[0];
fetchFinale(fetchParams, response);
};
fullyReadBody(response.body, processBody, processBodyError);
} else fetchFinale(fetchParams, response);
} catch (err) {
fetchParams.controller.terminate(err);
}
}
function schemeFetch(fetchParams) {
if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) return Promise.resolve(makeAppropriateNetworkError(fetchParams));
const { request: request$2 } = fetchParams;
const { protocol: scheme } = requestCurrentURL(request$2);
switch (scheme) {
case "about:": return Promise.resolve(makeNetworkError("about scheme is not supported"));
case "blob:": {
if (!resolveObjectURL) resolveObjectURL = __require$2("node:buffer").resolveObjectURL;
const blobURLEntry = requestCurrentURL(request$2);
if (blobURLEntry.search.length !== 0) return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
const blob = resolveObjectURL(blobURLEntry.toString());
if (request$2.method !== "GET" || !webidl$8.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 (!request$2.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 rangeValue = simpleRangeHeaderValue(request$2.headersList.get("range", true), 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 + 1, type);
response.body = extractBody(slicedBlob)[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 dataURLStruct = dataURLProcessor(requestCurrentURL(request$2));
if (dataURLStruct === "failure") return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
const mimeType = serializeAMimeType$1(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"));
}
}
function finalizeResponse(fetchParams, response) {
fetchParams.request.done = true;
if (fetchParams.processResponseDone != null) queueMicrotask(() => fetchParams.processResponseDone(response));
}
function fetchFinale(fetchParams, response) {
let timingInfo = fetchParams.timingInfo;
const processResponseEndOfBody = () => {
const unsafeEndTime = Date.now();
if (fetchParams.request.destination === "document") fetchParams.controller.fullTimingInfo = timingInfo;
fetchParams.controller.reportTimingSteps = () => {
if (!urlIsHttpHttpsScheme$1(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 = () => {
fetchParams.request.done = true;
if (fetchParams.processResponseEndOfBody != null) queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
if (fetchParams.request.initiatorType != null) fetchParams.controller.reportTimingSteps();
};
queueMicrotask(() => processResponseEndOfBodyTask());
};
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();
});
}
async function httpFetch(fetchParams) {
const request$2 = fetchParams.request;
let response = null;
let actualResponse = null;
const timingInfo = fetchParams.timingInfo;
if (request$2.serviceWorkers === "all") {}
if (response === null) {
if (request$2.redirect === "follow") request$2.serviceWorkers = "none";
actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
if (request$2.responseTainting === "cors" && corsCheck(request$2, response) === "failure") return makeNetworkError("cors failure");
if (TAOCheck(request$2, response) === "failure") request$2.timingAllowFailed = true;
}
if ((request$2.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(request$2.origin, request$2.client, request$2.destination, actualResponse) === "blocked") return makeNetworkError("blocked");
if (redirectStatusSet.has(actualResponse.status)) {
if (request$2.redirect !== "manual") fetchParams.controller.connection.destroy(void 0, false);
if (request$2.redirect === "error") response = makeNetworkError("unexpected redirect");
else if (request$2.redirect === "manual") response = actualResponse;
else if (request$2.redirect === "follow") response = await httpRedirectFetch(fetchParams, response);
else assert$6(false);
}
response.timingInfo = timingInfo;
return response;
}
function httpRedirectFetch(fetchParams, response) {
const request$2 = fetchParams.request;
const actualResponse = response.internalResponse ? response.internalResponse : response;
let locationURL;
try {
locationURL = responseLocationURL(actualResponse, requestCurrentURL(request$2).hash);
if (locationURL == null) return response;
} catch (err) {
return Promise.resolve(makeNetworkError(err));
}
if (!urlIsHttpHttpsScheme$1(locationURL)) return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
if (request$2.redirectCount === 20) return Promise.resolve(makeNetworkError("redirect count exceeded"));
request$2.redirectCount += 1;
if (request$2.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request$2, locationURL)) return Promise.resolve(makeNetworkError("cross origin not allowed for request mode \"cors\""));
if (request$2.responseTainting === "cors" && (locationURL.username || locationURL.password)) return Promise.resolve(makeNetworkError("URL cannot contain credentials for request mode \"cors\""));
if (actualResponse.status !== 303 && request$2.body != null && request$2.body.source == null) return Promise.resolve(makeNetworkError());
if ([301, 302].includes(actualResponse.status) && request$2.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request$2.method)) {
request$2.method = "GET";
request$2.body = null;
for (const headerName of requestBodyHeader) request$2.headersList.delete(headerName);
}
if (!sameOrigin(requestCurrentURL(request$2), locationURL)) {
request$2.headersList.delete("authorization", true);
request$2.headersList.delete("proxy-authorization", true);
request$2.headersList.delete("cookie", true);
request$2.headersList.delete("host", true);
}
if (request$2.body != null) {
assert$6(request$2.body.source != null);
request$2.body = safelyExtractBody(request$2.body.source)[0];
}
const timingInfo = fetchParams.timingInfo;
timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
if (timingInfo.redirectStartTime === 0) timingInfo.redirectStartTime = timingInfo.startTime;
request$2.urlList.push(locationURL);
setRequestReferrerPolicyOnRedirect(request$2, actualResponse);
return mainFetch(fetchParams, true);
}
async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
const request$2 = fetchParams.request;
let httpFetchParams = null;
let httpRequest = null;
let response = null;
const httpCache = null;
if (request$2.window === "no-window" && request$2.redirect === "error") {
httpFetchParams = fetchParams;
httpRequest = request$2;
} else {
httpRequest = cloneRequest(request$2);
httpFetchParams = { ...fetchParams };
httpFetchParams.request = httpRequest;
}
const includeCredentials = request$2.credentials === "include" || request$2.credentials === "same-origin" && request$2.responseTainting === "basic";
const contentLength = httpRequest.body ? httpRequest.body.length : null;
let contentLengthHeaderValue = null;
if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) contentLengthHeaderValue = "0";
if (contentLength != null) contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
if (contentLengthHeaderValue != null) httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
if (contentLength != null && httpRequest.keepalive) {}
if (webidl$8.is.URL(httpRequest.referrer)) httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
appendRequestOriginHeader(httpRequest);
appendFetchMetadata(httpRequest);
if (!httpRequest.headersList.contains("user-agent", true)) httpRequest.headersList.append("user-agent", defaultUserAgent, true);
if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) httpRequest.cache = "no-store";
if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) httpRequest.headersList.append("cache-control", "max-age=0", true);
if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
if (!httpRequest.headersList.contains("pragma", true)) httpRequest.headersList.append("pragma", "no-cache", true);
if (!httpRequest.headersList.contains("cache-control", true)) httpRequest.headersList.append("cache-control", "no-cache", true);
}
if (httpRequest.headersList.contains("range", true)) httpRequest.headersList.append("accept-encoding", "identity", true);
if (!httpRequest.headersList.contains("accept-encoding", true)) if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
else httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
httpRequest.headersList.delete("host", true);
if (includeCredentials) {
if (!httpRequest.headersList.contains("authorization", true)) {
let authorizationValue = null;
if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {} else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
const { username, password } = requestCurrentURL(httpRequest);
authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
}
if (authorizationValue !== null) httpRequest.headersList.append("Authorization", authorizationValue, false);
}
}
if (httpCache == null) httpRequest.cache = "no-store";
if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") {}
if (response == null) {
if (httpRequest.cache === "only-if-cached") return makeNetworkError("only if cached");
const forwardResponse = await httpNetworkFetch(httpFetchParams, includeCredentials, isNewConnectionFetch);
if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {}
if (response == null) response = forwardResponse;
}
response.urlList = [...httpRequest.urlList];
if (httpRequest.headersList.contains("range", true)) response.rangeRequested = true;
response.requestIncludesCredentials = includeCredentials;
if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request$2.useURLCredentials !== void 0 || isTraversableNavigable(request$2.traversableForUserPrompts))) {
if (request$2.body != null) {
if (request$2.body.source == null) return response;
request$2.body = safelyExtractBody(request$2.body.source)[0];
}
if (request$2.useURLCredentials === void 0 || isAuthenticationFetch) {
if (isCancelled(fetchParams)) return makeAppropriateNetworkError(fetchParams);
return response;
}
fetchParams.controller.connection.destroy();
response = await httpNetworkOrCacheFetch(fetchParams, true);
}
if (response.status === 407) {
if (request$2.window === "no-window") return makeNetworkError();
if (isCancelled(fetchParams)) return makeAppropriateNetworkError(fetchParams);
return makeNetworkError("proxy authentication required");
}
if (response.status === 421 && !isNewConnectionFetch && (request$2.body == null || request$2.body.source != null)) {
if (isCancelled(fetchParams)) return makeAppropriateNetworkError(fetchParams);
fetchParams.controller.connection.destroy();
response = await httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch, true);
}
if (isAuthenticationFetch) {}
return response;
}
async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
assert$6(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
fetchParams.controller.connection = {
abort: null,
destroyed: false,
destroy(err, abort$1 = true) {
if (!this.destroyed) {
this.destroyed = true;
if (abort$1) this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
}
}
};
const request$2 = fetchParams.request;
let response = null;
const timingInfo = fetchParams.timingInfo;
request$2.cache = "no-store";
if (request$2.mode === "websocket") {}
let requestBody = null;
if (request$2.body == null && fetchParams.processRequestEndOfBody) queueMicrotask(() => fetchParams.processRequestEndOfBody());
else if (request$2.body != null) {
const processBodyChunk = async function* (bytes) {
if (isCancelled(fetchParams)) return;
yield bytes;
fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
};
const processEndOfBody = () => {
if (isCancelled(fetchParams)) return;
if (fetchParams.processRequestEndOfBody) fetchParams.processRequestEndOfBody();
};
const processBodyError = (e) => {
if (isCancelled(fetchParams)) return;
if (e.name === "AbortError") fetchParams.controller.abort();
else fetchParams.controller.terminate(e);
};
requestBody = (async function* () {
try {
for await (const bytes of request$2.body.stream) yield* processBodyChunk(bytes);
processEndOfBody();
} catch (err) {
processBodyError(err);
}
})();
}
try {
const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
if (socket) response = makeResponse({
status,
statusText,
headersList,
socket
});
else {
const iterator = body[Symbol.asyncIterator]();
fetchParams.controller.next = () => iterator.next();
response = makeResponse({
status,
statusText,
headersList
});
}
} catch (err) {
if (err.name === "AbortError") {
fetchParams.controller.connection.destroy();
return makeAppropriateNetworkError(fetchParams, err);
}
return makeNetworkError(err);
}
const pullAlgorithm = () => {
return fetchParams.controller.resume();
};
const cancelAlgorithm = (reason) => {
if (!isCancelled(fetchParams)) fetchParams.controller.abort(reason);
};
const stream$2 = new ReadableStream({
start(controller) {
fetchParams.controller.controller = controller;
},
pull: pullAlgorithm,
cancel: cancelAlgorithm,
type: "bytes"
});
response.body = {
stream: stream$2,
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 (isAborted$2(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$1 = new Uint8Array(bytes);
if (buffer$1.byteLength) fetchParams.controller.controller.enqueue(buffer$1);
if (isErrored(stream$2)) {
fetchParams.controller.terminate();
return;
}
if (fetchParams.controller.controller.desiredSize <= 0) return;
}
};
function onAborted(reason) {
if (isAborted$2(fetchParams)) {
response.aborted = true;
if (isReadable(stream$2)) fetchParams.controller.controller.error(fetchParams.controller.serializedAbortReason);
} else if (isReadable(stream$2)) fetchParams.controller.controller.error(new TypeError("terminated", { cause: isErrorLike(reason) ? reason : void 0 }));
fetchParams.controller.connection.destroy();
}
return response;
function dispatch({ body }) {
const url = requestCurrentURL(request$2);
/** @type {import('../../..').Agent} */
const agent = fetchParams.controller.dispatcher;
const path$2 = url.pathname + url.search;
const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
return new Promise((resolve$4, reject) => agent.dispatch({
path: hasTrailingQuestionMark ? `${path$2}?` : path$2,
origin: url.origin,
method: request$2.method,
body: agent.isMockActive ? request$2.body && (request$2.body.source || request$2.body.stream) : body,
headers: request$2.headersList.entries,
maxRedirections: 0,
upgrade: request$2.mode === "websocket" ? "websocket" : void 0
}, {
body: null,
abort: null,
onConnect(abort$1) {
const { connection } = fetchParams.controller;
timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
if (connection.destroyed) abort$1(new DOMException("The operation was aborted.", "AbortError"));
else {
fetchParams.controller.on("terminated", abort$1);
this.abort = connection.abort = abort$1;
}
timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
},
onResponseStarted() {
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
},
onHeaders(status, rawHeaders, resume$1, statusText) {
if (status < 200) return false;
const headersList = new HeadersList();
for (let i$1 = 0; i$1 < rawHeaders.length; i$1 += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i$1]);
const value = rawHeaders[i$1 + 1];
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i$1 + 1])) for (const val of value) headersList.append(nameStr, val.toString("latin1"), true);
else headersList.append(nameStr, value.toString("latin1"), true);
}
const location = headersList.get("location", true);
this.body = new Readable({ read: resume$1 });
const willFollow = location && request$2.redirect === "follow" && redirectStatusSet.has(status);
const decoders = [];
if (request$2.method !== "HEAD" && request$2.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
const contentEncoding = headersList.get("content-encoding", true);
/** @type {string[]} */
const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : [];
const maxContentEncodings = 5;
if (codings.length > maxContentEncodings) {
reject(/* @__PURE__ */ new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));
return true;
}
for (let i$1 = codings.length - 1; i$1 >= 0; --i$1) {
const coding = codings[i$1].trim();
if (coding === "x-gzip" || coding === "gzip") decoders.push(zlib.createGunzip({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}));
else if (coding === "deflate") decoders.push(createInflate({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}));
else if (coding === "br") decoders.push(zlib.createBrotliDecompress({
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
}));
else if (coding === "zstd" && hasZstd) decoders.push(zlib.createZstdDecompress({
flush: zlib.constants.ZSTD_e_continue,
finishFlush: zlib.constants.ZSTD_e_end
}));
else {
decoders.length = 0;
break;
}
}
}
const onError$1 = this.onError.bind(this);
resolve$4({
status,
statusText,
headersList,
body: decoders.length ? pipeline$1(this.body, ...decoders, (err) => {
if (err) this.onError(err);
}).on("error", onError$1) : this.body.on("error", onError$1)
});
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(error) {
if (this.abort) fetchParams.controller.off("terminated", this.abort);
this.body?.destroy(error);
fetchParams.controller.terminate(error);
reject(error);
},
onRequestUpgrade(_controller, status, headers, socket) {
if (socket.session != null && status !== 200 || socket.session == null && status !== 101) return false;
const headersList = new HeadersList();
for (const [name, value] of Object.entries(headers)) {
if (value == null) continue;
const headerName = name.toLowerCase();
if (Array.isArray(value)) for (const entry of value) headersList.append(headerName, String(entry), true);
else headersList.append(headerName, String(value), true);
}
resolve$4({
status,
statusText: STATUS_CODES[status],
headersList,
socket
});
return true;
},
onUpgrade(status, rawHeaders, socket) {
if (socket.session != null && status !== 200 || socket.session == null && status !== 101) return false;
const headersList = new HeadersList();
for (let i$1 = 0; i$1 < rawHeaders.length; i$1 += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i$1]);
const value = rawHeaders[i$1 + 1];
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i$1 + 1])) for (const val of value) headersList.append(nameStr, val.toString("latin1"), true);
else headersList.append(nameStr, value.toString("latin1"), true);
}
resolve$4({
status,
statusText: STATUS_CODES[status],
headersList,
socket
});
return true;
}
}));
}
}
module.exports = {
fetch: fetch$2,
Fetch,
fetching: fetching$3,
finalizeAndReportTiming
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/util.js
var require_util$3 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/util.js": ((exports, module) => {
const assert$5 = __require$2("node:assert");
const { URLSerializer: URLSerializer$1 } = require_data_url();
const { isValidHeaderName } = require_util$4();
/**
* @see https://url.spec.whatwg.org/#concept-url-equals
* @param {URL} A
* @param {URL} B
* @param {boolean | undefined} excludeFragment
* @returns {boolean}
*/
function urlEquals$1(A, B, excludeFragment = false) {
return URLSerializer$1(A, excludeFragment) === URLSerializer$1(B, excludeFragment);
}
/**
* @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
* @param {string} header
*/
function getFieldValues$1(header) {
assert$5(header !== null);
const values = [];
for (let value of header.split(",")) {
value = value.trim();
if (isValidHeaderName(value)) values.push(value);
}
return values;
}
module.exports = {
urlEquals: urlEquals$1,
getFieldValues: getFieldValues$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/cache.js
var require_cache = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/cache.js": ((exports, module) => {
const assert$4 = __require$2("node:assert");
const { kConstruct: kConstruct$4 } = require_symbols();
const { urlEquals, getFieldValues } = require_util$3();
const { kEnumerableProperty: kEnumerableProperty$6, isDisturbed } = require_util$5();
const { webidl: webidl$7 } = require_webidl();
const { cloneResponse, fromInnerResponse, getResponseState } = require_response();
const { Request: Request$2, fromInnerRequest, getRequestState } = require_request();
const { fetching: fetching$2 } = require_fetch();
const { urlIsHttpHttpsScheme, readAllBytes } = require_util$4();
const { createDeferredPromise: createDeferredPromise$1 } = require_promise();
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
* @typedef {Object} CacheBatchOperation
* @property {'delete' | 'put'} type
* @property {any} request
* @property {any} response
* @property {import('../../../types/cache').CacheQueryOptions} options
*/
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
* @typedef {[any, any][]} requestResponseList
*/
var Cache$1 = class Cache$1 {
/**
* @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
* @type {requestResponseList}
*/
#relevantRequestResponseList;
constructor() {
if (arguments[0] !== kConstruct$4) webidl$7.illegalConstructor();
webidl$7.util.markAsUncloneable(this);
this.#relevantRequestResponseList = arguments[1];
}
async match(request$2, options = {}) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.match";
webidl$7.argumentLengthCheck(arguments, 1, prefix);
request$2 = webidl$7.converters.RequestInfo(request$2);
options = webidl$7.converters.CacheQueryOptions(options, prefix, "options");
const p$1 = this.#internalMatchAll(request$2, options, 1);
if (p$1.length === 0) return;
return p$1[0];
}
async matchAll(request$2 = void 0, options = {}) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.matchAll";
if (request$2 !== void 0) request$2 = webidl$7.converters.RequestInfo(request$2);
options = webidl$7.converters.CacheQueryOptions(options, prefix, "options");
return this.#internalMatchAll(request$2, options);
}
async add(request$2) {
webidl$7.brandCheck(this, Cache$1);
webidl$7.argumentLengthCheck(arguments, 1, "Cache.add");
request$2 = webidl$7.converters.RequestInfo(request$2);
const requests = [request$2];
return await this.addAll(requests);
}
async addAll(requests) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.addAll";
webidl$7.argumentLengthCheck(arguments, 1, prefix);
const responsePromises = [];
const requestList = [];
for (let request$2 of requests) {
if (request$2 === void 0) throw webidl$7.errors.conversionFailed({
prefix,
argument: "Argument 1",
types: ["undefined is not allowed"]
});
request$2 = webidl$7.converters.RequestInfo(request$2);
if (typeof request$2 === "string") continue;
const r$1 = getRequestState(request$2);
if (!urlIsHttpHttpsScheme(r$1.url) || r$1.method !== "GET") throw webidl$7.errors.exception({
header: prefix,
message: "Expected http/s scheme when method is not GET."
});
}
/** @type {ReturnType<typeof fetching>[]} */
const fetchControllers = [];
for (const request$2 of requests) {
const r$1 = getRequestState(new Request$2(request$2));
if (!urlIsHttpHttpsScheme(r$1.url)) throw webidl$7.errors.exception({
header: prefix,
message: "Expected http/s scheme."
});
r$1.initiator = "fetch";
r$1.destination = "subresource";
requestList.push(r$1);
const responsePromise = createDeferredPromise$1();
fetchControllers.push(fetching$2({
request: r$1,
processResponse(response) {
if (response.type === "error" || response.status === 206 || response.status < 200 || response.status > 299) responsePromise.reject(webidl$7.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$7.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 responses = await Promise.all(responsePromises);
const operations = [];
let index = 0;
for (const response of responses) {
/** @type {CacheBatchOperation} */
const operation = {
type: "put",
request: requestList[index],
response
};
operations.push(operation);
index++;
}
const cacheJobPromise = createDeferredPromise$1();
let errorData = null;
try {
this.#batchCacheOperations(operations);
} catch (e) {
errorData = e;
}
queueMicrotask(() => {
if (errorData === null) cacheJobPromise.resolve(void 0);
else cacheJobPromise.reject(errorData);
});
return cacheJobPromise.promise;
}
async put(request$2, response) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.put";
webidl$7.argumentLengthCheck(arguments, 2, prefix);
request$2 = webidl$7.converters.RequestInfo(request$2);
response = webidl$7.converters.Response(response, prefix, "response");
let innerRequest = null;
if (webidl$7.is.Request(request$2)) innerRequest = getRequestState(request$2);
else innerRequest = getRequestState(new Request$2(request$2));
if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") throw webidl$7.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$7.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$7.errors.exception({
header: prefix,
message: "Got * vary field value"
});
}
if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) throw webidl$7.errors.exception({
header: prefix,
message: "Response body is locked or disturbed"
});
const clonedResponse = cloneResponse(innerResponse);
const bodyReadPromise = createDeferredPromise$1();
if (innerResponse.body != null) readAllBytes(innerResponse.body.stream.getReader(), bodyReadPromise.resolve, bodyReadPromise.reject);
else bodyReadPromise.resolve(void 0);
/** @type {CacheBatchOperation[]} */
const operations = [];
/** @type {CacheBatchOperation} */
const operation = {
type: "put",
request: innerRequest,
response: clonedResponse
};
operations.push(operation);
const bytes = await bodyReadPromise.promise;
if (clonedResponse.body != null) clonedResponse.body.source = bytes;
const cacheJobPromise = createDeferredPromise$1();
let errorData = null;
try {
this.#batchCacheOperations(operations);
} catch (e) {
errorData = e;
}
queueMicrotask(() => {
if (errorData === null) cacheJobPromise.resolve();
else cacheJobPromise.reject(errorData);
});
return cacheJobPromise.promise;
}
async delete(request$2, options = {}) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.delete";
webidl$7.argumentLengthCheck(arguments, 1, prefix);
request$2 = webidl$7.converters.RequestInfo(request$2);
options = webidl$7.converters.CacheQueryOptions(options, prefix, "options");
/**
* @type {Request}
*/
let r$1 = null;
if (webidl$7.is.Request(request$2)) {
r$1 = getRequestState(request$2);
if (r$1.method !== "GET" && !options.ignoreMethod) return false;
} else {
assert$4(typeof request$2 === "string");
r$1 = getRequestState(new Request$2(request$2));
}
/** @type {CacheBatchOperation[]} */
const operations = [];
/** @type {CacheBatchOperation} */
const operation = {
type: "delete",
request: r$1,
options
};
operations.push(operation);
const cacheJobPromise = createDeferredPromise$1();
let errorData = null;
let requestResponses;
try {
requestResponses = this.#batchCacheOperations(operations);
} catch (e) {
errorData = e;
}
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(request$2 = void 0, options = {}) {
webidl$7.brandCheck(this, Cache$1);
const prefix = "Cache.keys";
if (request$2 !== void 0) request$2 = webidl$7.converters.RequestInfo(request$2);
options = webidl$7.converters.CacheQueryOptions(options, prefix, "options");
let r$1 = null;
if (request$2 !== void 0) {
if (webidl$7.is.Request(request$2)) {
r$1 = getRequestState(request$2);
if (r$1.method !== "GET" && !options.ignoreMethod) return [];
} else if (typeof request$2 === "string") r$1 = getRequestState(new Request$2(request$2));
}
const promise$1 = createDeferredPromise$1();
const requests = [];
if (request$2 === void 0) for (const requestResponse of this.#relevantRequestResponseList) requests.push(requestResponse[0]);
else {
const requestResponses = this.#queryCache(r$1, options);
for (const requestResponse of requestResponses) requests.push(requestResponse[0]);
}
queueMicrotask(() => {
const requestList = [];
for (const request$3 of requests) {
const requestObject = fromInnerRequest(request$3, void 0, new AbortController().signal, "immutable");
requestList.push(requestObject);
}
promise$1.resolve(Object.freeze(requestList));
});
return promise$1.promise;
}
/**
* @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
* @param {CacheBatchOperation[]} operations
* @returns {requestResponseList}
*/
#batchCacheOperations(operations) {
const cache$2 = this.#relevantRequestResponseList;
const backupCache = [...cache$2];
const addedItems = [];
const resultList = [];
try {
for (const operation of operations) {
if (operation.type !== "delete" && operation.type !== "put") throw webidl$7.errors.exception({
header: "Cache.#batchCacheOperations",
message: "operation type does not match \"delete\" or \"put\""
});
if (operation.type === "delete" && operation.response != null) throw webidl$7.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 = cache$2.indexOf(requestResponse);
assert$4(idx !== -1);
cache$2.splice(idx, 1);
}
} else if (operation.type === "put") {
if (operation.response == null) throw webidl$7.errors.exception({
header: "Cache.#batchCacheOperations",
message: "put operation should have an associated response"
});
const r$1 = operation.request;
if (!urlIsHttpHttpsScheme(r$1.url)) throw webidl$7.errors.exception({
header: "Cache.#batchCacheOperations",
message: "expected http or https scheme"
});
if (r$1.method !== "GET") throw webidl$7.errors.exception({
header: "Cache.#batchCacheOperations",
message: "not get method"
});
if (operation.options != null) throw webidl$7.errors.exception({
header: "Cache.#batchCacheOperations",
message: "options must not be defined"
});
requestResponses = this.#queryCache(operation.request);
for (const requestResponse of requestResponses) {
const idx = cache$2.indexOf(requestResponse);
assert$4(idx !== -1);
cache$2.splice(idx, 1);
}
cache$2.push([operation.request, operation.response]);
addedItems.push([operation.request, operation.response]);
}
resultList.push([operation.request, operation.response]);
}
return resultList;
} catch (e) {
this.#relevantRequestResponseList.length = 0;
this.#relevantRequestResponseList = backupCache;
throw e;
}
}
/**
* @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) {
/** @type {requestResponseList} */
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, request$2, response = null, options) {
const queryURL = new URL(requestQuery.url);
const cachedURL = new URL(request$2.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;
if (request$2.headersList.get(fieldValue) !== requestQuery.headersList.get(fieldValue)) return false;
}
return true;
}
#internalMatchAll(request$2, options, maxResponses = Infinity) {
let r$1 = null;
if (request$2 !== void 0) {
if (webidl$7.is.Request(request$2)) {
r$1 = getRequestState(request$2);
if (r$1.method !== "GET" && !options.ignoreMethod) return [];
} else if (typeof request$2 === "string") r$1 = getRequestState(new Request$2(request$2));
}
const responses = [];
if (request$2 === void 0) for (const requestResponse of this.#relevantRequestResponseList) responses.push(requestResponse[1]);
else {
const requestResponses = this.#queryCache(r$1, options);
for (const requestResponse of requestResponses) responses.push(requestResponse[1]);
}
const responseList = [];
for (const response of responses) {
const responseObject = fromInnerResponse(cloneResponse(response), "immutable");
responseList.push(responseObject);
if (responseList.length >= maxResponses) break;
}
return Object.freeze(responseList);
}
};
Object.defineProperties(Cache$1.prototype, {
[Symbol.toStringTag]: {
value: "Cache",
configurable: true
},
match: kEnumerableProperty$6,
matchAll: kEnumerableProperty$6,
add: kEnumerableProperty$6,
addAll: kEnumerableProperty$6,
put: kEnumerableProperty$6,
delete: kEnumerableProperty$6,
keys: kEnumerableProperty$6
});
const cacheQueryOptionConverters = [
{
key: "ignoreSearch",
converter: webidl$7.converters.boolean,
defaultValue: () => false
},
{
key: "ignoreMethod",
converter: webidl$7.converters.boolean,
defaultValue: () => false
},
{
key: "ignoreVary",
converter: webidl$7.converters.boolean,
defaultValue: () => false
}
];
webidl$7.converters.CacheQueryOptions = webidl$7.dictionaryConverter(cacheQueryOptionConverters);
webidl$7.converters.MultiCacheQueryOptions = webidl$7.dictionaryConverter([...cacheQueryOptionConverters, {
key: "cacheName",
converter: webidl$7.converters.DOMString
}]);
webidl$7.converters.Response = webidl$7.interfaceConverter(webidl$7.is.Response, "Response");
webidl$7.converters["sequence<RequestInfo>"] = webidl$7.sequenceConverter(webidl$7.converters.RequestInfo);
module.exports = { Cache: Cache$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cache/cachestorage.js": ((exports, module) => {
const { Cache } = require_cache();
const { webidl: webidl$6 } = require_webidl();
const { kEnumerableProperty: kEnumerableProperty$5 } = require_util$5();
const { kConstruct: kConstruct$3 } = require_symbols();
var CacheStorage$1 = class CacheStorage$1 {
/**
* @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$3) webidl$6.illegalConstructor();
webidl$6.util.markAsUncloneable(this);
}
async match(request$2, options = {}) {
webidl$6.brandCheck(this, CacheStorage$1);
webidl$6.argumentLengthCheck(arguments, 1, "CacheStorage.match");
request$2 = webidl$6.converters.RequestInfo(request$2);
options = webidl$6.converters.MultiCacheQueryOptions(options);
if (options.cacheName != null) {
if (this.#caches.has(options.cacheName)) return await new Cache(kConstruct$3, this.#caches.get(options.cacheName)).match(request$2, options);
} else for (const cacheList of this.#caches.values()) {
const response = await new Cache(kConstruct$3, cacheList).match(request$2, 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$6.brandCheck(this, CacheStorage$1);
const prefix = "CacheStorage.has";
webidl$6.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl$6.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$6.brandCheck(this, CacheStorage$1);
const prefix = "CacheStorage.open";
webidl$6.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl$6.converters.DOMString(cacheName, prefix, "cacheName");
if (this.#caches.has(cacheName)) return new Cache(kConstruct$3, this.#caches.get(cacheName));
const cache$2 = [];
this.#caches.set(cacheName, cache$2);
return new Cache(kConstruct$3, cache$2);
}
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
* @param {string} cacheName
* @returns {Promise<boolean>}
*/
async delete(cacheName) {
webidl$6.brandCheck(this, CacheStorage$1);
const prefix = "CacheStorage.delete";
webidl$6.argumentLengthCheck(arguments, 1, prefix);
cacheName = webidl$6.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$6.brandCheck(this, CacheStorage$1);
return [...this.#caches.keys()];
}
};
Object.defineProperties(CacheStorage$1.prototype, {
[Symbol.toStringTag]: {
value: "CacheStorage",
configurable: true
},
match: kEnumerableProperty$5,
has: kEnumerableProperty$5,
open: kEnumerableProperty$5,
delete: kEnumerableProperty$5,
keys: kEnumerableProperty$5
});
module.exports = { CacheStorage: CacheStorage$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/constants.js
var require_constants$2 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/constants.js": ((exports, module) => {
const maxAttributeValueSize$1 = 1024;
const maxNameValuePairSize$1 = 4096;
module.exports = {
maxAttributeValueSize: maxAttributeValueSize$1,
maxNameValuePairSize: maxNameValuePairSize$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/util.js
var require_util$2 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/util.js": ((exports, module) => {
/**
* @param {string} value
* @returns {boolean}
*/
function isCTLExcludingHtab$1(value) {
for (let i$1 = 0; i$1 < value.length; ++i$1) {
const code = value.charCodeAt(i$1);
if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) return true;
}
return false;
}
/**
CHAR = <any US-ASCII character (octets 0 - 127)>
token = 1*<any CHAR except CTLs or separators>
separators = "(" | ")" | "<" | ">" | "@"
| "," | ";" | ":" | "\" | <">
| "/" | "[" | "]" | "?" | "="
| "{" | "}" | SP | HT
* @param {string} name
*/
function validateCookieName(name) {
for (let i$1 = 0; i$1 < name.length; ++i$1) {
const code = name.charCodeAt(i$1);
if (code < 33 || code > 126 || 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");
}
}
/**
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
* @param {string} value
*/
function validateCookieValue(value) {
let len = value.length;
let i$1 = 0;
if (value[0] === "\"") {
if (len === 1 || value[len - 1] !== "\"") throw new Error("Invalid cookie value");
--len;
++i$1;
}
while (i$1 < len) {
const code = value.charCodeAt(i$1++);
if (code < 33 || code > 126 || code === 34 || code === 44 || code === 59 || code === 92) throw new Error("Invalid cookie value");
}
}
/**
* path-value = <any CHAR except CTLs or ";">
* @param {string} path
*/
function validateCookiePath(path$2) {
for (let i$1 = 0; i$1 < path$2.length; ++i$1) {
const code = path$2.charCodeAt(i$1);
if (code < 32 || code === 127 || code === 59) throw new Error("Invalid cookie path");
}
}
/**
* I have no idea why these values aren't allowed to be honest,
* but Deno tests these. - Khafra
* @param {string} domain
*/
function validateCookieDomain(domain) {
if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) throw new Error("Invalid cookie domain");
}
const IMFDays = [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
];
const IMFMonths = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
const IMFPaddedNumbers = Array(61).fill(0).map((_, i$1) => i$1.toString().padStart(2, "0"));
/**
* @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
* @param {number|Date} date
IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
; fixed length/zone/capitalization subset of the format
; see Section 3.3 of [RFC5322]
day-name = %x4D.6F.6E ; "Mon", case-sensitive
/ %x54.75.65 ; "Tue", case-sensitive
/ %x57.65.64 ; "Wed", case-sensitive
/ %x54.68.75 ; "Thu", case-sensitive
/ %x46.72.69 ; "Fri", case-sensitive
/ %x53.61.74 ; "Sat", case-sensitive
/ %x53.75.6E ; "Sun", case-sensitive
date1 = day SP month SP year
; e.g., 02 Jun 1982
day = 2DIGIT
month = %x4A.61.6E ; "Jan", case-sensitive
/ %x46.65.62 ; "Feb", case-sensitive
/ %x4D.61.72 ; "Mar", case-sensitive
/ %x41.70.72 ; "Apr", case-sensitive
/ %x4D.61.79 ; "May", case-sensitive
/ %x4A.75.6E ; "Jun", case-sensitive
/ %x4A.75.6C ; "Jul", case-sensitive
/ %x41.75.67 ; "Aug", case-sensitive
/ %x53.65.70 ; "Sep", case-sensitive
/ %x4F.63.74 ; "Oct", case-sensitive
/ %x4E.6F.76 ; "Nov", case-sensitive
/ %x44.65.63 ; "Dec", case-sensitive
year = 4DIGIT
GMT = %x47.4D.54 ; "GMT", case-sensitive
time-of-day = hour ":" minute ":" second
; 00:00:00 - 23:59:60 (leap second)
hour = 2DIGIT
minute = 2DIGIT
second = 2DIGIT
*/
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`;
}
/**
max-age-av = "Max-Age=" non-zero-digit *DIGIT
; In practice, both expires-av and max-age-av
; are limited to dates representable by the
; user agent.
* @param {number} maxAge
*/
function validateCookieMaxAge(maxAge) {
if (maxAge < 0) throw new Error("Invalid cookie max-age");
}
/**
* @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
* @param {import('./index').Cookie} cookie
*/
function stringify$1(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("; ");
}
module.exports = {
isCTLExcludingHtab: isCTLExcludingHtab$1,
validateCookieName,
validateCookiePath,
validateCookieValue,
toIMFDate,
stringify: stringify$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/parse.js
var require_parse$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/parse.js": ((exports, module) => {
const { collectASequenceOfCodePointsFast: collectASequenceOfCodePointsFast$1 } = require_infra();
const { maxNameValuePairSize, maxAttributeValueSize } = require_constants$2();
const { isCTLExcludingHtab } = require_util$2();
const assert$3 = __require$2("node:assert");
const { unescape: qsUnescape } = __require$2("node:querystring");
/**
* @description Parses the field-value attributes of a set-cookie header string.
* @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
* @param {string} header
* @returns {import('./index').Cookie|null} if the header is invalid, null will be returned
*/
function parseSetCookie$1(header) {
if (isCTLExcludingHtab(header)) return null;
let nameValuePair = "";
let unparsedAttributes = "";
let name = "";
let value = "";
if (header.includes(";")) {
const position = { position: 0 };
nameValuePair = collectASequenceOfCodePointsFast$1(";", header, position);
unparsedAttributes = header.slice(position.position);
} else nameValuePair = header;
if (!nameValuePair.includes("=")) value = nameValuePair;
else {
const position = { position: 0 };
name = collectASequenceOfCodePointsFast$1("=", nameValuePair, position);
value = nameValuePair.slice(position.position + 1);
}
name = name.trim();
value = value.trim();
if (name.length + value.length > maxNameValuePairSize) return null;
return {
name,
value: qsUnescape(value),
...parseUnparsedAttributes(unparsedAttributes)
};
}
/**
* Parses the remaining attributes of a set-cookie header
* @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
* @param {string} unparsedAttributes
* @param {Object.<string, unknown>} [cookieAttributeList={}]
*/
function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
if (unparsedAttributes.length === 0) return cookieAttributeList;
assert$3(unparsedAttributes[0] === ";");
unparsedAttributes = unparsedAttributes.slice(1);
let cookieAv = "";
if (unparsedAttributes.includes(";")) {
cookieAv = collectASequenceOfCodePointsFast$1(";", 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$1("=", 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") cookieAttributeList.expires = new Date(attributeValue);
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);
cookieAttributeList.maxAge = Number(attributeValue);
} 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);
}
module.exports = {
parseSetCookie: parseSetCookie$1,
parseUnparsedAttributes
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/index.js
var require_cookies = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/cookies/index.js": ((exports, module) => {
const { parseSetCookie } = require_parse$1();
const { stringify } = require_util$2();
const { webidl: webidl$5 } = require_webidl();
const { Headers: Headers$2 } = require_headers();
const brandChecks = webidl$5.brandCheckMultiple([Headers$2, globalThis.Headers].filter(Boolean));
/**
* @typedef {Object} Cookie
* @property {string} name
* @property {string} value
* @property {Date|number} [expires]
* @property {number} [maxAge]
* @property {string} [domain]
* @property {string} [path]
* @property {boolean} [secure]
* @property {boolean} [httpOnly]
* @property {'Strict'|'Lax'|'None'} [sameSite]
* @property {string[]} [unparsed]
*/
/**
* @param {Headers} headers
* @returns {Record<string, string>}
*/
function getCookies$1(headers) {
webidl$5.argumentLengthCheck(arguments, 1, "getCookies");
brandChecks(headers);
const cookie = headers.get("cookie");
/** @type {Record<string, string>} */
const out = {};
if (!cookie) return out;
for (const piece of cookie.split(";")) {
const [name, ...value] = piece.split("=");
out[name.trim()] = value.join("=");
}
return out;
}
/**
* @param {Headers} headers
* @param {string} name
* @param {{ path?: string, domain?: string }|undefined} attributes
* @returns {void}
*/
function deleteCookie$1(headers, name, attributes) {
brandChecks(headers);
const prefix = "deleteCookie";
webidl$5.argumentLengthCheck(arguments, 2, prefix);
name = webidl$5.converters.DOMString(name, prefix, "name");
attributes = webidl$5.converters.DeleteCookieAttributes(attributes);
setCookie$1(headers, {
name,
value: "",
expires: /* @__PURE__ */ new Date(0),
...attributes
});
}
/**
* @param {Headers} headers
* @returns {Cookie[]}
*/
function getSetCookies$1(headers) {
webidl$5.argumentLengthCheck(arguments, 1, "getSetCookies");
brandChecks(headers);
const cookies = headers.getSetCookie();
if (!cookies) return [];
return cookies.map((pair) => parseSetCookie(pair));
}
/**
* Parses a cookie string
* @param {string} cookie
*/
function parseCookie$1(cookie) {
cookie = webidl$5.converters.DOMString(cookie);
return parseSetCookie(cookie);
}
/**
* @param {Headers} headers
* @param {Cookie} cookie
* @returns {void}
*/
function setCookie$1(headers, cookie) {
webidl$5.argumentLengthCheck(arguments, 2, "setCookie");
brandChecks(headers);
cookie = webidl$5.converters.Cookie(cookie);
const str = stringify(cookie);
if (str) headers.append("set-cookie", str, true);
}
webidl$5.converters.DeleteCookieAttributes = webidl$5.dictionaryConverter([{
converter: webidl$5.nullableConverter(webidl$5.converters.DOMString),
key: "path",
defaultValue: () => null
}, {
converter: webidl$5.nullableConverter(webidl$5.converters.DOMString),
key: "domain",
defaultValue: () => null
}]);
webidl$5.converters.Cookie = webidl$5.dictionaryConverter([
{
converter: webidl$5.converters.DOMString,
key: "name"
},
{
converter: webidl$5.converters.DOMString,
key: "value"
},
{
converter: webidl$5.nullableConverter((value) => {
if (typeof value === "number") return webidl$5.converters["unsigned long long"](value);
return new Date(value);
}),
key: "expires",
defaultValue: () => null
},
{
converter: webidl$5.nullableConverter(webidl$5.converters["long long"]),
key: "maxAge",
defaultValue: () => null
},
{
converter: webidl$5.nullableConverter(webidl$5.converters.DOMString),
key: "domain",
defaultValue: () => null
},
{
converter: webidl$5.nullableConverter(webidl$5.converters.DOMString),
key: "path",
defaultValue: () => null
},
{
converter: webidl$5.nullableConverter(webidl$5.converters.boolean),
key: "secure",
defaultValue: () => null
},
{
converter: webidl$5.nullableConverter(webidl$5.converters.boolean),
key: "httpOnly",
defaultValue: () => null
},
{
converter: webidl$5.converters.USVString,
key: "sameSite",
allowedValues: [
"Strict",
"Lax",
"None"
]
},
{
converter: webidl$5.sequenceConverter(webidl$5.converters.DOMString),
key: "unparsed",
defaultValue: () => []
}
]);
module.exports = {
getCookies: getCookies$1,
deleteCookie: deleteCookie$1,
getSetCookies: getSetCookies$1,
setCookie: setCookie$1,
parseCookie: parseCookie$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/events.js
var require_events = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/events.js": ((exports, module) => {
const { webidl: webidl$4 } = require_webidl();
const { kEnumerableProperty: kEnumerableProperty$4 } = require_util$5();
const { kConstruct: kConstruct$2 } = require_symbols();
/**
* @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
*/
var MessageEvent$1 = class MessageEvent$1 extends Event {
#eventInit;
constructor(type, eventInitDict = {}) {
if (type === kConstruct$2) {
super(arguments[1], arguments[2]);
webidl$4.util.markAsUncloneable(this);
return;
}
const prefix = "MessageEvent constructor";
webidl$4.argumentLengthCheck(arguments, 1, prefix);
type = webidl$4.converters.DOMString(type, prefix, "type");
eventInitDict = webidl$4.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
super(type, eventInitDict);
this.#eventInit = eventInitDict;
webidl$4.util.markAsUncloneable(this);
}
get data() {
webidl$4.brandCheck(this, MessageEvent$1);
return this.#eventInit.data;
}
get origin() {
webidl$4.brandCheck(this, MessageEvent$1);
return this.#eventInit.origin;
}
get lastEventId() {
webidl$4.brandCheck(this, MessageEvent$1);
return this.#eventInit.lastEventId;
}
get source() {
webidl$4.brandCheck(this, MessageEvent$1);
return this.#eventInit.source;
}
get ports() {
webidl$4.brandCheck(this, MessageEvent$1);
if (!Object.isFrozen(this.#eventInit.ports)) Object.freeze(this.#eventInit.ports);
return this.#eventInit.ports;
}
initMessageEvent(type, bubbles = false, cancelable = false, data$1 = null, origin = "", lastEventId = "", source = null, ports = []) {
webidl$4.brandCheck(this, MessageEvent$1);
webidl$4.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
return new MessageEvent$1(type, {
bubbles,
cancelable,
data: data$1,
origin,
lastEventId,
source,
ports
});
}
static createFastMessageEvent(type, init) {
const messageEvent = new MessageEvent$1(kConstruct$2, type, init);
messageEvent.#eventInit = init;
messageEvent.#eventInit.data ??= null;
messageEvent.#eventInit.origin ??= "";
messageEvent.#eventInit.lastEventId ??= "";
messageEvent.#eventInit.source ??= null;
messageEvent.#eventInit.ports ??= [];
return messageEvent;
}
};
const { createFastMessageEvent: createFastMessageEvent$2 } = MessageEvent$1;
delete MessageEvent$1.createFastMessageEvent;
/**
* @see https://websockets.spec.whatwg.org/#the-closeevent-interface
*/
var CloseEvent$2 = class CloseEvent$2 extends Event {
#eventInit;
constructor(type, eventInitDict = {}) {
const prefix = "CloseEvent constructor";
webidl$4.argumentLengthCheck(arguments, 1, prefix);
type = webidl$4.converters.DOMString(type, prefix, "type");
eventInitDict = webidl$4.converters.CloseEventInit(eventInitDict);
super(type, eventInitDict);
this.#eventInit = eventInitDict;
webidl$4.util.markAsUncloneable(this);
}
get wasClean() {
webidl$4.brandCheck(this, CloseEvent$2);
return this.#eventInit.wasClean;
}
get code() {
webidl$4.brandCheck(this, CloseEvent$2);
return this.#eventInit.code;
}
get reason() {
webidl$4.brandCheck(this, CloseEvent$2);
return this.#eventInit.reason;
}
};
var ErrorEvent$2 = class ErrorEvent$2 extends Event {
#eventInit;
constructor(type, eventInitDict) {
const prefix = "ErrorEvent constructor";
webidl$4.argumentLengthCheck(arguments, 1, prefix);
super(type, eventInitDict);
webidl$4.util.markAsUncloneable(this);
type = webidl$4.converters.DOMString(type, prefix, "type");
eventInitDict = webidl$4.converters.ErrorEventInit(eventInitDict ?? {});
this.#eventInit = eventInitDict;
}
get message() {
webidl$4.brandCheck(this, ErrorEvent$2);
return this.#eventInit.message;
}
get filename() {
webidl$4.brandCheck(this, ErrorEvent$2);
return this.#eventInit.filename;
}
get lineno() {
webidl$4.brandCheck(this, ErrorEvent$2);
return this.#eventInit.lineno;
}
get colno() {
webidl$4.brandCheck(this, ErrorEvent$2);
return this.#eventInit.colno;
}
get error() {
webidl$4.brandCheck(this, ErrorEvent$2);
return this.#eventInit.error;
}
};
Object.defineProperties(MessageEvent$1.prototype, {
[Symbol.toStringTag]: {
value: "MessageEvent",
configurable: true
},
data: kEnumerableProperty$4,
origin: kEnumerableProperty$4,
lastEventId: kEnumerableProperty$4,
source: kEnumerableProperty$4,
ports: kEnumerableProperty$4,
initMessageEvent: kEnumerableProperty$4
});
Object.defineProperties(CloseEvent$2.prototype, {
[Symbol.toStringTag]: {
value: "CloseEvent",
configurable: true
},
reason: kEnumerableProperty$4,
code: kEnumerableProperty$4,
wasClean: kEnumerableProperty$4
});
Object.defineProperties(ErrorEvent$2.prototype, {
[Symbol.toStringTag]: {
value: "ErrorEvent",
configurable: true
},
message: kEnumerableProperty$4,
filename: kEnumerableProperty$4,
lineno: kEnumerableProperty$4,
colno: kEnumerableProperty$4,
error: kEnumerableProperty$4
});
webidl$4.converters.MessagePort = webidl$4.interfaceConverter(webidl$4.is.MessagePort, "MessagePort");
webidl$4.converters["sequence<MessagePort>"] = webidl$4.sequenceConverter(webidl$4.converters.MessagePort);
const eventInit = [
{
key: "bubbles",
converter: webidl$4.converters.boolean,
defaultValue: () => false
},
{
key: "cancelable",
converter: webidl$4.converters.boolean,
defaultValue: () => false
},
{
key: "composed",
converter: webidl$4.converters.boolean,
defaultValue: () => false
}
];
webidl$4.converters.MessageEventInit = webidl$4.dictionaryConverter([
...eventInit,
{
key: "data",
converter: webidl$4.converters.any,
defaultValue: () => null
},
{
key: "origin",
converter: webidl$4.converters.USVString,
defaultValue: () => ""
},
{
key: "lastEventId",
converter: webidl$4.converters.DOMString,
defaultValue: () => ""
},
{
key: "source",
converter: webidl$4.nullableConverter(webidl$4.converters.MessagePort),
defaultValue: () => null
},
{
key: "ports",
converter: webidl$4.converters["sequence<MessagePort>"],
defaultValue: () => []
}
]);
webidl$4.converters.CloseEventInit = webidl$4.dictionaryConverter([
...eventInit,
{
key: "wasClean",
converter: webidl$4.converters.boolean,
defaultValue: () => false
},
{
key: "code",
converter: webidl$4.converters["unsigned short"],
defaultValue: () => 0
},
{
key: "reason",
converter: webidl$4.converters.USVString,
defaultValue: () => ""
}
]);
webidl$4.converters.ErrorEventInit = webidl$4.dictionaryConverter([
...eventInit,
{
key: "message",
converter: webidl$4.converters.DOMString,
defaultValue: () => ""
},
{
key: "filename",
converter: webidl$4.converters.USVString,
defaultValue: () => ""
},
{
key: "lineno",
converter: webidl$4.converters["unsigned long"],
defaultValue: () => 0
},
{
key: "colno",
converter: webidl$4.converters["unsigned long"],
defaultValue: () => 0
},
{
key: "error",
converter: webidl$4.converters.any
}
]);
module.exports = {
MessageEvent: MessageEvent$1,
CloseEvent: CloseEvent$2,
ErrorEvent: ErrorEvent$2,
createFastMessageEvent: createFastMessageEvent$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/constants.js
var require_constants$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/constants.js": ((exports, module) => {
/**
* This is a Globally Unique Identifier unique used to validate that the
* endpoint accepts websocket connections.
* @see https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
* @type {'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'}
*/
const uid$1 = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/**
* @type {PropertyDescriptor}
*/
const staticPropertyDescriptors$1 = {
enumerable: true,
writable: false,
configurable: false
};
/**
* The states of the WebSocket connection.
*
* @readonly
* @enum
* @property {0} CONNECTING
* @property {1} OPEN
* @property {2} CLOSING
* @property {3} CLOSED
*/
const states$5 = {
CONNECTING: 0,
OPEN: 1,
CLOSING: 2,
CLOSED: 3
};
/**
* @readonly
* @enum
* @property {0} NOT_SENT
* @property {1} PROCESSING
* @property {2} SENT
*/
const sentCloseFrameState$4 = {
SENT: 1,
RECEIVED: 2
};
/**
* The WebSocket opcodes.
*
* @readonly
* @enum
* @property {0x0} CONTINUATION
* @property {0x1} TEXT
* @property {0x2} BINARY
* @property {0x8} CLOSE
* @property {0x9} PING
* @property {0xA} PONG
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
*/
const opcodes$7 = {
CONTINUATION: 0,
TEXT: 1,
BINARY: 2,
CLOSE: 8,
PING: 9,
PONG: 10
};
/**
* The maximum value for an unsigned 16-bit integer.
*
* @type {65535} 2 ** 16 - 1
*/
const maxUnsigned16Bit$1 = 65535;
/**
* The states of the parser.
*
* @readonly
* @enum
* @property {0} INFO
* @property {2} PAYLOADLENGTH_16
* @property {3} PAYLOADLENGTH_64
* @property {4} READ_DATA
*/
const parserStates$1 = {
INFO: 0,
PAYLOADLENGTH_16: 2,
PAYLOADLENGTH_64: 3,
READ_DATA: 4
};
/**
* An empty buffer.
*
* @type {Buffer}
*/
const emptyBuffer$2 = Buffer.allocUnsafe(0);
/**
* @readonly
* @property {1} text
* @property {2} typedArray
* @property {3} arrayBuffer
* @property {4} blob
*/
const sendHints$2 = {
text: 1,
typedArray: 2,
arrayBuffer: 3,
blob: 4
};
module.exports = {
uid: uid$1,
sentCloseFrameState: sentCloseFrameState$4,
staticPropertyDescriptors: staticPropertyDescriptors$1,
states: states$5,
opcodes: opcodes$7,
maxUnsigned16Bit: maxUnsigned16Bit$1,
parserStates: parserStates$1,
emptyBuffer: emptyBuffer$2,
sendHints: sendHints$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/util.js
var require_util$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/util.js": ((exports, module) => {
const { states: states$4, opcodes: opcodes$6 } = require_constants$1();
const { isUtf8 } = __require$2("node:buffer");
const { removeHTTPWhitespace } = require_data_url();
const { collectASequenceOfCodePointsFast } = require_infra();
/**
* @param {number} readyState
* @returns {boolean}
*/
function isConnecting$2(readyState) {
return readyState === states$4.CONNECTING;
}
/**
* @param {number} readyState
* @returns {boolean}
*/
function isEstablished$3(readyState) {
return readyState === states$4.OPEN;
}
/**
* @param {number} readyState
* @returns {boolean}
*/
function isClosing$2(readyState) {
return readyState === states$4.CLOSING;
}
/**
* @param {number} readyState
* @returns {boolean}
*/
function isClosed$2(readyState) {
return readyState === states$4.CLOSED;
}
/**
* @see https://dom.spec.whatwg.org/#concept-event-fire
* @param {string} e
* @param {EventTarget} target
* @param {(...args: ConstructorParameters<typeof Event>) => Event} eventFactory
* @param {EventInit | undefined} eventInitDict
* @returns {void}
*/
function fireEvent$1(e, target$1, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
const event = eventFactory(e, eventInitDict);
target$1.dispatchEvent(event);
}
/**
* @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
* @param {import('./websocket').Handler} handler
* @param {number} type Opcode
* @param {Buffer} data application data
* @returns {void}
*/
function websocketMessageReceived$1(handler, type, data$1) {
handler.onMessage(type, data$1);
}
/**
* @param {Buffer} buffer
* @returns {ArrayBuffer}
*/
function toArrayBuffer$1(buffer$1) {
if (buffer$1.byteLength === buffer$1.buffer.byteLength) return buffer$1.buffer;
return new Uint8Array(buffer$1).buffer;
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc6455
* @see https://datatracker.ietf.org/doc/html/rfc2616
* @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
* @param {string} protocol
* @returns {boolean}
*/
function isValidSubprotocol$2(protocol) {
if (protocol.length === 0) return false;
for (let i$1 = 0; i$1 < protocol.length; ++i$1) {
const code = protocol.charCodeAt(i$1);
if (code < 33 || 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;
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
* @param {number} code
* @returns {boolean}
*/
function isValidStatusCode$1(code) {
if (code >= 1e3 && code < 1015) return code !== 1004 && code !== 1005 && code !== 1006;
return code >= 3e3 && code <= 4999;
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
* @param {number} opcode
* @returns {boolean}
*/
function isControlFrame$1(opcode) {
return opcode === opcodes$6.CLOSE || opcode === opcodes$6.PING || opcode === opcodes$6.PONG;
}
/**
* @param {number} opcode
* @returns {boolean}
*/
function isContinuationFrame$1(opcode) {
return opcode === opcodes$6.CONTINUATION;
}
/**
* @param {number} opcode
* @returns {boolean}
*/
function isTextBinaryFrame$1(opcode) {
return opcode === opcodes$6.TEXT || opcode === opcodes$6.BINARY;
}
/**
*
* @param {number} opcode
* @returns {boolean}
*/
function isValidOpcode$1(opcode) {
return isTextBinaryFrame$1(opcode) || isContinuationFrame$1(opcode) || isControlFrame$1(opcode);
}
/**
* Parses a Sec-WebSocket-Extensions header value.
* @param {string} extensions
* @returns {Map<string, string>}
*/
function parseExtensions$1(extensions) {
const position = { position: 0 };
const extensionList = /* @__PURE__ */ new Map();
while (position.position < extensions.length) {
const [name, value = ""] = collectASequenceOfCodePointsFast(";", extensions, position).split("=", 2);
extensionList.set(removeHTTPWhitespace(name, true, false), removeHTTPWhitespace(value, false, true));
position.position++;
}
return extensionList;
}
/**
* @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2
* @description "client-max-window-bits = 1*DIGIT"
* @param {string} value
* @returns {boolean}
*/
function isValidClientWindowBits$1(value) {
if (value.length === 0) return false;
for (let i$1 = 0; i$1 < value.length; i$1++) {
const byte = value.charCodeAt(i$1);
if (byte < 48 || byte > 57) return false;
}
const num = Number.parseInt(value, 10);
return num >= 8 && num <= 15;
}
/**
* @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record
* @param {string} url
* @param {string} [baseURL]
*/
function getURLRecord$2(url, baseURL) {
let urlRecord;
try {
urlRecord = new URL(url, baseURL);
} catch (e) {
throw new DOMException(e, "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;
}
function validateCloseCodeAndReason$2(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");
}
}
/**
* Converts a Buffer to utf-8, even on platforms without icu.
* @type {(buffer: Buffer) => string}
*/
const utf8Decode$3 = (() => {
if (typeof process.versions.icu === "string") {
const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
return fatalDecoder.decode.bind(fatalDecoder);
}
return function(buffer$1) {
if (isUtf8(buffer$1)) return buffer$1.toString("utf-8");
throw new TypeError("Invalid utf-8 received.");
};
})();
module.exports = {
isConnecting: isConnecting$2,
isEstablished: isEstablished$3,
isClosing: isClosing$2,
isClosed: isClosed$2,
fireEvent: fireEvent$1,
isValidSubprotocol: isValidSubprotocol$2,
isValidStatusCode: isValidStatusCode$1,
websocketMessageReceived: websocketMessageReceived$1,
utf8Decode: utf8Decode$3,
isControlFrame: isControlFrame$1,
isContinuationFrame: isContinuationFrame$1,
isTextBinaryFrame: isTextBinaryFrame$1,
isValidOpcode: isValidOpcode$1,
parseExtensions: parseExtensions$1,
isValidClientWindowBits: isValidClientWindowBits$1,
toArrayBuffer: toArrayBuffer$1,
getURLRecord: getURLRecord$2,
validateCloseCodeAndReason: validateCloseCodeAndReason$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/frame.js
var require_frame = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/frame.js": ((exports, module) => {
const { runtimeFeatures: runtimeFeatures$1 } = require_runtime_features();
const { maxUnsigned16Bit, opcodes: opcodes$5 } = require_constants$1();
const BUFFER_SIZE = 8 * 1024;
let buffer = null;
let bufIdx = BUFFER_SIZE;
const randomFillSync = runtimeFeatures$1.has("crypto") ? __require$2("node:crypto").randomFillSync : function randomFillSync$1(buffer$1, _offset, _size) {
for (let i$1 = 0; i$1 < buffer$1.length; ++i$1) buffer$1[i$1] = Math.random() * 255 | 0;
return buffer$1;
};
function generateMask() {
if (bufIdx === BUFFER_SIZE) {
bufIdx = 0;
randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
}
return [
buffer[bufIdx++],
buffer[bufIdx++],
buffer[bufIdx++],
buffer[bufIdx++]
];
}
var WebsocketFrameSend$5 = class {
/**
* @param {Buffer|undefined} data
*/
constructor(data$1) {
this.frameData = data$1;
}
createFrame(opcode) {
const frameData = this.frameData;
const maskKey = generateMask();
const bodyLength$1 = frameData?.byteLength ?? 0;
/** @type {number} */
let payloadLength = bodyLength$1;
let offset = 6;
if (bodyLength$1 > maxUnsigned16Bit) {
offset += 8;
payloadLength = 127;
} else if (bodyLength$1 > 125) {
offset += 2;
payloadLength = 126;
}
const buffer$1 = Buffer.allocUnsafe(bodyLength$1 + offset);
buffer$1[0] = buffer$1[1] = 0;
buffer$1[0] |= 128;
buffer$1[0] = (buffer$1[0] & 240) + opcode;
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */
buffer$1[offset - 4] = maskKey[0];
buffer$1[offset - 3] = maskKey[1];
buffer$1[offset - 2] = maskKey[2];
buffer$1[offset - 1] = maskKey[3];
buffer$1[1] = payloadLength;
if (payloadLength === 126) buffer$1.writeUInt16BE(bodyLength$1, 2);
else if (payloadLength === 127) {
buffer$1[2] = buffer$1[3] = 0;
buffer$1.writeUIntBE(bodyLength$1, 4, 6);
}
buffer$1[1] |= 128;
for (let i$1 = 0; i$1 < bodyLength$1; ++i$1) buffer$1[offset + i$1] = frameData[i$1] ^ maskKey[i$1 & 3];
return buffer$1;
}
/**
* @param {Uint8Array} buffer
*/
static createFastTextFrame(buffer$1) {
const maskKey = generateMask();
const bodyLength$1 = buffer$1.length;
for (let i$1 = 0; i$1 < bodyLength$1; ++i$1) buffer$1[i$1] ^= maskKey[i$1 & 3];
let payloadLength = bodyLength$1;
let offset = 6;
if (bodyLength$1 > maxUnsigned16Bit) {
offset += 8;
payloadLength = 127;
} else if (bodyLength$1 > 125) {
offset += 2;
payloadLength = 126;
}
const head = Buffer.allocUnsafeSlow(offset);
head[0] = 128 | opcodes$5.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$1, 2);
else if (payloadLength === 127) {
head[2] = head[3] = 0;
head.writeUIntBE(bodyLength$1, 4, 6);
}
return [head, buffer$1];
}
};
module.exports = {
WebsocketFrameSend: WebsocketFrameSend$5,
generateMask
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/connection.js
var require_connection = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/connection.js": ((exports, module) => {
const { uid, states: states$3, sentCloseFrameState: sentCloseFrameState$3, emptyBuffer: emptyBuffer$1, opcodes: opcodes$4 } = require_constants$1();
const { parseExtensions, isClosed: isClosed$1, isClosing: isClosing$1, isEstablished: isEstablished$2, isConnecting: isConnecting$1, validateCloseCodeAndReason: validateCloseCodeAndReason$1 } = require_util$1();
const { makeRequest: makeRequest$1 } = require_request();
const { fetching: fetching$1 } = require_fetch();
const { Headers: Headers$1, getHeadersList } = require_headers();
const { getDecodeSplit } = require_util$4();
const { WebsocketFrameSend: WebsocketFrameSend$4 } = require_frame();
const assert$2 = __require$2("node:assert");
const { runtimeFeatures } = require_runtime_features();
const crypto = runtimeFeatures.has("crypto") ? __require$2("node:crypto") : null;
let warningEmitted = false;
/**
* @see https://websockets.spec.whatwg.org/#concept-websocket-establish
* @param {URL} url
* @param {string|string[]} protocols
* @param {import('./websocket').Handler} handler
* @param {Partial<import('../../../types/websocket').WebSocketInit>} options
*/
function establishWebSocketConnection$2(url, protocols, client, handler, options) {
const requestURL = url;
requestURL.protocol = url.protocol === "ws:" ? "http:" : "https:";
const request$2 = makeRequest$1({
urlList: [requestURL],
client,
serviceWorkers: "none",
referrer: "no-referrer",
mode: "websocket",
credentials: "include",
cache: "no-store",
redirect: "error",
useURLCredentials: true
});
if (options.headers) request$2.headersList = getHeadersList(new Headers$1(options.headers));
const keyValue = crypto.randomBytes(16).toString("base64");
request$2.headersList.append("sec-websocket-key", keyValue, true);
request$2.headersList.append("sec-websocket-version", "13", true);
for (const protocol of protocols) request$2.headersList.append("sec-websocket-protocol", protocol, true);
request$2.headersList.append("sec-websocket-extensions", "permessage-deflate; client_max_window_bits", true);
return fetching$1({
request: request$2,
useParallelQueue: true,
dispatcher: options.dispatcher,
processResponse(response) {
if (response.type === "error" || response.status !== 101) {
if (response.socket?.session == null) {
failWebsocketConnection$3(handler, 1002, "Received network error or non-101 status code.", response.error);
return;
}
if (response.status !== 200) {
failWebsocketConnection$3(handler, 1002, "Received network error or non-200 status code.", response.error);
return;
}
}
if (warningEmitted === false && response.socket?.session != null) {
process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.", "ExperimentalWarning");
warningEmitted = true;
}
if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
failWebsocketConnection$3(handler, 1002, "Server did not respond with sent protocols.");
return;
}
if (response.socket.session == null && response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
failWebsocketConnection$3(handler, 1002, "Server did not set Upgrade header to \"websocket\".");
return;
}
if (response.socket.session == null && response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
failWebsocketConnection$3(handler, 1002, "Server did not set Connection header to \"upgrade\".");
return;
}
if (response.headersList.get("Sec-WebSocket-Accept") !== crypto.hash("sha1", keyValue + uid, "base64")) {
failWebsocketConnection$3(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$3(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
return;
}
}
const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
if (secProtocol !== null) {
if (!getDecodeSplit("sec-websocket-protocol", request$2.headersList).includes(secProtocol)) {
failWebsocketConnection$3(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);
handler.wasEverConnected = true;
handler.onConnectionEstablished(response, extensions);
}
});
}
/**
* @see https://whatpr.org/websockets/48.html#close-the-websocket
* @param {import('./websocket').Handler} object
* @param {number} [code=null]
* @param {string} [reason='']
*/
function closeWebSocketConnection$2(object, code, reason, validate = false) {
code ??= null;
reason ??= "";
if (validate) validateCloseCodeAndReason$1(code, reason);
if (isClosed$1(object.readyState) || isClosing$1(object.readyState)) {} else if (!isEstablished$2(object.readyState)) {
failWebsocketConnection$3(object);
object.readyState = states$3.CLOSING;
} else if (!object.closeState.has(sentCloseFrameState$3.SENT) && !object.closeState.has(sentCloseFrameState$3.RECEIVED)) {
const frame = new WebsocketFrameSend$4();
if (reason.length !== 0 && code === null) code = 1e3;
assert$2(code === null || Number.isInteger(code));
if (code === null && reason.length === 0) frame.frameData = emptyBuffer$1;
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$1;
object.socket.write(frame.createFrame(opcodes$4.CLOSE));
object.closeState.add(sentCloseFrameState$3.SENT);
object.readyState = states$3.CLOSING;
} else object.readyState = states$3.CLOSING;
}
/**
* @param {import('./websocket').Handler} handler
* @param {number} code
* @param {string|undefined} reason
* @param {unknown} cause
* @returns {void}
*/
function failWebsocketConnection$3(handler, code, reason, cause) {
if (isEstablished$2(handler.readyState)) closeWebSocketConnection$2(handler, code, reason, false);
handler.controller.abort();
if (isConnecting$1(handler.readyState)) handler.onSocketClose();
else if (handler.socket?.destroyed === false) handler.socket.destroy();
}
module.exports = {
establishWebSocketConnection: establishWebSocketConnection$2,
failWebsocketConnection: failWebsocketConnection$3,
closeWebSocketConnection: closeWebSocketConnection$2
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/permessage-deflate.js": ((exports, module) => {
const { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require$2("node:zlib");
const { isValidClientWindowBits } = require_util$1();
const { MessageSizeExceededError: MessageSizeExceededError$1 } = require_errors();
const tail = Buffer.from([
0,
0,
255,
255
]);
const kBuffer = Symbol("kBuffer");
const kLength = Symbol("kLength");
const kDefaultMaxDecompressedSize = 4 * 1024 * 1024;
var PerMessageDeflate$1 = class {
/** @type {import('node:zlib').InflateRaw} */
#inflate;
#options = {};
/** @type {boolean} */
#aborted = false;
/** @type {Function|null} */
#currentCallback = null;
/**
* @param {Map<string, string>} extensions
*/
constructor(extensions) {
this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
}
decompress(chunk, fin, callback$1) {
if (this.#aborted) {
callback$1(new MessageSizeExceededError$1());
return;
}
if (!this.#inflate) {
let windowBits = Z_DEFAULT_WINDOWBITS;
if (this.#options.serverMaxWindowBits) {
if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
callback$1(/* @__PURE__ */ new Error("Invalid server_max_window_bits"));
return;
}
windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
}
try {
this.#inflate = createInflateRaw({ windowBits });
} catch (err) {
callback$1(err);
return;
}
this.#inflate[kBuffer] = [];
this.#inflate[kLength] = 0;
this.#inflate.on("data", (data$1) => {
if (this.#aborted) return;
this.#inflate[kLength] += data$1.length;
if (this.#inflate[kLength] > kDefaultMaxDecompressedSize) {
this.#aborted = true;
this.#inflate.removeAllListeners();
this.#inflate.destroy();
this.#inflate = null;
if (this.#currentCallback) {
const cb = this.#currentCallback;
this.#currentCallback = null;
cb(new MessageSizeExceededError$1());
}
return;
}
this.#inflate[kBuffer].push(data$1);
});
this.#inflate.on("error", (err) => {
this.#inflate = null;
callback$1(err);
});
}
this.#currentCallback = callback$1;
this.#inflate.write(chunk);
if (fin) this.#inflate.write(tail);
this.#inflate.flush(() => {
if (this.#aborted || !this.#inflate) return;
const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
this.#inflate[kBuffer].length = 0;
this.#inflate[kLength] = 0;
this.#currentCallback = null;
callback$1(null, full);
});
}
};
module.exports = { PerMessageDeflate: PerMessageDeflate$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/receiver.js
var require_receiver = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/receiver.js": ((exports, module) => {
const { Writable } = __require$2("node:stream");
const assert$1 = __require$2("node:assert");
const { parserStates, opcodes: opcodes$3, states: states$2, emptyBuffer, sentCloseFrameState: sentCloseFrameState$2 } = require_constants$1();
const { isValidStatusCode, isValidOpcode, websocketMessageReceived, utf8Decode: utf8Decode$2, isControlFrame, isTextBinaryFrame, isContinuationFrame } = require_util$1();
const { failWebsocketConnection: failWebsocketConnection$2 } = require_connection();
const { WebsocketFrameSend: WebsocketFrameSend$3 } = require_frame();
const { PerMessageDeflate } = require_permessage_deflate();
const { MessageSizeExceededError } = require_errors();
var ByteParser$2 = class extends Writable {
#buffers = [];
#fragmentsBytes = 0;
#byteOffset = 0;
#loop = false;
#state = parserStates.INFO;
#info = {};
#fragments = [];
/** @type {Map<string, PerMessageDeflate>} */
#extensions;
/** @type {import('./websocket').Handler} */
#handler;
/**
* @param {import('./websocket').Handler} handler
* @param {Map<string, string>|null} extensions
*/
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, _, callback$1) {
this.#buffers.push(chunk);
this.#byteOffset += chunk.length;
this.#loop = true;
this.run(callback$1);
}
/**
* 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$1) {
while (this.#loop) if (this.#state === parserStates.INFO) {
if (this.#byteOffset < 2) return callback$1();
const buffer$1 = this.consume(2);
const fin = (buffer$1[0] & 128) !== 0;
const opcode = buffer$1[0] & 15;
const masked = (buffer$1[1] & 128) === 128;
const fragmented = !fin && opcode !== opcodes$3.CONTINUATION;
const payloadLength = buffer$1[1] & 127;
const rsv1 = buffer$1[0] & 64;
const rsv2 = buffer$1[0] & 32;
const rsv3 = buffer$1[0] & 16;
if (!isValidOpcode(opcode)) {
failWebsocketConnection$2(this.#handler, 1002, "Invalid opcode received");
return callback$1();
}
if (masked) {
failWebsocketConnection$2(this.#handler, 1002, "Frame cannot be masked");
return callback$1();
}
if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
failWebsocketConnection$2(this.#handler, 1002, "Expected RSV1 to be clear.");
return;
}
if (rsv2 !== 0 || rsv3 !== 0) {
failWebsocketConnection$2(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear");
return;
}
if (fragmented && !isTextBinaryFrame(opcode)) {
failWebsocketConnection$2(this.#handler, 1002, "Invalid frame type was fragmented.");
return;
}
if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
failWebsocketConnection$2(this.#handler, 1002, "Expected continuation frame");
return;
}
if (this.#info.fragmented && fragmented) {
failWebsocketConnection$2(this.#handler, 1002, "Fragmented frame exceeded 125 bytes.");
return;
}
if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
failWebsocketConnection$2(this.#handler, 1002, "Control frame either too large or fragmented");
return;
}
if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
failWebsocketConnection$2(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$1();
const buffer$1 = this.consume(2);
this.#info.payloadLength = buffer$1.readUInt16BE(0);
this.#state = parserStates.READ_DATA;
} else if (this.#state === parserStates.PAYLOADLENGTH_64) {
if (this.#byteOffset < 8) return callback$1();
const buffer$1 = this.consume(8);
const upper = buffer$1.readUInt32BE(0);
const lower = buffer$1.readUInt32BE(4);
if (upper !== 0 || lower > 2 ** 31 - 1) {
failWebsocketConnection$2(this.#handler, 1009, "Received payload length > 2^31 bytes.");
return;
}
this.#info.payloadLength = lower;
this.#state = parserStates.READ_DATA;
} else if (this.#state === parserStates.READ_DATA) {
if (this.#byteOffset < this.#info.payloadLength) return callback$1();
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, (error, data$1) => {
if (error) {
const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
failWebsocketConnection$2(this.#handler, code, error.message);
return;
}
this.writeFragments(data$1);
if (!this.#info.fin) {
this.#state = parserStates.INFO;
this.#loop = true;
this.run(callback$1);
return;
}
websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
this.#loop = true;
this.#state = parserStates.INFO;
this.run(callback$1);
});
this.#loop = false;
break;
}
}
}
/**
* Take n bytes from the buffered Buffers
* @param {number} n
* @returns {Buffer}
*/
consume(n$1) {
if (n$1 > this.#byteOffset) throw new Error("Called consume() before buffers satiated.");
else if (n$1 === 0) return emptyBuffer;
this.#byteOffset -= n$1;
const first = this.#buffers[0];
if (first.length > n$1) {
this.#buffers[0] = first.subarray(n$1, first.length);
return first.subarray(0, n$1);
} else if (first.length === n$1) return this.#buffers.shift();
else {
let offset = 0;
const buffer$1 = Buffer.allocUnsafeSlow(n$1);
while (offset !== n$1) {
const next = this.#buffers[0];
const length = next.length;
if (length + offset === n$1) {
buffer$1.set(this.#buffers.shift(), offset);
break;
} else if (length + offset > n$1) {
buffer$1.set(next.subarray(0, n$1 - offset), offset);
this.#buffers[0] = next.subarray(n$1 - offset);
break;
} else {
buffer$1.set(this.#buffers.shift(), offset);
offset += length;
}
}
return buffer$1;
}
}
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 i$1 = 0; i$1 < fragments.length; ++i$1) {
const buffer$1 = fragments[i$1];
output.set(buffer$1, offset);
offset += buffer$1.length;
}
this.#fragments = [];
this.#fragmentsBytes = 0;
return output;
}
parseCloseBody(data$1) {
assert$1(data$1.length !== 1);
/** @type {number|undefined} */
let code;
if (data$1.length >= 2) code = data$1.readUInt16BE(0);
if (code !== void 0 && !isValidStatusCode(code)) return {
code: 1002,
reason: "Invalid status code",
error: true
};
/** @type {Buffer} */
let reason = data$1.subarray(2);
if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) reason = reason.subarray(3);
try {
reason = utf8Decode$2(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$3.CLOSE) {
if (payloadLength === 1) {
failWebsocketConnection$2(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$2(this.#handler, code, reason);
return false;
}
if (!this.#handler.closeState.has(sentCloseFrameState$2.SENT) && !this.#handler.closeState.has(sentCloseFrameState$2.RECEIVED)) {
let body$1 = emptyBuffer;
if (this.#info.closeInfo.code) {
body$1 = Buffer.allocUnsafe(2);
body$1.writeUInt16BE(this.#info.closeInfo.code, 0);
}
const closeFrame = new WebsocketFrameSend$3(body$1);
this.#handler.socket.write(closeFrame.createFrame(opcodes$3.CLOSE));
this.#handler.closeState.add(sentCloseFrameState$2.SENT);
}
this.#handler.readyState = states$2.CLOSING;
this.#handler.closeState.add(sentCloseFrameState$2.RECEIVED);
return false;
} else if (opcode === opcodes$3.PING) {
if (!this.#handler.closeState.has(sentCloseFrameState$2.RECEIVED)) {
const frame = new WebsocketFrameSend$3(body);
this.#handler.socket.write(frame.createFrame(opcodes$3.PONG));
this.#handler.onPing(body);
}
} else if (opcode === opcodes$3.PONG) this.#handler.onPong(body);
return true;
}
get closingInfo() {
return this.#info.closeInfo;
}
};
module.exports = { ByteParser: ByteParser$2 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/sender.js
var require_sender = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/sender.js": ((exports, module) => {
const { WebsocketFrameSend: WebsocketFrameSend$2 } = require_frame();
const { opcodes: opcodes$2, sendHints: sendHints$1 } = require_constants$1();
const FixedQueue = require_fixed_queue();
/**
* @typedef {object} SendQueueNode
* @property {Promise<void> | null} promise
* @property {((...args: any[]) => any)} callback
* @property {Buffer | null} frame
*/
var SendQueue$1 = class {
/**
* @type {FixedQueue}
*/
#queue = new FixedQueue();
/**
* @type {boolean}
*/
#running = false;
/** @type {import('node:net').Socket} */
#socket;
constructor(socket) {
this.#socket = socket;
}
add(item, cb, hint) {
if (hint !== sendHints$1.blob) {
if (!this.#running) if (hint === sendHints$1.text) {
const { 0: head, 1: body } = WebsocketFrameSend$2.createFastTextFrame(item);
this.#socket.cork();
this.#socket.write(head);
this.#socket.write(body, cb);
this.#socket.uncork();
} else this.#socket.write(createFrame(item, hint), cb);
else {
/** @type {SendQueueNode} */
const node$1 = {
promise: null,
callback: cb,
frame: createFrame(item, hint)
};
this.#queue.push(node$1);
}
return;
}
/** @type {SendQueueNode} */
const node = {
promise: item.arrayBuffer().then((ab) => {
node.promise = null;
node.frame = createFrame(ab, hint);
}),
callback: cb,
frame: null
};
this.#queue.push(node);
if (!this.#running) this.#run();
}
async #run() {
this.#running = true;
const queue = this.#queue;
while (!queue.isEmpty()) {
const node = queue.shift();
if (node.promise !== null) await node.promise;
this.#socket.write(node.frame, node.callback);
node.callback = node.frame = null;
}
this.#running = false;
}
};
function createFrame(data$1, hint) {
return new WebsocketFrameSend$2(toBuffer(data$1, hint)).createFrame(hint === sendHints$1.text ? opcodes$2.TEXT : opcodes$2.BINARY);
}
function toBuffer(data$1, hint) {
switch (hint) {
case sendHints$1.text:
case sendHints$1.typedArray: return new Uint8Array(data$1.buffer, data$1.byteOffset, data$1.byteLength);
case sendHints$1.arrayBuffer:
case sendHints$1.blob: return new Uint8Array(data$1);
}
}
module.exports = { SendQueue: SendQueue$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/websocket.js
var require_websocket = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/websocket.js": ((exports, module) => {
const { isArrayBuffer } = __require$2("node:util/types");
const { webidl: webidl$3 } = require_webidl();
const { URLSerializer } = require_data_url();
const { environmentSettingsObject: environmentSettingsObject$2 } = require_util$4();
const { staticPropertyDescriptors, states: states$1, sentCloseFrameState: sentCloseFrameState$1, sendHints, opcodes: opcodes$1 } = require_constants$1();
const { isConnecting, isEstablished: isEstablished$1, isClosing, isClosed, isValidSubprotocol: isValidSubprotocol$1, fireEvent, utf8Decode: utf8Decode$1, toArrayBuffer, getURLRecord: getURLRecord$1 } = require_util$1();
const { establishWebSocketConnection: establishWebSocketConnection$1, closeWebSocketConnection: closeWebSocketConnection$1, failWebsocketConnection: failWebsocketConnection$1 } = require_connection();
const { ByteParser: ByteParser$1 } = require_receiver();
const { kEnumerableProperty: kEnumerableProperty$3 } = require_util$5();
const { getGlobalDispatcher: getGlobalDispatcher$1 } = require_global();
const { ErrorEvent: ErrorEvent$1, CloseEvent: CloseEvent$1, createFastMessageEvent: createFastMessageEvent$1 } = require_events();
const { SendQueue } = require_sender();
const { WebsocketFrameSend: WebsocketFrameSend$1 } = require_frame();
const { channels: channels$1 } = require_diagnostics();
function getSocketAddress(socket) {
if (typeof socket?.address === "function") return socket.address();
if (typeof socket?.session?.socket?.address === "function") return socket.session.socket.address();
return null;
}
/**
* @typedef {object} Handler
* @property {(response: any, extensions?: string[]) => void} onConnectionEstablished
* @property {(opcode: number, data: Buffer) => void} onMessage
* @property {(error: Error) => void} onParserError
* @property {() => void} onParserDrain
* @property {(chunk: Buffer) => void} onSocketData
* @property {(err: Error) => void} onSocketError
* @property {() => void} onSocketClose
* @property {(body: Buffer) => void} onPing
* @property {(body: Buffer) => void} onPong
*
* @property {number} readyState
* @property {import('stream').Duplex} socket
* @property {Set<number>} closeState
* @property {import('../fetch/index').Fetch} controller
* @property {boolean} [wasEverConnected=false]
*/
var WebSocket$1 = class WebSocket$1 extends EventTarget {
#events = {
open: null,
error: null,
close: null,
message: null
};
#bufferedAmount = 0;
#protocol = "";
#extensions = "";
/** @type {SendQueue} */
#sendQueue;
/** @type {Handler} */
#handler = {
onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions),
onMessage: (opcode, data$1) => this.#onMessage(opcode, data$1),
onParserError: (err) => failWebsocketConnection$1(this.#handler, null, err.message),
onParserDrain: () => this.#onParserDrain(),
onSocketData: (chunk) => {
if (!this.#parser.write(chunk)) this.#handler.socket.pause();
},
onSocketError: (err) => {
this.#handler.readyState = states$1.CLOSING;
if (channels$1.socketError.hasSubscribers) channels$1.socketError.publish(err);
this.#handler.socket.destroy();
},
onSocketClose: () => this.#onSocketClose(),
onPing: (body) => {
if (channels$1.ping.hasSubscribers) channels$1.ping.publish({
payload: body,
websocket: this
});
},
onPong: (body) => {
if (channels$1.pong.hasSubscribers) channels$1.pong.publish({
payload: body,
websocket: this
});
},
readyState: states$1.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(url, protocols = []) {
super();
webidl$3.util.markAsUncloneable(this);
const prefix = "WebSocket constructor";
webidl$3.argumentLengthCheck(arguments, 1, prefix);
const options = webidl$3.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols, prefix, "options");
url = webidl$3.converters.USVString(url);
protocols = options.protocols;
const baseURL = environmentSettingsObject$2.settingsObject.baseUrl;
const urlRecord = getURLRecord$1(url, baseURL);
if (typeof protocols === "string") protocols = [protocols];
if (protocols.length !== new Set(protocols.map((p$1) => p$1.toLowerCase())).size) throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
if (protocols.length > 0 && !protocols.every((p$1) => isValidSubprotocol$1(p$1))) throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
this.#url = new URL(urlRecord.href);
const client = environmentSettingsObject$2.settingsObject;
this.#handler.controller = establishWebSocketConnection$1(urlRecord, protocols, client, this.#handler, options);
this.#handler.readyState = WebSocket$1.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$3.brandCheck(this, WebSocket$1);
const prefix = "WebSocket.close";
if (code !== void 0) code = webidl$3.converters["unsigned short"](code, prefix, "code", webidl$3.attributes.Clamp);
if (reason !== void 0) reason = webidl$3.converters.USVString(reason);
code ??= null;
reason ??= "";
closeWebSocketConnection$1(this.#handler, code, reason, true);
}
/**
* @see https://websockets.spec.whatwg.org/#dom-websocket-send
* @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
*/
send(data$1) {
webidl$3.brandCheck(this, WebSocket$1);
const prefix = "WebSocket.send";
webidl$3.argumentLengthCheck(arguments, 1, prefix);
data$1 = webidl$3.converters.WebSocketSendData(data$1, prefix, "data");
if (isConnecting(this.#handler.readyState)) throw new DOMException("Sent before connected.", "InvalidStateError");
if (!isEstablished$1(this.#handler.readyState) || isClosing(this.#handler.readyState)) return;
if (typeof data$1 === "string") {
const buffer$1 = Buffer.from(data$1);
this.#bufferedAmount += buffer$1.byteLength;
this.#sendQueue.add(buffer$1, () => {
this.#bufferedAmount -= buffer$1.byteLength;
}, sendHints.text);
} else if (isArrayBuffer(data$1)) {
this.#bufferedAmount += data$1.byteLength;
this.#sendQueue.add(data$1, () => {
this.#bufferedAmount -= data$1.byteLength;
}, sendHints.arrayBuffer);
} else if (ArrayBuffer.isView(data$1)) {
this.#bufferedAmount += data$1.byteLength;
this.#sendQueue.add(data$1, () => {
this.#bufferedAmount -= data$1.byteLength;
}, sendHints.typedArray);
} else if (webidl$3.is.Blob(data$1)) {
this.#bufferedAmount += data$1.size;
this.#sendQueue.add(data$1, () => {
this.#bufferedAmount -= data$1.size;
}, sendHints.blob);
}
}
get readyState() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#handler.readyState;
}
get bufferedAmount() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#bufferedAmount;
}
get url() {
webidl$3.brandCheck(this, WebSocket$1);
return URLSerializer(this.#url);
}
get extensions() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#extensions;
}
get protocol() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#protocol;
}
get onopen() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#events.open;
}
set onopen(fn) {
webidl$3.brandCheck(this, WebSocket$1);
if (this.#events.open) this.removeEventListener("open", this.#events.open);
const listener = webidl$3.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("open", listener);
this.#events.open = fn;
} else this.#events.open = null;
}
get onerror() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#events.error;
}
set onerror(fn) {
webidl$3.brandCheck(this, WebSocket$1);
if (this.#events.error) this.removeEventListener("error", this.#events.error);
const listener = webidl$3.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("error", listener);
this.#events.error = fn;
} else this.#events.error = null;
}
get onclose() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#events.close;
}
set onclose(fn) {
webidl$3.brandCheck(this, WebSocket$1);
if (this.#events.close) this.removeEventListener("close", this.#events.close);
const listener = webidl$3.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("close", listener);
this.#events.close = fn;
} else this.#events.close = null;
}
get onmessage() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#events.message;
}
set onmessage(fn) {
webidl$3.brandCheck(this, WebSocket$1);
if (this.#events.message) this.removeEventListener("message", this.#events.message);
const listener = webidl$3.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("message", listener);
this.#events.message = fn;
} else this.#events.message = null;
}
get binaryType() {
webidl$3.brandCheck(this, WebSocket$1);
return this.#binaryType;
}
set binaryType(type) {
webidl$3.brandCheck(this, WebSocket$1);
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 parser = new ByteParser$1(this.#handler, parsedExtensions);
parser.on("drain", () => this.#handler.onParserDrain());
parser.on("error", (err) => this.#handler.onParserError(err));
this.#parser = parser;
this.#sendQueue = new SendQueue(response.socket);
this.#handler.readyState = states$1.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);
if (channels$1.open.hasSubscribers) {
const headers = response.headersList.entries;
channels$1.open.publish({
address: getSocketAddress(response.socket),
protocol: this.#protocol,
extensions: this.#extensions,
websocket: this,
handshakeResponse: {
status: response.status,
statusText: response.statusText,
headers
}
});
}
}
#onMessage(type, data$1) {
if (this.#handler.readyState !== states$1.OPEN) return;
let dataForEvent;
if (type === opcodes$1.TEXT) try {
dataForEvent = utf8Decode$1(data$1);
} catch {
failWebsocketConnection$1(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
return;
}
else if (type === opcodes$1.BINARY) if (this.#binaryType === "blob") dataForEvent = new Blob([data$1]);
else dataForEvent = toArrayBuffer(data$1);
fireEvent("message", this, createFastMessageEvent$1, {
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$1.SENT) && this.#handler.closeState.has(sentCloseFrameState$1.RECEIVED);
let code = 1005;
let reason = "";
const result = this.#parser?.closingInfo;
if (result && !result.error) {
code = result.code ?? 1005;
reason = result.reason;
}
this.#handler.readyState = states$1.CLOSED;
if (!this.#handler.closeState.has(sentCloseFrameState$1.RECEIVED)) {
code = 1006;
fireEvent("error", this, (type, init) => new ErrorEvent$1(type, init), { error: new TypeError(reason) });
}
fireEvent("close", this, (type, init) => new CloseEvent$1(type, init), {
wasClean,
code,
reason
});
if (channels$1.close.hasSubscribers) channels$1.close.publish({
websocket: this,
code,
reason
});
}
/**
* @param {WebSocket} ws
* @param {Buffer|undefined} buffer
*/
static ping(ws, buffer$1) {
if (Buffer.isBuffer(buffer$1)) {
if (buffer$1.length > 125) throw new TypeError("A PING frame cannot have a body larger than 125 bytes.");
} else if (buffer$1 !== void 0) throw new TypeError("Expected buffer payload");
const readyState = ws.#handler.readyState;
if (isEstablished$1(readyState) && !isClosing(readyState) && !isClosed(readyState)) {
const frame = new WebsocketFrameSend$1(buffer$1);
ws.#handler.socket.write(frame.createFrame(opcodes$1.PING));
}
}
};
const { ping: ping$1 } = WebSocket$1;
Reflect.deleteProperty(WebSocket$1, "ping");
WebSocket$1.CONNECTING = WebSocket$1.prototype.CONNECTING = states$1.CONNECTING;
WebSocket$1.OPEN = WebSocket$1.prototype.OPEN = states$1.OPEN;
WebSocket$1.CLOSING = WebSocket$1.prototype.CLOSING = states$1.CLOSING;
WebSocket$1.CLOSED = WebSocket$1.prototype.CLOSED = states$1.CLOSED;
Object.defineProperties(WebSocket$1.prototype, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors,
url: kEnumerableProperty$3,
readyState: kEnumerableProperty$3,
bufferedAmount: kEnumerableProperty$3,
onopen: kEnumerableProperty$3,
onerror: kEnumerableProperty$3,
onclose: kEnumerableProperty$3,
close: kEnumerableProperty$3,
onmessage: kEnumerableProperty$3,
binaryType: kEnumerableProperty$3,
send: kEnumerableProperty$3,
extensions: kEnumerableProperty$3,
protocol: kEnumerableProperty$3,
[Symbol.toStringTag]: {
value: "WebSocket",
writable: false,
enumerable: false,
configurable: true
}
});
Object.defineProperties(WebSocket$1, {
CONNECTING: staticPropertyDescriptors,
OPEN: staticPropertyDescriptors,
CLOSING: staticPropertyDescriptors,
CLOSED: staticPropertyDescriptors
});
webidl$3.converters["sequence<DOMString>"] = webidl$3.sequenceConverter(webidl$3.converters.DOMString);
webidl$3.converters["DOMString or sequence<DOMString>"] = function(V, prefix, argument) {
if (webidl$3.util.Type(V) === webidl$3.util.Types.OBJECT && Symbol.iterator in V) return webidl$3.converters["sequence<DOMString>"](V);
return webidl$3.converters.DOMString(V, prefix, argument);
};
webidl$3.converters.WebSocketInit = webidl$3.dictionaryConverter([
{
key: "protocols",
converter: webidl$3.converters["DOMString or sequence<DOMString>"],
defaultValue: () => []
},
{
key: "dispatcher",
converter: webidl$3.converters.any,
defaultValue: () => getGlobalDispatcher$1()
},
{
key: "headers",
converter: webidl$3.nullableConverter(webidl$3.converters.HeadersInit)
}
]);
webidl$3.converters["DOMString or sequence<DOMString> or WebSocketInit"] = function(V) {
if (webidl$3.util.Type(V) === webidl$3.util.Types.OBJECT && !(Symbol.iterator in V)) return webidl$3.converters.WebSocketInit(V);
return { protocols: webidl$3.converters["DOMString or sequence<DOMString>"](V) };
};
webidl$3.converters.WebSocketSendData = function(V) {
if (webidl$3.util.Type(V) === webidl$3.util.Types.OBJECT) {
if (webidl$3.is.Blob(V)) return V;
if (webidl$3.is.BufferSource(V)) return V;
}
return webidl$3.converters.USVString(V);
};
module.exports = {
WebSocket: WebSocket$1,
ping: ping$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/stream/websocketerror.js
var require_websocketerror = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/stream/websocketerror.js": ((exports, module) => {
const { webidl: webidl$2 } = require_webidl();
const { validateCloseCodeAndReason } = require_util$1();
const { kConstruct: kConstruct$1 } = require_symbols();
const { kEnumerableProperty: kEnumerableProperty$2 } = require_util$5();
function createInheritableDOMException() {
class Test extends DOMException {
get reason() {
return "";
}
}
if (new Test().reason !== void 0) return DOMException;
return new Proxy(DOMException, { construct(target$1, args, newTarget) {
const instance$1 = Reflect.construct(target$1, args, target$1);
Object.setPrototypeOf(instance$1, newTarget.prototype);
return instance$1;
} });
}
var WebSocketError$1 = class WebSocketError$1 extends createInheritableDOMException() {
#closeCode;
#reason;
constructor(message = "", init = void 0) {
message = webidl$2.converters.DOMString(message, "WebSocketError", "message");
super(message, "WebSocketError");
if (init === kConstruct$1) return;
else if (init !== null) init = webidl$2.converters.WebSocketCloseInfo(init);
let code = init.closeCode ?? null;
const reason = init.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 error = new WebSocketError$1(message, kConstruct$1);
error.#closeCode = code;
error.#reason = reason;
return error;
}
};
const { createUnvalidatedWebSocketError: createUnvalidatedWebSocketError$1 } = WebSocketError$1;
delete WebSocketError$1.createUnvalidatedWebSocketError;
Object.defineProperties(WebSocketError$1.prototype, {
closeCode: kEnumerableProperty$2,
reason: kEnumerableProperty$2,
[Symbol.toStringTag]: {
value: "WebSocketError",
writable: false,
enumerable: false,
configurable: true
}
});
webidl$2.is.WebSocketError = webidl$2.util.MakeTypeAssertion(WebSocketError$1);
module.exports = {
WebSocketError: WebSocketError$1,
createUnvalidatedWebSocketError: createUnvalidatedWebSocketError$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/stream/websocketstream.js
var require_websocketstream = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/websocket/stream/websocketstream.js": ((exports, module) => {
const { createDeferredPromise } = require_promise();
const { environmentSettingsObject: environmentSettingsObject$1 } = require_util$4();
const { states, opcodes, sentCloseFrameState } = require_constants$1();
const { webidl: webidl$1 } = require_webidl();
const { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util$1();
const { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
const { channels } = require_diagnostics();
const { WebsocketFrameSend } = require_frame();
const { ByteParser } = require_receiver();
const { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror();
const { kEnumerableProperty: kEnumerableProperty$1 } = require_util$5();
const { utf8DecodeBytes } = require_encoding();
let emittedExperimentalWarning = false;
var WebSocketStream = class {
/** @type {URL} */
#url;
/** @type {import('../../../util/promise').DeferredPromise} */
#openedPromise;
/** @type {import('../../../util/promise').DeferredPromise} */
#closedPromise;
/** @type {ReadableStream} */
#readableStream;
/** @type {ReadableStreamDefaultController} */
#readableStreamController;
/** @type {WritableStream} */
#writableStream;
#handshakeAborted = false;
/** @type {import('../websocket').Handler} */
#handler = {
onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions),
onMessage: (opcode, data$1) => this.#onMessage(opcode, data$1),
onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
onParserDrain: () => this.#handler.socket.resume(),
onSocketData: (chunk) => {
if (!this.#parser.write(chunk)) this.#handler.socket.pause();
},
onSocketError: (err) => {
this.#handler.readyState = states.CLOSING;
if (channels.socketError.hasSubscribers) channels.socketError.publish(err);
this.#handler.socket.destroy();
},
onSocketClose: () => this.#onSocketClose(),
onPing: () => {},
onPong: () => {},
readyState: states.CONNECTING,
socket: null,
closeState: /* @__PURE__ */ new Set(),
controller: null,
wasEverConnected: false
};
/** @type {import('../receiver').ByteParser} */
#parser;
constructor(url, options = void 0) {
if (!emittedExperimentalWarning) {
process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", { code: "UNDICI-WSS" });
emittedExperimentalWarning = true;
}
webidl$1.argumentLengthCheck(arguments, 1, "WebSocket");
url = webidl$1.converters.USVString(url);
if (options !== null) options = webidl$1.converters.WebSocketStreamOptions(options);
const baseURL = environmentSettingsObject$1.settingsObject.baseUrl;
const urlRecord = getURLRecord(url, baseURL);
const protocols = options.protocols;
if (protocols.length !== new Set(protocols.map((p$1) => p$1.toLowerCase())).size) throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
if (protocols.length > 0 && !protocols.every((p$1) => isValidSubprotocol(p$1))) 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$1.settingsObject;
this.#handler.controller = establishWebSocketConnection(urlRecord, protocols, client, this.#handler, options);
}
get url() {
return this.#url.toString();
}
get opened() {
return this.#openedPromise.promise;
}
get closed() {
return this.#closedPromise.promise;
}
close(closeInfo = void 0) {
if (closeInfo !== null) closeInfo = webidl$1.converters.WebSocketCloseInfo(closeInfo);
const code = closeInfo.closeCode ?? null;
const reason = closeInfo.reason;
closeWebSocketConnection(this.#handler, code, reason, true);
}
#write(chunk) {
chunk = webidl$1.converters.WebSocketStreamWrite(chunk);
const promise$1 = createDeferredPromise();
let data$1 = null;
let opcode = null;
if (webidl$1.is.BufferSource(chunk)) {
data$1 = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice());
opcode = opcodes.BINARY;
} else {
let string;
try {
string = webidl$1.converters.DOMString(chunk);
} catch (e) {
promise$1.reject(e);
return promise$1.promise;
}
data$1 = 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$1);
this.#handler.socket.write(frame.createFrame(opcode), () => {
promise$1.resolve(void 0);
});
}
return promise$1.promise;
}
/** @type {import('../websocket').Handler['onConnectionEstablished']} */
#onConnectionEstablished(response, parsedExtensions) {
this.#handler.socket = response.socket;
const parser = new ByteParser(this.#handler, parsedExtensions);
parser.on("drain", () => this.#handler.onParserDrain());
parser.on("error", (err) => this.#handler.onParserError(err));
this.#parser = parser;
this.#handler.readyState = states.OPEN;
const extensions = parsedExtensions ?? "";
const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
const readable = new ReadableStream({
start: (controller) => {
this.#readableStreamController = controller;
},
pull(controller) {
let chunk;
while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) controller.enqueue(chunk);
},
cancel: (reason) => this.#cancel(reason)
});
const writable = new WritableStream({
write: (chunk) => this.#write(chunk),
close: () => closeWebSocketConnection(this.#handler, null, null),
abort: (reason) => this.#closeUsingReason(reason)
});
this.#readableStream = readable;
this.#writableStream = writable;
this.#openedPromise.resolve({
extensions,
protocol,
readable,
writable
});
}
/** @type {import('../websocket').Handler['onMessage']} */
#onMessage(type, data$1) {
if (this.#handler.readyState !== states.OPEN) return;
let chunk;
if (type === opcodes.TEXT) try {
chunk = utf8Decode(data$1);
} catch {
failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
return;
}
else if (type === opcodes.BINARY) chunk = new Uint8Array(data$1.buffer, data$1.byteOffset, data$1.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.#readableStreamController.close();
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 error = createUnvalidatedWebSocketError("unclean close", code, reason);
this.#readableStreamController?.error(error);
this.#writableStream?.abort(error);
this.#closedPromise.reject(error);
}
}
#closeUsingReason(reason) {
let code = null;
let reasonString = "";
if (webidl$1.is.WebSocketError(reason)) {
code = reason.closeCode;
reasonString = reason.reason;
}
closeWebSocketConnection(this.#handler, code, reasonString);
}
#cancel(reason) {
this.#closeUsingReason(reason);
}
};
Object.defineProperties(WebSocketStream.prototype, {
url: kEnumerableProperty$1,
opened: kEnumerableProperty$1,
closed: kEnumerableProperty$1,
close: kEnumerableProperty$1,
[Symbol.toStringTag]: {
value: "WebSocketStream",
writable: false,
enumerable: false,
configurable: true
}
});
webidl$1.converters.WebSocketStreamOptions = webidl$1.dictionaryConverter([{
key: "protocols",
converter: webidl$1.sequenceConverter(webidl$1.converters.USVString),
defaultValue: () => []
}, {
key: "signal",
converter: webidl$1.nullableConverter(webidl$1.converters.AbortSignal),
defaultValue: () => null
}]);
webidl$1.converters.WebSocketCloseInfo = webidl$1.dictionaryConverter([{
key: "closeCode",
converter: (V) => webidl$1.converters["unsigned short"](V, webidl$1.attributes.EnforceRange)
}, {
key: "reason",
converter: webidl$1.converters.USVString,
defaultValue: () => ""
}]);
webidl$1.converters.WebSocketStreamWrite = function(V) {
if (typeof V === "string") return webidl$1.converters.USVString(V);
return webidl$1.converters.BufferSource(V);
};
module.exports = { WebSocketStream };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/util.js
var require_util = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/util.js": ((exports, module) => {
/**
* Checks if the given value is a valid LastEventId.
* @param {string} value
* @returns {boolean}
*/
function isValidLastEventId$1(value) {
return value.indexOf("\0") === -1;
}
/**
* Checks if the given value is a base 10 digit.
* @param {string} value
* @returns {boolean}
*/
function isASCIINumber$1(value) {
if (value.length === 0) return false;
for (let i$1 = 0; i$1 < value.length; i$1++) if (value.charCodeAt(i$1) < 48 || value.charCodeAt(i$1) > 57) return false;
return true;
}
module.exports = {
isValidLastEventId: isValidLastEventId$1,
isASCIINumber: isASCIINumber$1
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/eventsource-stream.js": ((exports, module) => {
const { Transform } = __require$2("node:stream");
const { isASCIINumber, isValidLastEventId } = require_util();
/**
* @type {number[]} BOM
*/
const BOM = [
239,
187,
191
];
/**
* @type {10} LF
*/
const LF = 10;
/**
* @type {13} CR
*/
const CR = 13;
/**
* @type {58} COLON
*/
const COLON = 58;
/**
* @type {32} SPACE
*/
const SPACE$1 = 32;
/**
* @typedef {object} EventSourceStreamEvent
* @type {object}
* @property {string} [event] The event type.
* @property {string} [data] The data of the message.
* @property {string} [id] A unique ID for the event.
* @property {string} [retry] The reconnection time, in milliseconds.
*/
/**
* @typedef eventSourceSettings
* @type {object}
* @property {string} [lastEventId] The last event ID received from the server.
* @property {string} [origin] The origin of the event source.
* @property {number} [reconnectionTime] The reconnection time, in milliseconds.
*/
var EventSourceStream$1 = class extends Transform {
/**
* @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$1) {
if (chunk.length === 0) {
callback$1();
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$1();
return;
}
this.checkBOM = false;
callback$1();
return;
case 2:
if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
callback$1();
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$1();
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 !== void 0 || 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$1();
}
/**
* @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] === SPACE$1) ++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] += `\n${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 !== void 0 && 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
};
}
};
module.exports = { EventSourceStream: EventSourceStream$1 };
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/lib/web/eventsource/eventsource.js": ((exports, module) => {
const { pipeline } = __require$2("node:stream");
const { fetching } = require_fetch();
const { makeRequest } = require_request();
const { webidl } = require_webidl();
const { EventSourceStream } = require_eventsource_stream();
const { parseMIMEType: parseMIMEType$1 } = require_data_url();
const { createFastMessageEvent } = require_events();
const { isNetworkError } = require_response();
const { kEnumerableProperty } = require_util$5();
const { environmentSettingsObject } = require_util$4();
let experimentalWarned = false;
/**
* A reconnection time, in milliseconds. This must initially be an implementation-defined value,
* probably in the region of a few seconds.
*
* In Comparison:
* - Chrome uses 3000ms.
* - Deno uses 5000ms.
*
* @type {3000}
*/
const defaultReconnectionTime = 3e3;
/**
* The readyState attribute represents the state of the connection.
* @typedef ReadyState
* @type {0|1|2}
* @readonly
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
*/
/**
* The connection has not yet been established, or it was closed and the user
* agent is reconnecting.
* @type {0}
*/
const CONNECTING = 0;
/**
* The user agent has an open connection and is dispatching events as it
* receives them.
* @type {1}
*/
const OPEN = 1;
/**
* The connection is not open, and the user agent is not trying to reconnect.
* @type {2}
*/
const CLOSED = 2;
/**
* Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
* @type {'anonymous'}
*/
const ANONYMOUS = "anonymous";
/**
* Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
* @type {'use-credentials'}
*/
const USE_CREDENTIALS = "use-credentials";
/**
* The EventSource interface is used to receive server-sent events. It
* connects to a server over HTTP and receives events in text/event-stream
* format without closing the connection.
* @extends {EventTarget}
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
* @api public
*/
var EventSource$1 = class EventSource$1 extends EventTarget {
#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(url, 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" });
}
url = webidl.converters.USVString(url);
eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher;
this.#state = {
lastEventId: "",
reconnectionTime: eventSourceInitDict.node.reconnectionTime
};
const settings = environmentSettingsObject;
let urlRecord;
try {
urlRecord = new URL(url, settings.settingsObject.baseUrl);
this.#state.origin = urlRecord.origin;
} catch (e) {
throw new DOMException(e, "SyntaxError");
}
this.#url = urlRecord.href;
let corsAttributeState = ANONYMOUS;
if (eventSourceInitDict.withCredentials === true) {
corsAttributeState = USE_CREDENTIALS;
this.#withCredentials = true;
}
const initRequest = {
redirect: "follow",
keepalive: true,
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 = (response) => {
if (!isNetworkError(response)) return this.#reconnect();
};
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$1(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: (event) => {
this.dispatchEvent(createFastMessageEvent(event.type, event.options));
}
});
pipeline(response.body.stream, eventSourceStream, (error) => {
if (error?.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 {void}
*/
#reconnect() {
if (this.#readyState === CLOSED) return;
this.#readyState = CONNECTING;
this.dispatchEvent(new Event("error"));
setTimeout(() => {
if (this.#readyState !== CONNECTING) return;
if (this.#state.lastEventId.length) this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
this.#connect();
}, this.#state.reconnectionTime)?.unref();
}
/**
* Closes the connection, if any, and sets the readyState attribute to
* CLOSED.
*/
close() {
webidl.brandCheck(this, EventSource$1);
if (this.#readyState === CLOSED) return;
this.#readyState = CLOSED;
this.#controller.abort();
this.#request = null;
}
get onopen() {
return this.#events.open;
}
set onopen(fn) {
if (this.#events.open) this.removeEventListener("open", this.#events.open);
const listener = webidl.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("open", listener);
this.#events.open = fn;
} else this.#events.open = null;
}
get onmessage() {
return this.#events.message;
}
set onmessage(fn) {
if (this.#events.message) this.removeEventListener("message", this.#events.message);
const listener = webidl.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("message", listener);
this.#events.message = fn;
} else this.#events.message = null;
}
get onerror() {
return this.#events.error;
}
set onerror(fn) {
if (this.#events.error) this.removeEventListener("error", this.#events.error);
const listener = webidl.converters.EventHandlerNonNull(fn);
if (listener !== null) {
this.addEventListener("error", listener);
this.#events.error = fn;
} else this.#events.error = null;
}
};
const 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$1, constantsPropertyDescriptors);
Object.defineProperties(EventSource$1.prototype, constantsPropertyDescriptors);
Object.defineProperties(EventSource$1.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: () => false
},
{
key: "dispatcher",
converter: webidl.converters.any
},
{
key: "node",
converter: webidl.dictionaryConverter([{
key: "reconnectionTime",
converter: webidl.converters["unsigned long"],
defaultValue: () => defaultReconnectionTime
}, {
key: "dispatcher",
converter: webidl.converters.any
}]),
defaultValue: () => ({})
}
]);
module.exports = {
EventSource: EventSource$1,
defaultReconnectionTime
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/index.js
var require_undici = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/undici@7.24.8/node_modules/undici/index.js": ((exports, module) => {
const Client = require_client();
const Dispatcher = require_dispatcher();
const Pool = require_pool();
const BalancedPool = require_balanced_pool();
const RoundRobinPool = require_round_robin_pool();
const Agent = require_agent();
const ProxyAgent = require_proxy_agent();
const Socks5ProxyAgent = require_socks5_proxy_agent();
const EnvHttpProxyAgent = require_env_http_proxy_agent();
const RetryAgent = require_retry_agent();
const H2CClient = require_h2c_client();
const errors = require_errors();
const util$3 = require_util$5();
const { InvalidArgumentError } = errors;
const api = require_api();
const buildConnector = require_connect();
const MockClient = require_mock_client();
const { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
const MockAgent = require_mock_agent();
const MockPool = require_mock_pool();
const SnapshotAgent = require_snapshot_agent();
const mockErrors = require_mock_errors();
const RetryHandler = require_retry_handler();
const { getGlobalDispatcher, setGlobalDispatcher } = require_global();
const DecoratorHandler = require_decorator_handler();
const RedirectHandler = require_redirect_handler();
Object.assign(Dispatcher.prototype, api);
module.exports.Dispatcher = Dispatcher;
module.exports.Client = Client;
module.exports.Pool = Pool;
module.exports.BalancedPool = BalancedPool;
module.exports.RoundRobinPool = RoundRobinPool;
module.exports.Agent = Agent;
module.exports.ProxyAgent = ProxyAgent;
module.exports.Socks5ProxyAgent = Socks5ProxyAgent;
module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
module.exports.RetryAgent = RetryAgent;
module.exports.H2CClient = H2CClient;
module.exports.RetryHandler = RetryHandler;
module.exports.DecoratorHandler = DecoratorHandler;
module.exports.RedirectHandler = RedirectHandler;
module.exports.interceptors = {
redirect: require_redirect(),
responseError: require_response_error(),
retry: require_retry(),
dump: require_dump(),
dns: require_dns(),
cache: require_cache$1(),
decompress: require_decompress(),
deduplicate: require_deduplicate()
};
module.exports.cacheStores = { MemoryCacheStore: require_memory_cache_store() };
const SqliteCacheStore = require_sqlite_cache_store();
module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
module.exports.buildConnector = buildConnector;
module.exports.errors = errors;
module.exports.util = {
parseHeaders: util$3.parseHeaders,
headerNameToString: util$3.headerNameToString
};
function makeDispatcher(fn) {
return (url, opts, handler) => {
if (typeof opts === "function") {
handler = opts;
opts = null;
}
if (!url || typeof url !== "string" && typeof url !== "object" && !(url 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 path$2 = opts.path;
if (!opts.path.startsWith("/")) path$2 = `/${path$2}`;
url = new URL(util$3.parseOrigin(url).origin + path$2);
} else {
if (!opts) opts = typeof url === "object" ? url : {};
url = util$3.parseURL(url);
}
const { agent, dispatcher = getGlobalDispatcher() } = opts;
if (agent) throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
return fn.call(dispatcher, {
...opts,
origin: url.origin,
path: url.search ? `${url.pathname}${url.search}` : url.pathname,
method: opts.method || (opts.body ? "PUT" : "GET")
}, handler);
};
}
module.exports.setGlobalDispatcher = setGlobalDispatcher;
module.exports.getGlobalDispatcher = getGlobalDispatcher;
const fetchImpl = require_fetch().fetch;
const currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
function appendFetchStackTrace(err, filename) {
if (!err || typeof err !== "object") return;
const stack = typeof err.stack === "string" ? err.stack : "";
const normalizedFilename = filename.replace(/\\/g, "/");
if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) return;
const capture = {};
Error.captureStackTrace(capture, appendFetchStackTrace);
if (!capture.stack) return;
const captureLines = capture.stack.split("\n").slice(1).join("\n");
err.stack = stack ? `${stack}\n${captureLines}` : capture.stack;
}
module.exports.fetch = function fetch$3(init, options = void 0) {
return fetchImpl(init, options).catch((err) => {
if (currentFilename) appendFetchStackTrace(err, currentFilename);
else if (err && typeof err === "object") Error.captureStackTrace(err, module.exports.fetch);
throw err;
});
};
module.exports.Headers = require_headers().Headers;
module.exports.Response = require_response().Response;
module.exports.Request = require_request().Request;
module.exports.FormData = require_formdata().FormData;
const { setGlobalOrigin, getGlobalOrigin } = require_global$1();
module.exports.setGlobalOrigin = setGlobalOrigin;
module.exports.getGlobalOrigin = getGlobalOrigin;
const { CacheStorage } = require_cachestorage();
const { kConstruct } = require_symbols();
module.exports.caches = new CacheStorage(kConstruct);
const { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies();
module.exports.deleteCookie = deleteCookie;
module.exports.getCookies = getCookies;
module.exports.getSetCookies = getSetCookies;
module.exports.setCookie = setCookie;
module.exports.parseCookie = parseCookie;
const { parseMIMEType, serializeAMimeType } = require_data_url();
module.exports.parseMIMEType = parseMIMEType;
module.exports.serializeAMimeType = serializeAMimeType;
const { CloseEvent, ErrorEvent, MessageEvent } = require_events();
const { WebSocket, ping } = require_websocket();
module.exports.WebSocket = WebSocket;
module.exports.CloseEvent = CloseEvent;
module.exports.ErrorEvent = ErrorEvent;
module.exports.MessageEvent = MessageEvent;
module.exports.ping = ping;
module.exports.WebSocketStream = require_websocketstream().WebSocketStream;
module.exports.WebSocketError = require_websocketerror().WebSocketError;
module.exports.request = makeDispatcher(api.request);
module.exports.stream = makeDispatcher(api.stream);
module.exports.pipeline = makeDispatcher(api.pipeline);
module.exports.connect = makeDispatcher(api.connect);
module.exports.upgrade = makeDispatcher(api.upgrade);
module.exports.MockClient = MockClient;
module.exports.MockCallHistory = MockCallHistory;
module.exports.MockCallHistoryLog = MockCallHistoryLog;
module.exports.MockPool = MockPool;
module.exports.MockAgent = MockAgent;
module.exports.SnapshotAgent = SnapshotAgent;
module.exports.mockErrors = mockErrors;
const { EventSource } = require_eventsource();
module.exports.EventSource = EventSource;
function install() {
globalThis.fetch = module.exports.fetch;
globalThis.Headers = module.exports.Headers;
globalThis.Response = module.exports.Response;
globalThis.Request = module.exports.Request;
globalThis.FormData = module.exports.FormData;
globalThis.WebSocket = module.exports.WebSocket;
globalThis.CloseEvent = module.exports.CloseEvent;
globalThis.ErrorEvent = module.exports.ErrorEvent;
globalThis.MessageEvent = module.exports.MessageEvent;
globalThis.EventSource = module.exports.EventSource;
}
module.exports.install = install;
}) });
//#endregion
//#region ../workers-utils/dist/index.mjs
var import_undici = require_undici();
var require_XDGAppPaths = __commonJS({ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/lib/XDGAppPaths.js"(exports$1) {
exports$1.__esModule = true;
exports$1.Adapt = void 0;
function isBoolean2(t2) {
return typeOf(t2) === "boolean";
}
__name(isBoolean2, "isBoolean");
function isObject$2(t2) {
return typeOf(t2) === "object";
}
__name(isObject$2, "isObject");
function isString2(t2) {
return typeOf(t2) === "string";
}
__name(isString2, "isString");
function typeOf(t2) {
return typeof t2;
}
__name(typeOf, "typeOf");
function Adapt(adapter_) {
var meta = adapter_.meta, path4 = adapter_.path, xdg = adapter_.xdg;
return { XDGAppPaths: new (/* @__PURE__ */ function() {
function XDGAppPaths_2(options_) {
if (options_ === void 0) options_ = {};
var _a, _b, _c;
function XDGAppPaths(options2) {
if (options2 === void 0) options2 = {};
return new XDGAppPaths_2(options2);
}
__name(XDGAppPaths, "XDGAppPaths");
var options = isObject$2(options_) ? options_ : { name: options_ };
var suffix = (_a = options.suffix) !== null && _a !== void 0 ? _a : "";
var isolated_ = (_b = options.isolated) !== null && _b !== void 0 ? _b : true;
var namePriorityList = [
options.name,
meta.pkgMainFilename(),
meta.mainFilename()
];
var name = path4.parse(((_c = namePriorityList.find(function(e2) {
return isString2(e2);
})) !== null && _c !== void 0 ? _c : "$eval") + suffix).name;
XDGAppPaths.$name = /* @__PURE__ */ __name(function $name() {
return name;
}, "$name");
XDGAppPaths.$isolated = /* @__PURE__ */ __name(function $isolated() {
return isolated_;
}, "$isolated");
function isIsolated(dirOptions) {
var _a2;
dirOptions = dirOptions !== null && dirOptions !== void 0 ? dirOptions : { isolated: isolated_ };
return isBoolean2(dirOptions) ? dirOptions : (_a2 = dirOptions.isolated) !== null && _a2 !== void 0 ? _a2 : isolated_;
}
__name(isIsolated, "isIsolated");
function finalPathSegment(dirOptions) {
return isIsolated(dirOptions) ? name : "";
}
__name(finalPathSegment, "finalPathSegment");
XDGAppPaths.cache = /* @__PURE__ */ __name(function cache$2(dirOptions) {
return path4.join(xdg.cache(), finalPathSegment(dirOptions));
}, "cache");
XDGAppPaths.config = /* @__PURE__ */ __name(function config(dirOptions) {
return path4.join(xdg.config(), finalPathSegment(dirOptions));
}, "config");
XDGAppPaths.data = /* @__PURE__ */ __name(function data$1(dirOptions) {
return path4.join(xdg.data(), finalPathSegment(dirOptions));
}, "data");
XDGAppPaths.runtime = /* @__PURE__ */ __name(function runtime(dirOptions) {
return xdg.runtime() ? path4.join(xdg.runtime(), finalPathSegment(dirOptions)) : void 0;
}, "runtime");
XDGAppPaths.state = /* @__PURE__ */ __name(function state(dirOptions) {
return path4.join(xdg.state(), finalPathSegment(dirOptions));
}, "state");
XDGAppPaths.configDirs = /* @__PURE__ */ __name(function configDirs(dirOptions) {
return xdg.configDirs().map(function(s) {
return path4.join(s, finalPathSegment(dirOptions));
});
}, "configDirs");
XDGAppPaths.dataDirs = /* @__PURE__ */ __name(function dataDirs(dirOptions) {
return xdg.dataDirs().map(function(s) {
return path4.join(s, finalPathSegment(dirOptions));
});
}, "dataDirs");
return XDGAppPaths;
}
__name(XDGAppPaths_2, "XDGAppPaths_");
return XDGAppPaths_2;
}())() };
}
__name(Adapt, "Adapt");
exports$1.Adapt = Adapt;
} });
var require_XDG = __commonJS({ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/lib/XDG.js"(exports$1) {
var __spreadArray = exports$1 && exports$1.__spreadArray || function(to, from) {
for (var i$1 = 0, il = from.length, j = to.length; i$1 < il; i$1++, j++) to[j] = from[i$1];
return to;
};
exports$1.__esModule = true;
exports$1.Adapt = void 0;
function Adapt(adapter_) {
var env$1 = adapter_.env, osPaths = adapter_.osPaths, path4 = 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(val, pathSegments) {
return val || path4.join.apply(path4, pathSegments);
}
__name(valOrPath, "valOrPath");
var linux = /* @__PURE__ */ __name(function() {
return {
cache: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
}, "cache"),
config: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
}, "config"),
data: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_DATA_HOME"), [
baseDir(),
".local",
"share"
]);
}, "data"),
runtime: /* @__PURE__ */ __name(function() {
return env$1.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime"),
state: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_STATE_HOME"), [
baseDir(),
".local",
"state"
]);
}, "state")
};
}, "linux");
var macos = /* @__PURE__ */ __name(function() {
return {
cache: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CACHE_HOME"), [
baseDir(),
"Library",
"Caches"
]);
}, "cache"),
config: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CONFIG_HOME"), [
baseDir(),
"Library",
"Preferences"
]);
}, "config"),
data: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_DATA_HOME"), [
baseDir(),
"Library",
"Application Support"
]);
}, "data"),
runtime: /* @__PURE__ */ __name(function() {
return env$1.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime"),
state: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_STATE_HOME"), [
baseDir(),
"Library",
"State"
]);
}, "state")
};
}, "macos");
var windows = /* @__PURE__ */ __name(function() {
function appData() {
return valOrPath(env$1.get("APPDATA"), [
baseDir(),
"AppData",
"Roaming"
]);
}
__name(appData, "appData");
function localAppData() {
return valOrPath(env$1.get("LOCALAPPDATA"), [
baseDir(),
"AppData",
"Local"
]);
}
__name(localAppData, "localAppData");
return {
cache: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CACHE_HOME"), [localAppData(), "xdg.cache"]);
}, "cache"),
config: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_CONFIG_HOME"), [appData(), "xdg.config"]);
}, "config"),
data: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_DATA_HOME"), [appData(), "xdg.data"]);
}, "data"),
runtime: /* @__PURE__ */ __name(function() {
return env$1.get("XDG_RUNTIME_DIR") || void 0;
}, "runtime"),
state: /* @__PURE__ */ __name(function() {
return valOrPath(env$1.get("XDG_STATE_HOME"), [localAppData(), "xdg.state"]);
}, "state")
};
}, "windows");
return { XDG: new (/* @__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 = env$1.get("XDG_CONFIG_DIRS");
return __spreadArray([extension.config()], pathList ? pathList.split(path4.delimiter) : []);
}, "configDirs");
XDG.dataDirs = /* @__PURE__ */ __name(function dataDirs() {
var pathList = env$1.get("XDG_DATA_DIRS");
return __spreadArray([extension.data()], pathList ? pathList.split(path4.delimiter) : []);
}, "dataDirs");
return XDG;
}
__name(XDG_2, "XDG_");
return XDG_2;
}())() };
}
__name(Adapt, "Adapt");
exports$1.Adapt = Adapt;
} });
var require_OSPaths = __commonJS({ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/lib/OSPaths.js"(exports$1) {
var __spreadArray = exports$1 && exports$1.__spreadArray || function(to, from) {
for (var i$1 = 0, il = from.length, j = to.length; i$1 < il; i$1++, j++) to[j] = from[i$1];
return to;
};
exports$1.__esModule = true;
exports$1.Adapt = void 0;
function isEmpty(s) {
return !s;
}
__name(isEmpty, "isEmpty");
function Adapt(adapter_) {
var env$1 = adapter_.env, os2 = adapter_.os, path4 = adapter_.path;
var isWinOS = /^win/i.test(adapter_.process.platform);
function normalizePath$2(path_) {
return path_ ? adapter_.path.normalize(adapter_.path.join(path_, ".")) : void 0;
}
__name(normalizePath$2, "normalizePath");
function home() {
return isWinOS ? (/* @__PURE__ */ __name(function() {
return normalizePath$2([
typeof os2.homedir === "function" ? os2.homedir() : void 0,
env$1.get("USERPROFILE"),
env$1.get("HOME"),
env$1.get("HOMEDRIVE") || env$1.get("HOMEPATH") ? path4.join(env$1.get("HOMEDRIVE") || "", env$1.get("HOMEPATH") || "") : void 0
].find(function(v) {
return !isEmpty(v);
}));
}, "windows"))() : (/* @__PURE__ */ __name(function() {
return normalizePath$2((typeof os2.homedir === "function" ? os2.homedir() : void 0) || env$1.get("HOME"));
}, "posix"))();
}
__name(home, "home");
function temp() {
function joinPathToBase(base, segments) {
return base ? path4.join.apply(path4, __spreadArray([base], segments)) : void 0;
}
__name(joinPathToBase, "joinPathToBase");
function posix$1() {
return normalizePath$2([
typeof os2.tmpdir === "function" ? os2.tmpdir() : void 0,
env$1.get("TMPDIR"),
env$1.get("TEMP"),
env$1.get("TMP")
].find(function(v) {
return !isEmpty(v);
})) || "/tmp";
}
__name(posix$1, "posix");
function windows() {
var fallback = "C:\\Temp";
var v = [
typeof os2.tmpdir === "function" ? os2.tmpdir : function() {},
function() {
return env$1.get("TEMP");
},
function() {
return env$1.get("TMP");
},
function() {
return joinPathToBase(env$1.get("LOCALAPPDATA"), ["Temp"]);
},
function() {
return joinPathToBase(home(), [
"AppData",
"Local",
"Temp"
]);
},
function() {
return joinPathToBase(env$1.get("ALLUSERSPROFILE"), ["Temp"]);
},
function() {
return joinPathToBase(env$1.get("SystemRoot"), ["Temp"]);
},
function() {
return joinPathToBase(env$1.get("windir"), ["Temp"]);
},
function() {
return joinPathToBase(env$1.get("SystemDrive"), ["\\", "Temp"]);
}
].find(function(v2) {
return v2 && !isEmpty(v2());
});
return v && normalizePath$2(v()) || fallback;
}
__name(windows, "windows");
return isWinOS ? windows() : posix$1();
}
__name(temp, "temp");
return { OSPaths: new (/* @__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;
}())() };
}
__name(Adapt, "Adapt");
exports$1.Adapt = Adapt;
} });
var require_node = __commonJS({ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/platform-adapters/node.js"(exports$1) {
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: /* @__PURE__ */ __name(function() {
return m[k];
}, "get")
});
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports$1 && exports$1.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports$1 && exports$1.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
exports$1.__esModule = true;
exports$1.adapter = void 0;
var os2 = __importStar(__require$1("os"));
var path4 = __importStar(__require$1("path"));
exports$1.adapter = {
atImportPermissions: { env: true },
env: { get: /* @__PURE__ */ __name(function(s) {
return process.env[s];
}, "get") },
os: os2,
path: path4,
process
};
} });
var require_mod_cjs = __commonJS({ "../../node_modules/.pnpm/os-paths@7.4.0/node_modules/os-paths/dist/cjs/mod.cjs.js"(exports$1, module$1) {
var OSPaths_js_1 = require_OSPaths();
var node_js_1 = require_node();
module$1.exports = OSPaths_js_1.Adapt(node_js_1.adapter).OSPaths;
} });
var require_node2 = __commonJS({ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/platform-adapters/node.js"(exports$1) {
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: /* @__PURE__ */ __name(function() {
return m[k];
}, "get")
});
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports$1 && exports$1.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports$1 && exports$1.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports$1 && exports$1.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
exports$1.__esModule = true;
exports$1.adapter = void 0;
var path4 = __importStar(__require$1("path"));
var os_paths_1 = __importDefault(require_mod_cjs());
exports$1.adapter = {
atImportPermissions: { env: true },
env: { get: /* @__PURE__ */ __name(function(s) {
return process.env[s];
}, "get") },
osPaths: os_paths_1["default"],
path: path4,
process
};
} });
var require_mod_cjs2 = __commonJS({ "../../node_modules/.pnpm/xdg-portable@10.6.0/node_modules/xdg-portable/dist/cjs/mod.cjs.js"(exports$1, module$1) {
var XDG_js_1 = require_XDG();
var node_js_1 = require_node2();
module$1.exports = XDG_js_1.Adapt(node_js_1.adapter).XDG;
} });
var require_node3 = __commonJS({ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/platform-adapters/node.js"(exports$1) {
var __createBinding = exports$1 && exports$1.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, {
enumerable: true,
get: /* @__PURE__ */ __name(function() {
return m[k];
}, "get")
});
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports$1 && exports$1.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports$1 && exports$1.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports$1 && exports$1.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
exports$1.__esModule = true;
exports$1.adapter = void 0;
var path4 = __importStar(__require$1("path"));
var xdg_portable_1 = __importDefault(require_mod_cjs2());
exports$1.adapter = {
atImportPermissions: {
env: true,
read: true
},
meta: {
mainFilename: /* @__PURE__ */ __name(function() {
var requireMainFilename = (typeof __require$1 !== "undefined" && __require$1 !== null && __require$1.main ? __require$1.main : { filename: void 0 }).filename;
return (requireMainFilename !== process.execArgv[0] ? requireMainFilename : void 0) || (typeof process._eval === "undefined" ? process.argv[1] : void 0);
}, "mainFilename"),
pkgMainFilename: /* @__PURE__ */ __name(function() {
return process.pkg ? process.execPath : void 0;
}, "pkgMainFilename")
},
path: path4,
process,
xdg: xdg_portable_1["default"]
};
} });
var require_mod_cjs3 = __commonJS({ "../../node_modules/.pnpm/xdg-app-paths@8.3.0/node_modules/xdg-app-paths/dist/cjs/mod.cjs.js"(exports$1, module$1) {
var XDGAppPaths_js_1 = require_XDGAppPaths();
var node_js_1 = require_node3();
module$1.exports = XDGAppPaths_js_1.Adapt(node_js_1.adapter).XDGAppPaths;
} });
var require_command_exists = __commonJS({ "../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/lib/command-exists.js"(exports$1, module$1) {
var exec = __require$1("child_process").exec;
var execSync = __require$1("child_process").execSync;
var fs2 = __require$1("fs");
var path4 = __require$1("path");
var access = fs2.access;
var accessSync2 = fs2.accessSync;
var constants2 = fs2.constants || fs2;
var isUsingWindows = process.platform == "win32";
var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback$1) {
access(commandName, constants2.F_OK, function(err) {
callback$1(!err);
});
}, "fileNotExists");
var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
try {
accessSync2(commandName, constants2.F_OK);
return false;
} catch (e2) {
return true;
}
}, "fileNotExistsSync");
var localExecutable = /* @__PURE__ */ __name(function(commandName, callback$1) {
access(commandName, constants2.F_OK | constants2.X_OK, function(err) {
callback$1(null, !err);
});
}, "localExecutable");
var localExecutableSync = /* @__PURE__ */ __name(function(commandName) {
try {
accessSync2(commandName, constants2.F_OK | constants2.X_OK);
return true;
} catch (e2) {
return false;
}
}, "localExecutableSync");
var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback$1) {
fileNotExists(commandName, function(isFile) {
if (!isFile) {
exec("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }", function(error, stdout, stderr) {
callback$1(null, !!stdout);
});
return;
}
localExecutable(commandName, callback$1);
});
}, "commandExistsUnix");
var commandExistsWindows = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback$1) {
if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
callback$1(null, false);
return;
}
exec("where " + cleanedCommandName, function(error) {
if (error !== null) callback$1(null, false);
else callback$1(null, true);
});
}, "commandExistsWindows");
var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
if (fileNotExistsSync(commandName)) try {
return !!execSync("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }");
} catch (error) {
return false;
}
return localExecutableSync(commandName);
}, "commandExistsUnixSync");
var commandExistsWindowsSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback$1) {
if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) return false;
try {
return !!execSync("where " + cleanedCommandName, { stdio: [] });
} catch (error) {
return false;
}
}, "commandExistsWindowsSync");
var cleanInput = /* @__PURE__ */ __name(function(s) {
if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
s = "'" + s.replace(/'/g, "'\\''") + "'";
s = s.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
}
return s;
}, "cleanInput");
if (isUsingWindows) cleanInput = /* @__PURE__ */ __name(function(s) {
if (/[\\]/.test(s)) {
var dirname2 = "\"" + path4.dirname(s) + "\"";
var basename$1 = "\"" + path4.basename(s) + "\"";
return dirname2 + ":" + basename$1;
}
return "\"" + s + "\"";
}, "cleanInput");
module$1.exports = /* @__PURE__ */ __name(function commandExists(commandName, callback$1) {
var cleanedCommandName = cleanInput(commandName);
if (!callback$1 && typeof Promise !== "undefined") return new Promise(function(resolve$4, reject) {
commandExists(commandName, function(error, output) {
if (output) resolve$4(commandName);
else reject(error);
});
});
if (isUsingWindows) commandExistsWindows(commandName, cleanedCommandName, callback$1);
else commandExistsUnix(commandName, cleanedCommandName, callback$1);
}, "commandExists");
module$1.exports.sync = function(commandName) {
var cleanedCommandName = cleanInput(commandName);
if (isUsingWindows) return commandExistsWindowsSync(commandName, cleanedCommandName);
else return commandExistsUnixSync(commandName, cleanedCommandName);
};
} });
var require_command_exists2 = __commonJS({ "../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/index.js"(exports$1, module$1) {
module$1.exports = require_command_exists();
} });
var defaultWranglerConfig = {
configPath: void 0,
userConfigPath: void 0,
topLevelName: void 0,
definedEnvironments: void 0,
targetEnvironment: void 0,
pages_build_output_dir: void 0,
send_metrics: void 0,
dev: {
ip: process.platform === "win32" ? "127.0.0.1" : "localhost",
port: void 0,
inspector_port: void 0,
inspector_ip: void 0,
local_protocol: "http",
upstream_protocol: "http",
host: void 0,
enable_containers: true,
container_engine: void 0,
generate_types: false
},
name: void 0,
compatibility_date: void 0,
compatibility_flags: [],
limits: void 0,
placement: void 0,
vars: {},
durable_objects: { bindings: [] },
kv_namespaces: [],
queues: {
producers: [],
consumers: []
},
r2_buckets: [],
d1_databases: [],
vectorize: [],
ai_search_namespaces: [],
ai_search: [],
hyperdrive: [],
workflows: [],
secrets_store_secrets: [],
artifacts: [],
services: [],
analytics_engine_datasets: [],
ai: void 0,
images: void 0,
stream: void 0,
media: void 0,
version_metadata: void 0,
unsafe_hello_world: [],
flagship: [],
ratelimits: [],
worker_loaders: [],
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,
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: void 0,
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 },
cache: void 0,
compliance_region: void 0,
python_modules: { exclude: ["**/*.pyc"] },
previews: void 0,
define: {},
cloudchamber: {},
containers: void 0,
send_email: [],
browser: void 0,
unsafe: {},
mtls_certificates: [],
tail_consumers: void 0,
streaming_tail_consumers: void 0,
pipelines: [],
vpc_services: [],
vpc_networks: []
};
var PatchConfigError = class extends Error {
static {
__name(this, "PatchConfigError");
}
};
var util$2;
(function(util2) {
util2.assertEqual = (val) => val;
function assertIs(_arg) {}
__name(assertIs, "assertIs");
util2.assertIs = assertIs;
function assertNever2(_x) {
throw new Error();
}
__name(assertNever2, "assertNever");
util2.assertNever = assertNever2;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) obj[item] = item;
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) filtered[k] = obj[k];
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function(e2) {
return obj[e2];
});
};
util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
const keys = [];
for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) if (checker(item)) return item;
};
util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
__name(joinValues, "joinValues");
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_2, value) => {
if (typeof value === "bigint") return value.toString();
return value;
};
})(util$2 || (util$2 = {}));
var objectUtil$1;
(function(objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil$1 || (objectUtil$1 = {}));
var ZodParsedType$1 = util$2.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
var getParsedType$1 = /* @__PURE__ */ __name((data$1) => {
switch (typeof data$1) {
case "undefined": return ZodParsedType$1.undefined;
case "string": return ZodParsedType$1.string;
case "number": return isNaN(data$1) ? ZodParsedType$1.nan : ZodParsedType$1.number;
case "boolean": return ZodParsedType$1.boolean;
case "function": return ZodParsedType$1.function;
case "bigint": return ZodParsedType$1.bigint;
case "symbol": return ZodParsedType$1.symbol;
case "object":
if (Array.isArray(data$1)) return ZodParsedType$1.array;
if (data$1 === null) return ZodParsedType$1.null;
if (data$1.then && typeof data$1.then === "function" && data$1.catch && typeof data$1.catch === "function") return ZodParsedType$1.promise;
if (typeof Map !== "undefined" && data$1 instanceof Map) return ZodParsedType$1.map;
if (typeof Set !== "undefined" && data$1 instanceof Set) return ZodParsedType$1.set;
if (typeof Date !== "undefined" && data$1 instanceof Date) return ZodParsedType$1.date;
return ZodParsedType$1.object;
default: return ZodParsedType$1.unknown;
}
}, "getParsedType");
var ZodIssueCode$1 = util$2.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
var quotelessJson = /* @__PURE__ */ __name((obj) => {
return JSON.stringify(obj, null, 2).replace(/"([^"]+)":/g, "$1:");
}, "quotelessJson");
var ZodError$1 = 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((error) => {
for (const issue of error.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 i$1 = 0;
while (i$1 < issue.path.length) {
const el = issue.path[i$1];
if (!(i$1 === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i$1++;
}
}
}, "processError");
processError(this);
return fieldErrors;
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util$2.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$1.create = (issues) => {
return new ZodError$1(issues);
};
var errorMap$1 = /* @__PURE__ */ __name((issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode$1.invalid_type:
if (issue.received === ZodParsedType$1.undefined) message = "Required";
else message = `Expected ${issue.expected}, received ${issue.received}`;
break;
case ZodIssueCode$1.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$2.jsonStringifyReplacer)}`;
break;
case ZodIssueCode$1.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util$2.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode$1.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode$1.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util$2.joinValues(issue.options)}`;
break;
case ZodIssueCode$1.invalid_enum_value:
message = `Invalid enum value. Expected ${util$2.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode$1.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode$1.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode$1.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode$1.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$2.assertNever(issue.validation);
else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
else message = "Invalid";
break;
case ZodIssueCode$1.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$1.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$1.custom:
message = `Invalid input`;
break;
case ZodIssueCode$1.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode$1.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode$1.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util$2.assertNever(issue);
}
return { message };
}, "errorMap");
var overrideErrorMap$1 = errorMap$1;
function setErrorMap(map) {
overrideErrorMap$1 = map;
}
__name(setErrorMap, "setErrorMap");
function getErrorMap$1() {
return overrideErrorMap$1;
}
__name(getErrorMap$1, "getErrorMap");
var makeIssue$1 = /* @__PURE__ */ __name((params) => {
const { data: data$1, path: path4, errorMaps, issueData } = params;
const fullPath = [...path4, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) errorMessage = map(fullIssue, {
data: data$1,
defaultError: errorMessage
}).message;
return {
...issueData,
path: fullPath,
message: issueData.message || errorMessage
};
}, "makeIssue");
var EMPTY_PATH = [];
function addIssueToContext$1(ctx, issueData) {
const issue = makeIssue$1({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap$1(),
errorMap$1
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
__name(addIssueToContext$1, "addIssueToContext");
var ParseStatus$1 = 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(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted") return INVALID$1;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return {
status: status.value,
value: arrayValue
};
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) syncPairs.push({
key: await pair.key,
value: await pair.value
});
return _ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID$1;
if (value.status === "aborted") return INVALID$1;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
}
return {
status: status.value,
value: finalObject
};
}
};
var INVALID$1 = Object.freeze({ status: "aborted" });
var DIRTY$1 = /* @__PURE__ */ __name((value) => ({
status: "dirty",
value
}), "DIRTY");
var OK$1 = /* @__PURE__ */ __name((value) => ({
status: "valid",
value
}), "OK");
var isAborted$1 = /* @__PURE__ */ __name((x) => x.status === "aborted", "isAborted");
var isDirty$1 = /* @__PURE__ */ __name((x) => x.status === "dirty", "isDirty");
var isValid$1 = /* @__PURE__ */ __name((x) => x.status === "valid", "isValid");
var isAsync$1 = /* @__PURE__ */ __name((x) => typeof Promise !== "undefined" && x instanceof Promise, "isAsync");
var errorUtil$1;
(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$1 || (errorUtil$1 = {}));
var ParseInputLazyPath$1 = class {
static {
__name(this, "ParseInputLazyPath");
}
constructor(parent, value, path4, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path4;
this._key = key;
}
get path() {
if (!this._cachedPath.length) if (this._key instanceof Array) this._cachedPath.push(...this._path, ...this._key);
else this._cachedPath.push(...this._path, this._key);
return this._cachedPath;
}
};
var handleResult$1 = /* @__PURE__ */ __name((ctx, result) => {
if (isValid$1(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;
this._error = new ZodError$1(ctx.common.issues);
return this._error;
}
};
}
}, "handleResult");
function processCreateParams$1(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
};
return {
errorMap: /* @__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"),
description
};
}
__name(processCreateParams$1, "processCreateParams");
var ZodType$1 = 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$1(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType$1(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus$1(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType$1(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync$1(result)) throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data$1, params) {
const result = this.safeParse(data$1, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data$1, params) {
var _a;
const ctx = {
common: {
issues: [],
async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: data$1,
parsedType: getParsedType$1(data$1)
};
return handleResult$1(ctx, this._parseSync({
data: data$1,
path: ctx.path,
parent: ctx
}));
}
async parseAsync(data$1, params) {
const result = await this.safeParseAsync(data$1, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data$1, 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: data$1,
parsedType: getParsedType$1(data$1)
};
const maybeAsyncResult = this._parse({
data: data$1,
path: ctx.path,
parent: ctx
});
return handleResult$1(ctx, await (isAsync$1(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)));
}
refine(check, message) {
const getIssueProperties = /* @__PURE__ */ __name((val) => {
if (typeof message === "string" || typeof message === "undefined") return { message };
else if (typeof message === "function") return message(val);
else return message;
}, "getIssueProperties");
return this._refinement((val, ctx) => {
const result = check(val);
const setError = /* @__PURE__ */ __name(() => ctx.addIssue({
code: ZodIssueCode$1.custom,
...getIssueProperties(val)
}), "setError");
if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data$1) => {
if (!data$1) {
setError();
return false;
} else return true;
});
if (!result) {
setError();
return false;
} else return true;
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else return true;
});
}
_refinement(refinement) {
return new ZodEffects$1({
schema: this,
typeName: ZodFirstPartyTypeKind$1.ZodEffects,
effect: {
type: "refinement",
refinement
}
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional$1.create(this, this._def);
}
nullable() {
return ZodNullable$1.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray$1.create(this, this._def);
}
promise() {
return ZodPromise$1.create(this, this._def);
}
or(option) {
return ZodUnion$1.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection$1.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects$1({
...processCreateParams$1(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind$1.ZodEffects,
effect: {
type: "transform",
transform
}
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault$1({
...processCreateParams$1(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind$1.ZodDefault
});
}
brand() {
return new ZodBranded$1({
typeName: ZodFirstPartyTypeKind$1.ZodBranded,
type: this,
...processCreateParams$1(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch$1({
...processCreateParams$1(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind$1.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target$1) {
return ZodPipeline$1.create(this, target$1);
}
readonly() {
return ZodReadonly$1.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
var cuidRegex$1 = /^c[^\s-]{8,}$/i;
var cuid2Regex$1 = /^[a-z][a-z0-9]*$/;
var ulidRegex$1 = /[0-9A-HJKMNP-TV-Z]{26}/;
var uuidRegex$1 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var emailRegex$1 = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var emojiRegex$1 = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u;
var ipv4Regex$1 = /^(((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}))$/;
var ipv6Regex$1 = /^(([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})))$/;
var datetimeRegex$1 = /* @__PURE__ */ __name((args) => {
if (args.precision) if (args.offset) return /* @__PURE__ */ 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 /* @__PURE__ */ 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 /* @__PURE__ */ new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
else return /* @__PURE__ */ new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
else if (args.offset) return /* @__PURE__ */ new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
else return /* @__PURE__ */ new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
}, "datetimeRegex");
function isValidIP$1(ip, version$2) {
if ((version$2 === "v4" || !version$2) && ipv4Regex$1.test(ip)) return true;
if ((version$2 === "v6" || !version$2) && ipv6Regex$1.test(ip)) return true;
return false;
}
__name(isValidIP$1, "isValidIP");
var ZodString$1 = class _ZodString extends ZodType$1 {
static {
__name(this, "ZodString");
}
constructor() {
super(...arguments);
this._regex = (regex, validation, message) => this.refinement((data$1) => regex.test(data$1), {
validation,
code: ZodIssueCode$1.invalid_string,
...errorUtil$1.errToObj(message)
});
this.nonempty = (message) => this.min(1, errorUtil$1.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);
if (this._getType(input) !== ZodParsedType$1.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext$1(ctx2, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.string,
received: ctx2.parsedType
});
return INVALID$1;
}
const status = new ParseStatus$1();
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$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.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$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
else if (tooSmall) addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "email",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "emoji",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "uuid",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "cuid",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "cuid2",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex$1.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "ulid",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "url") try {
new URL(input.data);
} catch (_a) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "url",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
else if (check.kind === "regex") {
check.regex.lastIndex = 0;
if (!check.regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "regex",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.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$1(ctx, {
code: ZodIssueCode$1.invalid_string,
validation: {
includes: check.value,
position: check.position
},
message: check.message
});
status.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$1(ctx, {
code: ZodIssueCode$1.invalid_string,
validation: { startsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_string,
validation: { endsWith: check.value },
message: check.message
});
status.dirty();
}
} else if (check.kind === "datetime") {
if (!datetimeRegex$1(check).test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP$1(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
validation: "ip",
code: ZodIssueCode$1.invalid_string,
message: check.message
});
status.dirty();
}
} else util$2.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_addCheck(check) {
return new _ZodString({
...this._def,
checks: [...this._def.checks, check]
});
}
email(message) {
return this._addCheck({
kind: "email",
...errorUtil$1.errToObj(message)
});
}
url(message) {
return this._addCheck({
kind: "url",
...errorUtil$1.errToObj(message)
});
}
emoji(message) {
return this._addCheck({
kind: "emoji",
...errorUtil$1.errToObj(message)
});
}
uuid(message) {
return this._addCheck({
kind: "uuid",
...errorUtil$1.errToObj(message)
});
}
cuid(message) {
return this._addCheck({
kind: "cuid",
...errorUtil$1.errToObj(message)
});
}
cuid2(message) {
return this._addCheck({
kind: "cuid2",
...errorUtil$1.errToObj(message)
});
}
ulid(message) {
return this._addCheck({
kind: "ulid",
...errorUtil$1.errToObj(message)
});
}
ip(options) {
return this._addCheck({
kind: "ip",
...errorUtil$1.errToObj(options)
});
}
datetime(options) {
var _a;
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: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
...errorUtil$1.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil$1.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options === null || options === void 0 ? void 0 : options.position,
...errorUtil$1.errToObj(options === null || options === void 0 ? void 0 : options.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil$1.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil$1.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil$1.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil$1.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil$1.errToObj(message)
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodString$1.create = (params) => {
var _a;
return new ZodString$1({
checks: [],
typeName: ZodFirstPartyTypeKind$1.ZodString,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams$1(params)
});
};
function floatSafeRemainder$1(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
return parseInt(val.toFixed(decCount).replace(".", "")) % parseInt(step.toFixed(decCount).replace(".", "")) / Math.pow(10, decCount);
}
__name(floatSafeRemainder$1, "floatSafeRemainder");
var ZodNumber$1 = class _ZodNumber extends ZodType$1 {
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);
if (this._getType(input) !== ZodParsedType$1.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext$1(ctx2, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.number,
received: ctx2.parsedType
});
return INVALID$1;
}
let ctx = void 0;
const status = new ParseStatus$1();
for (const check of this._def.checks) if (check.kind === "int") {
if (!util$2.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder$1(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.not_finite,
message: check.message
});
status.dirty();
}
} else util$2.assertNever(check);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil$1.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil$1.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil$1.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil$1.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil$1.toString(message)
}]
});
}
_addCheck(check) {
return new _ZodNumber({
...this._def,
checks: [...this._def.checks, check]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil$1.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil$1.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil$1.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil$1.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil$1.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil$1.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil$1.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil$1.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil$1.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util$2.isInteger(ch.value));
}
get isFinite() {
let max = null, min = null;
for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
else if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber$1.create = (params) => {
return new ZodNumber$1({
checks: [],
typeName: ZodFirstPartyTypeKind$1.ZodNumber,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams$1(params)
});
};
var ZodBigInt$1 = class _ZodBigInt extends ZodType$1 {
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);
if (this._getType(input) !== ZodParsedType$1.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext$1(ctx2, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.bigint,
received: ctx2.parsedType
});
return INVALID$1;
}
let ctx = void 0;
const status = new ParseStatus$1();
for (const check of this._def.checks) if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else util$2.assertNever(check);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil$1.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil$1.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil$1.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil$1.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new _ZodBigInt({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil$1.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$1.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil$1.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil$1.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil$1.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil$1.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodBigInt$1.create = (params) => {
var _a;
return new ZodBigInt$1({
checks: [],
typeName: ZodFirstPartyTypeKind$1.ZodBigInt,
coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
...processCreateParams$1(params)
});
};
var ZodBoolean$1 = class extends ZodType$1 {
static {
__name(this, "ZodBoolean");
}
_parse(input) {
if (this._def.coerce) input.data = Boolean(input.data);
if (this._getType(input) !== ZodParsedType$1.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.boolean,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1(input.data);
}
};
ZodBoolean$1.create = (params) => {
return new ZodBoolean$1({
typeName: ZodFirstPartyTypeKind$1.ZodBoolean,
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams$1(params)
});
};
var ZodDate$1 = class _ZodDate extends ZodType$1 {
static {
__name(this, "ZodDate");
}
_parse(input) {
if (this._def.coerce) input.data = new Date(input.data);
if (this._getType(input) !== ZodParsedType$1.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext$1(ctx2, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.date,
received: ctx2.parsedType
});
return INVALID$1;
}
if (isNaN(input.data.getTime())) {
addIssueToContext$1(this._getOrReturnCtx(input), { code: ZodIssueCode$1.invalid_date });
return INVALID$1;
}
const status = new ParseStatus$1();
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$1(ctx, {
code: ZodIssueCode$1.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else util$2.assertNever(check);
return {
status: status.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$1.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil$1.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max != null ? new Date(max) : null;
}
};
ZodDate$1.create = (params) => {
return new ZodDate$1({
checks: [],
coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind$1.ZodDate,
...processCreateParams$1(params)
});
};
var ZodSymbol$1 = class extends ZodType$1 {
static {
__name(this, "ZodSymbol");
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.symbol,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1(input.data);
}
};
ZodSymbol$1.create = (params) => {
return new ZodSymbol$1({
typeName: ZodFirstPartyTypeKind$1.ZodSymbol,
...processCreateParams$1(params)
});
};
var ZodUndefined$1 = class extends ZodType$1 {
static {
__name(this, "ZodUndefined");
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.undefined,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1(input.data);
}
};
ZodUndefined$1.create = (params) => {
return new ZodUndefined$1({
typeName: ZodFirstPartyTypeKind$1.ZodUndefined,
...processCreateParams$1(params)
});
};
var ZodNull$1 = class extends ZodType$1 {
static {
__name(this, "ZodNull");
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.null,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1(input.data);
}
};
ZodNull$1.create = (params) => {
return new ZodNull$1({
typeName: ZodFirstPartyTypeKind$1.ZodNull,
...processCreateParams$1(params)
});
};
var ZodAny$1 = class extends ZodType$1 {
static {
__name(this, "ZodAny");
}
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK$1(input.data);
}
};
ZodAny$1.create = (params) => {
return new ZodAny$1({
typeName: ZodFirstPartyTypeKind$1.ZodAny,
...processCreateParams$1(params)
});
};
var ZodUnknown$1 = class extends ZodType$1 {
static {
__name(this, "ZodUnknown");
}
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK$1(input.data);
}
};
ZodUnknown$1.create = (params) => {
return new ZodUnknown$1({
typeName: ZodFirstPartyTypeKind$1.ZodUnknown,
...processCreateParams$1(params)
});
};
var ZodNever$1 = class extends ZodType$1 {
static {
__name(this, "ZodNever");
}
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.never,
received: ctx.parsedType
});
return INVALID$1;
}
};
ZodNever$1.create = (params) => {
return new ZodNever$1({
typeName: ZodFirstPartyTypeKind$1.ZodNever,
...processCreateParams$1(params)
});
};
var ZodVoid$1 = class extends ZodType$1 {
static {
__name(this, "ZodVoid");
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.void,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1(input.data);
}
};
ZodVoid$1.create = (params) => {
return new ZodVoid$1({
typeName: ZodFirstPartyTypeKind$1.ZodVoid,
...processCreateParams$1(params)
});
};
var ZodArray$1 = class _ZodArray extends ZodType$1 {
static {
__name(this, "ZodArray");
}
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType$1.array) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.array,
received: ctx.parsedType
});
return INVALID$1;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext$1(ctx, {
code: tooBig ? ZodIssueCode$1.too_big : ZodIssueCode$1.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) return Promise.all([...ctx.data].map((item, i$1) => {
return def.type._parseAsync(new ParseInputLazyPath$1(ctx, item, ctx.path, i$1));
})).then((result2) => {
return ParseStatus$1.mergeArray(status, result2);
});
const result = [...ctx.data].map((item, i$1) => {
return def.type._parseSync(new ParseInputLazyPath$1(ctx, item, ctx.path, i$1));
});
return ParseStatus$1.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new _ZodArray({
...this._def,
minLength: {
value: minLength,
message: errorUtil$1.toString(message)
}
});
}
max(maxLength, message) {
return new _ZodArray({
...this._def,
maxLength: {
value: maxLength,
message: errorUtil$1.toString(message)
}
});
}
length(len, message) {
return new _ZodArray({
...this._def,
exactLength: {
value: len,
message: errorUtil$1.toString(message)
}
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray$1.create = (schema, params) => {
return new ZodArray$1({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind$1.ZodArray,
...processCreateParams$1(params)
});
};
function deepPartialify$1(schema) {
if (schema instanceof ZodObject$1) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional$1.create(deepPartialify$1(fieldSchema));
}
return new ZodObject$1({
...schema._def,
shape: /* @__PURE__ */ __name(() => newShape, "shape")
});
} else if (schema instanceof ZodArray$1) return new ZodArray$1({
...schema._def,
type: deepPartialify$1(schema.element)
});
else if (schema instanceof ZodOptional$1) return ZodOptional$1.create(deepPartialify$1(schema.unwrap()));
else if (schema instanceof ZodNullable$1) return ZodNullable$1.create(deepPartialify$1(schema.unwrap()));
else if (schema instanceof ZodTuple$1) return ZodTuple$1.create(schema.items.map((item) => deepPartialify$1(item)));
else return schema;
}
__name(deepPartialify$1, "deepPartialify");
var ZodObject$1 = class _ZodObject extends ZodType$1 {
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();
return this._cached = {
shape,
keys: util$2.objectKeys(shape)
};
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext$1(ctx2, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.object,
received: ctx2.parsedType
});
return INVALID$1;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever$1 && 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$1(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever$1) {
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$1(ctx, {
code: ZodIssueCode$1.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip");
else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: catchall._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, key)),
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$1.mergeObjectSync(status, syncPairs);
});
else return ParseStatus$1.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil$1.errToObj;
return new _ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? { errorMap: /* @__PURE__ */ __name((issue, ctx) => {
var _a, _b, _c, _d;
const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;
if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil$1.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError };
return { message: defaultError };
}, "errorMap") } : {}
});
}
strip() {
return new _ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new _ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
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) {
return new _ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: /* @__PURE__ */ __name(() => ({
...this._def.shape(),
...merging._def.shape()
}), "shape"),
typeName: ZodFirstPartyTypeKind$1.ZodObject
});
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new _ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
util$2.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$2.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$1(this);
}
partial(mask) {
const newShape = {};
util$2.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$2.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) newShape[key] = this.shape[key];
else {
let newField = this.shape[key];
while (newField instanceof ZodOptional$1) newField = newField._def.innerType;
newShape[key] = newField;
}
});
return new _ZodObject({
...this._def,
shape: /* @__PURE__ */ __name(() => newShape, "shape")
});
}
keyof() {
return createZodEnum$1(util$2.objectKeys(this.shape));
}
};
ZodObject$1.create = (shape, params) => {
return new ZodObject$1({
shape: /* @__PURE__ */ __name(() => shape, "shape"),
unknownKeys: "strip",
catchall: ZodNever$1.create(),
typeName: ZodFirstPartyTypeKind$1.ZodObject,
...processCreateParams$1(params)
});
};
ZodObject$1.strictCreate = (shape, params) => {
return new ZodObject$1({
shape: /* @__PURE__ */ __name(() => shape, "shape"),
unknownKeys: "strict",
catchall: ZodNever$1.create(),
typeName: ZodFirstPartyTypeKind$1.ZodObject,
...processCreateParams$1(params)
});
};
ZodObject$1.lazycreate = (shape, params) => {
return new ZodObject$1({
shape,
unknownKeys: "strip",
catchall: ZodNever$1.create(),
typeName: ZodFirstPartyTypeKind$1.ZodObject,
...processCreateParams$1(params)
});
};
var ZodUnion$1 = class extends ZodType$1 {
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$1(result.ctx.common.issues));
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_union,
unionErrors
});
return INVALID$1;
}
__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$1(issues2));
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_union,
unionErrors
});
return INVALID$1;
}
}
get options() {
return this._def.options;
}
};
ZodUnion$1.create = (types$4, params) => {
return new ZodUnion$1({
options: types$4,
typeName: ZodFirstPartyTypeKind$1.ZodUnion,
...processCreateParams$1(params)
});
};
var getDiscriminator$1 = /* @__PURE__ */ __name((type) => {
if (type instanceof ZodLazy$1) return getDiscriminator$1(type.schema);
else if (type instanceof ZodEffects$1) return getDiscriminator$1(type.innerType());
else if (type instanceof ZodLiteral$1) return [type.value];
else if (type instanceof ZodEnum$1) return type.options;
else if (type instanceof ZodNativeEnum$1) return Object.keys(type.enum);
else if (type instanceof ZodDefault$1) return getDiscriminator$1(type._def.innerType);
else if (type instanceof ZodUndefined$1) return [void 0];
else if (type instanceof ZodNull$1) return [null];
else return null;
}, "getDiscriminator");
var ZodDiscriminatedUnion$1 = class _ZodDiscriminatedUnion extends ZodType$1 {
static {
__name(this, "ZodDiscriminatedUnion");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.object) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.object,
received: ctx.parsedType
});
return INVALID$1;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID$1;
}
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$1(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$1.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams$1(params)
});
}
};
function mergeValues$1(a, b) {
const aType = getParsedType$1(a);
const bType = getParsedType$1(b);
if (a === b) return {
valid: true,
data: a
};
else if (aType === ZodParsedType$1.object && bType === ZodParsedType$1.object) {
const bKeys = util$2.objectKeys(b);
const sharedKeys = util$2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
for (const key of sharedKeys) {
const sharedValue = mergeValues$1(a[key], b[key]);
if (!sharedValue.valid) return { valid: false };
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
} else if (aType === ZodParsedType$1.array && bType === ZodParsedType$1.array) {
if (a.length !== b.length) return { valid: false };
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues$1(itemA, itemB);
if (!sharedValue.valid) return { valid: false };
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
} else if (aType === ZodParsedType$1.date && bType === ZodParsedType$1.date && +a === +b) return {
valid: true,
data: a
};
else return { valid: false };
}
__name(mergeValues$1, "mergeValues");
var ZodIntersection$1 = class extends ZodType$1 {
static {
__name(this, "ZodIntersection");
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = /* @__PURE__ */ __name((parsedLeft, parsedRight) => {
if (isAborted$1(parsedLeft) || isAborted$1(parsedRight)) return INVALID$1;
const merged = mergeValues$1(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext$1(ctx, { code: ZodIssueCode$1.invalid_intersection_types });
return INVALID$1;
}
if (isDirty$1(parsedLeft) || isDirty$1(parsedRight)) status.dirty();
return {
status: status.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(([left, right]) => handleParsed(left, right));
else return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
};
ZodIntersection$1.create = (left, right, params) => {
return new ZodIntersection$1({
left,
right,
typeName: ZodFirstPartyTypeKind$1.ZodIntersection,
...processCreateParams$1(params)
});
};
var ZodTuple$1 = class _ZodTuple extends ZodType$1 {
static {
__name(this, "ZodTuple");
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.array) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.array,
received: ctx.parsedType
});
return INVALID$1;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID$1;
}
if (!this._def.rest && ctx.data.length > this._def.items.length) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) return Promise.all(items).then((results) => {
return ParseStatus$1.mergeArray(status, results);
});
else return ParseStatus$1.mergeArray(status, items);
}
get items() {
return this._def.items;
}
rest(rest) {
return new _ZodTuple({
...this._def,
rest
});
}
};
ZodTuple$1.create = (schemas, params) => {
if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
return new ZodTuple$1({
items: schemas,
typeName: ZodFirstPartyTypeKind$1.ZodTuple,
rest: null,
...processCreateParams$1(params)
});
};
var ZodRecord$1 = class _ZodRecord extends ZodType$1 {
static {
__name(this, "ZodRecord");
}
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.object) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.object,
received: ctx.parsedType
});
return INVALID$1;
}
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$1(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath$1(ctx, ctx.data[key], ctx.path, key))
});
if (ctx.common.async) return ParseStatus$1.mergeObjectAsync(status, pairs);
else return ParseStatus$1.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType$1) return new _ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind$1.ZodRecord,
...processCreateParams$1(third)
});
return new _ZodRecord({
keyType: ZodString$1.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind$1.ZodRecord,
...processCreateParams$1(second)
});
}
};
var ZodMap$1 = class extends ZodType$1 {
static {
__name(this, "ZodMap");
}
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.map) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.map,
received: ctx.parsedType
});
return INVALID$1;
}
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$1(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath$1(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$1;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID$1;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
}
}
};
ZodMap$1.create = (keyType, valueType, params) => {
return new ZodMap$1({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind$1.ZodMap,
...processCreateParams$1(params)
});
};
var ZodSet$1 = class _ZodSet extends ZodType$1 {
static {
__name(this, "ZodSet");
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.set) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.set,
received: ctx.parsedType
});
return INVALID$1;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements2) {
if (element.status === "aborted") return INVALID$1;
if (element.status === "dirty") status.dirty();
parsedSet.add(element.value);
}
return {
status: status.value,
value: parsedSet
};
}
__name(finalizeSet, "finalizeSet");
const elements = [...ctx.data.values()].map((item, i$1) => valueType._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, i$1)));
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$1.toString(message)
}
});
}
max(maxSize, message) {
return new _ZodSet({
...this._def,
maxSize: {
value: maxSize,
message: errorUtil$1.toString(message)
}
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet$1.create = (valueType, params) => {
return new ZodSet$1({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind$1.ZodSet,
...processCreateParams$1(params)
});
};
var ZodFunction$1 = class _ZodFunction extends ZodType$1 {
static {
__name(this, "ZodFunction");
}
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.function) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.function,
received: ctx.parsedType
});
return INVALID$1;
}
function makeArgsIssue(args, error) {
return makeIssue$1({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap$1(),
errorMap$1
].filter((x) => !!x),
issueData: {
code: ZodIssueCode$1.invalid_arguments,
argumentsError: error
}
});
}
__name(makeArgsIssue, "makeArgsIssue");
function makeReturnsIssue(returns, error) {
return makeIssue$1({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap$1(),
errorMap$1
].filter((x) => !!x),
issueData: {
code: ZodIssueCode$1.invalid_return_type,
returnTypeError: error
}
});
}
__name(makeReturnsIssue, "makeReturnsIssue");
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise$1) {
const me = this;
return OK$1(async function(...args) {
const error = new ZodError$1([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
error.addIssue(makeArgsIssue(args, e2));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
return await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
error.addIssue(makeReturnsIssue(result, e2));
throw error;
});
});
} else {
const me = this;
return OK$1(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) throw new ZodError$1([makeArgsIssue(args, parsedArgs.error)]);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) throw new ZodError$1([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$1.create(items).rest(ZodUnknown$1.create())
});
}
returns(returnType) {
return new _ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
return this.parse(func);
}
strictImplement(func) {
return this.parse(func);
}
static create(args, returns, params) {
return new _ZodFunction({
args: args ? args : ZodTuple$1.create([]).rest(ZodUnknown$1.create()),
returns: returns || ZodUnknown$1.create(),
typeName: ZodFirstPartyTypeKind$1.ZodFunction,
...processCreateParams$1(params)
});
}
};
var ZodLazy$1 = class extends ZodType$1 {
static {
__name(this, "ZodLazy");
}
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
return this._def.getter()._parse({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
};
ZodLazy$1.create = (getter, params) => {
return new ZodLazy$1({
getter,
typeName: ZodFirstPartyTypeKind$1.ZodLazy,
...processCreateParams$1(params)
});
};
var ZodLiteral$1 = class extends ZodType$1 {
static {
__name(this, "ZodLiteral");
}
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
received: ctx.data,
code: ZodIssueCode$1.invalid_literal,
expected: this._def.value
});
return INVALID$1;
}
return {
status: "valid",
value: input.data
};
}
get value() {
return this._def.value;
}
};
ZodLiteral$1.create = (value, params) => {
return new ZodLiteral$1({
value,
typeName: ZodFirstPartyTypeKind$1.ZodLiteral,
...processCreateParams$1(params)
});
};
function createZodEnum$1(values, params) {
return new ZodEnum$1({
values,
typeName: ZodFirstPartyTypeKind$1.ZodEnum,
...processCreateParams$1(params)
});
}
__name(createZodEnum$1, "createZodEnum");
var ZodEnum$1 = class _ZodEnum extends ZodType$1 {
static {
__name(this, "ZodEnum");
}
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext$1(ctx, {
expected: util$2.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode$1.invalid_type
});
return INVALID$1;
}
if (this._def.values.indexOf(input.data) === -1) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext$1(ctx, {
received: ctx.data,
code: ZodIssueCode$1.invalid_enum_value,
options: expectedValues
});
return INVALID$1;
}
return OK$1(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
extract(values) {
return _ZodEnum.create(values);
}
exclude(values) {
return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
}
};
ZodEnum$1.create = createZodEnum$1;
var ZodNativeEnum$1 = class extends ZodType$1 {
static {
__name(this, "ZodNativeEnum");
}
_parse(input) {
const nativeEnumValues = util$2.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType$1.string && ctx.parsedType !== ZodParsedType$1.number) {
const expectedValues = util$2.objectValues(nativeEnumValues);
addIssueToContext$1(ctx, {
expected: util$2.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode$1.invalid_type
});
return INVALID$1;
}
if (nativeEnumValues.indexOf(input.data) === -1) {
const expectedValues = util$2.objectValues(nativeEnumValues);
addIssueToContext$1(ctx, {
received: ctx.data,
code: ZodIssueCode$1.invalid_enum_value,
options: expectedValues
});
return INVALID$1;
}
return OK$1(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum$1.create = (values, params) => {
return new ZodNativeEnum$1({
values,
typeName: ZodFirstPartyTypeKind$1.ZodNativeEnum,
...processCreateParams$1(params)
});
};
var ZodPromise$1 = class extends ZodType$1 {
static {
__name(this, "ZodPromise");
}
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType$1.promise && ctx.common.async === false) {
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.promise,
received: ctx.parsedType
});
return INVALID$1;
}
return OK$1((ctx.parsedType === ZodParsedType$1.promise ? ctx.data : Promise.resolve(ctx.data)).then((data$1) => {
return this._def.type.parseAsync(data$1, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise$1.create = (schema, params) => {
return new ZodPromise$1({
type: schema,
typeName: ZodFirstPartyTypeKind$1.ZodPromise,
...processCreateParams$1(params)
});
};
var ZodEffects$1 = class extends ZodType$1 {
static {
__name(this, "ZodEffects");
}
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind$1.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: /* @__PURE__ */ __name((arg) => {
addIssueToContext$1(ctx, arg);
if (arg.fatal) status.abort();
else status.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$1;
if (inner.status === "dirty") status.dirty();
executeRefinement(inner.value);
return {
status: status.value,
value: inner.value
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((inner) => {
if (inner.status === "aborted") return INVALID$1;
if (inner.status === "dirty") status.dirty();
return executeRefinement(inner.value).then(() => {
return {
status: status.value,
value: inner.value
};
});
});
}
if (effect.type === "transform") if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid$1(base)) return base;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
return {
status: status.value,
value: result
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((base) => {
if (!isValid$1(base)) return base;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
util$2.assertNever(effect);
}
};
ZodEffects$1.create = (schema, effect, params) => {
return new ZodEffects$1({
schema,
typeName: ZodFirstPartyTypeKind$1.ZodEffects,
effect,
...processCreateParams$1(params)
});
};
ZodEffects$1.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects$1({
schema,
effect: {
type: "preprocess",
transform: preprocess
},
typeName: ZodFirstPartyTypeKind$1.ZodEffects,
...processCreateParams$1(params)
});
};
var ZodOptional$1 = class extends ZodType$1 {
static {
__name(this, "ZodOptional");
}
_parse(input) {
if (this._getType(input) === ZodParsedType$1.undefined) return OK$1(void 0);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional$1.create = (type, params) => {
return new ZodOptional$1({
innerType: type,
typeName: ZodFirstPartyTypeKind$1.ZodOptional,
...processCreateParams$1(params)
});
};
var ZodNullable$1 = class extends ZodType$1 {
static {
__name(this, "ZodNullable");
}
_parse(input) {
if (this._getType(input) === ZodParsedType$1.null) return OK$1(null);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable$1.create = (type, params) => {
return new ZodNullable$1({
innerType: type,
typeName: ZodFirstPartyTypeKind$1.ZodNullable,
...processCreateParams$1(params)
});
};
var ZodDefault$1 = class extends ZodType$1 {
static {
__name(this, "ZodDefault");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
let data$1 = ctx.data;
if (ctx.parsedType === ZodParsedType$1.undefined) data$1 = this._def.defaultValue();
return this._def.innerType._parse({
data: data$1,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault$1.create = (type, params) => {
return new ZodDefault$1({
innerType: type,
typeName: ZodFirstPartyTypeKind$1.ZodDefault,
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
...processCreateParams$1(params)
});
};
var ZodCatch$1 = class extends ZodType$1 {
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$1(result)) return result.then((result2) => {
return {
status: "valid",
value: result2.status === "valid" ? result2.value : this._def.catchValue({
get error() {
return new ZodError$1(newCtx.common.issues);
},
input: newCtx.data
})
};
});
else return {
status: "valid",
value: result.status === "valid" ? result.value : this._def.catchValue({
get error() {
return new ZodError$1(newCtx.common.issues);
},
input: newCtx.data
})
};
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch$1.create = (type, params) => {
return new ZodCatch$1({
innerType: type,
typeName: ZodFirstPartyTypeKind$1.ZodCatch,
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams$1(params)
});
};
var ZodNaN$1 = class extends ZodType$1 {
static {
__name(this, "ZodNaN");
}
_parse(input) {
if (this._getType(input) !== ZodParsedType$1.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext$1(ctx, {
code: ZodIssueCode$1.invalid_type,
expected: ZodParsedType$1.nan,
received: ctx.parsedType
});
return INVALID$1;
}
return {
status: "valid",
value: input.data
};
}
};
ZodNaN$1.create = (params) => {
return new ZodNaN$1({
typeName: ZodFirstPartyTypeKind$1.ZodNaN,
...processCreateParams$1(params)
});
};
var BRAND = Symbol("zod_brand");
var ZodBranded$1 = class extends ZodType$1 {
static {
__name(this, "ZodBranded");
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const data$1 = ctx.data;
return this._def.type._parse({
data: data$1,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline$1 = class _ZodPipeline extends ZodType$1 {
static {
__name(this, "ZodPipeline");
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) return (/* @__PURE__ */ __name(async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID$1;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY$1(inResult.value);
} else return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}, "handleAsync"))();
else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID$1;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a, b) {
return new _ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind$1.ZodPipeline
});
}
};
var ZodReadonly$1 = class extends ZodType$1 {
static {
__name(this, "ZodReadonly");
}
_parse(input) {
const result = this._def.innerType._parse(input);
if (isValid$1(result)) result.value = Object.freeze(result.value);
return result;
}
};
ZodReadonly$1.create = (type, params) => {
return new ZodReadonly$1({
innerType: type,
typeName: ZodFirstPartyTypeKind$1.ZodReadonly,
...processCreateParams$1(params)
});
};
var custom = /* @__PURE__ */ __name((check, params = {}, fatal) => {
if (check) return ZodAny$1.create().superRefine((data$1, ctx) => {
var _a, _b;
if (!check(data$1)) {
const p$1 = typeof params === "function" ? params(data$1) : typeof params === "string" ? { message: params } : params;
const _fatal = (_b = (_a = p$1.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
const p2 = typeof p$1 === "string" ? { message: p$1 } : p$1;
ctx.addIssue({
code: "custom",
...p2,
fatal: _fatal
});
}
});
return ZodAny$1.create();
}, "custom");
var late$1 = { object: ZodObject$1.lazycreate };
var ZodFirstPartyTypeKind$1;
(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$1 || (ZodFirstPartyTypeKind$1 = {}));
var instanceOfType = /* @__PURE__ */ __name((cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data$1) => data$1 instanceof cls, params), "instanceOfType");
var stringType$1 = ZodString$1.create;
var numberType$1 = ZodNumber$1.create;
var nanType$1 = ZodNaN$1.create;
var bigIntType$1 = ZodBigInt$1.create;
var booleanType$1 = ZodBoolean$1.create;
var dateType$1 = ZodDate$1.create;
var symbolType$1 = ZodSymbol$1.create;
var undefinedType$1 = ZodUndefined$1.create;
var nullType$1 = ZodNull$1.create;
var anyType$1 = ZodAny$1.create;
var unknownType$1 = ZodUnknown$1.create;
var neverType$1 = ZodNever$1.create;
var voidType$1 = ZodVoid$1.create;
var arrayType$1 = ZodArray$1.create;
var objectType$1 = ZodObject$1.create;
var strictObjectType$1 = ZodObject$1.strictCreate;
var unionType$1 = ZodUnion$1.create;
var discriminatedUnionType$1 = ZodDiscriminatedUnion$1.create;
var intersectionType$1 = ZodIntersection$1.create;
var tupleType$1 = ZodTuple$1.create;
var recordType$1 = ZodRecord$1.create;
var mapType$1 = ZodMap$1.create;
var setType$1 = ZodSet$1.create;
var functionType$1 = ZodFunction$1.create;
var lazyType$1 = ZodLazy$1.create;
var literalType$1 = ZodLiteral$1.create;
var enumType$1 = ZodEnum$1.create;
var nativeEnumType$1 = ZodNativeEnum$1.create;
var promiseType$1 = ZodPromise$1.create;
var effectsType$1 = ZodEffects$1.create;
var optionalType$1 = ZodOptional$1.create;
var nullableType$1 = ZodNullable$1.create;
var preprocessType$1 = ZodEffects$1.createWithPreprocess;
var pipelineType$1 = ZodPipeline$1.create;
var ostring = /* @__PURE__ */ __name(() => stringType$1().optional(), "ostring");
var onumber = /* @__PURE__ */ __name(() => numberType$1().optional(), "onumber");
var oboolean = /* @__PURE__ */ __name(() => booleanType$1().optional(), "oboolean");
var coerce = {
string: /* @__PURE__ */ __name((arg) => ZodString$1.create({
...arg,
coerce: true
}), "string"),
number: /* @__PURE__ */ __name((arg) => ZodNumber$1.create({
...arg,
coerce: true
}), "number"),
boolean: /* @__PURE__ */ __name((arg) => ZodBoolean$1.create({
...arg,
coerce: true
}), "boolean"),
bigint: /* @__PURE__ */ __name((arg) => ZodBigInt$1.create({
...arg,
coerce: true
}), "bigint"),
date: /* @__PURE__ */ __name((arg) => ZodDate$1.create({
...arg,
coerce: true
}), "date")
};
var NEVER = INVALID$1;
var z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap$1,
setErrorMap,
getErrorMap: getErrorMap$1,
makeIssue: makeIssue$1,
EMPTY_PATH,
addIssueToContext: addIssueToContext$1,
ParseStatus: ParseStatus$1,
INVALID: INVALID$1,
DIRTY: DIRTY$1,
OK: OK$1,
isAborted: isAborted$1,
isDirty: isDirty$1,
isValid: isValid$1,
isAsync: isAsync$1,
get util() {
return util$2;
},
get objectUtil() {
return objectUtil$1;
},
ZodParsedType: ZodParsedType$1,
getParsedType: getParsedType$1,
ZodType: ZodType$1,
ZodString: ZodString$1,
ZodNumber: ZodNumber$1,
ZodBigInt: ZodBigInt$1,
ZodBoolean: ZodBoolean$1,
ZodDate: ZodDate$1,
ZodSymbol: ZodSymbol$1,
ZodUndefined: ZodUndefined$1,
ZodNull: ZodNull$1,
ZodAny: ZodAny$1,
ZodUnknown: ZodUnknown$1,
ZodNever: ZodNever$1,
ZodVoid: ZodVoid$1,
ZodArray: ZodArray$1,
ZodObject: ZodObject$1,
ZodUnion: ZodUnion$1,
ZodDiscriminatedUnion: ZodDiscriminatedUnion$1,
ZodIntersection: ZodIntersection$1,
ZodTuple: ZodTuple$1,
ZodRecord: ZodRecord$1,
ZodMap: ZodMap$1,
ZodSet: ZodSet$1,
ZodFunction: ZodFunction$1,
ZodLazy: ZodLazy$1,
ZodLiteral: ZodLiteral$1,
ZodEnum: ZodEnum$1,
ZodNativeEnum: ZodNativeEnum$1,
ZodPromise: ZodPromise$1,
ZodEffects: ZodEffects$1,
ZodTransformer: ZodEffects$1,
ZodOptional: ZodOptional$1,
ZodNullable: ZodNullable$1,
ZodDefault: ZodDefault$1,
ZodCatch: ZodCatch$1,
ZodNaN: ZodNaN$1,
BRAND,
ZodBranded: ZodBranded$1,
ZodPipeline: ZodPipeline$1,
ZodReadonly: ZodReadonly$1,
custom,
Schema: ZodType$1,
ZodSchema: ZodType$1,
late: late$1,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind$1;
},
coerce,
any: anyType$1,
array: arrayType$1,
bigint: bigIntType$1,
boolean: booleanType$1,
date: dateType$1,
discriminatedUnion: discriminatedUnionType$1,
effect: effectsType$1,
"enum": enumType$1,
"function": functionType$1,
"instanceof": instanceOfType,
intersection: intersectionType$1,
lazy: lazyType$1,
literal: literalType$1,
map: mapType$1,
nan: nanType$1,
nativeEnum: nativeEnumType$1,
never: neverType$1,
"null": nullType$1,
nullable: nullableType$1,
number: numberType$1,
object: objectType$1,
oboolean,
onumber,
optional: optionalType$1,
ostring,
pipeline: pipelineType$1,
preprocess: preprocessType$1,
promise: promiseType$1,
record: recordType$1,
set: setType$1,
strictObject: strictObjectType$1,
string: stringType$1,
symbol: symbolType$1,
transformer: effectsType$1,
tuple: tupleType$1,
"undefined": undefinedType$1,
union: unionType$1,
unknown: unknownType$1,
"void": voidType$1,
NEVER,
ZodIssueCode: ZodIssueCode$1,
quotelessJson,
ZodError: ZodError$1
});
var MAX_WORKFLOW_NAME_LENGTH = 64;
var ALLOWED_WORKFLOW_NAME_REGEX = new RegExp("^[a-zA-Z0-9_][a-zA-Z0-9-_]*$");
function isValidWorkflowName(name) {
if (typeof name !== "string") return false;
if (name.length > MAX_WORKFLOW_NAME_LENGTH) return false;
return ALLOWED_WORKFLOW_NAME_REGEX.test(name);
}
__name(isValidWorkflowName, "isValidWorkflowName");
z.object({
retries: z.object({
delay: z.number().gte(0).or(z.string()),
limit: z.number().gte(0),
backoff: z.enum([
"constant",
"linear",
"exponential"
]).optional()
}).strict().optional(),
timeout: z.number().gte(0).or(z.string()).optional()
}).strict();
var mod_esm_exports = {};
__export(mod_esm_exports, { default: () => mod_esm_default });
var import_mod_cjs = __toESM(require_mod_cjs3(), 1);
__reExport(mod_esm_exports, __toESM(require_mod_cjs3(), 1));
var mod_esm_default = import_mod_cjs.default;
function getGlobalWranglerConfigPath() {
const configDir = mod_esm_default(".wrangler").config();
const legacyConfigDir = path.join(os.homedir(), ".wrangler");
if (isDirectory(legacyConfigDir)) return legacyConfigDir;
else return configDir;
}
__name(getGlobalWranglerConfigPath, "getGlobalWranglerConfigPath");
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])}`, { telemetryMessage: false });
}
};
}
__name(getBooleanEnvironmentVariableFactory, "getBooleanEnvironmentVariableFactory");
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?.();
};
}
__name(getEnvironmentVariableFactory, "getEnvironmentVariableFactory");
function getProcessEnv(variableName, choices) {
assertOneOf(choices, process.env[variableName]);
return process.env[variableName];
}
__name(getProcessEnv, "getProcessEnv");
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)}`, { telemetryMessage: false });
}
__name(assertOneOf, "assertOneOf");
var getC3CommandFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_C3_COMMAND",
defaultValue: /* @__PURE__ */ __name(() => "create cloudflare", "defaultValue")
});
var getWranglerSendMetricsFromEnv = getBooleanEnvironmentVariableFactory({ variableName: "WRANGLER_SEND_METRICS" });
var getWranglerSendErrorReportsFromEnv = getBooleanEnvironmentVariableFactory({ variableName: "WRANGLER_SEND_ERROR_REPORTS" });
var getCloudflareApiEnvironmentFromEnv = getEnvironmentVariableFactory({
variableName: "WRANGLER_API_ENVIRONMENT",
defaultValue: /* @__PURE__ */ __name(() => "production", "defaultValue"),
choices: ["production", "staging"]
});
var getCloudflareComplianceRegionFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_COMPLIANCE_REGION",
choices: ["public", "fedramp_high"]
});
var 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}\`
`, { telemetryMessage: false });
return complianceRegionFromEnv || complianceConfig?.compliance_region || "public";
}, "getCloudflareComplianceRegion");
var getCloudflareApiBaseUrlFromEnv = getEnvironmentVariableFactory({
variableName: "CLOUDFLARE_API_BASE_URL",
deprecatedName: "CF_API_BASE_URL"
});
function getComplianceRegionSubdomain(complianceConfig) {
return getCloudflareComplianceRegion(complianceConfig) === "fedramp_high" ? ".fed" : "";
}
__name(getComplianceRegionSubdomain, "getComplianceRegionSubdomain");
function getStagingSubdomain() {
return getCloudflareApiEnvironmentFromEnv() === "staging" ? ".staging" : "";
}
__name(getStagingSubdomain, "getStagingSubdomain");
var getSanitizeLogs = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_LOG_SANITIZE",
defaultValue: true
});
var getOutputFileDirectoryFromEnv = getEnvironmentVariableFactory({ variableName: "WRANGLER_OUTPUT_FILE_DIRECTORY" });
var getOutputFilePathFromEnv = getEnvironmentVariableFactory({ variableName: "WRANGLER_OUTPUT_FILE_PATH" });
var getCIMatchTag = getEnvironmentVariableFactory({ variableName: "WRANGLER_CI_MATCH_TAG" });
var getCIOverrideName = getEnvironmentVariableFactory({ variableName: "WRANGLER_CI_OVERRIDE_NAME" });
var getCIOverrideNetworkModeHost = getEnvironmentVariableFactory({ variableName: "WRANGLER_CI_OVERRIDE_NETWORK_MODE_HOST" });
var getCIGeneratePreviewAlias = getEnvironmentVariableFactory({
variableName: "WRANGLER_CI_GENERATE_PREVIEW_ALIAS",
defaultValue: /* @__PURE__ */ __name(() => "false", "defaultValue"),
choices: ["true", "false"]
});
var getWorkersCIBranchName = getEnvironmentVariableFactory({ variableName: "WORKERS_CI_BRANCH" });
var getBuildConditionsFromEnv = getEnvironmentVariableFactory({ variableName: "WRANGLER_BUILD_CONDITIONS" });
var getBuildPlatformFromEnv = getEnvironmentVariableFactory({ variableName: "WRANGLER_BUILD_PLATFORM" });
var getRegistryPath = getEnvironmentVariableFactory({
variableName: "WRANGLER_REGISTRY_PATH",
defaultValue() {
return path.join(getGlobalWranglerConfigPath(), "registry");
}
});
var getD1ExtraLocationChoices = getEnvironmentVariableFactory({ variableName: "WRANGLER_D1_EXTRA_LOCATION_CHOICES" });
var getDockerPath$1 = getEnvironmentVariableFactory({
variableName: "WRANGLER_DOCKER_BIN",
defaultValue() {
return "docker";
}
});
var getSubdomainMixedStateCheckDisabled = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_DISABLE_SUBDOMAIN_MIXED_STATE_CHECK",
defaultValue: false
});
var getCloudflareLoadDevVarsFromDotEnv = getBooleanEnvironmentVariableFactory({
variableName: "CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV",
defaultValue: true
});
var getCloudflareIncludeProcessEnvFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "CLOUDFLARE_INCLUDE_PROCESS_ENV",
defaultValue: false
});
var getTraceHeader = getEnvironmentVariableFactory({ variableName: "WRANGLER_TRACE_ID" });
var getDisableConfigWatching = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_CI_DISABLE_CONFIG_WATCHING",
defaultValue: false
});
var getWranglerHideBanner = getBooleanEnvironmentVariableFactory({
variableName: "WRANGLER_HIDE_BANNER",
defaultValue: false
});
var getCloudflareEnv = getEnvironmentVariableFactory({ variableName: "CLOUDFLARE_ENV" });
var getOpenNextDeployFromEnv = getEnvironmentVariableFactory({ variableName: "OPEN_NEXT_DEPLOY" });
var getLocalExplorerEnabledFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "X_LOCAL_EXPLORER",
defaultValue: true
});
var getBrowserRenderingHeadfulFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "X_BROWSER_HEADFUL",
defaultValue: false
});
var getCfFetchEnabledFromEnv = getBooleanEnvironmentVariableFactory({
variableName: "CLOUDFLARE_CF_FETCH_ENABLED",
defaultValue: true
});
var getCfFetchPathFromEnv = getEnvironmentVariableFactory({ variableName: "CLOUDFLARE_CF_FETCH_PATH" });
var getWranglerCacheDirFromEnv = getEnvironmentVariableFactory({ variableName: "WRANGLER_CACHE_DIR" });
var getCloudflaredPathFromEnv = getEnvironmentVariableFactory({ variableName: "CLOUDFLARED_PATH" });
var 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 = [];
/** Set to true when an unexpected/unknown field is encountered during validation. */
hasUnexpectedFields = false;
/**
* 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());
}
/** Does this or any of its children have unexpected fields. */
hasUnexpectedFieldsInTree() {
if (this.hasUnexpectedFields) return true;
else return this.children.some((child) => child.hasUnexpectedFieldsInTree());
}
/** 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}
` + this[field].map((message) => `- ${indentText(message)}`).join("\n") + this.children.map((child) => child[hasMethod]() ? "\n- " + child.render(field) : "").filter((output) => output !== "").join("\n"));
}
};
function indentText(str) {
return str.split("\n").map((line, index) => (index === 0 ? line : ` ${line}`).replace(/^\s*$/, "")).join("\n");
}
__name(indentText, "indentText");
function deprecated(diagnostics, config, fieldPath, message, remove, title = "Deprecation", type = "warning") {
const diagnosticMessage = `[1m${title}[0m: "${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];
}
}
__name(deprecated, "deprecated");
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.`);
}
__name(experimental, "experimental");
function inheritable(diagnostics, topLevelEnv, rawEnv, field, validate, defaultValue, transformFn = (v) => v) {
validate(diagnostics, field, rawEnv[field], topLevelEnv);
return (rawEnv !== topLevelEnv ? rawEnv[field] : void 0) ?? transformFn(topLevelEnv?.[field]) ?? defaultValue;
}
__name(inheritable, "inheritable");
function inheritableInWranglerEnvironments(diagnostics, useServiceEnvironments, topLevelEnv, rawEnv, field, validate, transformFn = (v) => v, defaultValue) {
return useServiceEnvironments && topLevelEnv !== void 0 ? notAllowedInNamedServiceEnvironment(diagnostics, topLevelEnv, rawEnv, field) : inheritable(diagnostics, topLevelEnv, rawEnv, field, validate, defaultValue, transformFn);
}
__name(inheritableInWranglerEnvironments, "inheritableInWranglerEnvironments");
var appendEnvName = /* @__PURE__ */ __name((envName) => (fieldValue) => fieldValue ? `${fieldValue}-${envName}` : void 0, "appendEnvName");
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];
}
__name(notAllowedInNamedServiceEnvironment, "notAllowedInNamedServiceEnvironment");
function notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, field, validate, defaultValue) {
if (rawEnv[field] !== void 0) validate(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;
}
__name(notInheritable, "notInheritable");
function unwindPropertyPath(root, path4) {
let container = root;
const parts = path4.split(".");
for (let i$1 = 0; i$1 < parts.length - 1; i$1++) {
if (!hasProperty(container, parts[i$1])) return;
container = container[parts[i$1]];
}
return {
container,
field: parts[parts.length - 1]
};
}
__name(unwindPropertyPath, "unwindPropertyPath");
var isString$2 = /* @__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");
var 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");
var isValidDateTimeStringFormat = /* @__PURE__ */ __name((diagnostics, field, value) => {
let isValid2 = true;
if (value.includes("–") || value.includes("—")) {
diagnostics.errors.push(`"${field}" field should use ISO-8601 accepted hyphens (-) rather than en-dashes (\u2013) or em-dashes (\u2014).`);
isValid2 = false;
}
const data$1 = new Date(value.replaceAll(/–|—/g, "-"));
if (isNaN(data$1.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");
var 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");
var 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");
var all = /* @__PURE__ */ __name((...validations) => {
return (diagnostics, field, value, config) => {
let passedValidations = true;
for (const validate of validations) if (!validate(diagnostics, field, value, config)) passedValidations = false;
return passedValidations;
};
}, "all");
var 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");
var 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");
var 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");
var 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$1 = [];
for (const prop of properties) {
if (typeof prop.value === prop.type) return true;
errors$1.push(`Expected "${containerPath}${prop.key}" to be of type ${prop.type} but got ${JSON.stringify(prop.value)}.`);
}
diagnostics.errors.push(...errors$1);
return false;
}, "validateAtLeastOnePropertyRequired");
var validateOptionalProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
if (value !== void 0) return validateRequiredProperty(diagnostics, container, key, value, type, choices);
return true;
}, "validateOptionalProperty");
var 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 i$1 = 0; i$1 < value.length; i$1++) isValid2 = validateRequiredProperty(diagnostics, container, `[${i$1}]`, value[i$1], type) && isValid2;
return isValid2;
}, "validateTypedArray");
var validateOptionalTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
if (value !== void 0) return validateTypedArray(diagnostics, container, value, type);
return true;
}, "validateOptionalTypedArray");
var isRequiredProperty = /* @__PURE__ */ __name((target$1, property, type, choices) => hasProperty(target$1, property) && typeof target$1[property] === type && (choices === void 0 || choices.includes(target$1[property])), "isRequiredProperty");
var isOptionalProperty = /* @__PURE__ */ __name((target$1, property, type) => !hasProperty(target$1, property) || typeof target$1[property] === type, "isOptionalProperty");
var hasProperty = /* @__PURE__ */ __name((target$1, property) => property in target$1, "hasProperty");
var 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}`);
diagnostics.hasUnexpectedFields = true;
return false;
}
return true;
}, "validateAdditionalProperties");
var getBindingNames = /* @__PURE__ */ __name((value) => {
if (typeof value !== "object" || value === null) return [];
if (isBindingList(value)) return value.bindings.map(({ name }) => name);
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((k) => value[k] !== void 0);
} else return [];
}, "getBindingNames");
var 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");
var isNamespaceList = /* @__PURE__ */ __name((value) => Array.isArray(value) && value.every((entry) => isRecord(entry) && "binding" in entry && typeof entry.binding === "string"), "isNamespaceList");
var isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
var validateUniqueNameProperty = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (Array.isArray(value)) {
const nameCount = /* @__PURE__ */ new Map();
Object.entries(value).forEach(([_2, entry]) => {
nameCount.set(entry.name, (nameCount.get(entry.name) ?? 0) + 1);
});
const duplicates = Array.from(nameCount.entries()).filter(([_2, count]) => count > 1).map(([name]) => name);
if (duplicates.length > 0) {
const list$1 = duplicates.join("\", \"");
diagnostics.errors.push(`"${field}" bindings must have unique "name" values; duplicate(s) found: "${list$1}"`);
return false;
}
}
return true;
}, "validateUniqueNameProperty");
function isValidR2BucketName(name) {
return typeof name === "string" && /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(name);
}
__name(isValidR2BucketName, "isValidR2BucketName");
var 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.`;
var 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",
ai_search_namespaces: "AI Search Namespace",
ai_search: "AI Search Instance",
hyperdrive: "Hyperdrive Config",
r2_buckets: "R2 Bucket",
logfwdr: "logfwdr",
services: "Worker",
analytics_engine_datasets: "Analytics Engine Dataset",
text_blobs: "Text Blob",
browser: "Browser Run",
ai: "AI",
images: "Images",
stream: "Stream",
media: "Media",
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",
artifacts: "Artifacts",
ratelimits: "Rate Limit",
assets: "Assets",
unsafe_hello_world: "Hello World",
flagship: "Flagship",
worker_loaders: "Worker Loader",
vpc_services: "VPC Service",
vpc_networks: "VPC Network"
};
var bindingTypeFriendlyNames = {
plain_text: "Environment Variable",
secret_text: "Environment Variable",
json: "Environment Variable",
kv_namespace: "KV Namespace",
send_email: "Send Email",
wasm_module: "Wasm Module",
text_blob: "Text Blob",
browser: "Browser Run",
ai: "AI",
images: "Images",
stream: "Stream",
version_metadata: "Worker Version Metadata",
data_blob: "Data Blob",
durable_object_namespace: "Durable Object",
workflow: "Workflow",
queue: "Queue",
r2_bucket: "R2 Bucket",
d1: "D1 Database",
vectorize: "Vectorize Index",
ai_search_namespace: "AI Search Namespace",
ai_search: "AI Search Instance",
hyperdrive: "Hyperdrive Config",
service: "Worker",
fetcher: "Service Binding",
analytics_engine: "Analytics Engine Dataset",
dispatch_namespace: "Dispatch Namespace",
mtls_certificate: "mTLS Certificate",
pipeline: "Pipeline",
secrets_store_secret: "Secrets Store Secret",
artifacts: "Artifacts",
logfwdr: "logfwdr",
unsafe_hello_world: "Hello World",
flagship: "Flagship",
ratelimit: "Rate Limit",
worker_loader: "Worker Loader",
vpc_service: "VPC Service",
vpc_network: "VPC Network",
media: "Media",
assets: "Assets",
inherit: "Inherited"
};
function getBindingTypeFriendlyName(bindingType) {
if (bindingType in bindingTypeFriendlyNames) return bindingTypeFriendlyNames[bindingType];
if (bindingType.startsWith("unsafe_")) return "Unsafe Metadata";
return bindingType;
}
__name(getBindingTypeFriendlyName, "getBindingTypeFriendlyName");
var ENGLISH = new Intl.ListFormat("en-US");
var ALLOWED_INSTANCE_TYPES = [
"lite",
"basic",
"standard-1",
"standard-2",
"standard-3",
"standard-4",
"dev",
"standard"
];
function isPagesConfig(rawConfig) {
return rawConfig.pages_build_output_dir !== void 0;
}
__name(isPagesConfig, "isPagesConfig");
function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args, preserveOriginalMain = false) {
const diagnostics = new Diagnostics(`Processing ${configPath ? path.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 useServiceEnvironments = !(args["legacy-env"] ?? rawConfig.legacy_env ?? true);
if (useServiceEnvironments) diagnostics.warnings.push("Service environments are deprecated, and will be removed 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, preserveOriginalMain);
const isRedirectedConfig2 = isRedirectedRawConfig(rawConfig, configPath, userConfigPath);
const definedEnvironments = Object.keys(rawConfig.env ?? {});
if (isRedirectedConfig2 && definedEnvironments.length > 0) diagnostics.errors.push(dedent`
Redirected configurations cannot include environments but the following have been found:\n${definedEnvironments.map((env$1) => ` - ${env$1}`).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 ?? getCloudflareEnv();
assert(envName === void 0 || typeof envName === "string");
let activeEnv = topLevelEnv;
if (envName) if (isRedirectedConfig2) {
if (!isPagesConfig(rawConfig) && rawConfig.targetEnvironment && rawConfig.targetEnvironment !== envName) {
const via = args.env !== void 0 ? "via the `--env/-e` CLI argument" : "via the CLOUDFLARE_ENV environment variable";
throw new Error(dedent`
You have specified the environment "${envName}" ${via}.
This does not match the target environment "${rawConfig.targetEnvironment}" that was used when building the application.
Perhaps you need to re-run the custom build of the project with "${envName}" as the selected environment?
`);
}
} else {
const envDiagnostics = new Diagnostics(`"env.${envName}" environment configuration`);
const rawEnv = rawConfig.env?.[envName];
if (rawEnv !== void 0) {
activeEnv = normalizeAndValidateEnvironment(envDiagnostics, configPath, rawEnv, isDispatchNamespace, preserveOriginalMain, envName, topLevelEnv, useServiceEnvironments, rawConfig);
diagnostics.addChild(envDiagnostics);
} else if (!isPagesConfig(rawConfig)) {
activeEnv = normalizeAndValidateEnvironment(envDiagnostics, configPath, topLevelEnv, isDispatchNamespace, preserveOriginalMain, envName, topLevelEnv, useServiceEnvironments, 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: isRedirectedConfig2 ? rawConfig.topLevelName : rawConfig.name,
definedEnvironments: isRedirectedConfig2 ? rawConfig.definedEnvironments : definedEnvironments,
targetEnvironment: isRedirectedConfig2 ? rawConfig.targetEnvironment : envName,
pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir(configPath, rawConfig.pages_build_output_dir),
legacy_env: !useServiceEnvironments,
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
};
}
__name(normalizeAndValidateConfig, "normalizeAndValidateConfig");
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.", { telemetryMessage: false });
}
}
__name(applyPythonConfig, "applyPythonConfig");
function normalizeAndValidateBuild(diagnostics, rawEnv, rawBuild, configPath) {
const { command, cwd, watch_dir = "./src",...rest } = rawBuild;
validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
validateOptionalProperty(diagnostics, "build", "command", command, "string");
validateOptionalProperty(diagnostics, "build", "cwd", cwd, "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,
watch_dir: command && configPath ? Array.isArray(watch_dir) ? watch_dir.map((dir) => path.relative(process.cwd(), path.join(path.dirname(configPath), `${dir}`))) : path.relative(process.cwd(), path.join(path.dirname(configPath), `${watch_dir}`)) : watch_dir,
cwd
};
}
__name(normalizeAndValidateBuild, "normalizeAndValidateBuild");
function normalizeAndValidateMainField(configPath, rawMain) {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawMain !== void 0) if (typeof rawMain === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawMain);
} else return rawMain;
else return;
}
__name(normalizeAndValidateMainField, "normalizeAndValidateMainField");
function normalizeAndValidateBaseDirField(configPath, rawDir) {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawDir !== void 0) if (typeof rawDir === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawDir);
} else return rawDir;
else return;
}
__name(normalizeAndValidateBaseDirField, "normalizeAndValidateBaseDirField");
function normalizeAndValidatePagesBuildOutputDir(configPath, rawPagesDir) {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawPagesDir !== void 0) if (typeof rawPagesDir === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawPagesDir);
} else return rawPagesDir;
else return;
}
__name(normalizeAndValidatePagesBuildOutputDir, "normalizeAndValidatePagesBuildOutputDir");
function normalizeAndValidateDev(diagnostics, rawDev, args) {
assert(typeof args === "object" && args !== null && !Array.isArray(args));
const { localProtocol: localProtocolArg, upstreamProtocol: upstreamProtocolArg, remote: remoteArg, enableContainers: enableContainersArg, generateTypes: generateTypesArg } = args;
assert(localProtocolArg === void 0 || localProtocolArg === "http" || localProtocolArg === "https");
assert(upstreamProtocolArg === void 0 || upstreamProtocolArg === "http" || upstreamProtocolArg === "https");
assert(remoteArg === void 0 || typeof remoteArg === "boolean");
assert(enableContainersArg === void 0 || typeof enableContainersArg === "boolean");
assert(generateTypesArg === void 0 || typeof generateTypesArg === "boolean");
const { ip = process.platform === "win32" ? "127.0.0.1" : "localhost", port, inspector_port, inspector_ip, local_protocol = localProtocolArg ?? "http", upstream_protocol = upstreamProtocolArg ?? remoteArg ? "https" : local_protocol, host, enable_containers = enableContainersArg ?? true, container_engine, generate_types = generateTypesArg ?? false,...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", "inspector_ip", inspector_ip, "string");
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");
validateOptionalProperty(diagnostics, "dev", "generate_types", generate_types, "boolean");
return {
ip,
port,
inspector_port,
inspector_ip,
local_protocol,
upstream_protocol,
host,
enable_containers,
container_engine,
generate_types
};
}
__name(normalizeAndValidateDev, "normalizeAndValidateDev");
function normalizeAndValidateAssets(diagnostics, topLevelEnv, rawEnv) {
return inheritable(diagnostics, topLevelEnv, rawEnv, "assets", validateAssetsConfig, void 0);
}
__name(normalizeAndValidateAssets, "normalizeAndValidateAssets");
function normalizeAndValidateSite(diagnostics, configPath, rawConfig, mainEntryPoint) {
if (rawConfig?.site !== void 0) {
const { bucket, include = [], exclude = [],...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", exclude, "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 = "${path.join(String(rawConfig.site["entry-point"]) || "workers-site", path.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 = path.relative(process.cwd(), path.join(path.dirname(configPath), siteEntryPoint));
return {
bucket,
"entry-point": siteEntryPoint,
include,
exclude
};
}
}
__name(normalizeAndValidateSite, "normalizeAndValidateSite");
function normalizeAndValidateAliases(diagnostics, configPath, rawConfig) {
if (rawConfig?.alias === void 0) return;
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;
}
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;
}
__name(normalizeAndValidateAliases, "normalizeAndValidateAliases");
function normalizeAndValidateModulePaths(diagnostics, configPath, field, rawMapping) {
if (rawMapping === void 0) return;
const mapping = {};
for (const [name, filePath] of Object.entries(rawMapping)) if (isString$2(diagnostics, `${field}['${name}']`, filePath, void 0)) {
if (configPath) mapping[name] = configPath ? path.relative(process.cwd(), path.join(path.dirname(configPath), filePath)) : filePath;
}
return mapping;
}
__name(normalizeAndValidateModulePaths, "normalizeAndValidateModulePaths");
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 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";
const hasEnabled = hasProperty(item, "enabled") && typeof item.enabled === "boolean";
const hasPreviewsEnabled = hasProperty(item, "previews_enabled") && typeof item.previews_enabled === "boolean";
if ([
hasZoneId,
hasZoneName,
hasCustomDomainFlag,
hasEnabled,
hasPreviewsEnabled
].filter(Boolean).length !== Object.keys(item).length - 1) return false;
if (hasZoneId && hasZoneName) return false;
if ((hasEnabled || hasPreviewsEnabled) && !hasCustomDomainFlag) return false;
if (hasZoneId || hasZoneName || hasCustomDomainFlag) return true;
}
return false;
}
__name(isValidRouteValue, "isValidRouteValue");
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;
}
__name(mutateEmptyStringAccountIDValue, "mutateEmptyStringAccountIDValue");
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;
}
__name(mutateEmptyStringRouteValue, "mutateEmptyStringRouteValue");
var 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, enabled, previews_enabled }, but got ${JSON.stringify(value)}.`);
return false;
}
return true;
}, "isRoute");
var 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, enabled, previews_enabled }, but these weren't valid: ${JSON.stringify(invalidRoutes, null, 2)}.`);
return invalidRoutes.length === 0;
}, "isRouteArray");
function normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv) {
return inheritable(diagnostics, topLevelEnv, mutateEmptyStringRouteValue(diagnostics, rawEnv), "route", isRoute, void 0);
}
__name(normalizeAndValidateRoute, "normalizeAndValidateRoute");
function validateRoutes(diagnostics, topLevelEnv, rawEnv) {
return inheritable(diagnostics, topLevelEnv, rawEnv, "routes", all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")), void 0);
}
__name(validateRoutes, "validateRoutes");
function normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv) {
if (rawEnv.placement) {
const placement = rawEnv.placement;
const hasHint = "hint" in placement;
const hasRegion = "region" in placement;
const hasHost = "host" in placement;
const hasHostname = "hostname" in placement;
const hasTargetedFields = hasRegion || hasHost || hasHostname;
if (hasHint && hasTargetedFields) {
diagnostics.errors.push(`"placement" cannot have both "hint" (smart format) and "region"/"host"/"hostname" (targeted format) fields`);
return inheritable(diagnostics, topLevelEnv, rawEnv, "placement", () => true, void 0);
}
if (hasHint) {
validateRequiredProperty(diagnostics, "placement", "mode", placement.mode, "string", ["off", "smart"]);
const mode = placement.mode;
const hint = placement.hint;
if (hint !== void 0 && typeof hint !== "string") diagnostics.errors.push(`"placement.hint" must be a string when "placement.mode" is "${mode}"`);
if (hint && mode !== "smart") diagnostics.errors.push(`"placement.hint" can only be set when "placement.mode" is "smart"`);
} else if (hasTargetedFields) {
validateOptionalProperty(diagnostics, "placement", "mode", placement.mode, "string", ["off", "targeted"]);
if (hasRegion) validateOptionalProperty(diagnostics, "placement", "region", placement.region, "string");
if (hasHost) validateOptionalProperty(diagnostics, "placement", "host", placement.host, "string");
if (hasHostname) validateOptionalProperty(diagnostics, "placement", "hostname", placement.hostname, "string");
if ([
hasRegion,
hasHost,
hasHostname
].filter(Boolean).length > 1) {
const presentFields = [];
if (hasRegion) presentFields.push("region");
if (hasHost) presentFields.push("host");
if (hasHostname) presentFields.push("hostname");
diagnostics.errors.push(`"placement" fields ${presentFields.map((f) => `"${f}"`).join(", ")} are mutually exclusive. Only one can be specified.`);
}
} else validateRequiredProperty(diagnostics, "placement", "mode", placement.mode, "string", [
"off",
"smart",
"targeted"
]);
}
return inheritable(diagnostics, topLevelEnv, rawEnv, "placement", () => true, void 0);
}
__name(normalizeAndValidatePlacement, "normalizeAndValidatePlacement");
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;
}
__name(validateTailConsumer, "validateTailConsumer");
var 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 i$1 = 0; i$1 < value.length; i$1++) isValid2 = validateTailConsumer(diagnostics, `${field}[${i$1}]`, value[i$1]) && isValid2;
return isValid2;
}, "validateTailConsumers");
function validateStreamingTailConsumer(diagnostics, field, value) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(`"${field}" should be an object but got ${JSON.stringify(value)}.`);
return false;
}
return validateRequiredProperty(diagnostics, field, "service", value.service, "string");
}
__name(validateStreamingTailConsumer, "validateStreamingTailConsumer");
var validateStreamingTailConsumers = /* @__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 i$1 = 0; i$1 < value.length; i$1++) isValid2 = validateStreamingTailConsumer(diagnostics, `${field}[${i$1}]`, value[i$1]) && isValid2;
return isValid2;
}, "validateStreamingTailConsumers");
function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDispatchNamespace, preserveOriginalMain, envName = "top level", topLevelEnv, useServiceEnvironments, rawConfig) {
deprecated(diagnostics, rawEnv, "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");
if (topLevelEnv === void 0 || rawConfig?.unsafe === void 0) experimental(diagnostics, rawEnv, "unsafe");
const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
const account_id = inheritableInWranglerEnvironments(diagnostics, useServiceEnvironments, topLevelEnv, mutateEmptyStringAccountIDValue(diagnostics, rawEnv), "account_id", isString$2, void 0, void 0);
const routes = validateRoutes(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, void 0);
const build$8 = normalizeAndValidateBuild(diagnostics, rawEnv, rawEnv.build ?? topLevelEnv?.build ?? {}, configPath);
const environment = {
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", isString$2, "React.createElement"),
jsx_fragment: inheritable(diagnostics, topLevelEnv, rawEnv, "jsx_fragment", isString$2, "React.Fragment"),
tsconfig: validateAndNormalizeTsconfig(diagnostics, topLevelEnv, rawEnv, configPath),
rules: validateAndNormalizeRules(diagnostics, topLevelEnv, rawEnv, envName),
name: inheritableInWranglerEnvironments(diagnostics, useServiceEnvironments, topLevelEnv, rawEnv, "name", isDispatchNamespace ? isString$2 : isValidName, appendEnvName(envName), void 0),
main: preserveOriginalMain ? inheritable(diagnostics, topLevelEnv, rawEnv, "main", isString$2, void 0) : normalizeAndValidateMainField(configPath, inheritable(diagnostics, topLevelEnv, rawEnv, "main", isString$2, 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", isString$2, 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: build$8,
workers_dev,
preview_urls,
vars: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "vars", validateVars(envName), {}),
secrets: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "secrets", validateSecrets(envName), void 0),
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), []),
ai_search_namespaces: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "ai_search_namespaces", validateBindingArray(envName, validateAISearchNamespaceBinding), []),
ai_search: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "ai_search", validateBindingArray(envName, validateAISearchBinding), []),
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),
streaming_tail_consumers: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "streaming_tail_consumers", validateStreamingTailConsumers, 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),
stream: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "stream", validateNamedSimpleBinding(envName), void 0),
media: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "media", 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), []),
artifacts: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "artifacts", validateBindingArray(envName, validateArtifactsBinding), []),
unsafe_hello_world: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "unsafe_hello_world", validateBindingArray(envName, validateHelloWorldBinding), []),
flagship: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "flagship", validateBindingArray(envName, validateFlagshipBinding), []),
worker_loaders: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "worker_loaders", validateBindingArray(envName, validateWorkerLoaderBinding), []),
ratelimits: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "ratelimits", validateBindingArray(envName, validateRateLimitBinding), []),
vpc_services: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "vpc_services", validateBindingArray(envName, validateVpcServiceBinding), []),
vpc_networks: notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, "vpc_networks", validateBindingArray(envName, validateVpcNetworkBinding), []),
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),
cache: inheritable(diagnostics, topLevelEnv, rawEnv, "cache", validateCache, void 0),
compliance_region: inheritable(diagnostics, topLevelEnv, rawEnv, "compliance_region", isOneOf("public", "fedramp_high"), void 0),
python_modules: inheritable(diagnostics, topLevelEnv, rawEnv, "python_modules", validatePythonModules, { exclude: ["**/*.pyc"] }),
previews: inheritable(diagnostics, topLevelEnv, rawEnv, "previews", validatePreviewsConfig(envName), void 0)
};
warnIfDurableObjectsHaveNoMigrations(diagnostics, environment.durable_objects, environment.migrations, configPath);
if (envName !== "top level") validateAdditionalProperties(diagnostics, "env." + envName, Object.keys(rawEnv), Object.keys(environment));
return environment;
}
__name(normalizeAndValidateEnvironment, "normalizeAndValidateEnvironment");
function validateAndNormalizeTsconfig(diagnostics, topLevelEnv, rawEnv, configPath) {
const tsconfig = inheritable(diagnostics, topLevelEnv, rawEnv, "tsconfig", isString$2, void 0);
return configPath && tsconfig ? path.relative(process.cwd(), path.join(path.dirname(configPath), tsconfig)) : tsconfig;
}
__name(validateAndNormalizeTsconfig, "validateAndNormalizeTsconfig");
var validateAndNormalizeRules = /* @__PURE__ */ __name((diagnostics, topLevelEnv, rawEnv, envName) => {
return inheritable(diagnostics, topLevelEnv, rawEnv, "rules", validateRules(envName), []);
}, "validateAndNormalizeRules");
var 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");
var 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 i$1 = 0; i$1 < envValue.length; i$1++) isValid2 = validateRule(diagnostics, `${fieldPath}[${i$1}]`, envValue[i$1], config) && isValid2;
return isValid2;
}, "validateRules");
var 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");
var 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);
const missingDefines = configDefines.filter((varName) => !(varName in value));
if (missingDefines.length > 0) diagnostics.warnings.push(`The following define entries exist at the top level, but not on "${fieldPath}".
This is probably not what you want, since "define" configuration is not inherited by environments.
Please add these entries to "env.${envName}.define":
` + missingDefines.map((varName) => `- ${varName}`).join("\n"));
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");
var validateVars = /* @__PURE__ */ __name((envName) => (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) {
diagnostics.errors.push(`The field "${fieldPath}" should be an object but got ${JSON.stringify(value)}.
`);
isValid2 = false;
} else for (const [varName, varValue] of Object.entries(value)) if (varValue instanceof Date) {
diagnostics.errors.push(`The field "${fieldPath}.${varName}" is a TOML date, which is not supported. Please use a string instead, e.g. ${varName} = "2025-12-19".`);
isValid2 = false;
}
}
const configVars = Object.keys(config?.vars ?? {});
if (configVars.length > 0) {
if (typeof value === "object" && value !== null) {
const missingVars = configVars.filter((varName) => !(varName in value));
if (missingVars.length > 0) diagnostics.warnings.push(`The following vars exist at the top level, but not on "${fieldPath}".
This is probably not what you want, since "vars" configuration is not inherited by environments.
Please add these vars to "env.${envName}.vars":
` + missingVars.map((varName) => `- ${varName}`).join("\n"));
}
}
return isValid2;
}, "validateVars");
var validateSecrets = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
if (value === void 0) return true;
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;
validateAdditionalProperties(diagnostics, fieldPath, Object.keys(value), ["required"]);
isValid2 = validateOptionalTypedArray(diagnostics, `${fieldPath}.required`, value.required, "string") && isValid2;
return isValid2;
}, "validateSecrets");
var 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 i$1 = 0; i$1 < value.bindings.length; i$1++) {
const binding = value.bindings[i$1];
const bindingDiagnostics = new Diagnostics(`"${fieldPath}.bindings[${i$1}]": ${JSON.stringify(binding)}`);
isValid2 = validateBinding(bindingDiagnostics, `${fieldPath}.bindings[${i$1}]`, 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((name) => !envBindingNames.has(name));
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((name) => `- ${name}`).join("\n"));
}
}
return isValid2;
}, "validateBindingsProperty");
var 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) {
if (!validateBindingsProperty(envName, validateUnsafeBinding)(diagnostics, field, value, config)) 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");
var 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");
var workflowNameFormatMessage = `Workflow names must be 1-64 characters long, start with a letter, number, or underscore, and may only contain letters, numbers, underscores, or hyphens.`;
var 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 (!isValidWorkflowName(value.name)) {
diagnostics.errors.push(`"${field}" binding "name" field is invalid. ${workflowNameFormatMessage}`);
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, "remote", "boolean")) {
diagnostics.errors.push(`"${field}" bindings should, optionally, have a boolean "remote" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
if (hasProperty(value, "limits") && value.limits !== void 0) if (typeof value.limits !== "object" || value.limits === null || Array.isArray(value.limits)) {
diagnostics.errors.push(`"${field}" bindings should, optionally, have an object "limits" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
} else {
const limits = value.limits;
if (limits.steps !== void 0) {
if (typeof limits.steps !== "number" || !Number.isInteger(limits.steps) || limits.steps < 1) {
diagnostics.errors.push(`"${field}" bindings "limits.steps" field must be a positive integer but got ${JSON.stringify(limits.steps)}.`);
isValid2 = false;
} else if (limits.steps > 25e3) diagnostics.warnings.push(`"${field}" has a step limit of ${limits.steps}, which exceeds the production maximum of 25,000. This configuration may not work when deployed.`);
}
validateAdditionalProperties(diagnostics, `${field}.limits`, Object.keys(limits), ["steps"]);
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"name",
"class_name",
"script_name",
"remote",
"limits"
]);
return isValid2;
}, "validateWorkflowBinding");
var validateCflogfwdrObject = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, topLevelEnv) => {
if (!validateBindingsProperty(envName, validateCflogfwdrBinding)(diagnostics, field, value, topLevelEnv)) return false;
if (value?.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");
var 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");
var 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");
var 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", "remote"]);
return isValid2;
}, "validateNamedSimpleBinding");
var 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");
var 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");
var 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")) {
if ([
"plain_text",
"secret_text",
"json",
"wasm_module",
"data_blob",
"text_blob",
"browser",
"ai",
"ai_search_namespace",
"ai_search",
"kv_namespace",
"durable_object_namespace",
"d1_database",
"r2_bucket",
"service",
"logfwdr",
"mtls_certificate",
"pipeline",
"worker_loader",
"vpc_service",
"flagship",
"vpc_network",
"stream",
"media",
"artifacts"
].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");
var 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 i$1 = 0; i$1 < envValue.length; i$1++) isValid2 = validateBinding(diagnostics, `${fieldPath}[${i$1}]`, envValue[i$1], 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");
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 name = `${topLevelName}-${containerAppOptional.class_name}`;
name += config === void 0 ? "" : `-${envName}`;
containerAppOptional.name = name.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 ? path.dirname(configPath) : process.cwd();
resolvedImage = path.resolve(baseDir, resolvedImage);
resolvedBuildContextPath = containerAppOptional.image_build_context ? path.resolve(baseDir, containerAppOptional.image_build_context) : path.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") {
if (![
5,
10,
20,
25,
50,
100
].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.`);
if ("wrangler_ssh" in containerAppOptional) diagnostics.warnings.push(`"containers.wrangler_ssh" is deprecated. Use "containers.ssh" instead.`);
if ("unsafe" in containerAppOptional) {
if (containerAppOptional.unsafe && typeof containerAppOptional.unsafe !== "object" || Array.isArray(containerAppOptional.unsafe)) diagnostics.errors.push(`The field "containers.unsafe" should be an object but got ${JSON.stringify(typeof containerAppOptional.unsafe)}.`);
}
validateAdditionalProperties(diagnostics, field, Object.keys(containerAppOptional), [
"name",
"instances",
"max_instances",
"image",
"image_build_context",
"image_vars",
"class_name",
"scheduling_policy",
"instance_type",
"ssh",
"wrangler_ssh",
"authorized_keys",
"trusted_user_ca_keys",
"configuration",
"constraints",
"affinities",
"rollout_step_percentage",
"rollout_kind",
"durable_objects",
"rollout_active_grace_period",
"unsafe"
]);
if ("configuration" in containerAppOptional) validateAdditionalProperties(diagnostics, `${field}.configuration`, Object.keys(containerAppOptional.configuration), [
"image",
"secrets",
"labels",
"disk",
"vcpu",
"memory_mib"
]);
let sshField;
let sshConfig;
if ("ssh" in containerAppOptional) {
sshField = "ssh";
sshConfig = containerAppOptional.ssh;
containerAppOptional.wrangler_ssh = containerAppOptional.ssh;
delete containerAppOptional.ssh;
} else if ("wrangler_ssh" in containerAppOptional) {
sshField = "wrangler_ssh";
sshConfig = containerAppOptional.wrangler_ssh;
}
if (sshField !== void 0) {
const sshConfigObject = typeof sshConfig === "object" && sshConfig !== null ? sshConfig : {};
if (!isRequiredProperty(sshConfigObject, "enabled", "boolean")) diagnostics.errors.push(`${field}.${sshField}.enabled must be a boolean`);
const sshPort = "port" in sshConfigObject ? sshConfigObject.port : void 0;
if (!isOptionalProperty(sshConfigObject, "port", "number") || typeof sshPort === "number" && (sshPort < 1 || sshPort > 65535)) diagnostics.errors.push(`${field}.${sshField}.port must be a number between 1 and 65535 inclusive`);
}
if ("authorized_keys" in containerAppOptional) if (!Array.isArray(containerAppOptional.authorized_keys)) diagnostics.errors.push(`${field}.authorized_keys must be an array`);
else for (const index in containerAppOptional.authorized_keys) {
const fieldPath = `${field}.authorized_keys[${index}]`;
const key = containerAppOptional.authorized_keys[index];
if (!isRequiredProperty(key, "name", "string")) diagnostics.errors.push(`${fieldPath}.name must be a string`);
if (!isRequiredProperty(key, "public_key", "string")) diagnostics.errors.push(`${fieldPath}.public_key must be a string`);
if (!key.public_key.toLowerCase().startsWith("ssh-ed25519")) diagnostics.errors.push(`${fieldPath}.public_key is a unsupported key type. Please provide a ED25519 public key.`);
}
if ("trusted_user_ca_keys" in containerAppOptional) if (!Array.isArray(containerAppOptional.trusted_user_ca_keys)) diagnostics.errors.push(`${field}.trusted_user_ca_keys must be an array`);
else for (const index in containerAppOptional.trusted_user_ca_keys) {
const fieldPath = `${field}.trusted_user_ca_keys[${index}]`;
const key = containerAppOptional.trusted_user_ca_keys[index];
if (!isOptionalProperty(key, "name", "string")) diagnostics.errors.push(`${fieldPath}.name must be a string`);
if (!isRequiredProperty(key, "public_key", "string")) diagnostics.errors.push(`${fieldPath}.public_key must be a string`);
if (!key.public_key.toLowerCase().startsWith("ssh-ed25519")) diagnostics.errors.push(`${fieldPath}.public_key is a unsupported key type. Please provide a ED25519 public key.`);
}
if (validateOptionalProperty(diagnostics, field, "constraints", containerAppOptional.constraints, "object") && containerAppOptional.constraints) {
const constraints = containerAppOptional.constraints;
if ("tier" in constraints) {
diagnostics.warnings.push(`"constraints.tier" has been deprecated in favor of "constraints.tiers". Please update your configuration to use "constraints.tiers" instead.`);
if ("tiers" in constraints) diagnostics.errors.push(`${field}.constraints.tier and ${field}.constraints.tiers cannot both be set`);
}
validateOptionalTypedArray(diagnostics, `${field}.constraints.tiers`, constraints.tiers, "number");
validateOptionalProperty(diagnostics, `${field}.constraints`, "jurisdiction", constraints.jurisdiction, "string");
if (constraints.jurisdiction && !["eu", "fedramp"].includes(constraints.jurisdiction)) diagnostics.errors.push(`${field}.constraints.jurisdiction must be one of: "eu", "fedramp"`);
if (validateOptionalTypedArray(diagnostics, `${field}.constraints.regions`, constraints.regions, "string") && constraints.regions && Array.isArray(constraints.regions)) {
const validRegions = [
"ENAM",
"WNAM",
"EEUR",
"WEUR",
"APAC",
"SAM",
"ME",
"OC",
"AFR"
];
for (const region of constraints.regions) if (typeof region === "string" && !validRegions.includes(region.toUpperCase())) diagnostics.errors.push(`${field}.constraints.regions contains invalid region "${region}". Valid regions are: ${validRegions.join(", ")}`);
}
}
if (typeof containerAppOptional.instance_type === "string") {
validateOptionalProperty(diagnostics, field, "instance_type", containerAppOptional.instance_type, "string", ALLOWED_INSTANCE_TYPES);
if (containerAppOptional.instance_type === "dev") diagnostics.warnings.push(`The "dev" instance_type has been renamed to "lite" and will be removed in a subsequent version. Please update your configuration to use "lite" instead.`);
if (containerAppOptional.instance_type === "standard") diagnostics.warnings.push(`The "standard" instance_type has been renamed to "standard-1" and will be removed in a subsequent version. Please update your configuration to use "standard-1" instead.`);
} 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;
};
}
__name(validateContainerApp, "validateContainerApp");
var 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" || !ALLOWED_INSTANCE_TYPES.includes(value.instance_type)) diagnostics.errors.push(`"instance_type" should be one of 'lite', 'basic', 'standard-1', 'standard-2', 'standard-3', or 'standard-4', 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");
var 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 (!isOptionalProperty(value, "id", "string") || value.id !== void 0 && 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",
"remote"
]);
return isValid2;
}, "validateKVBinding");
var 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 (!isOptionalProperty(value, "allowed_sender_addresses", "object")) {
diagnostics.errors.push(`"${field}" bindings should, optionally, have a []string "allowed_sender_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_sender_addresses",
"allowed_destination_addresses",
"destination_address",
"name",
"binding",
"remote"
]);
return isValid2;
}, "validateSendEmailBinding");
var 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",
"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;
}
for (const optionalOpt of [{
key: "delivery_delay",
type: "number"
}]) 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 (hasProperty(value, "delivery_delay") && value.delivery_delay !== void 0) diagnostics.warnings.push(`The "delivery_delay" field in "${field}" is deprecated and has no effect. Queue-level settings should be configured using "wrangler queues update" instead. This setting will be removed in a future version.`);
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
return isValid2;
}, "validateQueueBinding");
var 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 (!isOptionalProperty(value, "bucket_name", "string") || value.bucket_name !== void 0 && 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",
"remote"
]);
return isValid2;
}, "validateR2Binding");
var 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 (!isOptionalProperty(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",
"remote"
]);
return isValid2;
}, "validateD1Binding");
var 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",
"remote"
]);
return isValid2;
}, "validateVectorizeBinding");
var validateAISearchNamespaceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"ai_search_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 (!isRequiredProperty(value, "namespace", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a "namespace" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"namespace",
"remote"
]);
return isValid2;
}, "validateAISearchNamespaceBinding");
var validateAISearchBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"ai_search" 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, "instance_name", "string")) {
diagnostics.errors.push(`"${field}" bindings must have an "instance_name" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"instance_name",
"remote"
]);
return isValid2;
}, "validateAISearchBinding");
var 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");
var validateVpcServiceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"vpc_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_id", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a "service_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"service_id",
"remote"
]);
return isValid2;
}, "validateVpcServiceBinding");
var validateVpcNetworkBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"vpc_networks" 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;
}
const hasTunnelId = hasProperty(value, "tunnel_id");
const hasNetworkId = hasProperty(value, "network_id");
if (hasTunnelId && hasNetworkId) {
diagnostics.errors.push(`"${field}" bindings must have either a "tunnel_id" or "network_id", but not both.`);
isValid2 = false;
} else if (!hasTunnelId && !hasNetworkId) {
diagnostics.errors.push(`"${field}" bindings must have either a "tunnel_id" or "network_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
} else if (hasTunnelId && typeof value.tunnel_id !== "string") {
diagnostics.errors.push(`"${field}" bindings must have a string "tunnel_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
} else if (hasNetworkId && typeof value.network_id !== "string") {
diagnostics.errors.push(`"${field}" bindings must have a string "network_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"tunnel_id",
"network_id",
"remote"
]);
return isValid2;
}, "validateVpcNetworkBinding");
var 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])]));
bindingsGroupedByType["Secret"] = config.secrets?.required ?? [];
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, i$1) => bindingTypes.indexOf(type) !== i$1).filter((type, i$1, duplicateBindingTypes) => duplicateBindingTypes.indexOf(type) === i$1);
const differentTypes = bindingTypes.filter((type, i$1) => bindingTypes.indexOf(type) === i$1);
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) diagnostics.errors.push(`Bindings must have unique names, so that they can all be referenced in the worker.
Please change your bindings to have unique names.`);
return !hasDuplicates;
}, "validateBindingsHaveUniqueNames");
var 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");
var 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");
var 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");
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;
}
__name(validateWorkerNamespaceOutbound, "validateWorkerNamespaceOutbound");
var 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",
"remote"
]);
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
return isValid2;
}, "validateMTlsCertificateBinding");
function validateQueues(envName) {
return (diagnostics, field, value, config) => {
if (value === void 0) return true;
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 i$1 = 0; i$1 < consumers.length; i$1++) {
const consumer = consumers[i$1];
if (!validateConsumer(diagnostics, `${fieldPath}.consumers[${i$1}]`, consumer, config)) isValid2 = false;
}
}
if (hasProperty(value, "producers")) {
if (!validateBindingArray(envName, validateQueueBinding)(diagnostics, `${field}.producers`, value.producers, config)) isValid2 = false;
}
return isValid2;
};
}
__name(validateQueues, "validateQueues");
var 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)}.`);
if ("type" in value && value.type !== void 0 && value.type !== "worker") {
diagnostics.errors.push(`"${field}.type" has an invalid value "${value.type}". Only "worker" consumers can be configured in your Wrangler configuration.`);
isValid2 = false;
}
for (const optionalOpt of [
{
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"
}
]) 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");
var 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");
var 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",
"remote"
]);
return isValid2;
}, "validatePipelineBinding");
var 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");
var validateArtifactsBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"artifacts" 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, "namespace", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a string "namespace" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"namespace",
"remote"
]);
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
return isValid2;
}, "validateArtifactsBinding");
var 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");
var validateFlagshipBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"flagship" 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, "app_id", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a string "app_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"binding",
"app_id",
"remote"
]);
if (!isRemoteValid(value, field, diagnostics)) isValid2 = false;
return isValid2;
}, "validateFlagshipBinding");
var validateWorkerLoaderBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"worker_loader" 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;
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), ["binding"]);
return isValid2;
}, "validateWorkerLoaderBinding");
var validateRateLimitBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
if (typeof value !== "object" || value === null) {
diagnostics.errors.push(`"ratelimits" bindings should be objects, but got ${JSON.stringify(value)}`);
return false;
}
let isValid2 = true;
if (!isRequiredProperty(value, "name", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a string "name" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
if (!isRequiredProperty(value, "namespace_id", "string")) {
diagnostics.errors.push(`"${field}" bindings must have a string "namespace_id" field but got ${JSON.stringify(value)}.`);
isValid2 = false;
}
if (!hasProperty(value, "simple") || typeof value.simple !== "object" || value.simple === null) {
diagnostics.errors.push(`"${field}" bindings must have a "simple" configuration object but got ${JSON.stringify(value)}.`);
isValid2 = false;
} else {
if (!isRequiredProperty(value.simple, "limit", "number")) {
diagnostics.errors.push(`"${field}" bindings "simple.limit" must be a number but got ${JSON.stringify(value.simple)}.`);
isValid2 = false;
}
if (!isRequiredProperty(value.simple, "period", "number")) {
diagnostics.errors.push(`"${field}" bindings "simple.period" is required and must be a number but got ${JSON.stringify(value.simple)}.`);
isValid2 = false;
} else if (![10, 60].includes(value.simple.period)) {
diagnostics.errors.push(`"${field}" bindings "simple.period" must be either 10 or 60 but got ${JSON.stringify(value.simple.period)}.`);
isValid2 = false;
}
validateAdditionalProperties(diagnostics, `${field}.simple`, Object.keys(value.simple), ["limit", "period"]);
}
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
"name",
"namespace_id",
"simple"
]);
return isValid2;
}, "validateRateLimitBinding");
function normalizeAndValidateLimits(diagnostics, topLevelEnv, rawEnv) {
if (rawEnv.limits) {
validateOptionalProperty(diagnostics, "limits", "cpu_ms", rawEnv.limits.cpu_ms, "number");
validateOptionalProperty(diagnostics, "limits", "subrequests", rawEnv.limits.subrequests, "number");
}
return inheritable(diagnostics, topLevelEnv, rawEnv, "limits", () => true, void 0);
}
__name(normalizeAndValidateLimits, "normalizeAndValidateLimits");
var validatePreviewsConfig = /* @__PURE__ */ __name((envName) => (diagnostics, field, value) => {
if (value === void 0) return true;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(`The field "${field}" should be an object but got ${JSON.stringify(value)}.`);
return false;
}
const previews = value;
let isValid2 = true;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(previews), [
"vars",
"define",
"durable_objects",
"workflows",
"kv_namespaces",
"send_email",
"queues",
"d1_databases",
"r2_buckets",
"vectorize",
"hyperdrive",
"services",
"analytics_engine_datasets",
"dispatch_namespaces",
"mtls_certificates",
"tail_consumers",
"streaming_tail_consumers",
"unsafe",
"browser",
"ai",
"images",
"stream",
"media",
"pipelines",
"secrets_store_secrets",
"artifacts",
"unsafe_hello_world",
"flagship",
"worker_loaders",
"ratelimits",
"vpc_services",
"version_metadata",
"logpush",
"observability",
"limits",
"cache"
]) && isValid2;
isValid2 = validateVars(envName)(diagnostics, `${field}.vars`, previews.vars, void 0) && isValid2;
isValid2 = validateDefines(envName)(diagnostics, `${field}.define`, previews.define, void 0) && isValid2;
isValid2 = validateBindingsProperty(envName, validateDurableObjectBinding)(diagnostics, `${field}.durable_objects`, previews.durable_objects, void 0) && isValid2;
isValid2 = all(validateBindingArray(envName, validateWorkflowBinding), validateUniqueNameProperty)(diagnostics, `${field}.workflows`, previews.workflows, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateKVBinding)(diagnostics, `${field}.kv_namespaces`, previews.kv_namespaces, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateSendEmailBinding)(diagnostics, `${field}.send_email`, previews.send_email, void 0) && isValid2;
isValid2 = validateQueues(envName)(diagnostics, `${field}.queues`, previews.queues, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateD1Binding)(diagnostics, `${field}.d1_databases`, previews.d1_databases, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateR2Binding)(diagnostics, `${field}.r2_buckets`, previews.r2_buckets, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateVectorizeBinding)(diagnostics, `${field}.vectorize`, previews.vectorize, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateHyperdriveBinding)(diagnostics, `${field}.hyperdrive`, previews.hyperdrive, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateServiceBinding)(diagnostics, `${field}.services`, previews.services, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateAnalyticsEngineBinding)(diagnostics, `${field}.analytics_engine_datasets`, previews.analytics_engine_datasets, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateWorkerNamespaceBinding)(diagnostics, `${field}.dispatch_namespaces`, previews.dispatch_namespaces, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateMTlsCertificateBinding)(diagnostics, `${field}.mtls_certificates`, previews.mtls_certificates, void 0) && isValid2;
isValid2 = validateTailConsumers(diagnostics, `${field}.tail_consumers`, previews.tail_consumers, void 0) && isValid2;
isValid2 = validateStreamingTailConsumers(diagnostics, `${field}.streaming_tail_consumers`, previews.streaming_tail_consumers, void 0) && isValid2;
if (previews.unsafe !== void 0) isValid2 = validateUnsafeSettings(envName)(diagnostics, `${field}.unsafe`, previews.unsafe, void 0) && isValid2;
if (previews.browser !== void 0) isValid2 = validateNamedSimpleBinding(envName)(diagnostics, `${field}.browser`, previews.browser, void 0) && isValid2;
if (previews.ai !== void 0) isValid2 = validateAIBinding(envName)(diagnostics, `${field}.ai`, previews.ai, void 0) && isValid2;
if (previews.images !== void 0) isValid2 = validateNamedSimpleBinding(envName)(diagnostics, `${field}.images`, previews.images, void 0) && isValid2;
if (previews.stream !== void 0) isValid2 = validateNamedSimpleBinding(envName)(diagnostics, `${field}.stream`, previews.stream, void 0) && isValid2;
if (previews.media !== void 0) isValid2 = validateNamedSimpleBinding(envName)(diagnostics, `${field}.media`, previews.media, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validatePipelineBinding)(diagnostics, `${field}.pipelines`, previews.pipelines, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateSecretsStoreSecretBinding)(diagnostics, `${field}.secrets_store_secrets`, previews.secrets_store_secrets, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateArtifactsBinding)(diagnostics, `${field}.artifacts`, previews.artifacts, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateHelloWorldBinding)(diagnostics, `${field}.unsafe_hello_world`, previews.unsafe_hello_world, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateFlagshipBinding)(diagnostics, `${field}.flagship`, previews.flagship, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateWorkerLoaderBinding)(diagnostics, `${field}.worker_loaders`, previews.worker_loaders, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateRateLimitBinding)(diagnostics, `${field}.ratelimits`, previews.ratelimits, void 0) && isValid2;
isValid2 = validateBindingArray(envName, validateVpcServiceBinding)(diagnostics, `${field}.vpc_services`, previews.vpc_services, void 0) && isValid2;
if (previews.version_metadata !== void 0) isValid2 = validateVersionMetadataBinding(envName)(diagnostics, `${field}.version_metadata`, previews.version_metadata, void 0) && isValid2;
isValid2 = isBoolean(diagnostics, `${field}.logpush`, previews.logpush, void 0) && isValid2;
isValid2 = validateObservability(diagnostics, `${field}.observability`, previews.observability, void 0) && isValid2;
if (previews.limits) {
isValid2 = validateOptionalProperty(diagnostics, `${field}.limits`, "cpu_ms", previews.limits.cpu_ms, "number") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, `${field}.limits`, "subrequests", previews.limits.subrequests, "number") && isValid2;
}
isValid2 = validateCache(diagnostics, `${field}.cache`, previews.cache, void 0) && isValid2;
return isValid2;
}, "validatePreviewsConfig");
var 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$2 = true;
for (let i$1 = 0; i$1 < rawMigrations.length; i$1++) {
const { tag, new_classes, new_sqlite_classes, renamed_classes, deleted_classes, transferred_classes,...rest } = rawMigrations[i$1];
valid$2 = validateAdditionalProperties(diagnostics, "migrations", Object.keys(rest), []) && valid$2;
valid$2 = validateRequiredProperty(diagnostics, `migrations[${i$1}]`, `tag`, tag, "string") && valid$2;
valid$2 = validateOptionalTypedArray(diagnostics, `migrations[${i$1}].new_classes`, new_classes, "string") && valid$2;
valid$2 = validateOptionalTypedArray(diagnostics, `migrations[${i$1}].new_sqlite_classes`, new_sqlite_classes, "string") && valid$2;
if (renamed_classes !== void 0) {
if (!Array.isArray(renamed_classes)) {
diagnostics.errors.push(`Expected "migrations[${i$1}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(renamed_classes)}.`);
valid$2 = false;
} else if (renamed_classes.some((c) => typeof c !== "object" || !isRequiredProperty(c, "from", "string") || !isRequiredProperty(c, "to", "string"))) {
diagnostics.errors.push(`Expected "migrations[${i$1}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(renamed_classes)}.`);
valid$2 = false;
}
}
if (transferred_classes !== void 0) {
if (!Array.isArray(transferred_classes)) {
diagnostics.errors.push(`Expected "migrations[${i$1}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(transferred_classes)}.`);
valid$2 = false;
} else if (transferred_classes.some((c) => typeof c !== "object" || !isRequiredProperty(c, "from", "string") || !isRequiredProperty(c, "from_script", "string") || !isRequiredProperty(c, "to", "string"))) {
diagnostics.errors.push(`Expected "migrations[${i$1}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(transferred_classes)}.`);
valid$2 = false;
}
}
valid$2 = validateOptionalTypedArray(diagnostics, `migrations[${i$1}].deleted_classes`, deleted_classes, "string") && valid$2;
}
return valid$2;
}, "validateMigrations");
var 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 val = value;
let isValid2 = true;
isValid2 = validateAtLeastOnePropertyRequired(diagnostics, field, [
{
key: "enabled",
value: val.enabled,
type: "boolean"
},
{
key: "logs.enabled",
value: val.logs?.enabled,
type: "boolean"
},
{
key: "traces.enabled",
value: val.traces?.enabled,
type: "boolean"
}
]) && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "head_sampling_rate", val.head_sampling_rate, "number") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "logs", val.logs, "object") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "traces", val.traces, "object") && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
"enabled",
"head_sampling_rate",
"logs",
"traces"
]) && isValid2;
if (typeof val.logs === "object") {
isValid2 = validateOptionalProperty(diagnostics, field, "logs.enabled", val.logs.enabled, "boolean") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "logs.head_sampling_rate", val.logs.head_sampling_rate, "number") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "logs.invocation_logs", val.logs.invocation_logs, "boolean") && isValid2;
isValid2 = validateOptionalTypedArray(diagnostics, "logs.destinations", val.logs?.destinations, "string") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "logs.persist", val.logs.persist, "boolean") && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val.logs), [
"enabled",
"head_sampling_rate",
"invocation_logs",
"destinations",
"persist"
]) && isValid2;
}
if (typeof val.traces === "object") {
isValid2 = validateOptionalProperty(diagnostics, field, "traces.enabled", val.traces.enabled, "boolean") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "traces.head_sampling_rate", val.traces.head_sampling_rate, "number") && isValid2;
isValid2 = validateOptionalTypedArray(diagnostics, "traces.destinations", val.traces?.destinations, "string") && isValid2;
isValid2 = validateOptionalProperty(diagnostics, field, "traces.persist", val.traces.persist, "boolean") && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val.traces), [
"enabled",
"head_sampling_rate",
"destinations",
"persist"
]) && isValid2;
}
const samplingRate = val?.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");
var validateCache = /* @__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 ${JSON.stringify(value)}.`);
return false;
}
const val = value;
let isValid2 = true;
isValid2 = validateRequiredProperty(diagnostics, field, "enabled", val.enabled, "boolean") && isValid2;
isValid2 = validateAdditionalProperties(diagnostics, field, Object.keys(val), ["enabled"]) && isValid2;
return isValid2;
}, "validateCache");
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_sqlite_classes: durableObjectClassnames
}] }, configPath)}
\`\`\`
Refer to https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/ for more details.`);
}
}
}
}
__name(warnIfDurableObjectsHaveNoMigrations, "warnIfDurableObjectsHaveNoMigrations");
var validatePythonModules = /* @__PURE__ */ __name((diagnostics, field, value, topLevelEnv) => {
if (value === void 0) return true;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
diagnostics.errors.push(`"${field}" should be an object but got ${JSON.stringify(value)}.`);
return false;
}
const val = value;
if (!("exclude" in val)) return false;
if (!isStringArray(diagnostics, `${field}.exclude`, val.exclude, topLevelEnv)) return false;
return true;
}, "validatePythonModules");
function isRemoteValid(targetObject, fieldPath, diagnostics) {
if (!isOptionalProperty(targetObject, "remote", "boolean")) {
diagnostics.errors.push(`"${fieldPath}" should, optionally, have a boolean "remote" field but got ${JSON.stringify(targetObject)}.`);
return false;
}
return true;
}
__name(isRemoteValid, "isRemoteValid");
function isDockerfile(imagePath, configPath) {
const baseDir = configPath ? path.dirname(configPath) : process.cwd();
const maybeDockerfile = path.resolve(baseDir, imagePath);
if (fs.existsSync(maybeDockerfile)) {
if (isDirectory(maybeDockerfile)) throw new UserError(`${imagePath} is a directory, you should specify a path to the Dockerfile`, { telemetryMessage: false });
return true;
}
const errorPrefix = `The image "${imagePath}" does not appear to be a valid path to a Dockerfile, or a valid image registry path:
`;
try {
new URL(`https://${imagePath}`);
} catch (e2) {
if (e2 instanceof Error) throw new UserError(errorPrefix + e2.message, { telemetryMessage: false });
throw e2;
}
const imageParts = imagePath.split("/");
if (!imageParts[imageParts.length - 1]?.includes(":")) throw new UserError(errorPrefix + `If this is an image registry path, it needs to include at least a tag ':' (e.g: docker.io/httpd:1)`, { telemetryMessage: false });
if (imagePath.includes("://")) throw new UserError(errorPrefix + `Image reference should not include the protocol part (e.g: docker.io/httpd:1, not https://docker.io/httpd:1)`, { telemetryMessage: false });
return false;
}
__name(isDockerfile, "isDockerfile");
var supportedPagesConfigFields = [
"pages_build_output_dir",
"name",
"compatibility_date",
"compatibility_flags",
"send_metrics",
"no_bundle",
"limits",
"placement",
"vars",
"durable_objects",
"kv_namespaces",
"queues",
"r2_buckets",
"d1_databases",
"vectorize",
"hyperdrive",
"services",
"analytics_engine_datasets",
"ai",
"version_metadata",
"dev",
"mtls_certificates",
"browser",
"upload_source_maps",
"configPath",
"userConfigPath",
"topLevelName",
"definedEnvironments",
"targetEnvironment"
];
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.`, { telemetryMessage: false });
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;
}
__name(validatePagesConfig, "validatePagesConfig");
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.`);
}
__name(validateMainField, "validateMainField");
function validateProjectName(name, diagnostics) {
if (name === void 0 || name.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.`);
}
__name(validateProjectName, "validateProjectName");
function validatePagesEnvironmentNames(envNames, diagnostics) {
if (!envNames?.length) return;
const unsupportedPagesEnvNames = envNames.filter((name) => name !== "preview" && name !== "production");
if (unsupportedPagesEnvNames.length > 0) diagnostics.errors.push(`Configuration file contains the following environment names that are not supported by Pages projects:
${unsupportedPagesEnvNames.map((name) => `"${name}"`).join()}.
The supported named-environments for Pages are "preview" and "production".`);
}
__name(validatePagesEnvironmentNames, "validatePagesEnvironmentNames");
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) Array.from(unsupportedFields.keys()).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}"`);
});
}
__name(validateUnsupportedFields, "validateUnsupportedFields");
function validateDurableObjectBinding2(config, diagnostics) {
if (config.durable_objects.bindings.length > 0) {
if (config.durable_objects.bindings.filter((binding) => !isRequiredProperty(binding, "script_name", "string")).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.`);
}
}
__name(validateDurableObjectBinding2, "validateDurableObjectBinding");
var import_command_exists = __toESM(require_command_exists2());
var UPDATE_SERVICE_URL = "https://update.argotunnel.com";
var CLOUDFLARED_VERSION_PATTERN = /^\d{4}\.\d+\.\d+$/;
function sha256Hex(buffer$1) {
return createHash("sha256").update(buffer$1).digest("hex");
}
__name(sha256Hex, "sha256Hex");
function getGoArch() {
const nodeArch = arch();
switch (nodeArch) {
case "x64": return "amd64";
case "arm64": return "arm64";
case "arm": return "arm";
default: throw new UserError(`Unsupported architecture for cloudflared: ${nodeArch}
cloudflared supports: x64 (amd64), arm64, arm
You can manually install cloudflared and set the CLOUDFLARED_PATH environment variable.
Download instructions: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`, { telemetryMessage: "tunnel cloudflared unsupported architecture" });
}
}
__name(getGoArch, "getGoArch");
function getGoOS() {
switch (process.platform) {
case "darwin": return "darwin";
case "linux": return "linux";
case "win32": return "windows";
default: throw new UserError(`Unsupported platform for cloudflared: ${process.platform}
cloudflared supports: darwin (macOS), linux, win32 (Windows)
You can manually install cloudflared and set the CLOUDFLARED_PATH environment variable.
Download instructions: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`, { telemetryMessage: "tunnel cloudflared unsupported platform" });
}
}
__name(getGoOS, "getGoOS");
var GITHUB_RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/download";
function getAssetFilename(goOS, goArch) {
if (goOS === "windows") return `cloudflared-${goOS}-${goArch}.exe`;
if (goOS === "darwin") return `cloudflared-${goOS}-${goArch}.tgz`;
return `cloudflared-${goOS}-${goArch}`;
}
__name(getAssetFilename, "getAssetFilename");
async function queryUpdateService(goOS, goArch, options) {
const { logger } = options ?? {};
const url = new URL(UPDATE_SERVICE_URL);
url.searchParams.set("os", goOS);
url.searchParams.set("arch", goArch);
logger?.debug(`Checking for latest cloudflared: ${url.toString()}`);
let response;
try {
response = await (0, import_undici.fetch)(url.toString(), { headers: { "User-Agent": "wrangler" } });
} catch (e2) {
logger?.debug(`Failed to reach update service: ${e2 instanceof Error ? e2.message : String(e2)}`);
return null;
}
if (!response.ok) {
logger?.debug(`Update service returned ${response.status} for ${goOS}/${goArch}`);
return null;
}
let data$1;
try {
data$1 = await response.json();
} catch (e2) {
logger?.debug(`Update service returned non-JSON response: ${e2 instanceof Error ? e2.message : String(e2)}`);
return null;
}
if (typeof data$1.version === "string" && !CLOUDFLARED_VERSION_PATTERN.test(data$1.version)) throw new Error(`[cloudflared] Invalid cloudflared version returned by update service: ${data$1.version}`);
if (data$1.error || !data$1.url || !data$1.version) return data$1.version ? data$1 : null;
return data$1;
}
__name(queryUpdateService, "queryUpdateService");
async function getLatestVersionInfo(options) {
const { logger } = options ?? {};
const goOS = getGoOS();
const goArch = getGoArch();
const primary = await queryUpdateService(goOS, goArch, { logger });
if (primary && primary.url && primary.version) return primary;
logger?.debug(`Update worker had no result for ${goOS}/${goArch}, falling back to GitHub release URL`);
const fallback = await queryUpdateService("linux", "amd64", { logger });
if (!fallback?.version) throw new UserError(`[cloudflared] Failed to determine the latest cloudflared version.
The update service did not return results for ${goOS}/${goArch},
and the fallback query also failed.
You can manually install cloudflared from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`, { telemetryMessage: "tunnel cloudflared version lookup failed" });
const version$2 = fallback.version;
const filename = getAssetFilename(goOS, goArch);
return {
url: `${GITHUB_RELEASE_BASE}/${version$2}/${filename}`,
version: version$2,
checksum: "",
compressed: filename.endsWith(".tgz"),
shouldUpdate: true,
userMessage: "",
error: ""
};
}
__name(getLatestVersionInfo, "getLatestVersionInfo");
function getCacheDir(version$2) {
return join(getGlobalWranglerConfigPath(), "cloudflared", version$2);
}
__name(getCacheDir, "getCacheDir");
function getCloudflaredBinPath(version$2) {
const binName = process.platform === "win32" ? "cloudflared.exe" : "cloudflared";
return join(getCacheDir(version$2), binName);
}
__name(getCloudflaredBinPath, "getCloudflaredBinPath");
function isBinaryExecutable(binPath) {
try {
accessSync(binPath, constants.X_OK);
return true;
} catch {
return false;
}
}
__name(isBinaryExecutable, "isBinaryExecutable");
function validateBinary(binPath, options) {
const { logger } = options ?? {};
try {
const output = execFileSync(binPath, ["--version"], {
stdio: [
"pipe",
"pipe",
"pipe"
],
timeout: 1e4,
encoding: "utf8"
}).trim();
logger?.debug(`cloudflared version: ${output}`);
} catch {
let errorMessage = `[cloudflared] Failed to validate cloudflared binary at ${binPath}
`;
errorMessage += `This usually means:
`;
errorMessage += ` - The binary is corrupted or incomplete
`;
errorMessage += ` - You're missing required system libraries
`;
if (process.platform === "linux") {
errorMessage += `
On Linux, make sure you have the required dependencies:
`;
errorMessage += ` - glibc (GNU C Library)
`;
errorMessage += ` - For Debian/Ubuntu: sudo apt-get install libc6
`;
}
const cacheDir = join(getGlobalWranglerConfigPath(), "cloudflared");
errorMessage += `
You can try:
`;
errorMessage += ` 1. Deleting the cache directory: rm -rf ${cacheDir}
`;
errorMessage += ` 2. Running the command again to re-download
`;
errorMessage += ` 3. Manually installing cloudflared: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/
`;
errorMessage += ` 4. Setting CLOUDFLARED_PATH to point to your cloudflared binary`;
throw new UserError(errorMessage, { telemetryMessage: "tunnel cloudflared validation failed" });
}
}
__name(validateBinary, "validateBinary");
function redactCloudflaredArgsForLogging(args) {
const redacted = [...args];
for (let i$1 = 0; i$1 < redacted.length; i$1++) {
const arg = redacted[i$1];
if (arg === "--token" && i$1 + 1 < redacted.length) redacted[i$1 + 1] = "[REDACTED]";
if (arg.startsWith("--token=")) redacted[i$1] = "--token=[REDACTED]";
}
return redacted;
}
__name(redactCloudflaredArgsForLogging, "redactCloudflaredArgsForLogging");
function tryGetCloudflaredFromPath(options) {
const { logger } = options ?? {};
if (!(0, import_command_exists.sync)("cloudflared")) return null;
try {
validateBinary("cloudflared", { logger });
return "cloudflared";
} catch (e2) {
logger?.debug("cloudflared found in PATH but failed validation", e2);
return null;
}
}
__name(tryGetCloudflaredFromPath, "tryGetCloudflaredFromPath");
function getInstalledVersion(binPath) {
try {
const match = execFileSync(binPath, ["--version"], {
stdio: [
"pipe",
"pipe",
"pipe"
],
timeout: 1e4,
encoding: "utf8"
}).match(/(\d+\.\d+\.\d+)/);
return match ? match[1] : null;
} catch {
return null;
}
}
__name(getInstalledVersion, "getInstalledVersion");
function isVersionOutdated(installed, latest) {
const parse$10 = /* @__PURE__ */ __name((v) => v.split(".").map(Number), "parse");
const [iYear, iMonth, iPatch] = parse$10(installed);
const [lYear, lMonth, lPatch] = parse$10(latest);
if (iYear !== lYear) return iYear < lYear;
if (iMonth !== lMonth) return iMonth < lMonth;
return iPatch < lPatch;
}
__name(isVersionOutdated, "isVersionOutdated");
async function warnIfOutdated(binPath, options) {
const { logger } = options ?? {};
try {
const installed = getInstalledVersion(binPath);
if (!installed) return;
const latestVersion = (await queryUpdateService(getGoOS(), getGoArch(), { logger }) ?? await queryUpdateService("linux", "amd64", { logger }))?.version;
if (!latestVersion) return;
if (isVersionOutdated(installed, latestVersion)) logger?.warn(`Your cloudflared (${installed}) is outdated. Latest version is ${latestVersion}.
Update: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`);
} catch (e2) {
logger?.debug("Failed to check cloudflared version", e2);
}
}
__name(warnIfOutdated, "warnIfOutdated");
function writeFileAtomic(filePath, contents) {
const tmpPath = join(dirname(filePath), `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
try {
writeFileSync(tmpPath, contents);
renameSync(tmpPath, filePath);
} finally {
try {
if (existsSync(tmpPath)) unlinkSync(tmpPath);
} catch {}
}
}
__name(writeFileAtomic, "writeFileAtomic");
async function downloadCloudflared(versionInfo, binPath, options) {
const { logger } = options ?? {};
const { url, version: version$2, checksum, compressed } = versionInfo;
logger?.log(`Downloading cloudflared ${version$2}...`);
logger?.debug(`Download URL: ${url}`);
const cacheDir = dirname(binPath);
mkdirSync(cacheDir, { recursive: true });
let response;
try {
response = await (0, import_undici.fetch)(url, { headers: { "User-Agent": "wrangler" } });
} catch (e2) {
throw new UserError(`[cloudflared] Failed to download cloudflared from ${url}
Network error: ${e2 instanceof Error ? e2.message : String(e2)}
Please check your internet connection and try again.
If you're behind a proxy, make sure it's configured correctly.`, { telemetryMessage: "tunnel cloudflared download network failed" });
}
if (!response.ok) throw new UserError(`[cloudflared] Failed to download cloudflared from ${url}
HTTP ${response.status}: ${response.statusText}
You can manually download cloudflared from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`, { telemetryMessage: "tunnel cloudflared download response failed" });
try {
if (compressed) await downloadAndExtractTarball(response, checksum, binPath, cacheDir);
else await downloadBinary(response, checksum, binPath);
} catch (e2) {
try {
if (existsSync(binPath)) unlinkSync(binPath);
} catch {}
if (e2 instanceof UserError) throw e2;
throw new UserError(`[cloudflared] Failed to save cloudflared binary
Error: ${e2 instanceof Error ? e2.message : String(e2)}
Please ensure you have write permissions to: ${cacheDir}`, { telemetryMessage: "tunnel cloudflared save failed" });
}
if (process.platform !== "win32") chmodSync(binPath, 493);
logger?.log(`cloudflared ${version$2} installed`);
logger?.debug(`Binary location: ${binPath}`);
}
__name(downloadCloudflared, "downloadCloudflared");
async function downloadAndExtractTarball(response, expectedChecksum, binPath, cacheDir) {
const tempTarPath = join(cacheDir, "cloudflared.tgz");
const buffer$1 = Buffer.from(await response.arrayBuffer());
if (expectedChecksum) {
const actualSha256 = sha256Hex(buffer$1);
if (actualSha256 !== expectedChecksum) throw new UserError(`[cloudflared] SHA256 mismatch for downloaded cloudflared tarball.
Expected: ${expectedChecksum}
Actual: ${actualSha256}`, { telemetryMessage: "tunnel cloudflared tarball checksum mismatch" });
}
writeFileSync(tempTarPath, buffer$1);
try {
execFileSync("tar", [
"-xzf",
tempTarPath,
"-C",
cacheDir
], { stdio: "ignore" });
const extractedPath = join(cacheDir, "cloudflared");
if (extractedPath !== binPath && existsSync(extractedPath)) renameSync(extractedPath, binPath);
} finally {
try {
if (existsSync(tempTarPath)) unlinkSync(tempTarPath);
} catch {}
}
}
__name(downloadAndExtractTarball, "downloadAndExtractTarball");
async function downloadBinary(response, expectedChecksum, binPath) {
const buffer$1 = Buffer.from(await response.arrayBuffer());
if (expectedChecksum) {
const actualSha256 = sha256Hex(buffer$1);
if (actualSha256 !== expectedChecksum) throw new UserError(`[cloudflared] SHA256 mismatch for downloaded cloudflared binary.
Expected: ${expectedChecksum}
Actual: ${actualSha256}`, { telemetryMessage: "tunnel cloudflared binary checksum mismatch" });
}
writeFileAtomic(binPath, buffer$1);
}
__name(downloadBinary, "downloadBinary");
async function getCloudflaredPath(options) {
const logger = options?.logger;
const envPath = getCloudflaredPathFromEnv();
if (envPath) {
if (!existsSync(envPath)) throw new UserError(`CLOUDFLARED_PATH is set to "${envPath}" but the file does not exist.
Please ensure the path points to a valid cloudflared binary.`, { telemetryMessage: "tunnel cloudflared env path missing" });
logger?.debug(`Using cloudflared from CLOUDFLARED_PATH: ${envPath}`);
return envPath;
}
const pathBin = tryGetCloudflaredFromPath({ logger });
if (pathBin) {
logger?.debug("Using cloudflared from PATH");
if (!options?.skipVersionCheck) await warnIfOutdated(pathBin, { logger });
return pathBin;
}
const versionInfo = await getLatestVersionInfo({ logger });
const binPath = getCloudflaredBinPath(versionInfo.version);
let needsDownload = !isBinaryExecutable(binPath);
if (!needsDownload) try {
validateBinary(binPath, { logger });
logger?.debug(`Using cached cloudflared ${versionInfo.version}: ${binPath}`);
return binPath;
} catch (e2) {
logger?.debug("Cached cloudflared failed validation; re-downloading", e2);
needsDownload = true;
}
if (!(await options?.confirmDownload?.(`cloudflared (${versionInfo.version}) is needed but not installed. Download to ${binPath}?`) ?? true)) throw new UserError(`cloudflared is required to run this command.
You can install it manually from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/
Then either add it to your PATH or set CLOUDFLARED_PATH.`, { telemetryMessage: "tunnel cloudflared download declined" });
if (existsSync(binPath)) {
const cacheDir = removeCloudflaredCache(versionInfo.version);
if (cacheDir) logger?.log(`Removed cloudflared cache: ${cacheDir}`);
}
await downloadCloudflared(versionInfo, binPath, { logger });
validateBinary(binPath, { logger });
return binPath;
}
__name(getCloudflaredPath, "getCloudflaredPath");
async function spawnCloudflared(args, options) {
const logger = options?.logger;
const binPath = await getCloudflaredPath({
skipVersionCheck: options?.skipVersionCheck,
confirmDownload: options?.confirmDownload,
logger
});
logger?.debug(`Spawning cloudflared: ${binPath} ${redactCloudflaredArgsForLogging(args).join(" ")}`);
return spawn(binPath, args, {
stdio: options?.stdio ?? "inherit",
env: options?.env ? {
...process.env,
...options.env
} : void 0
});
}
__name(spawnCloudflared, "spawnCloudflared");
function removeCloudflaredCache(version$2) {
const cacheDir = version$2 ? getCacheDir(version$2) : join(getGlobalWranglerConfigPath(), "cloudflared");
if (existsSync(cacheDir)) {
removeDirSync(cacheDir);
return cacheDir;
}
return null;
}
__name(removeCloudflaredCache, "removeCloudflaredCache");
var TUNNEL_STARTUP_TIMEOUT_MS = 3e4;
var TUNNEL_FORCE_KILL_TIMEOUT_MS = 5e3;
var DEFAULT_TUNNEL_EXPIRY_MS = 3600 * 1e3;
var DEFAULT_TUNNEL_EXTENSION_MS = 3600 * 1e3;
var DEFAULT_TUNNEL_MAX_REMAINING_MS = 10800 * 1e3;
var DEFAULT_TUNNEL_REMINDER_INTERVAL_MS = 600 * 1e3;
var QUICK_TUNNEL_URL_REGEX = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/;
function startTunnel(options) {
let disposed = false;
let reminderInterval;
let expiryTimeout;
let expiresAt = 0;
let cloudflaredProcess;
const logger = options.logger;
const timeoutMs = options.timeoutMs ?? TUNNEL_STARTUP_TIMEOUT_MS;
const reminderIntervalMs = options.reminderIntervalMs ?? DEFAULT_TUNNEL_REMINDER_INTERVAL_MS;
const defaultExpiryMs = options.expiryMs ?? DEFAULT_TUNNEL_EXPIRY_MS;
const isNamedTunnel = options.token !== void 0;
const timeFormatter = new Intl.DateTimeFormat(void 0, { timeStyle: "short" });
const readyPromise = spawnCloudflared(isNamedTunnel ? [
"tunnel",
"--no-autoupdate",
"run"
] : [
"tunnel",
"--no-autoupdate",
"--url",
options.origin.href
], {
stdio: "pipe",
env: options.token ? { TUNNEL_TOKEN: options.token } : void 0,
skipVersionCheck: true,
logger
}).then((process2) => {
cloudflaredProcess = process2;
if (disposed) terminateCloudflared(process2);
return process2;
}).then((process2) => {
if (isNamedTunnel) return { mode: "named" };
return waitForQuickTunnelReady(process2, timeoutMs, {
logger,
origin: options.origin
});
}).then((result) => {
expiresAt = Date.now() + defaultExpiryMs;
scheduleExpiryTimeout();
scheduleReminder(result.mode === "quick" ? result.publicUrl.origin : void 0);
return result;
});
function disposeTunnel() {
disposed = true;
clearTunnelTimers();
if (cloudflaredProcess) terminateCloudflared(cloudflaredProcess);
}
__name(disposeTunnel, "disposeTunnel");
function clearTunnelTimers() {
if (expiryTimeout) {
clearTimeout(expiryTimeout);
expiryTimeout = void 0;
}
if (reminderInterval) {
clearInterval(reminderInterval);
reminderInterval = void 0;
}
}
__name(clearTunnelTimers, "clearTunnelTimers");
function scheduleReminder(publicURL) {
if (reminderIntervalMs > 0) {
reminderInterval = setInterval(() => {
if (disposed) return;
const remainingMs = expiresAt - Date.now();
if (remainingMs <= 0) return;
logger?.log(`${publicURL ? `The tunnel is still open at ${publicURL}.` : "The tunnel is still open."} It expires in ${formatTunnelDuration(remainingMs)}. ${options.extendHint ?? ""}`);
}, reminderIntervalMs);
reminderInterval.unref?.();
}
}
__name(scheduleReminder, "scheduleReminder");
function scheduleExpiryTimeout() {
if (disposed) return;
if (expiryTimeout) clearTimeout(expiryTimeout);
expiryTimeout = setTimeout(() => {
if (disposed) return;
logger?.log("Tunnel expired. Closing tunnel.");
disposeTunnel();
}, Math.max(0, expiresAt - Date.now()));
expiryTimeout.unref();
}
__name(scheduleExpiryTimeout, "scheduleExpiryTimeout");
function extendExpiry(ms = DEFAULT_TUNNEL_EXTENSION_MS) {
if (disposed || !expiryTimeout || ms <= 0) return;
const now = Date.now();
const previousExpiresAt = expiresAt;
expiresAt = Math.min(now + DEFAULT_TUNNEL_MAX_REMAINING_MS, Math.max(expiresAt, now) + ms);
const extendedByMs = expiresAt - previousExpiresAt;
if (extendedByMs < ms) {
logger?.log(`Tunnel expiry extended to the ${formatTunnelDuration(DEFAULT_TUNNEL_MAX_REMAINING_MS)} limit. It now expires at ${timeFormatter.format(new Date(expiresAt))}.`);
scheduleExpiryTimeout();
return;
}
logger?.log(`Tunnel expiry extended by ${formatTunnelDuration(extendedByMs)}. It now expires at ${timeFormatter.format(new Date(expiresAt))}.`);
scheduleExpiryTimeout();
}
__name(extendExpiry, "extendExpiry");
return {
ready: /* @__PURE__ */ __name(() => readyPromise, "ready"),
isOpen: /* @__PURE__ */ __name(() => !disposed, "isOpen"),
dispose: disposeTunnel,
extendExpiry
};
}
__name(startTunnel, "startTunnel");
function formatTunnelDuration(durationMs) {
const totalMinutes = Math.max(1, Math.ceil(durationMs / 6e4));
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (hours === 0) return `${minutes}m`;
if (minutes === 0) return `${hours}h`;
return `${hours}h ${minutes}m`;
}
__name(formatTunnelDuration, "formatTunnelDuration");
function terminateCloudflared(cloudflared) {
if (cloudflared.killed) return;
cloudflared.unref();
cloudflared.kill("SIGTERM");
setTimeout(() => {
if (!cloudflared.killed) cloudflared.kill("SIGKILL");
}, TUNNEL_FORCE_KILL_TIMEOUT_MS).unref();
}
__name(terminateCloudflared, "terminateCloudflared");
function waitForQuickTunnelReady(cloudflared, timeoutMs, options) {
return new Promise((resolve$4, reject) => {
let resolved = false;
let stderrOutput = "";
const logger = options?.logger;
const origin = options?.origin;
const timeoutId = setTimeout(() => {
if (!resolved) {
resolved = true;
terminateCloudflared(cloudflared);
reject(createTunnelStartupError(`Timed out waiting for cloudflared to start (${timeoutMs / 1e3}s).`, stderrOutput, origin));
}
}, timeoutMs);
timeoutId.unref();
if (cloudflared.stderr) cloudflared.stderr.on("data", (data$1) => {
const chunk = data$1.toString();
stderrOutput += chunk;
logger?.debug("[cloudflared]", chunk.trimEnd());
const match = QUICK_TUNNEL_URL_REGEX.exec(stderrOutput);
if (match && !resolved) {
resolved = true;
clearTimeout(timeoutId);
resolve$4({
mode: "quick",
publicUrl: new URL(match[0])
});
}
});
cloudflared.on("error", (error) => {
if (!resolved) {
resolved = true;
clearTimeout(timeoutId);
reject(/* @__PURE__ */ new Error(`Failed to start cloudflared: ${error.message}`));
}
});
cloudflared.on("exit", (code, signal) => {
if (!resolved) {
resolved = true;
clearTimeout(timeoutId);
reject(createTunnelStartupError(`cloudflared ${signal ? `terminated by signal ${signal}` : `exited with code ${code}`} before the tunnel was ready.`, stderrOutput, origin));
}
});
});
}
__name(waitForQuickTunnelReady, "waitForQuickTunnelReady");
function createTunnelStartupError(message, stderrOutput, origin) {
const isQuickTunnelRateLimited = stderrOutput.includes("429 Too Many Requests");
const errorMessage = `${message}
cloudflared output:
${stderrOutput || "(no output)"}
The local dev server started at ${origin.href}.
` + (isQuickTunnelRateLimited ? "Cloudflare Quick Tunnel creation was rate limited. Try again in a few minutes, or use a named tunnel if you need more reliable access." : `Check the cloudflared output above for more details, and verify that ${origin.href} is reachable from this machine if this keeps happening.`);
if (isQuickTunnelRateLimited) return new UserError(errorMessage, { telemetryMessage: false });
return new Error(errorMessage);
}
__name(createTunnelStartupError, "createTunnelStartupError");
//#endregion
//#region ../../node_modules/.pnpm/get-port@7.1.0/node_modules/get-port/index.js
var Locked = class extends Error {
constructor(port) {
super(`${port} is locked`);
}
};
const lockedPorts = {
old: /* @__PURE__ */ new Set(),
young: /* @__PURE__ */ new Set()
};
const releaseOldLockedPortsIntervalMs = 1e3 * 15;
const minPort = 1024;
const maxPort = 65535;
let timeout;
const getLocalHosts = () => {
const interfaces = os.networkInterfaces();
const results = 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;
};
const checkAvailablePort = (options) => new Promise((resolve$4, reject) => {
const server = net.createServer();
server.unref();
server.on("error", reject);
server.listen(options, () => {
const { port } = server.address();
server.close(() => {
resolve$4(port);
});
});
});
const getAvailablePort = 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 (error) {
if (!["EADDRNOTAVAIL", "EINVAL"].includes(error.code)) throw error;
}
return options.port;
};
const portCheckSequence = function* (ports) {
if (ports) yield* ports;
yield 0;
};
async function getPorts(options) {
let ports;
let exclude = /* @__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`);
}
exclude = 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 (exclude.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 (error) {
if (!["EADDRINUSE", "EACCES"].includes(error.code) && !(error instanceof Locked)) throw error;
}
throw new Error("No available ports found");
}
function portNumbers(from, to) {
if (!Number.isInteger(from) || !Number.isInteger(to)) throw new TypeError("`from` and `to` must be integer numbers");
if (from < minPort || from > maxPort) throw new RangeError(`'from' must be between ${minPort} and ${maxPort}`);
if (to < minPort || to > maxPort) throw new RangeError(`'to' must be between ${minPort} and ${maxPort}`);
if (from > to) throw new RangeError("`to` must be greater than or equal to `from`");
const generator = function* (from$1, to$1) {
for (let port = from$1; port <= to$1; port++) yield port;
};
return generator(from, to);
}
//#endregion
//#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
var require_picocolors = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js": ((exports, module) => {
let p = process || {}, argv = p.argv || [], env = p.env || {};
let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
let formatter = (open$1, close, replace = open$1) => (input) => {
let string = "" + input, index = string.indexOf(close, open$1.length);
return ~index ? open$1 + replaceClose(string, close, replace, index) + close : open$1 + string + close;
};
let replaceClose = (string, close, replace, index) => {
let result = "", cursor = 0;
do {
result += string.substring(cursor, index) + replace;
cursor = index + close.length;
index = string.indexOf(close, cursor);
} while (~index);
return result + string.substring(cursor);
};
let createColors = (enabled = isColorSupported) => {
let f = enabled ? formatter : () => String;
return {
isColorSupported: enabled,
reset: f("\x1B[0m", "\x1B[0m"),
bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
italic: f("\x1B[3m", "\x1B[23m"),
underline: f("\x1B[4m", "\x1B[24m"),
inverse: f("\x1B[7m", "\x1B[27m"),
hidden: f("\x1B[8m", "\x1B[28m"),
strikethrough: f("\x1B[9m", "\x1B[29m"),
black: f("\x1B[30m", "\x1B[39m"),
red: f("\x1B[31m", "\x1B[39m"),
green: f("\x1B[32m", "\x1B[39m"),
yellow: f("\x1B[33m", "\x1B[39m"),
blue: f("\x1B[34m", "\x1B[39m"),
magenta: f("\x1B[35m", "\x1B[39m"),
cyan: f("\x1B[36m", "\x1B[39m"),
white: f("\x1B[37m", "\x1B[39m"),
gray: f("\x1B[90m", "\x1B[39m"),
bgBlack: f("\x1B[40m", "\x1B[49m"),
bgRed: f("\x1B[41m", "\x1B[49m"),
bgGreen: f("\x1B[42m", "\x1B[49m"),
bgYellow: f("\x1B[43m", "\x1B[49m"),
bgBlue: f("\x1B[44m", "\x1B[49m"),
bgMagenta: f("\x1B[45m", "\x1B[49m"),
bgCyan: f("\x1B[46m", "\x1B[49m"),
bgWhite: f("\x1B[47m", "\x1B[49m"),
blackBright: f("\x1B[90m", "\x1B[39m"),
redBright: f("\x1B[91m", "\x1B[39m"),
greenBright: f("\x1B[92m", "\x1B[39m"),
yellowBright: f("\x1B[93m", "\x1B[39m"),
blueBright: f("\x1B[94m", "\x1B[39m"),
magentaBright: f("\x1B[95m", "\x1B[39m"),
cyanBright: f("\x1B[96m", "\x1B[39m"),
whiteBright: f("\x1B[97m", "\x1B[39m"),
bgBlackBright: f("\x1B[100m", "\x1B[49m"),
bgRedBright: f("\x1B[101m", "\x1B[49m"),
bgGreenBright: f("\x1B[102m", "\x1B[49m"),
bgYellowBright: f("\x1B[103m", "\x1B[49m"),
bgBlueBright: f("\x1B[104m", "\x1B[49m"),
bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
bgCyanBright: f("\x1B[106m", "\x1B[49m"),
bgWhiteBright: f("\x1B[107m", "\x1B[49m")
};
};
module.exports = createColors();
module.exports.createColors = createColors;
}) });
//#endregion
//#region src/plugins/tunnel.ts
var import_picocolors$5 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
function createPublicExposureWarning(mode, name, shortcutPressed) {
const intro = name === void 0 ? import_picocolors$5.default.dim("Once connected, this tunnel will be ") + "publicly accessible" + import_picocolors$5.default.dim(". Anyone who can reach it can:") : import_picocolors$5.default.dim("Once connected, this tunnel may be reachable from the Internet. Anyone who can reach it can:");
const concerns = [
"Call ungated endpoints",
"Trigger logic that uses remote bindings",
"Reach internal services if your Worker proxies requests"
];
const hints = [name === void 0 ? "Consider using a named tunnel with Cloudflare Access to restrict access." : "Consider using Cloudflare Access to restrict access."];
if (mode === "dev") {
concerns.push("Request module source and other dev-server assets", "Access HMR messages, including absolute file system paths", "Observe file-change cadence and parts of the live module graph");
hints.unshift("If you only need to share a running build, use vite preview to avoid HMR and other dev-server exposure.");
}
const lines = [
intro,
...concerns.map((concern) => import_picocolors$5.default.dim(`• ${concern}`)),
"",
...hints.map((guidance) => import_picocolors$5.default.dim(guidance)),
""
];
if (shortcutPressed) lines.push("Press t + enter again to close the tunnel.", "");
const spacing = " ";
return lines.map((line) => spacing + line).join("\n");
}
const QUICK_TUNNEL_SSE_WARNING = "Quick tunnels do not support Server-Sent Events (SSE). Use a named Cloudflare Tunnel if you need SSE over a public URL.";
const QUICK_TUNNEL_ALLOWED_HOST = ".trycloudflare.com";
var TunnelManager = class {
#logger;
#origin;
#publicUrls;
#requestedTunnel;
#tunnel;
#abortController;
#hasWarnedAboutSse = false;
constructor(logger) {
this.#logger = logger;
}
isStarted(origin, name) {
return this.#origin === origin && this.#requestedTunnel === name;
}
isOpen() {
if (!this.#tunnel) return this.#origin !== void 0;
const isOpen = this.#tunnel.isOpen();
if (!isOpen) {
this.#tunnel = void 0;
this.dispose();
}
return isOpen;
}
async startTunnel(options) {
try {
if (this.#tunnel) this.dispose();
const abortController = new AbortController();
this.#abortController = abortController;
this.#origin = options.origin;
this.#requestedTunnel = options.name;
this.#logger.info(import_picocolors$5.default.dim("\n ➜ Starting tunnel (usually takes a few seconds)...\n"));
this.#logger.warn(createPublicExposureWarning(options.mode, options.name, options.shortcutPressed ?? false));
const namedTunnel = options.name !== void 0 ? await wrangler.unstable_resolveNamedTunnel(options.name, new URL(options.origin), {
accountId: options.accountId,
complianceRegion: options.complianceRegion
}) : void 0;
if (abortController.signal.aborted) return null;
if (namedTunnel) this.#publicUrls = namedTunnel.hostnames.map((hostname) => `https://${hostname}`);
if (options.mode === "preview") {
if (namedTunnel) {
const allowedUrls = getAllowedTunnelUrls(this.#publicUrls ?? [], options.allowedHosts);
if (allowedUrls.length === 0) {
const suggestedAllowedHosts = getSuggestedAllowedHosts(namedTunnel.hostnames);
throw new Error("The resolved tunnel hostnames are not allowed by Vite preview host validation.\n\nAdd at least one of these hosts to `preview.allowedHosts` in your Vite config.\nYou can use exact hostnames or a domain suffix:\n" + suggestedAllowedHosts.map((hostname) => ` - ${hostname}`).join("\n") + "\n");
}
this.#publicUrls = allowedUrls;
} else if (!isQuickTunnelAllowed(options.allowedHosts)) throw new Error(`Quick tunnel hostnames are not allowed by Vite preview host validation.
Add \`${QUICK_TUNNEL_ALLOWED_HOST}\` to \`preview.allowedHosts\` in your Vite config.\n`);
}
const tunnel = startTunnel({
origin: new URL(options.origin),
token: namedTunnel?.token,
extendHint: "Press a + enter to extend by 1 hour.",
logger: {
log: (message) => this.#logger.info(message),
warn: (message) => this.#logger.warn(message),
debug: (message) => debuglog(message)
}
});
this.#tunnel = tunnel;
return await this.#waitForPublicUrls(tunnel);
} catch (error) {
this.#origin = void 0;
this.#publicUrls = void 0;
this.#requestedTunnel = void 0;
throw error;
}
}
async #waitForPublicUrls(tunnel) {
try {
const result = await tunnel.ready();
if (this.#tunnel !== tunnel) {
debuglog("Tunnel was restarted before it finished starting. Ignoring this tunnel's public URL:", result.mode === "quick" ? result.publicUrl : this.#publicUrls);
return null;
}
if (result.mode === "named") return this.#publicUrls ?? null;
const { publicUrl } = result;
debuglog("Tunnel is ready with public URL:", publicUrl);
this.#publicUrls = [publicUrl.toString()];
return this.#publicUrls;
} catch (error) {
if (this.#tunnel !== tunnel) return null;
this.#tunnel = void 0;
throw error;
}
}
get publicUrls() {
return this.#publicUrls;
}
extendExpiry() {
this.#tunnel?.extendExpiry();
}
warnIfQuickTunnelSseResponse(contentType) {
if (this.#hasWarnedAboutSse || this.#requestedTunnel !== void 0 || !this.#tunnel || contentType === null || !contentType.toLowerCase().startsWith("text/event-stream")) return;
this.#hasWarnedAboutSse = true;
this.#logger.warn(QUICK_TUNNEL_SSE_WARNING);
}
dispose() {
const tunnel = this.#tunnel;
this.#abortController?.abort();
this.#origin = void 0;
this.#publicUrls = void 0;
this.#requestedTunnel = void 0;
this.#tunnel = void 0;
this.#hasWarnedAboutSse = false;
debuglog("Disposing tunnel...");
if (tunnel) tunnel.dispose();
this.#logger.info(" ➜ Tunnel closed");
}
disposeOnExit() {
try {
this.dispose();
} catch (e) {
this.#logger.error("Failed to dispose tunnel on exit:" + (e instanceof Error ? e.message : `${e}`));
}
}
};
let tunnelManager;
process.on("exit", () => {
tunnelManager?.disposeOnExit();
});
function warnIfQuickTunnelSseResponse(contentType) {
tunnelManager?.warnIfQuickTunnelSseResponse(contentType);
}
function extendTunnelExpiry() {
tunnelManager?.extendExpiry();
}
function isTunnelOpen() {
return tunnelManager?.isOpen() ?? false;
}
async function toggleTunnel(server, ctx) {
if (!tunnelManager) return;
if (tunnelManager.isOpen()) {
ctx.clearTunnelHostnames();
tunnelManager.dispose();
return;
}
if ("restart" in server) await setupDevTunnel(server, ctx, tunnelManager, true);
else await setupPreviewTunnel(server, ctx, tunnelManager, true);
}
/**
* Resolve the dev tunnel origin from the running server.
*
* This simply waits for Vite to start listening and then reuses its resolved URL.
*/
async function resolveDevTunnelOrigin(server) {
const httpServer = server.httpServer;
if (!httpServer) throw new Error("No HTTP server available for tunnel sharing. Tunnels are not supported in middleware mode.");
if (!httpServer.listening) await new Promise((resolve$4) => {
httpServer.once("listening", () => resolve$4());
});
const url = server.resolvedUrls?.local?.[0] ?? server.resolvedUrls?.network?.[0];
if (!url) throw new Error("Could not determine the local dev server URL for tunnel sharing.");
return url;
}
/**
* Resolve the preview tunnel origin before preview starts listening.
*
* Unlike dev, preview does not give us a similar `server.listen()` hook where
* we can wait for the final bound URL before starting the tunnel. We resolve
* the port up front using Vite's preview port rules so the tunnel and preview
* server agree on the same origin:
*
* - `port: 0`: use any free port
* - `strictPort: true`: use the exact port or fail
* - otherwise: use the first free port at or above `preview.port`
*/
async function resolvePreviewTunnelOrigin(server) {
const { preview } = server.config;
const host = typeof preview.host === "string" ? preview.host : void 0;
let resolvedPort = preview.port;
if (!server.httpServer.listening) if (preview.port === 0) resolvedPort = await getPorts({
port: 0,
host
});
else if (preview.strictPort) {
resolvedPort = await getPorts({
port: preview.port,
host
});
if (resolvedPort !== preview.port) throw new Error(`Port ${preview.port} is already in use.`);
} else {
function* candidatePorts() {
for (let port = preview.port; port <= 65535; port++) yield port;
}
resolvedPort = await getPorts({
host,
port: candidatePorts()
});
}
return new URL(buildPublicUrl({
hostname: host,
port: resolvedPort,
secure: !!preview.https
}));
}
async function setupDevTunnel(server, ctx, manager, shortcutPressed) {
const origin = await resolveDevTunnelOrigin(server);
const tunnel = ctx.resolvedPluginConfig.tunnel;
if (manager.isStarted(origin, tunnel.name)) {
debuglog("Tunnel is already started on", origin);
return;
}
const publicUrls = await manager.startTunnel({
mode: "dev",
origin,
shortcutPressed,
name: tunnel.name,
accountId: ctx.entryWorkerConfig?.account_id,
complianceRegion: ctx.entryWorkerConfig?.compliance_region,
allowedHosts: true
});
if (!publicUrls) return;
const allowedHosts = server.config.server.allowedHosts;
const tunnelHostnames = publicUrls.map((url) => new URL(url).hostname);
ctx.replaceTunnelHostnames(tunnelHostnames);
if (allowedHosts !== true && tunnelHostnames.some((hostname) => !allowedHosts.includes(hostname))) await server.restart();
if (shortcutPressed) server.printUrls();
}
/**
* Start a preview tunnel on the resolved preview origin.
*
* We write the resolved port back to preview config so the server binds the
* same port that the tunnel is sharing.
*/
async function setupPreviewTunnel(server, ctx, manager, shortcutPressed) {
const { preview } = server.config;
const originalPort = preview.port;
const resolvedOrigin = await resolvePreviewTunnelOrigin(server);
const resolvedPort = Number(resolvedOrigin.port);
preview.port = resolvedPort;
preview.strictPort = true;
if (originalPort !== 0 && resolvedPort !== originalPort) server.config.logger.info(import_picocolors$5.default.dim(`Port ${originalPort} is in use, using ${resolvedPort} instead for preview tunnel sharing.\n`));
const tunnel = ctx.resolvedPluginConfig.tunnel;
const origin = resolvedOrigin.toString();
if (manager.isStarted(origin, tunnel.name)) {
debuglog("Tunnel is already started on", origin);
return;
}
if (!await manager.startTunnel({
mode: "preview",
origin,
shortcutPressed,
name: tunnel.name,
allowedHosts: preview?.allowedHosts,
accountId: ctx.allWorkerConfigs[0]?.account_id,
complianceRegion: ctx.allWorkerConfigs[0]?.compliance_region
})) return;
if (shortcutPressed) server.printUrls();
}
function patchPrintUrls(server) {
const serverPrintUrls = server.printUrls.bind(server);
server.printUrls = () => {
serverPrintUrls();
const publicUrls = tunnelManager?.publicUrls;
if (!publicUrls || publicUrls.length === 0) return;
for (let i$1 = 0; i$1 < publicUrls.length; i$1++) if (i$1 === 0) server.config.logger.info(`${import_picocolors$5.default.green(" ➜")} ${import_picocolors$5.default.bold("Tunnel:")} ${import_picocolors$5.default.cyan(publicUrls[i$1])}`);
else server.config.logger.info(` ${import_picocolors$5.default.cyan(publicUrls[i$1])}`);
server.config.logger.info("");
};
}
function isQuickTunnelAllowed(allowedHosts) {
if (allowedHosts === void 0) return false;
if (allowedHosts === true) return true;
return allowedHosts.some((allowedHost) => allowedHost.toLowerCase() === QUICK_TUNNEL_ALLOWED_HOST);
}
function getAllowedTunnelUrls(publicUrls, allowedHosts) {
if (allowedHosts === void 0) return [];
if (allowedHosts === true) return publicUrls;
return publicUrls.filter((publicUrl) => {
const hostname = new URL(publicUrl).hostname.toLowerCase();
return allowedHosts.some((allowedHost) => {
const normalizedAllowedHost = allowedHost.toLowerCase();
if (normalizedAllowedHost.startsWith(".")) return hostname === normalizedAllowedHost.slice(1) || hostname.endsWith(normalizedAllowedHost);
return hostname === normalizedAllowedHost;
});
});
}
function getSuggestedAllowedHosts(hostnames) {
const suggestions = new Set(hostnames);
for (const hostname of hostnames) {
const segments = hostname.split(".");
if (segments.length > 2) suggestions.add(`.${segments.slice(1).join(".")}`);
}
return Array.from(suggestions);
}
const tunnelPlugin = createPlugin("tunnel", (ctx) => {
function stopTunnel() {
ctx.clearTunnelHostnames();
tunnelManager?.dispose();
}
return {
buildEnd() {
if (!ctx.isRestartingDevServer) stopTunnel();
},
configureServer(server) {
assertIsNotPreview(ctx);
tunnelManager ??= new TunnelManager(server.config.logger);
patchPrintUrls(server);
if (!ctx.resolvedPluginConfig.tunnel.autoStart) return;
const serverListen = server.listen.bind(server);
server.listen = async (...args) => {
const result = await serverListen(...args);
try {
await setupDevTunnel(server, ctx, tunnelManager);
return result;
} catch (error) {
await Promise.allSettled([(async () => {
stopTunnel();
})(), server.close()]);
throw error;
}
};
},
async configurePreviewServer(server) {
assertIsPreview(ctx);
tunnelManager ??= new TunnelManager(server.config.logger);
patchPrintUrls(server);
if (ctx.resolvedPluginConfig.tunnel.autoStart) await setupPreviewTunnel(server, ctx, tunnelManager);
const closePreviewServer = server.close.bind(server);
server.close = async () => {
const closePromise = closePreviewServer();
try {
stopTunnel();
} finally {
await closePromise;
}
};
}
};
});
//#endregion
//#region src/utils.ts
const debuglog = util$1.debuglog("@cloudflare:vite-plugin");
/**
* Creates an internal plugin to be used inside the main `vite-plugin-cloudflare` plugin.
* The provided `name` will be prefixed with `vite-plugin-cloudflare:`.
*/
function createPlugin(name, pluginFactory) {
return (ctx) => {
return {
name: `vite-plugin-cloudflare:${name}`,
sharedDuringBuild: true,
...pluginFactory(ctx)
};
};
}
function getOutputDirectory(userConfig, environmentName) {
const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
return userConfig.environments?.[environmentName]?.build?.outDir ?? nodePath.join(rootOutputDirectory, environmentName);
}
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
function withTrailingSlash(path$2) {
return path$2.endsWith("/") ? path$2 : `${path$2}/`;
}
function createRequestHandler(handler) {
return async (req, res, next) => {
let request$2;
try {
if (req.originalUrl) req.url = req.originalUrl;
const protocol = getForwardedProto(req);
request$2 = createRequest(req, res, protocol ? { protocol } : void 0);
let response = await handler(toMiniflareRequest(request$2), req);
if (req.httpVersionMajor === 2) {
response = new Response$1(response.body, response);
response.headers.delete("transfer-encoding");
}
warnIfQuickTunnelSseResponse(response.headers.get("content-type"));
await sendResponse(res, response);
} catch (error) {
if (request$2?.signal.aborted) return;
next(error);
}
};
}
function satisfiesMinimumViteVersion(minVersion$2) {
return (0, import_gte.default)(version, minVersion$2);
}
function toMiniflareRequest(request$2) {
const host = request$2.headers.get("Host");
const xForwardedHost = request$2.headers.get("X-Forwarded-Host");
if (host && !xForwardedHost) request$2.headers.set("X-Forwarded-Host", host);
request$2.headers.set(CoreHeaders.PROXY_SHARED_SECRET, PROXY_SHARED_SECRET);
const secFetchMode = request$2.headers.get("Sec-Fetch-Mode");
if (secFetchMode) request$2.headers.set(CoreHeaders.SEC_FETCH_MODE, secFetchMode);
return new Request$1(request$2.url, {
method: request$2.method,
headers: [["accept-encoding", "identity"], ...request$2.headers],
body: request$2.body,
duplex: "half",
signal: request$2.signal
});
}
const isRolldown = "rolldownVersion" in vite;
/**
* Parses the `X-Forwarded-Proto` header from an incoming Node.js request.
*
* If multiple proxies are in the chain, the header may be a comma-separated
* list — the left-most value is the original client-facing protocol.
* Returns `undefined` if the header is missing or holds an unsupported value.
*/
function getForwardedProto(req) {
const raw = req.headers["x-forwarded-proto"];
const value = Array.isArray(raw) ? raw[0] : raw;
if (!value) return;
const first = value.split(",")[0]?.trim().toLowerCase();
if (first === "http" || first === "https") return `${first}:`;
}
//#endregion
//#region src/export-types.ts
function getWorkerNameToWorkerEntrypointExportsMap(workers) {
const workerNameToWorkerEntrypointExportsMap = new Map(workers.map((worker) => [worker.config.name, /* @__PURE__ */ new Set()]));
for (const worker of workers) for (const value of worker.config.services ?? []) if (value.entrypoint !== void 0 && value.entrypoint !== "default") workerNameToWorkerEntrypointExportsMap.get(value.service)?.add(value.entrypoint);
return workerNameToWorkerEntrypointExportsMap;
}
function getWorkerNameToDurableObjectExportsMap(workers) {
const workerNameToDurableObjectExportsMap = new Map(workers.map((worker) => [worker.config.name, new Set(wrangler.unstable_getDurableObjectClassNameToUseSQLiteMap(worker.config.migrations).keys())]));
for (const worker of workers) for (const value of worker.config.durable_objects.bindings) if (value.script_name) workerNameToDurableObjectExportsMap.get(value.script_name)?.add(value.class_name);
else workerNameToDurableObjectExportsMap.get(worker.config.name)?.add(value.class_name);
return workerNameToDurableObjectExportsMap;
}
function getWorkerNameToWorkflowEntrypointExportsMap(workers) {
const workerNameToWorkflowEntrypointExportsMap = new Map(workers.map((worker) => [worker.config.name, /* @__PURE__ */ new Set()]));
for (const worker of workers) for (const value of worker.config.workflows) if (value.script_name) workerNameToWorkflowEntrypointExportsMap.get(value.script_name)?.add(value.class_name);
else workerNameToWorkflowEntrypointExportsMap.get(worker.config.name)?.add(value.class_name);
return workerNameToWorkflowEntrypointExportsMap;
}
/**
* Derives initial export types for all Workers from the Worker config files and returns them in a Map
*/
function getInitialWorkerNameToExportTypesMap(resolvedPluginConfig) {
const workers = [...resolvedPluginConfig.environmentNameToWorkerMap.values()];
const workerNameToWorkerEntrypointExportsMap = getWorkerNameToWorkerEntrypointExportsMap(workers);
const workerNameToDurableObjectExportsMap = getWorkerNameToDurableObjectExportsMap(workers);
const workerNameToWorkflowEntrypointExportsMap = getWorkerNameToWorkflowEntrypointExportsMap(workers);
return new Map(workers.map((worker) => {
const workerEntrypointExports = workerNameToWorkerEntrypointExportsMap.get(worker.config.name);
assert(workerEntrypointExports, `WorkerEntrypoint exports not found for Worker "${worker.config.name}"`);
const durableObjectExports = workerNameToDurableObjectExportsMap.get(worker.config.name);
assert(durableObjectExports, `DurableObject exports not found for Worker "${worker.config.name}"`);
const workflowEntrypointExports = workerNameToWorkflowEntrypointExportsMap.get(worker.config.name);
assert(workflowEntrypointExports, `WorkflowEntrypoint exports not found for Worker "${worker.config.name}"`);
const exportTypes = {};
for (const exportName of workerEntrypointExports) exportTypes[exportName] = "WorkerEntrypoint";
for (const exportName of durableObjectExports) exportTypes[exportName] = "DurableObject";
for (const exportName of workflowEntrypointExports) exportTypes[exportName] = "WorkflowEntrypoint";
return [worker.config.name, exportTypes];
}));
}
/**
* Fetches the export types for all Workers and returns them in a Map
*/
async function getCurrentWorkerNameToExportTypesMap(resolvedPluginConfig, viteDevServer, miniflare) {
await viteDevServer.environments.client.pluginContainer.buildStart();
const results = await Promise.all([...resolvedPluginConfig.environmentNameToWorkerMap].map(async ([environmentName, worker]) => {
debuglog(`Fetching export types for worker "${worker.config.name}"`);
const exportTypes = await viteDevServer.environments[environmentName].fetchWorkerExportTypes(miniflare, worker.config);
return [worker.config.name, exportTypes];
}));
return new Map(results);
}
/**
* Compares the export types for all Workers and returns `true` if any have changed
*/
function compareWorkerNameToExportTypesMaps(oldWorkerNameToExportTypesMap, newWorkerNameToExportTypesMap) {
for (const workerName of newWorkerNameToExportTypesMap.keys()) {
const oldExportTypes = oldWorkerNameToExportTypesMap.get(workerName);
assert(oldExportTypes, "Expected old export types to be defined");
const newExportTypes = newWorkerNameToExportTypesMap.get(workerName);
assert(newExportTypes, "Expected new export types to be defined");
if (compareExportTypes(oldExportTypes, newExportTypes)) return true;
}
return false;
}
/**
* Compares two `ExportTypes` objects and returns true if they do not match.
* Checks for added/removed exports and changed export types.
*/
function compareExportTypes(oldExportTypes, newExportTypes) {
const oldKeys = Object.keys(oldExportTypes);
const newKeys = Object.keys(newExportTypes);
if (oldKeys.length !== newKeys.length) return true;
for (const key of newKeys) if (!(key in oldExportTypes) || oldExportTypes[key] !== newExportTypes[key]) return true;
return false;
}
//#endregion
//#region src/context.ts
/**
* Used to provide context to internal plugins.
* It should be reinstantiated each time the main plugin is created.
*/
var PluginContext = class {
#sharedContext;
#resolvedPluginConfig;
#resolvedViteConfig;
constructor(sharedContext$1) {
this.#sharedContext = sharedContext$1;
}
/** Creates a new Miniflare instance or updates the existing instance */
async startOrUpdateMiniflare(options) {
if (!this.#sharedContext.miniflare) {
debuglog("Creating new Miniflare instance");
this.#sharedContext.miniflare = new Miniflare(options);
} else {
debuglog("Updating the existing Miniflare instance");
await this.#sharedContext.miniflare.setOptions(options);
}
debuglog("Miniflare is ready");
}
async disposeMiniflare() {
await this.#sharedContext.miniflare?.dispose();
this.#sharedContext.miniflare = void 0;
}
get miniflare() {
assert(this.#sharedContext.miniflare, "Expected `miniflare` to be defined");
return this.#sharedContext.miniflare;
}
/**
* Gets the resolved inspector port provided by Miniflare
*/
async getResolvedInspectorPort() {
if (this.resolvedPluginConfig.inspectorPort === false || !this.#sharedContext.miniflare) return null;
const miniflareInspectorUrl = await this.#sharedContext.miniflare.getInspectorURL();
return Number.parseInt(miniflareInspectorUrl.port);
}
setWorkerNameToExportTypesMap(workerNameToExportTypesMap) {
this.#sharedContext.workerNameToExportTypesMap = workerNameToExportTypesMap;
}
get workerNameToExportTypesMap() {
if (!this.#sharedContext.workerNameToExportTypesMap) {
if (this.resolvedPluginConfig.type !== "workers") return /* @__PURE__ */ new Map();
return getInitialWorkerNameToExportTypesMap(this.resolvedPluginConfig);
}
return this.#sharedContext.workerNameToExportTypesMap;
}
setHasShownWorkerConfigWarnings(hasShownWorkerConfigWarnings) {
this.#sharedContext.hasShownWorkerConfigWarnings = hasShownWorkerConfigWarnings;
}
get hasShownWorkerConfigWarnings() {
return this.#sharedContext.hasShownWorkerConfigWarnings;
}
beginRestartingDevServer() {
this.#sharedContext.restartingDevServerCount++;
}
endRestartingDevServer() {
this.#sharedContext.restartingDevServerCount--;
}
get isRestartingDevServer() {
return this.#sharedContext.restartingDevServerCount > 0;
}
getTunnelHostnames() {
return Array.from(this.#sharedContext.tunnelHostnames);
}
replaceTunnelHostnames(tunnelHostnames) {
this.#sharedContext.tunnelHostnames.clear();
for (const tunnelHostname of tunnelHostnames) this.#sharedContext.tunnelHostnames.add(tunnelHostname);
}
clearTunnelHostnames() {
this.#sharedContext.tunnelHostnames.clear();
}
setResolvedPluginConfig(resolvedPluginConfig) {
this.#resolvedPluginConfig = resolvedPluginConfig;
}
get resolvedPluginConfig() {
assert(this.#resolvedPluginConfig, "Expected `resolvedPluginConfig` to be defined");
return this.#resolvedPluginConfig;
}
setResolvedViteConfig(resolvedViteConfig) {
this.#resolvedViteConfig = resolvedViteConfig;
}
get resolvedViteConfig() {
assert(this.#resolvedViteConfig, "Expected `resolvedViteConfig` to be defined");
return this.#resolvedViteConfig;
}
isChildEnvironment(environmentName) {
if (this.resolvedPluginConfig.type === "preview") return false;
for (const childEnvironmentNames of this.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.values()) if (childEnvironmentNames.includes(environmentName)) return true;
return false;
}
#getWorker(environmentName) {
if (this.resolvedPluginConfig.type === "preview") return;
const worker = this.resolvedPluginConfig.environmentNameToWorkerMap.get(environmentName);
if (worker) return worker;
for (const [parentEnvironmentName, childEnvironmentNames] of this.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap) if (childEnvironmentNames.includes(environmentName)) return this.resolvedPluginConfig.environmentNameToWorkerMap.get(parentEnvironmentName);
}
getWorkerConfig(environmentName) {
return this.#getWorker(environmentName)?.config;
}
get allWorkerConfigs() {
if (this.resolvedPluginConfig.type === "preview") return this.resolvedPluginConfig.workers;
return Array.from(this.resolvedPluginConfig.environmentNameToWorkerMap.values()).map((worker) => worker.config);
}
get entryWorkerConfig() {
if (this.resolvedPluginConfig.type !== "workers") return;
return this.resolvedPluginConfig.environmentNameToWorkerMap.get(this.resolvedPluginConfig.entryWorkerEnvironmentName)?.config;
}
getNodeJsCompat(environmentName) {
return this.#getWorker(environmentName)?.nodeJsCompat;
}
};
function assertIsNotPreview(ctx) {
assert(ctx.resolvedPluginConfig.type !== "preview", `Expected "assets-only" or "workers" plugin config`);
}
function assertIsPreview(ctx) {
assert(ctx.resolvedPluginConfig.type === "preview", `Expected "preview" plugin config`);
}
//#endregion
//#region ../workers-shared/utils/configuration/constants.ts
const REDIRECTS_VERSION = 1;
const HEADERS_VERSION = 2;
const PERMITTED_STATUS_CODES = new Set([
200,
301,
302,
303,
307,
308
]);
const HEADER_SEPARATOR = ":";
const MAX_LINE_LENGTH = 2e3;
const MAX_HEADER_RULES = 100;
const MAX_DYNAMIC_REDIRECT_RULES = 100;
const MAX_STATIC_REDIRECT_RULES = 2e3;
const UNSET_OPERATOR = "! ";
const SPLAT_REGEX = /\*/g;
const PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
/** Max number of rules in `run_worker_first` */
const MAX_ROUTES_RULES = 100;
/** Max char length of each rule in `run_worker_first` */
const MAX_ROUTES_RULE_LENGTH = 100;
//#endregion
//#region ../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;
}
const formatInvalidRoutes = (invalidRules) => {
if (invalidRules.length === 0) return;
return `Invalid routes in \`run_worker_first\`:\n` + invalidRules.join("\n");
};
//#endregion
//#region ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
function isPlainObject(value) {
if (value === null || typeof value !== "object") return false;
const prototype = Object.getPrototypeOf(value);
if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
if (Symbol.iterator in value) return false;
if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
return true;
}
function _defu(baseObject, defaults, namespace = ".", merger) {
if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
const object = Object.assign({}, defaults);
for (const key in baseObject) {
if (key === "__proto__" || key === "constructor") continue;
const value = baseObject[key];
if (value === null || value === void 0) continue;
if (merger && merger(object, key, value, namespace)) continue;
if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
else if (isPlainObject(value) && isPlainObject(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
else object[key] = value;
}
return object;
}
function createDefu(merger) {
return (...arguments_) => arguments_.reduce((p$1, c) => _defu(p$1, c, "", merger), {});
}
const defu = createDefu();
const defuFn = createDefu((object, key, currentValue) => {
if (object[key] !== void 0 && typeof currentValue === "function") {
object[key] = currentValue(object[key]);
return true;
}
});
const defuArrayFn = createDefu((object, key, currentValue) => {
if (Array.isArray(object[key]) && typeof currentValue === "function") {
object[key] = currentValue(object[key]);
return true;
}
});
//#endregion
//#region src/deploy-config.ts
function getDeployConfigPath(root) {
return nodePath.resolve(root, ".wrangler", "deploy", "config.json");
}
function getWorkerConfigs(root, isPrerender) {
const deployConfigPath = getDeployConfigPath(root);
const deployConfig = JSON.parse(fs$2.readFileSync(deployConfigPath, "utf-8"));
return [
...isPrerender && deployConfig.prerenderWorkerConfigPath ? [{ configPath: deployConfig.prerenderWorkerConfigPath }] : [],
{ configPath: deployConfig.configPath },
...deployConfig.auxiliaryWorkers
].map(({ configPath }) => {
const resolvedConfigPath = nodePath.resolve(nodePath.dirname(deployConfigPath), configPath);
return wrangler.unstable_readConfig({ config: resolvedConfigPath });
});
}
function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
return nodePath.relative(deployConfigDirectory, nodePath.resolve(root, outputDirectory, "wrangler.json"));
}
function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
const deployConfigDirectory = nodePath.dirname(deployConfigPath);
fs$2.mkdirSync(deployConfigDirectory, { recursive: true });
if (resolvedPluginConfig.type === "assets-only") {
const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
assert(clientOutputDirectory, "Unexpected error: client environment output directory is undefined");
const prerenderOutputDirectory = resolvedPluginConfig.prerenderWorkerEnvironmentName ? resolvedViteConfig.environments[resolvedPluginConfig.prerenderWorkerEnvironmentName]?.build.outDir : void 0;
const deployConfig = {
configPath: getRelativePathToWorkerConfig(deployConfigDirectory, resolvedViteConfig.root, clientOutputDirectory),
auxiliaryWorkers: [],
prerenderWorkerConfigPath: prerenderOutputDirectory ? getRelativePathToWorkerConfig(deployConfigDirectory, resolvedViteConfig.root, prerenderOutputDirectory) : void 0
};
fs$2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
} else {
let entryWorkerConfigPath;
let prerenderWorkerConfigPath;
const auxiliaryWorkers = [];
for (const environmentName of resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
assert(outputDirectory, `Unexpected error: ${environmentName} environment output directory is undefined`);
const configPath = getRelativePathToWorkerConfig(deployConfigDirectory, resolvedViteConfig.root, outputDirectory);
if (environmentName === resolvedPluginConfig.entryWorkerEnvironmentName) entryWorkerConfigPath = configPath;
else if (environmentName === resolvedPluginConfig.prerenderWorkerEnvironmentName) prerenderWorkerConfigPath = configPath;
else auxiliaryWorkers.push({ configPath });
}
assert(entryWorkerConfigPath, `Unexpected error: entryWorkerConfigPath is undefined`);
const deployConfig = {
configPath: entryWorkerConfigPath,
auxiliaryWorkers,
prerenderWorkerConfigPath
};
fs$2.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
}
}
//#endregion
//#region ../../node_modules/.pnpm/acorn@8.14.0/node_modules/acorn/dist/acorn.mjs
var astralIdentifierCodes = [
509,
0,
227,
0,
150,
4,
294,
9,
1368,
2,
2,
1,
6,
3,
41,
2,
5,
0,
166,
1,
574,
3,
9,
9,
7,
9,
32,
4,
318,
1,
80,
3,
71,
10,
50,
3,
123,
2,
54,
14,
32,
10,
3,
1,
11,
3,
46,
10,
8,
0,
46,
9,
7,
2,
37,
13,
2,
9,
6,
1,
45,
0,
13,
2,
49,
13,
9,
3,
2,
11,
83,
11,
7,
0,
3,
0,
158,
11,
6,
9,
7,
3,
56,
1,
2,
6,
3,
1,
3,
2,
10,
0,
11,
1,
3,
6,
4,
4,
68,
8,
2,
0,
3,
0,
2,
3,
2,
4,
2,
0,
15,
1,
83,
17,
10,
9,
5,
0,
82,
19,
13,
9,
214,
6,
3,
8,
28,
1,
83,
16,
16,
9,
82,
12,
9,
9,
7,
19,
58,
14,
5,
9,
243,
14,
166,
9,
71,
5,
2,
1,
3,
3,
2,
0,
2,
1,
13,
9,
120,
6,
3,
6,
4,
0,
29,
9,
41,
6,
2,
3,
9,
0,
10,
10,
47,
15,
343,
9,
54,
7,
2,
7,
17,
9,
57,
21,
2,
13,
123,
5,
4,
0,
2,
1,
2,
6,
2,
0,
9,
9,
49,
4,
2,
1,
2,
4,
9,
9,
330,
3,
10,
1,
2,
0,
49,
6,
4,
4,
14,
10,
5350,
0,
7,
14,
11465,
27,
2343,
9,
87,
9,
39,
4,
60,
6,
26,
9,
535,
9,
470,
0,
2,
54,
8,
3,
82,
0,
12,
1,
19628,
1,
4178,
9,
519,
45,
3,
22,
543,
4,
4,
5,
9,
7,
3,
6,
31,
3,
149,
2,
1418,
49,
513,
54,
5,
49,
9,
0,
15,
0,
23,
4,
2,
14,
1361,
6,
2,
16,
3,
6,
2,
1,
2,
4,
101,
0,
161,
6,
10,
9,
357,
0,
62,
13,
499,
13,
245,
1,
2,
9,
726,
6,
110,
6,
6,
9,
4759,
9,
787719,
239
];
var astralIdentifierStartCodes = [
0,
11,
2,
25,
2,
18,
2,
1,
2,
14,
3,
13,
35,
122,
70,
52,
268,
28,
4,
48,
48,
31,
14,
29,
6,
37,
11,
29,
3,
35,
5,
7,
2,
4,
43,
157,
19,
35,
5,
35,
5,
39,
9,
51,
13,
10,
2,
14,
2,
6,
2,
1,
2,
10,
2,
14,
2,
6,
2,
1,
4,
51,
13,
310,
10,
21,
11,
7,
25,
5,
2,
41,
2,
8,
70,
5,
3,
0,
2,
43,
2,
1,
4,
0,
3,
22,
11,
22,
10,
30,
66,
18,
2,
1,
11,
21,
11,
25,
71,
55,
7,
1,
65,
0,
16,
3,
2,
2,
2,
28,
43,
28,
4,
28,
36,
7,
2,
27,
28,
53,
11,
21,
11,
18,
14,
17,
111,
72,
56,
50,
14,
50,
14,
35,
39,
27,
10,
22,
251,
41,
7,
1,
17,
2,
60,
28,
11,
0,
9,
21,
43,
17,
47,
20,
28,
22,
13,
52,
58,
1,
3,
0,
14,
44,
33,
24,
27,
35,
30,
0,
3,
0,
9,
34,
4,
0,
13,
47,
15,
3,
22,
0,
2,
0,
36,
17,
2,
24,
20,
1,
64,
6,
2,
0,
2,
3,
2,
14,
2,
9,
8,
46,
39,
7,
3,
1,
3,
21,
2,
6,
2,
1,
2,
4,
4,
0,
19,
0,
13,
4,
31,
9,
2,
0,
3,
0,
2,
37,
2,
0,
26,
0,
2,
0,
45,
52,
19,
3,
21,
2,
31,
47,
21,
1,
2,
0,
185,
46,
42,
3,
37,
47,
21,
0,
60,
42,
14,
0,
72,
26,
38,
6,
186,
43,
117,
63,
32,
7,
3,
0,
3,
7,
2,
1,
2,
23,
16,
0,
2,
0,
95,
7,
3,
38,
17,
0,
2,
0,
29,
0,
11,
39,
8,
0,
22,
0,
12,
45,
20,
0,
19,
72,
200,
32,
32,
8,
2,
36,
18,
0,
50,
29,
113,
6,
2,
1,
2,
37,
22,
0,
26,
5,
2,
1,
2,
31,
15,
0,
328,
18,
16,
0,
2,
12,
2,
33,
125,
0,
80,
921,
103,
110,
18,
195,
2637,
96,
16,
1071,
18,
5,
26,
3994,
6,
582,
6842,
29,
1763,
568,
8,
30,
18,
78,
18,
29,
19,
47,
17,
3,
32,
20,
6,
18,
433,
44,
212,
63,
129,
74,
6,
0,
67,
12,
65,
1,
2,
0,
29,
6135,
9,
1237,
42,
9,
8936,
3,
2,
6,
2,
1,
2,
290,
16,
0,
30,
2,
3,
0,
15,
3,
9,
395,
2309,
106,
6,
12,
4,
8,
8,
9,
5991,
84,
2,
70,
2,
1,
3,
0,
3,
1,
3,
3,
2,
11,
2,
0,
2,
6,
2,
64,
2,
3,
3,
7,
2,
6,
2,
27,
2,
3,
2,
4,
2,
0,
4,
6,
2,
339,
3,
24,
2,
24,
2,
30,
2,
24,
2,
30,
2,
24,
2,
30,
2,
24,
2,
30,
2,
24,
2,
7,
1845,
30,
7,
5,
262,
61,
147,
44,
11,
6,
17,
0,
322,
29,
19,
43,
485,
27,
229,
29,
3,
0,
496,
6,
2,
3,
2,
1,
2,
14,
2,
196,
60,
67,
8,
0,
1205,
3,
2,
26,
2,
1,
2,
0,
3,
0,
2,
9,
2,
3,
2,
0,
2,
0,
7,
0,
5,
0,
2,
0,
2,
0,
2,
2,
2,
1,
2,
0,
3,
0,
2,
0,
2,
0,
2,
0,
2,
0,
2,
1,
2,
0,
3,
3,
2,
6,
2,
3,
2,
3,
2,
0,
2,
9,
2,
16,
6,
2,
2,
4,
2,
16,
4421,
42719,
33,
4153,
7,
221,
3,
5761,
15,
7472,
16,
621,
2467,
541,
1507,
4938,
6,
4191
];
var nonASCIIidentifierChars = "·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・";
var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ꟑꟑꟓꟕ-ꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
};
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords$1 = {
5: ecma5AndLessKeywords,
"5module": ecma5AndLessKeywords + " export import",
6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
var nonASCIIidentifierStart = /* @__PURE__ */ new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = /* @__PURE__ */ new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
function isInAstralSet(code, set) {
var pos = 65536;
for (var i$1 = 0; i$1 < set.length; i$1 += 2) {
pos += set[i$1];
if (pos > code) return false;
pos += set[i$1 + 1];
if (pos >= code) return true;
}
return false;
}
function isIdentifierStart(code, astral) {
if (code < 65) return code === 36;
if (code < 91) return true;
if (code < 97) return code === 95;
if (code < 123) return true;
if (code <= 65535) return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
if (astral === false) return false;
return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code < 91) return true;
if (code < 97) return code === 95;
if (code < 123) return true;
if (code <= 65535) return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
if (astral === false) return false;
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
var TokenType = function TokenType$1(label, conf) {
if (conf === void 0) conf = {};
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
this.isLoop = !!conf.isLoop;
this.isAssign = !!conf.isAssign;
this.prefix = !!conf.prefix;
this.postfix = !!conf.postfix;
this.binop = conf.binop || null;
this.updateContext = null;
};
function binop(name, prec) {
return new TokenType(name, {
beforeExpr: true,
binop: prec
});
}
var beforeExpr = { beforeExpr: true }, startsExpr = { startsExpr: true };
var keywords = {};
function kw(name, options) {
if (options === void 0) options = {};
options.keyword = name;
return keywords[name] = new TokenType(name, options);
}
var types$1$1 = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
privateId: new TokenType("privateId", startsExpr),
eof: new TokenType("eof"),
bracketL: new TokenType("[", {
beforeExpr: true,
startsExpr: true
}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {
beforeExpr: true,
startsExpr: true
}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {
beforeExpr: true,
startsExpr: true
}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
questionDot: new TokenType("?."),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
invalidTemplate: new TokenType("invalidTemplate"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {
beforeExpr: true,
startsExpr: true
}),
eq: new TokenType("=", {
beforeExpr: true,
isAssign: true
}),
assign: new TokenType("_=", {
beforeExpr: true,
isAssign: true
}),
incDec: new TokenType("++/--", {
prefix: true,
postfix: true,
startsExpr: true
}),
prefix: new TokenType("!/~", {
beforeExpr: true,
prefix: true,
startsExpr: true
}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=/===/!==", 6),
relational: binop("</>/<=/>=", 7),
bitShift: binop("<</>>/>>>", 8),
plusMin: new TokenType("+/-", {
beforeExpr: true,
binop: 9,
prefix: true,
startsExpr: true
}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", { beforeExpr: true }),
coalesce: binop("??", 1),
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {
isLoop: true,
beforeExpr: true
}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", { isLoop: true }),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", { isLoop: true }),
_with: kw("with"),
_new: kw("new", {
beforeExpr: true,
startsExpr: true
}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class", startsExpr),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import", startsExpr),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {
beforeExpr: true,
binop: 7
}),
_instanceof: kw("instanceof", {
beforeExpr: true,
binop: 7
}),
_typeof: kw("typeof", {
beforeExpr: true,
prefix: true,
startsExpr: true
}),
_void: kw("void", {
beforeExpr: true,
prefix: true,
startsExpr: true
}),
_delete: kw("delete", {
beforeExpr: true,
prefix: true,
startsExpr: true
})
};
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code) {
return code === 10 || code === 13 || code === 8232 || code === 8233;
}
function nextLineBreak(code, from, end) {
if (end === void 0) end = code.length;
for (var i$1 = from; i$1 < end; i$1++) {
var next = code.charCodeAt(i$1);
if (isNewLine(next)) return i$1 < end - 1 && next === 13 && code.charCodeAt(i$1 + 1) === 10 ? i$1 + 2 : i$1 + 1;
}
return -1;
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty$2 = ref.hasOwnProperty;
var toString$1 = ref.toString;
var hasOwn = Object.hasOwn || (function(obj, propName) {
return hasOwnProperty$2.call(obj, propName);
});
var isArray = Array.isArray || (function(obj) {
return toString$1.call(obj) === "[object Array]";
});
var regexpCache = Object.create(null);
function wordsRegexp(words) {
return regexpCache[words] || (regexpCache[words] = /* @__PURE__ */ new RegExp("^(?:" + words.replace(/ /g, "|") + ")$"));
}
function codePointToString(code) {
if (code <= 65535) return String.fromCharCode(code);
code -= 65536;
return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
var Position = function Position$1(line, col) {
this.line = line;
this.column = col;
};
Position.prototype.offset = function offset(n$1) {
return new Position(this.line, this.column + n$1);
};
var SourceLocation = function SourceLocation$1(p$1, start, end) {
this.start = start;
this.end = end;
if (p$1.sourceFile !== null) this.source = p$1.sourceFile;
};
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
var nextBreak = nextLineBreak(input, cur, offset);
if (nextBreak < 0) return new Position(line, offset - cur);
++line;
cur = nextBreak;
}
}
var defaultOptions = {
ecmaVersion: null,
sourceType: "script",
onInsertedSemicolon: null,
onTrailingComma: null,
allowReserved: null,
allowReturnOutsideFunction: false,
allowImportExportEverywhere: false,
allowAwaitOutsideFunction: null,
allowSuperOutsideMethod: null,
allowHashBang: false,
checkPrivateFields: true,
locations: false,
onToken: null,
onComment: null,
ranges: false,
program: null,
sourceFile: null,
directSourceFile: null,
preserveParens: false
};
var warnedAboutEcmaVersion = false;
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions) options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt];
if (options.ecmaVersion === "latest") options.ecmaVersion = 1e8;
else if (options.ecmaVersion == null) {
if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
warnedAboutEcmaVersion = true;
console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
}
options.ecmaVersion = 11;
} else if (options.ecmaVersion >= 2015) options.ecmaVersion -= 2009;
if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
if (!opts || opts.allowHashBang == null) options.allowHashBang = options.ecmaVersion >= 14;
if (isArray(options.onToken)) {
var tokens = options.onToken;
options.onToken = function(token) {
return tokens.push(token);
};
}
if (isArray(options.onComment)) options.onComment = pushComment(options, options.onComment);
return options;
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start,
end
};
if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc);
if (options.ranges) comment.range = [start, end];
array.push(comment);
};
}
var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128, SCOPE_CLASS_STATIC_BLOCK = 256, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
function functionFlags(async, generator) {
return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
}
var BIND_NONE = 0, BIND_VAR = 1, BIND_LEXICAL = 2, BIND_FUNCTION = 3, BIND_SIMPLE_CATCH = 4, BIND_OUTSIDE = 5;
var Parser = function Parser$2(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
var reserved = "";
if (options.allowReserved !== true) {
reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
if (options.sourceType === "module") reserved += " await";
}
this.reservedWords = wordsRegexp(reserved);
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
this.reservedWordsStrict = wordsRegexp(reservedStrict);
this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
this.input = String(input);
this.containsEsc = false;
if (startPos) {
this.pos = startPos;
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
this.type = types$1$1.eof;
this.value = null;
this.start = this.end = this.pos;
this.startLoc = this.endLoc = this.curPosition();
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
this.context = this.initialContext();
this.exprAllowed = true;
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
this.potentialArrowAt = -1;
this.potentialArrowInForAwait = false;
this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
this.labels = [];
this.undefinedExports = Object.create(null);
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2);
this.scopeStack = [];
this.enterScope(SCOPE_TOP);
this.regexpState = null;
this.privateNameStack = [];
};
var prototypeAccessors = {
inFunction: { configurable: true },
inGenerator: { configurable: true },
inAsync: { configurable: true },
canAwait: { configurable: true },
allowSuper: { configurable: true },
allowDirectSuper: { configurable: true },
treatFunctionsAsVar: { configurable: true },
allowNewDotTarget: { configurable: true },
inClassStaticBlock: { configurable: true }
};
Parser.prototype.parse = function parse$10() {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node);
};
prototypeAccessors.inFunction.get = function() {
return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
};
prototypeAccessors.inGenerator.get = function() {
return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors.inAsync.get = function() {
return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors.canAwait.get = function() {
for (var i$1 = this.scopeStack.length - 1; i$1 >= 0; i$1--) {
var scope = this.scopeStack[i$1];
if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) return false;
if (scope.flags & SCOPE_FUNCTION) return (scope.flags & SCOPE_ASYNC) > 0;
}
return this.inModule && this.options.ecmaVersion >= 13 || this.options.allowAwaitOutsideFunction;
};
prototypeAccessors.allowSuper.get = function() {
var ref$1 = this.currentThisScope();
var flags = ref$1.flags;
var inClassFieldInit = ref$1.inClassFieldInit;
return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod;
};
prototypeAccessors.allowDirectSuper.get = function() {
return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
};
prototypeAccessors.treatFunctionsAsVar.get = function() {
return this.treatFunctionsAsVarInScope(this.currentScope());
};
prototypeAccessors.allowNewDotTarget.get = function() {
var ref$1 = this.currentThisScope();
var flags = ref$1.flags;
var inClassFieldInit = ref$1.inClassFieldInit;
return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit;
};
prototypeAccessors.inClassStaticBlock.get = function() {
return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0;
};
Parser.extend = function extend() {
var plugins = [], len = arguments.length;
while (len--) plugins[len] = arguments[len];
var cls = this;
for (var i$1 = 0; i$1 < plugins.length; i$1++) cls = plugins[i$1](cls);
return cls;
};
Parser.parse = function parse$10(input, options) {
return new this(options, input).parse();
};
Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {
var parser = new this(options, input, pos);
parser.nextToken();
return parser.parseExpression();
};
Parser.tokenizer = function tokenizer(input, options) {
return new this(options, input);
};
Object.defineProperties(Parser.prototype, prototypeAccessors);
var pp$9 = Parser.prototype;
var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
pp$9.strictDirective = function(start) {
if (this.options.ecmaVersion < 5) return false;
for (;;) {
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
var match = literal.exec(this.input.slice(start));
if (!match) return false;
if ((match[1] || match[2]) === "use strict") {
skipWhiteSpace.lastIndex = start + match[0].length;
var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
var next = this.input.charAt(end);
return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
}
start += match[0].length;
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
if (this.input[start] === ";") start++;
}
};
pp$9.eat = function(type) {
if (this.type === type) {
this.next();
return true;
} else return false;
};
pp$9.isContextual = function(name) {
return this.type === types$1$1.name && this.value === name && !this.containsEsc;
};
pp$9.eatContextual = function(name) {
if (!this.isContextual(name)) return false;
this.next();
return true;
};
pp$9.expectContextual = function(name) {
if (!this.eatContextual(name)) this.unexpected();
};
pp$9.canInsertSemicolon = function() {
return this.type === types$1$1.eof || this.type === types$1$1.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$9.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
return true;
}
};
pp$9.semicolon = function() {
if (!this.eat(types$1$1.semi) && !this.insertSemicolon()) this.unexpected();
};
pp$9.afterTrailingComma = function(tokType, notNext) {
if (this.type === tokType) {
if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
if (!notNext) this.next();
return true;
}
};
pp$9.expect = function(type) {
this.eat(type) || this.unexpected();
};
pp$9.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token");
};
var DestructuringErrors = function DestructuringErrors$1() {
this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
};
pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) return;
if (refDestructuringErrors.trailingComma > -1) this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
if (parens > -1) this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern");
};
pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
if (!refDestructuringErrors) return false;
var shorthandAssign = refDestructuringErrors.shorthandAssign;
var doubleProto = refDestructuringErrors.doubleProto;
if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
if (shorthandAssign >= 0) this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
if (doubleProto >= 0) this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
};
pp$9.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) this.raise(this.yieldPos, "Yield expression cannot be a default value");
if (this.awaitPos) this.raise(this.awaitPos, "Await expression cannot be a default value");
};
pp$9.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression") return this.isSimpleAssignTarget(expr.expression);
return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$8 = Parser.prototype;
pp$8.parseTopLevel = function(node) {
var exports$1 = Object.create(null);
if (!node.body) node.body = [];
while (this.type !== types$1$1.eof) {
var stmt = this.parseStatement(null, true, exports$1);
node.body.push(stmt);
}
if (this.inModule) for (var i$1 = 0, list$1 = Object.keys(this.undefinedExports); i$1 < list$1.length; i$1 += 1) {
var name = list$1[i$1];
this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
}
this.adaptDirectivePrologue(node.body);
this.next();
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program");
};
var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" };
pp$8.isLet = function(context) {
if (this.options.ecmaVersion < 6 || !this.isContextual("let")) return false;
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 91 || nextCh === 92) return true;
if (context) return false;
if (nextCh === 123 || nextCh > 55295 && nextCh < 56320) return true;
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1;
while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) ++pos;
if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) return true;
var ident = this.input.slice(next, pos);
if (!keywordRelationalOperator.test(ident)) return true;
}
return false;
};
pp$8.isAsyncFunction = function() {
if (this.options.ecmaVersion < 8 || !this.isContextual("async")) return false;
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, after;
return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320));
};
pp$8.parseStatement = function(context, topLevel, exports$1) {
var starttype = this.type, node = this.startNode(), kind;
if (this.isLet(context)) {
starttype = types$1$1._var;
kind = "let";
}
switch (starttype) {
case types$1$1._break:
case types$1$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword);
case types$1$1._debugger: return this.parseDebuggerStatement(node);
case types$1$1._do: return this.parseDoStatement(node);
case types$1$1._for: return this.parseForStatement(node);
case types$1$1._function:
if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) this.unexpected();
return this.parseFunctionStatement(node, false, !context);
case types$1$1._class:
if (context) this.unexpected();
return this.parseClass(node, true);
case types$1$1._if: return this.parseIfStatement(node);
case types$1$1._return: return this.parseReturnStatement(node);
case types$1$1._switch: return this.parseSwitchStatement(node);
case types$1$1._throw: return this.parseThrowStatement(node);
case types$1$1._try: return this.parseTryStatement(node);
case types$1$1._const:
case types$1$1._var:
kind = kind || this.value;
if (context && kind !== "var") this.unexpected();
return this.parseVarStatement(node, kind);
case types$1$1._while: return this.parseWhileStatement(node);
case types$1$1._with: return this.parseWithStatement(node);
case types$1$1.braceL: return this.parseBlock(true, node);
case types$1$1.semi: return this.parseEmptyStatement(node);
case types$1$1._export:
case types$1$1._import:
if (this.options.ecmaVersion > 10 && starttype === types$1$1._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 40 || nextCh === 46) return this.parseExpressionStatement(node, this.parseExpression());
}
if (!this.options.allowImportExportEverywhere) {
if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
}
return starttype === types$1$1._import ? this.parseImport(node) : this.parseExport(node, exports$1);
default:
if (this.isAsyncFunction()) {
if (context) this.unexpected();
this.next();
return this.parseFunctionStatement(node, true, !context);
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types$1$1.name && expr.type === "Identifier" && this.eat(types$1$1.colon)) return this.parseLabeledStatement(node, maybeName, expr, context);
else return this.parseExpressionStatement(node, expr);
}
};
pp$8.parseBreakContinueStatement = function(node, keyword) {
var isBreak = keyword === "break";
this.next();
if (this.eat(types$1$1.semi) || this.insertSemicolon()) node.label = null;
else if (this.type !== types$1$1.name) this.unexpected();
else {
node.label = this.parseIdent();
this.semicolon();
}
var i$1 = 0;
for (; i$1 < this.labels.length; ++i$1) {
var lab = this.labels[i$1];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
if (node.label && isBreak) break;
}
}
if (i$1 === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$8.parseDebuggerStatement = function(node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement");
};
pp$8.parseDoStatement = function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement("do");
this.labels.pop();
this.expect(types$1$1._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6) this.eat(types$1$1.semi);
else this.semicolon();
return this.finishNode(node, "DoWhileStatement");
};
pp$8.parseForStatement = function(node) {
this.next();
var awaitAt = this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await") ? this.lastTokStart : -1;
this.labels.push(loopLabel);
this.enterScope(0);
this.expect(types$1$1.parenL);
if (this.type === types$1$1.semi) {
if (awaitAt > -1) this.unexpected(awaitAt);
return this.parseFor(node, null);
}
var isLet = this.isLet();
if (this.type === types$1$1._var || this.type === types$1$1._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types$1$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
if (this.options.ecmaVersion >= 9) if (this.type === types$1$1._in) {
if (awaitAt > -1) this.unexpected(awaitAt);
} else node.await = awaitAt > -1;
return this.parseForIn(node, init$1);
}
if (awaitAt > -1) this.unexpected(awaitAt);
return this.parseFor(node, init$1);
}
var startsWithLet = this.isContextual("let"), isForOf = false;
var containsEsc = this.containsEsc;
var refDestructuringErrors = new DestructuringErrors();
var initPos = this.start;
var init = awaitAt > -1 ? this.parseExprSubscripts(refDestructuringErrors, "await") : this.parseExpression(true, refDestructuringErrors);
if (this.type === types$1$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (awaitAt > -1) {
if (this.type === types$1$1._in) this.unexpected(awaitAt);
node.await = true;
} else if (isForOf && this.options.ecmaVersion >= 8) {
if (init.start === initPos && !containsEsc && init.type === "Identifier" && init.name === "async") this.unexpected();
else if (this.options.ecmaVersion >= 9) node.await = false;
}
if (startsWithLet && isForOf) this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'.");
this.toAssignable(init, false, refDestructuringErrors);
this.checkLValPattern(init);
return this.parseForIn(node, init);
} else this.checkExpressionErrors(refDestructuringErrors, true);
if (awaitAt > -1) this.unexpected(awaitAt);
return this.parseFor(node, init);
};
pp$8.parseFunctionStatement = function(node, isAsync$2, declarationPosition) {
this.next();
return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync$2);
};
pp$8.parseIfStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
node.consequent = this.parseStatement("if");
node.alternate = this.eat(types$1$1._else) ? this.parseStatement("if") : null;
return this.finishNode(node, "IfStatement");
};
pp$8.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
this.next();
if (this.eat(types$1$1.semi) || this.insertSemicolon()) node.argument = null;
else {
node.argument = this.parseExpression();
this.semicolon();
}
return this.finishNode(node, "ReturnStatement");
};
pp$8.parseSwitchStatement = function(node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(types$1$1.braceL);
this.labels.push(switchLabel);
this.enterScope(0);
var cur;
for (var sawDefault = false; this.type !== types$1$1.braceR;) if (this.type === types$1$1._case || this.type === types$1$1._default) {
var isCase = this.type === types$1$1._case;
if (cur) this.finishNode(cur, "SwitchCase");
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) cur.test = this.parseExpression();
else {
if (sawDefault) this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
sawDefault = true;
cur.test = null;
}
this.expect(types$1$1.colon);
} else {
if (!cur) this.unexpected();
cur.consequent.push(this.parseStatement(null));
}
this.exitScope();
if (cur) this.finishNode(cur, "SwitchCase");
this.next();
this.labels.pop();
return this.finishNode(node, "SwitchStatement");
};
pp$8.parseThrowStatement = function(node) {
this.next();
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement");
};
var empty$1$1 = [];
pp$8.parseCatchClauseParam = function() {
var param = this.parseBindingAtom();
var simple = param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types$1$1.parenR);
return param;
};
pp$8.parseTryStatement = function(node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === types$1$1._catch) {
var clause = this.startNode();
this.next();
if (this.eat(types$1$1.parenL)) clause.param = this.parseCatchClauseParam();
else {
if (this.options.ecmaVersion < 10) this.unexpected();
clause.param = null;
this.enterScope(0);
}
clause.body = this.parseBlock(false);
this.exitScope();
node.handler = this.finishNode(clause, "CatchClause");
}
node.finalizer = this.eat(types$1$1._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
return this.finishNode(node, "TryStatement");
};
pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
this.next();
this.parseVar(node, false, kind, allowMissingInitializer);
this.semicolon();
return this.finishNode(node, "VariableDeclaration");
};
pp$8.parseWhileStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
this.labels.push(loopLabel);
node.body = this.parseStatement("while");
this.labels.pop();
return this.finishNode(node, "WhileStatement");
};
pp$8.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode");
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement("with");
return this.finishNode(node, "WithStatement");
};
pp$8.parseEmptyStatement = function(node) {
this.next();
return this.finishNode(node, "EmptyStatement");
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
for (var i$1 = 0, list$1 = this.labels; i$1 < list$1.length; i$1 += 1) if (list$1[i$1].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
var kind = this.type.isLoop ? "loop" : this.type === types$1$1._switch ? "switch" : null;
for (var i$2 = this.labels.length - 1; i$2 >= 0; i$2--) {
var label$1 = this.labels[i$2];
if (label$1.statementStart === node.start) {
label$1.statementStart = this.start;
label$1.kind = kind;
} else break;
}
this.labels.push({
name: maybeName,
kind,
statementStart: this.start
});
node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
this.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement");
};
pp$8.parseExpressionStatement = function(node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement");
};
pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
if (createNewLexicalScope === void 0) createNewLexicalScope = true;
if (node === void 0) node = this.startNode();
node.body = [];
this.expect(types$1$1.braceL);
if (createNewLexicalScope) this.enterScope(0);
while (this.type !== types$1$1.braceR) {
var stmt = this.parseStatement(null);
node.body.push(stmt);
}
if (exitStrict) this.strict = false;
this.next();
if (createNewLexicalScope) this.exitScope();
return this.finishNode(node, "BlockStatement");
};
pp$8.parseFor = function(node, init) {
node.init = init;
this.expect(types$1$1.semi);
node.test = this.type === types$1$1.semi ? null : this.parseExpression();
this.expect(types$1$1.semi);
node.update = this.type === types$1$1.parenR ? null : this.parseExpression();
this.expect(types$1$1.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, "ForStatement");
};
pp$8.parseForIn = function(node, init) {
var isForIn = this.type === types$1$1._in;
this.next();
if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) this.raise(init.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
node.left = init;
node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
this.expect(types$1$1.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
node.declarations = [];
node.kind = kind;
for (;;) {
var decl = this.startNode();
this.parseVarId(decl, kind);
if (this.eat(types$1$1.eq)) decl.init = this.parseMaybeAssign(isFor);
else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1$1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) this.unexpected();
else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1$1._in || this.isContextual("of")))) this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
else decl.init = null;
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(types$1$1.comma)) break;
}
return node;
};
pp$8.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom();
this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync$2, forInit) {
this.initFunction(node);
if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync$2) {
if (this.type === types$1$1.star && statement & FUNC_HANGING_STATEMENT) this.unexpected();
node.generator = this.eat(types$1$1.star);
}
if (this.options.ecmaVersion >= 8) node.async = !!isAsync$2;
if (statement & FUNC_STATEMENT) {
node.id = statement & FUNC_NULLABLE_ID && this.type !== types$1$1.name ? null : this.parseIdent();
if (node.id && !(statement & FUNC_HANGING_STATEMENT)) this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
}
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(node.async, node.generator));
if (!(statement & FUNC_STATEMENT)) node.id = this.type === types$1$1.name ? this.parseIdent() : null;
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody, false, forInit);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
};
pp$8.parseFunctionParams = function(node) {
this.expect(types$1$1.parenL);
node.params = this.parseBindingList(types$1$1.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
};
pp$8.parseClass = function(node, isStatement) {
this.next();
var oldStrict = this.strict;
this.strict = true;
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var privateNameMap = this.enterClassBody();
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types$1$1.braceL);
while (this.type !== types$1$1.braceR) {
var element = this.parseClassElement(node.superClass !== null);
if (element) {
classBody.body.push(element);
if (element.type === "MethodDefinition" && element.kind === "constructor") {
if (hadConstructor) this.raiseRecoverable(element.start, "Duplicate constructor in the same class");
hadConstructor = true;
} else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
}
}
this.strict = oldStrict;
this.next();
node.body = this.finishNode(classBody, "ClassBody");
this.exitClassBody();
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$8.parseClassElement = function(constructorAllowsSuper) {
if (this.eat(types$1$1.semi)) return null;
var ecmaVersion$1 = this.options.ecmaVersion;
var node = this.startNode();
var keyName = "";
var isGenerator = false;
var isAsync$2 = false;
var kind = "method";
var isStatic = false;
if (this.eatContextual("static")) {
if (ecmaVersion$1 >= 13 && this.eat(types$1$1.braceL)) {
this.parseClassStaticBlock(node);
return node;
}
if (this.isClassElementNameStart() || this.type === types$1$1.star) isStatic = true;
else keyName = "static";
}
node.static = isStatic;
if (!keyName && ecmaVersion$1 >= 8 && this.eatContextual("async")) if ((this.isClassElementNameStart() || this.type === types$1$1.star) && !this.canInsertSemicolon()) isAsync$2 = true;
else keyName = "async";
if (!keyName && (ecmaVersion$1 >= 9 || !isAsync$2) && this.eat(types$1$1.star)) isGenerator = true;
if (!keyName && !isAsync$2 && !isGenerator) {
var lastValue = this.value;
if (this.eatContextual("get") || this.eatContextual("set")) if (this.isClassElementNameStart()) kind = lastValue;
else keyName = lastValue;
}
if (keyName) {
node.computed = false;
node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
node.key.name = keyName;
this.finishNode(node.key, "Identifier");
} else this.parseClassElementName(node);
if (ecmaVersion$1 < 13 || this.type === types$1$1.parenL || kind !== "method" || isGenerator || isAsync$2) {
var isConstructor = !node.static && checkKeyName(node, "constructor");
var allowsDirectSuper = isConstructor && constructorAllowsSuper;
if (isConstructor && kind !== "method") this.raise(node.key.start, "Constructor can't have get/set modifier");
node.kind = isConstructor ? "constructor" : kind;
this.parseClassMethod(node, isGenerator, isAsync$2, allowsDirectSuper);
} else this.parseClassField(node);
return node;
};
pp$8.isClassElementNameStart = function() {
return this.type === types$1$1.name || this.type === types$1$1.privateId || this.type === types$1$1.num || this.type === types$1$1.string || this.type === types$1$1.bracketL || this.type.keyword;
};
pp$8.parseClassElementName = function(element) {
if (this.type === types$1$1.privateId) {
if (this.value === "constructor") this.raise(this.start, "Classes can't have an element named '#constructor'");
element.computed = false;
element.key = this.parsePrivateIdent();
} else this.parsePropertyName(element);
};
pp$8.parseClassMethod = function(method, isGenerator, isAsync$2, allowsDirectSuper) {
var key = method.key;
if (method.kind === "constructor") {
if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
if (isAsync$2) this.raise(key.start, "Constructor can't be an async method");
} else if (method.static && checkKeyName(method, "prototype")) this.raise(key.start, "Classes may not have a static property named prototype");
var value = method.value = this.parseMethod(isGenerator, isAsync$2, allowsDirectSuper);
if (method.kind === "get" && value.params.length !== 0) this.raiseRecoverable(value.start, "getter should have no params");
if (method.kind === "set" && value.params.length !== 1) this.raiseRecoverable(value.start, "setter should have exactly one param");
if (method.kind === "set" && value.params[0].type === "RestElement") this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
return this.finishNode(method, "MethodDefinition");
};
pp$8.parseClassField = function(field) {
if (checkKeyName(field, "constructor")) this.raise(field.key.start, "Classes can't have a field named 'constructor'");
else if (field.static && checkKeyName(field, "prototype")) this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
if (this.eat(types$1$1.eq)) {
var scope = this.currentThisScope();
var inClassFieldInit = scope.inClassFieldInit;
scope.inClassFieldInit = true;
field.value = this.parseMaybeAssign();
scope.inClassFieldInit = inClassFieldInit;
} else field.value = null;
this.semicolon();
return this.finishNode(field, "PropertyDefinition");
};
pp$8.parseClassStaticBlock = function(node) {
node.body = [];
var oldLabels = this.labels;
this.labels = [];
this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
while (this.type !== types$1$1.braceR) {
var stmt = this.parseStatement(null);
node.body.push(stmt);
}
this.next();
this.exitScope();
this.labels = oldLabels;
return this.finishNode(node, "StaticBlock");
};
pp$8.parseClassId = function(node, isStatement) {
if (this.type === types$1$1.name) {
node.id = this.parseIdent();
if (isStatement) this.checkLValSimple(node.id, BIND_LEXICAL, false);
} else {
if (isStatement === true) this.unexpected();
node.id = null;
}
};
pp$8.parseClassSuper = function(node) {
node.superClass = this.eat(types$1$1._extends) ? this.parseExprSubscripts(null, false) : null;
};
pp$8.enterClassBody = function() {
var element = {
declared: Object.create(null),
used: []
};
this.privateNameStack.push(element);
return element.declared;
};
pp$8.exitClassBody = function() {
var ref$1 = this.privateNameStack.pop();
var declared = ref$1.declared;
var used = ref$1.used;
if (!this.options.checkPrivateFields) return;
var len = this.privateNameStack.length;
var parent = len === 0 ? null : this.privateNameStack[len - 1];
for (var i$1 = 0; i$1 < used.length; ++i$1) {
var id = used[i$1];
if (!hasOwn(declared, id.name)) if (parent) parent.used.push(id);
else this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
}
};
function isPrivateNameConflicted(privateNameMap, element) {
var name = element.key.name;
var curr = privateNameMap[name];
var next = "true";
if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) next = (element.static ? "s" : "i") + element.kind;
if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
privateNameMap[name] = "true";
return false;
} else if (!curr) {
privateNameMap[name] = next;
return false;
} else return true;
}
function checkKeyName(node, name) {
var computed = node.computed;
var key = node.key;
return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
}
pp$8.parseExportAllDeclaration = function(node, exports$1) {
if (this.options.ecmaVersion >= 11) if (this.eatContextual("as")) {
node.exported = this.parseModuleExportName();
this.checkExport(exports$1, node.exported, this.lastTokStart);
} else node.exported = null;
this.expectContextual("from");
if (this.type !== types$1$1.string) this.unexpected();
node.source = this.parseExprAtom();
if (this.options.ecmaVersion >= 16) node.attributes = this.parseWithClause();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration");
};
pp$8.parseExport = function(node, exports$1) {
this.next();
if (this.eat(types$1$1.star)) return this.parseExportAllDeclaration(node, exports$1);
if (this.eat(types$1$1._default)) {
this.checkExport(exports$1, "default", this.lastTokStart);
node.declaration = this.parseExportDefaultDeclaration();
return this.finishNode(node, "ExportDefaultDeclaration");
}
if (this.shouldParseExportStatement()) {
node.declaration = this.parseExportDeclaration(node);
if (node.declaration.type === "VariableDeclaration") this.checkVariableExport(exports$1, node.declaration.declarations);
else this.checkExport(exports$1, node.declaration.id, node.declaration.id.start);
node.specifiers = [];
node.source = null;
} else {
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports$1);
if (this.eatContextual("from")) {
if (this.type !== types$1$1.string) this.unexpected();
node.source = this.parseExprAtom();
if (this.options.ecmaVersion >= 16) node.attributes = this.parseWithClause();
} else {
for (var i$1 = 0, list$1 = node.specifiers; i$1 < list$1.length; i$1 += 1) {
var spec = list$1[i$1];
this.checkUnreserved(spec.local);
this.checkLocalExport(spec.local);
if (spec.local.type === "Literal") this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
}
node.source = null;
}
this.semicolon();
}
return this.finishNode(node, "ExportNamedDeclaration");
};
pp$8.parseExportDeclaration = function(node) {
return this.parseStatement(null);
};
pp$8.parseExportDefaultDeclaration = function() {
var isAsync$2;
if (this.type === types$1$1._function || (isAsync$2 = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync$2) this.next();
return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync$2);
} else if (this.type === types$1$1._class) {
var cNode = this.startNode();
return this.parseClass(cNode, "nullableID");
} else {
var declaration = this.parseMaybeAssign();
this.semicolon();
return declaration;
}
};
pp$8.checkExport = function(exports$1, name, pos) {
if (!exports$1) return;
if (typeof name !== "string") name = name.type === "Identifier" ? name.name : name.value;
if (hasOwn(exports$1, name)) this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
exports$1[name] = true;
};
pp$8.checkPatternExport = function(exports$1, pat) {
var type = pat.type;
if (type === "Identifier") this.checkExport(exports$1, pat, pat.start);
else if (type === "ObjectPattern") for (var i$1 = 0, list$1 = pat.properties; i$1 < list$1.length; i$1 += 1) {
var prop = list$1[i$1];
this.checkPatternExport(exports$1, prop);
}
else if (type === "ArrayPattern") for (var i$1$1 = 0, list$1$1 = pat.elements; i$1$1 < list$1$1.length; i$1$1 += 1) {
var elt = list$1$1[i$1$1];
if (elt) this.checkPatternExport(exports$1, elt);
}
else if (type === "Property") this.checkPatternExport(exports$1, pat.value);
else if (type === "AssignmentPattern") this.checkPatternExport(exports$1, pat.left);
else if (type === "RestElement") this.checkPatternExport(exports$1, pat.argument);
};
pp$8.checkVariableExport = function(exports$1, decls) {
if (!exports$1) return;
for (var i$1 = 0, list$1 = decls; i$1 < list$1.length; i$1 += 1) {
var decl = list$1[i$1];
this.checkPatternExport(exports$1, decl.id);
}
};
pp$8.shouldParseExportStatement = function() {
return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$8.parseExportSpecifier = function(exports$1) {
var node = this.startNode();
node.local = this.parseModuleExportName();
node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
this.checkExport(exports$1, node.exported, node.exported.start);
return this.finishNode(node, "ExportSpecifier");
};
pp$8.parseExportSpecifiers = function(exports$1) {
var nodes = [], first = true;
this.expect(types$1$1.braceL);
while (!this.eat(types$1$1.braceR)) {
if (!first) {
this.expect(types$1$1.comma);
if (this.afterTrailingComma(types$1$1.braceR)) break;
} else first = false;
nodes.push(this.parseExportSpecifier(exports$1));
}
return nodes;
};
pp$8.parseImport = function(node) {
this.next();
if (this.type === types$1$1.string) {
node.specifiers = empty$1$1;
node.source = this.parseExprAtom();
} else {
node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from");
node.source = this.type === types$1$1.string ? this.parseExprAtom() : this.unexpected();
}
if (this.options.ecmaVersion >= 16) node.attributes = this.parseWithClause();
this.semicolon();
return this.finishNode(node, "ImportDeclaration");
};
pp$8.parseImportSpecifier = function() {
var node = this.startNode();
node.imported = this.parseModuleExportName();
if (this.eatContextual("as")) node.local = this.parseIdent();
else {
this.checkUnreserved(node.imported);
node.local = node.imported;
}
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportSpecifier");
};
pp$8.parseImportDefaultSpecifier = function() {
var node = this.startNode();
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportDefaultSpecifier");
};
pp$8.parseImportNamespaceSpecifier = function() {
var node = this.startNode();
this.next();
this.expectContextual("as");
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportNamespaceSpecifier");
};
pp$8.parseImportSpecifiers = function() {
var nodes = [], first = true;
if (this.type === types$1$1.name) {
nodes.push(this.parseImportDefaultSpecifier());
if (!this.eat(types$1$1.comma)) return nodes;
}
if (this.type === types$1$1.star) {
nodes.push(this.parseImportNamespaceSpecifier());
return nodes;
}
this.expect(types$1$1.braceL);
while (!this.eat(types$1$1.braceR)) {
if (!first) {
this.expect(types$1$1.comma);
if (this.afterTrailingComma(types$1$1.braceR)) break;
} else first = false;
nodes.push(this.parseImportSpecifier());
}
return nodes;
};
pp$8.parseWithClause = function() {
var nodes = [];
if (!this.eat(types$1$1._with)) return nodes;
this.expect(types$1$1.braceL);
var attributeKeys = {};
var first = true;
while (!this.eat(types$1$1.braceR)) {
if (!first) {
this.expect(types$1$1.comma);
if (this.afterTrailingComma(types$1$1.braceR)) break;
} else first = false;
var attr = this.parseImportAttribute();
var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
if (hasOwn(attributeKeys, keyName)) this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
attributeKeys[keyName] = true;
nodes.push(attr);
}
return nodes;
};
pp$8.parseImportAttribute = function() {
var node = this.startNode();
node.key = this.type === types$1$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
this.expect(types$1$1.colon);
if (this.type !== types$1$1.string) this.unexpected();
node.value = this.parseExprAtom();
return this.finishNode(node, "ImportAttribute");
};
pp$8.parseModuleExportName = function() {
if (this.options.ecmaVersion >= 13 && this.type === types$1$1.string) {
var stringLiteral = this.parseLiteral(this.value);
if (loneSurrogate.test(stringLiteral.value)) this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
return stringLiteral;
}
return this.parseIdent(true);
};
pp$8.adaptDirectivePrologue = function(statements) {
for (var i$1 = 0; i$1 < statements.length && this.isDirectiveCandidate(statements[i$1]); ++i$1) statements[i$1].directive = statements[i$1].expression.raw.slice(1, -1);
};
pp$8.isDirectiveCandidate = function(statement) {
return this.options.ecmaVersion >= 5 && statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === "\"" || this.input[statement.start] === "'");
};
var pp$7 = Parser.prototype;
pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
if (this.options.ecmaVersion >= 6 && node) switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await") this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
break;
case "ObjectPattern":
case "ArrayPattern":
case "AssignmentPattern":
case "RestElement": break;
case "ObjectExpression":
node.type = "ObjectPattern";
if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true);
for (var i$1 = 0, list$1 = node.properties; i$1 < list$1.length; i$1 += 1) {
var prop = list$1[i$1];
this.toAssignable(prop, isBinding);
if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) this.raise(prop.argument.start, "Unexpected token");
}
break;
case "Property":
if (node.kind !== "init") this.raise(node.key.start, "Object pattern can't contain getter or setter");
this.toAssignable(node.value, isBinding);
break;
case "ArrayExpression":
node.type = "ArrayPattern";
if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true);
this.toAssignableList(node.elements, isBinding);
break;
case "SpreadElement":
node.type = "RestElement";
this.toAssignable(node.argument, isBinding);
if (node.argument.type === "AssignmentPattern") this.raise(node.argument.start, "Rest elements cannot have a default value");
break;
case "AssignmentExpression":
if (node.operator !== "=") this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
node.type = "AssignmentPattern";
delete node.operator;
this.toAssignable(node.left, isBinding);
break;
case "ParenthesizedExpression":
this.toAssignable(node.expression, isBinding, refDestructuringErrors);
break;
case "ChainExpression":
this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
break;
case "MemberExpression": if (!isBinding) break;
default: this.raise(node.start, "Assigning to rvalue");
}
else if (refDestructuringErrors) this.checkPatternErrors(refDestructuringErrors, true);
return node;
};
pp$7.toAssignableList = function(exprList, isBinding) {
var end = exprList.length;
for (var i$1 = 0; i$1 < end; i$1++) {
var elt = exprList[i$1];
if (elt) this.toAssignable(elt, isBinding);
}
if (end) {
var last = exprList[end - 1];
if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start);
}
return exprList;
};
pp$7.parseSpread = function(refDestructuringErrors) {
var node = this.startNode();
this.next();
node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
return this.finishNode(node, "SpreadElement");
};
pp$7.parseRestBinding = function() {
var node = this.startNode();
this.next();
if (this.options.ecmaVersion === 6 && this.type !== types$1$1.name) this.unexpected();
node.argument = this.parseBindingAtom();
return this.finishNode(node, "RestElement");
};
pp$7.parseBindingAtom = function() {
if (this.options.ecmaVersion >= 6) switch (this.type) {
case types$1$1.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(types$1$1.bracketR, true, true);
return this.finishNode(node, "ArrayPattern");
case types$1$1.braceL: return this.parseObj(true);
}
return this.parseIdent();
};
pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
var elts = [], first = true;
while (!this.eat(close)) {
if (first) first = false;
else this.expect(types$1$1.comma);
if (allowEmpty && this.type === types$1$1.comma) elts.push(null);
else if (allowTrailingComma && this.afterTrailingComma(close)) break;
else if (this.type === types$1$1.ellipsis) {
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types$1$1.comma) this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
this.expect(close);
break;
} else elts.push(this.parseAssignableListItem(allowModifiers));
}
return elts;
};
pp$7.parseAssignableListItem = function(allowModifiers) {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
return elem;
};
pp$7.parseBindingListItem = function(param) {
return param;
};
pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom();
if (this.options.ecmaVersion < 6 || !this.eat(types$1$1.eq)) return left;
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.right = this.parseMaybeAssign();
return this.finishNode(node, "AssignmentPattern");
};
pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
if (bindingType === void 0) bindingType = BIND_NONE;
var isBind = bindingType !== BIND_NONE;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
if (isBind) {
if (bindingType === BIND_LEXICAL && expr.name === "let") this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
if (checkClashes) {
if (hasOwn(checkClashes, expr.name)) this.raiseRecoverable(expr.start, "Argument name clash");
checkClashes[expr.name] = true;
}
if (bindingType !== BIND_OUTSIDE) this.declareName(expr.name, bindingType, expr.start);
}
break;
case "ChainExpression":
this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
break;
case "MemberExpression":
if (isBind) this.raiseRecoverable(expr.start, "Binding member expression");
break;
case "ParenthesizedExpression":
if (isBind) this.raiseRecoverable(expr.start, "Binding parenthesized expression");
return this.checkLValSimple(expr.expression, bindingType, checkClashes);
default: this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
}
};
pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
if (bindingType === void 0) bindingType = BIND_NONE;
switch (expr.type) {
case "ObjectPattern":
for (var i$1 = 0, list$1 = expr.properties; i$1 < list$1.length; i$1 += 1) {
var prop = list$1[i$1];
this.checkLValInnerPattern(prop, bindingType, checkClashes);
}
break;
case "ArrayPattern":
for (var i$1$1 = 0, list$1$1 = expr.elements; i$1$1 < list$1$1.length; i$1$1 += 1) {
var elem = list$1$1[i$1$1];
if (elem) this.checkLValInnerPattern(elem, bindingType, checkClashes);
}
break;
default: this.checkLValSimple(expr, bindingType, checkClashes);
}
};
pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
if (bindingType === void 0) bindingType = BIND_NONE;
switch (expr.type) {
case "Property":
this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
break;
case "AssignmentPattern":
this.checkLValPattern(expr.left, bindingType, checkClashes);
break;
case "RestElement":
this.checkLValPattern(expr.argument, bindingType, checkClashes);
break;
default: this.checkLValPattern(expr, bindingType, checkClashes);
}
};
var TokContext = function TokContext$1(token, isExpr, preserveSpace, override, generator) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override;
this.generator = !!generator;
};
var types$2 = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", false),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function(p$1) {
return p$1.tryReadTemplateToken();
}),
f_stat: new TokContext("function", false),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
};
var pp$6 = Parser.prototype;
pp$6.initialContext = function() {
return [types$2.b_stat];
};
pp$6.curContext = function() {
return this.context[this.context.length - 1];
};
pp$6.braceIsBlock = function(prevType) {
var parent = this.curContext();
if (parent === types$2.f_expr || parent === types$2.f_stat) return true;
if (prevType === types$1$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr)) return !parent.isExpr;
if (prevType === types$1$1._return || prevType === types$1$1.name && this.exprAllowed) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
if (prevType === types$1$1._else || prevType === types$1$1.semi || prevType === types$1$1.eof || prevType === types$1$1.parenR || prevType === types$1$1.arrow) return true;
if (prevType === types$1$1.braceL) return parent === types$2.b_stat;
if (prevType === types$1$1._var || prevType === types$1$1._const || prevType === types$1$1.name) return false;
return !this.exprAllowed;
};
pp$6.inGeneratorContext = function() {
for (var i$1 = this.context.length - 1; i$1 >= 1; i$1--) {
var context = this.context[i$1];
if (context.token === "function") return context.generator;
}
return false;
};
pp$6.updateContext = function(prevType) {
var update, type = this.type;
if (type.keyword && prevType === types$1$1.dot) this.exprAllowed = false;
else if (update = type.updateContext) update.call(this, prevType);
else this.exprAllowed = type.beforeExpr;
};
pp$6.overrideContext = function(tokenCtx) {
if (this.curContext() !== tokenCtx) this.context[this.context.length - 1] = tokenCtx;
};
types$1$1.parenR.updateContext = types$1$1.braceR.updateContext = function() {
if (this.context.length === 1) {
this.exprAllowed = true;
return;
}
var out = this.context.pop();
if (out === types$2.b_stat && this.curContext().token === "function") out = this.context.pop();
this.exprAllowed = !out.isExpr;
};
types$1$1.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr);
this.exprAllowed = true;
};
types$1$1.dollarBraceL.updateContext = function() {
this.context.push(types$2.b_tmpl);
this.exprAllowed = true;
};
types$1$1.parenL.updateContext = function(prevType) {
var statementParens = prevType === types$1$1._if || prevType === types$1$1._for || prevType === types$1$1._with || prevType === types$1$1._while;
this.context.push(statementParens ? types$2.p_stat : types$2.p_expr);
this.exprAllowed = true;
};
types$1$1.incDec.updateContext = function() {};
types$1$1._function.updateContext = types$1$1._class.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== types$1$1._else && !(prevType === types$1$1.semi && this.curContext() !== types$2.p_stat) && !(prevType === types$1$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types$1$1.colon || prevType === types$1$1.braceL) && this.curContext() === types$2.b_stat)) this.context.push(types$2.f_expr);
else this.context.push(types$2.f_stat);
this.exprAllowed = false;
};
types$1$1.colon.updateContext = function() {
if (this.curContext().token === "function") this.context.pop();
this.exprAllowed = true;
};
types$1$1.backQuote.updateContext = function() {
if (this.curContext() === types$2.q_tmpl) this.context.pop();
else this.context.push(types$2.q_tmpl);
this.exprAllowed = false;
};
types$1$1.star.updateContext = function(prevType) {
if (prevType === types$1$1._function) {
var index = this.context.length - 1;
if (this.context[index] === types$2.f_expr) this.context[index] = types$2.f_expr_gen;
else this.context[index] = types$2.f_gen;
}
this.exprAllowed = true;
};
types$1$1.name.updateContext = function(prevType) {
var allowed = false;
if (this.options.ecmaVersion >= 6 && prevType !== types$1$1.dot) {
if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) allowed = true;
}
this.exprAllowed = allowed;
};
var pp$5 = Parser.prototype;
pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") return;
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
var key = prop.key;
var name;
switch (key.type) {
case "Identifier":
name = key.name;
break;
case "Literal":
name = String(key.value);
break;
default: return;
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) if (refDestructuringErrors) {
if (refDestructuringErrors.doubleProto < 0) refDestructuringErrors.doubleProto = key.start;
} else this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
propHash.proto = true;
}
return;
}
name = "$" + name;
var other = propHash[name];
if (other) {
var redefinition;
if (kind === "init") redefinition = this.strict && other.init || other.get || other.set;
else redefinition = other.init || other[kind];
if (redefinition) this.raiseRecoverable(key.start, "Redefinition of property");
} else other = propHash[name] = {
init: false,
get: false,
set: false
};
other[kind] = true;
};
pp$5.parseExpression = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
if (this.type === types$1$1.comma) {
var node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(types$1$1.comma)) node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors));
return this.finishNode(node, "SequenceExpression");
}
return expr;
};
pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
if (this.isContextual("yield")) if (this.inGenerator) return this.parseYield(forInit);
else this.exprAllowed = false;
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign;
oldTrailingComma = refDestructuringErrors.trailingComma;
oldDoubleProto = refDestructuringErrors.doubleProto;
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
} else {
refDestructuringErrors = new DestructuringErrors();
ownDestructuringErrors = true;
}
var startPos = this.start, startLoc = this.startLoc;
if (this.type === types$1$1.parenL || this.type === types$1$1.name) {
this.potentialArrowAt = this.start;
this.potentialArrowInForAwait = forInit === "await";
}
var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
if (this.type.isAssign) {
var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value;
if (this.type === types$1$1.eq) left = this.toAssignable(left, false, refDestructuringErrors);
if (!ownDestructuringErrors) refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
if (refDestructuringErrors.shorthandAssign >= left.start) refDestructuringErrors.shorthandAssign = -1;
if (this.type === types$1$1.eq) this.checkLValPattern(left);
else this.checkLValSimple(left);
node.left = left;
this.next();
node.right = this.parseMaybeAssign(forInit);
if (oldDoubleProto > -1) refDestructuringErrors.doubleProto = oldDoubleProto;
return this.finishNode(node, "AssignmentExpression");
} else if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true);
if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign;
if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma;
return left;
};
pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprOps(forInit, refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
if (this.eat(types$1$1.question)) {
var node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(types$1$1.colon);
node.alternate = this.parseMaybeAssign(forInit);
return this.finishNode(node, "ConditionalExpression");
}
return expr;
};
pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit);
};
pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
var prec = this.type.binop;
if (prec != null && (!forInit || this.type !== types$1$1._in)) {
if (prec > minPrec) {
var logical = this.type === types$1$1.logicalOR || this.type === types$1$1.logicalAND;
var coalesce = this.type === types$1$1.coalesce;
if (coalesce) prec = types$1$1.logicalAND.binop;
var op = this.value;
this.next();
var startPos = this.start, startLoc = this.startLoc;
var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
if (logical && this.type === types$1$1.coalesce || coalesce && (this.type === types$1$1.logicalOR || this.type === types$1$1.logicalAND)) this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit);
}
}
return left;
};
pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
if (right.type === "PrivateIdentifier") this.raise(right.start, "Private identifier can only be left side of binary expression");
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.operator = op;
node.right = right;
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
var startPos = this.start, startLoc = this.startLoc, expr;
if (this.isContextual("await") && this.canAwait) {
expr = this.parseAwait(forInit);
sawUnary = true;
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === types$1$1.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary(null, true, update, forInit);
this.checkExpressionErrors(refDestructuringErrors, true);
if (update) this.checkLValSimple(node.argument);
else if (this.strict && node.operator === "delete" && isLocalVariableAccess(node.argument)) this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) this.raiseRecoverable(node.start, "Private fields can not be deleted");
else sawUnary = true;
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
} else if (!sawUnary && this.type === types$1$1.privateId) {
if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) this.unexpected();
expr = this.parsePrivateIdent();
if (this.type !== types$1$1._in) this.unexpected();
} else {
expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.operator = this.value;
node$1.prefix = false;
node$1.argument = expr;
this.checkLValSimple(expr);
this.next();
expr = this.finishNode(node$1, "UpdateExpression");
}
}
if (!incDec && this.eat(types$1$1.starstar)) if (sawUnary) this.unexpected(this.lastTokStart);
else return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false);
else return expr;
};
function isLocalVariableAccess(node) {
return node.type === "Identifier" || node.type === "ParenthesizedExpression" && isLocalVariableAccess(node.expression);
}
function isPrivateFieldAccess(node) {
return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) || node.type === "ParenthesizedExpression" && isPrivateFieldAccess(node.expression);
}
pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprAtom(refDestructuringErrors, forInit);
if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") return expr;
var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1;
if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1;
if (refDestructuringErrors.trailingComma >= result.start) refDestructuringErrors.trailingComma = -1;
}
return result;
};
pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;
var optionalChained = false;
while (true) {
var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
if (element.optional) optionalChained = true;
if (element === base || element.type === "ArrowFunctionExpression") {
if (optionalChained) {
var chainNode = this.startNodeAt(startPos, startLoc);
chainNode.expression = element;
element = this.finishNode(chainNode, "ChainExpression");
}
return element;
}
base = element;
}
};
pp$5.shouldParseAsyncArrow = function() {
return !this.canInsertSemicolon() && this.eat(types$1$1.arrow);
};
pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit);
};
pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
var optionalSupported = this.options.ecmaVersion >= 11;
var optional = optionalSupported && this.eat(types$1$1.questionDot);
if (noCalls && optional) this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
var computed = this.eat(types$1$1.bracketL);
if (computed || optional && this.type !== types$1$1.parenL && this.type !== types$1$1.backQuote || this.eat(types$1$1.dot)) {
var node = this.startNodeAt(startPos, startLoc);
node.object = base;
if (computed) {
node.property = this.parseExpression();
this.expect(types$1$1.bracketR);
} else if (this.type === types$1$1.privateId && base.type !== "Super") node.property = this.parsePrivateIdent();
else node.property = this.parseIdent(this.options.allowReserved !== "never");
node.computed = !!computed;
if (optionalSupported) node.optional = optional;
base = this.finishNode(node, "MemberExpression");
} else if (!noCalls && this.eat(types$1$1.parenL)) {
var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types$1$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
if (this.awaitIdentPos > 0) this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit);
}
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
if (optionalSupported) node$1.optional = optional;
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types$1$1.backQuote) {
if (optional || optionalChained) this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
var node$2 = this.startNodeAt(startPos, startLoc);
node$2.tag = base;
node$2.quasi = this.parseTemplate({ isTagged: true });
base = this.finishNode(node$2, "TaggedTemplateExpression");
}
return base;
};
pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
if (this.type === types$1$1.slash) this.readRegexp();
var node, canBeArrow = this.potentialArrowAt === this.start;
switch (this.type) {
case types$1$1._super:
if (!this.allowSuper) this.raise(this.start, "'super' keyword outside a method");
node = this.startNode();
this.next();
if (this.type === types$1$1.parenL && !this.allowDirectSuper) this.raise(node.start, "super() call outside constructor of a subclass");
if (this.type !== types$1$1.dot && this.type !== types$1$1.bracketL && this.type !== types$1$1.parenL) this.unexpected();
return this.finishNode(node, "Super");
case types$1$1._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression");
case types$1$1.name:
var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
var id = this.parseIdent(false);
if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1$1._function)) {
this.overrideContext(types$2.f_expr);
return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit);
}
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(types$1$1.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit);
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1$1.name && !containsEsc && (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
id = this.parseIdent(false);
if (this.canInsertSemicolon() || !this.eat(types$1$1.arrow)) this.unexpected();
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit);
}
}
return id;
case types$1$1.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = {
pattern: value.pattern,
flags: value.flags
};
return node;
case types$1$1.num:
case types$1$1.string: return this.parseLiteral(this.value);
case types$1$1._null:
case types$1$1._true:
case types$1$1._false:
node = this.startNode();
node.value = this.type === types$1$1._null ? null : this.type === types$1$1._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal");
case types$1$1.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) refDestructuringErrors.parenthesizedAssign = start;
if (refDestructuringErrors.parenthesizedBind < 0) refDestructuringErrors.parenthesizedBind = start;
}
return expr;
case types$1$1.bracketL:
node = this.startNode();
this.next();
node.elements = this.parseExprList(types$1$1.bracketR, true, true, refDestructuringErrors);
return this.finishNode(node, "ArrayExpression");
case types$1$1.braceL:
this.overrideContext(types$2.b_expr);
return this.parseObj(false, refDestructuringErrors);
case types$1$1._function:
node = this.startNode();
this.next();
return this.parseFunction(node, 0);
case types$1$1._class: return this.parseClass(this.startNode(), false);
case types$1$1._new: return this.parseNew();
case types$1$1.backQuote: return this.parseTemplate();
case types$1$1._import: if (this.options.ecmaVersion >= 11) return this.parseExprImport(forNew);
else return this.unexpected();
default: return this.parseExprAtomDefault();
}
};
pp$5.parseExprAtomDefault = function() {
this.unexpected();
};
pp$5.parseExprImport = function(forNew) {
var node = this.startNode();
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword import");
this.next();
if (this.type === types$1$1.parenL && !forNew) return this.parseDynamicImport(node);
else if (this.type === types$1$1.dot) {
var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
meta.name = "import";
node.meta = this.finishNode(meta, "Identifier");
return this.parseImportMeta(node);
} else this.unexpected();
};
pp$5.parseDynamicImport = function(node) {
this.next();
node.source = this.parseMaybeAssign();
if (this.options.ecmaVersion >= 16) if (!this.eat(types$1$1.parenR)) {
this.expect(types$1$1.comma);
if (!this.afterTrailingComma(types$1$1.parenR)) {
node.options = this.parseMaybeAssign();
if (!this.eat(types$1$1.parenR)) {
this.expect(types$1$1.comma);
if (!this.afterTrailingComma(types$1$1.parenR)) this.unexpected();
}
} else node.options = null;
} else node.options = null;
else if (!this.eat(types$1$1.parenR)) {
var errorPos = this.start;
if (this.eat(types$1$1.comma) && this.eat(types$1$1.parenR)) this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
else this.unexpected(errorPos);
}
return this.finishNode(node, "ImportExpression");
};
pp$5.parseImportMeta = function(node) {
this.next();
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "meta") this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
if (containsEsc) this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
return this.finishNode(node, "MetaProperty");
};
pp$5.parseLiteral = function(value) {
var node = this.startNode();
node.value = value;
node.raw = this.input.slice(this.start, this.end);
if (node.raw.charCodeAt(node.raw.length - 1) === 110) node.bigint = node.raw.slice(0, -1).replace(/_/g, "");
this.next();
return this.finishNode(node, "Literal");
};
pp$5.parseParenExpression = function() {
this.expect(types$1$1.parenL);
var val = this.parseExpression();
this.expect(types$1$1.parenR);
return val;
};
pp$5.shouldParseArrow = function(exprList) {
return !this.canInsertSemicolon();
};
pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
if (this.options.ecmaVersion >= 6) {
this.next();
var innerStartPos = this.start, innerStartLoc = this.startLoc;
var exprList = [], first = true, lastIsComma = false;
var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
this.yieldPos = 0;
this.awaitPos = 0;
while (this.type !== types$1$1.parenR) {
first ? first = false : this.expect(types$1$1.comma);
if (allowTrailingComma && this.afterTrailingComma(types$1$1.parenR, true)) {
lastIsComma = true;
break;
} else if (this.type === types$1$1.ellipsis) {
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRestBinding()));
if (this.type === types$1$1.comma) this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
break;
} else exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
}
var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
this.expect(types$1$1.parenR);
if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1$1.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return this.parseParenArrowList(startPos, startLoc, exprList, forInit);
}
if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart);
if (spreadStart) this.unexpected(spreadStart);
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else val = exprList[0];
} else val = this.parseParenExpression();
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc);
par.expression = val;
return this.finishNode(par, "ParenthesizedExpression");
} else return val;
};
pp$5.parseParenItem = function(item) {
return item;
};
pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit);
};
var empty$3 = [];
pp$5.parseNew = function() {
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword new");
var node = this.startNode();
this.next();
if (this.options.ecmaVersion >= 6 && this.type === types$1$1.dot) {
var meta = this.startNodeAt(node.start, node.loc && node.loc.start);
meta.name = "new";
node.meta = this.finishNode(meta, "Identifier");
this.next();
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "target") this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
if (containsEsc) this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
if (!this.allowNewDotTarget) this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block");
return this.finishNode(node, "MetaProperty");
}
var startPos = this.start, startLoc = this.startLoc;
node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
if (this.eat(types$1$1.parenL)) node.arguments = this.parseExprList(types$1$1.parenR, this.options.ecmaVersion >= 8, false);
else node.arguments = empty$3;
return this.finishNode(node, "NewExpression");
};
pp$5.parseTemplateElement = function(ref$1) {
var isTagged = ref$1.isTagged;
var elem = this.startNode();
if (this.type === types$1$1.invalidTemplate) {
if (!isTagged) this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
elem.value = {
raw: this.value.replace(/\r\n?/g, "\n"),
cooked: null
};
} else elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
};
this.next();
elem.tail = this.type === types$1$1.backQuote;
return this.finishNode(elem, "TemplateElement");
};
pp$5.parseTemplate = function(ref$1) {
if (ref$1 === void 0) ref$1 = {};
var isTagged = ref$1.isTagged;
if (isTagged === void 0) isTagged = false;
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement({ isTagged });
node.quasis = [curElt];
while (!curElt.tail) {
if (this.type === types$1$1.eof) this.raise(this.pos, "Unterminated template literal");
this.expect(types$1$1.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(types$1$1.braceR);
node.quasis.push(curElt = this.parseTemplateElement({ isTagged }));
}
this.next();
return this.finishNode(node, "TemplateLiteral");
};
pp$5.isAsyncProp = function(prop) {
return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types$1$1.name || this.type === types$1$1.num || this.type === types$1$1.string || this.type === types$1$1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types$1$1.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$5.parseObj = function(isPattern, refDestructuringErrors) {
var node = this.startNode(), first = true, propHash = {};
node.properties = [];
this.next();
while (!this.eat(types$1$1.braceR)) {
if (!first) {
this.expect(types$1$1.comma);
if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1$1.braceR)) break;
} else first = false;
var prop = this.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) this.checkPropClash(prop, propHash, refDestructuringErrors);
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
var prop = this.startNode(), isGenerator, isAsync$2, startPos, startLoc;
if (this.options.ecmaVersion >= 9 && this.eat(types$1$1.ellipsis)) {
if (isPattern) {
prop.argument = this.parseIdent(false);
if (this.type === types$1$1.comma) this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
return this.finishNode(prop, "RestElement");
}
prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
if (this.type === types$1$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) refDestructuringErrors.trailingComma = this.start;
return this.finishNode(prop, "SpreadElement");
}
if (this.options.ecmaVersion >= 6) {
prop.method = false;
prop.shorthand = false;
if (isPattern || refDestructuringErrors) {
startPos = this.start;
startLoc = this.startLoc;
}
if (!isPattern) isGenerator = this.eat(types$1$1.star);
}
var containsEsc = this.containsEsc;
this.parsePropertyName(prop);
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync$2 = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1$1.star);
this.parsePropertyName(prop);
} else isAsync$2 = false;
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync$2, startPos, startLoc, refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property");
};
pp$5.parseGetterSetter = function(prop) {
prop.kind = prop.key.name;
this.parsePropertyName(prop);
prop.value = this.parseMethod(false);
var paramCount = prop.kind === "get" ? 0 : 1;
if (prop.value.params.length !== paramCount) {
var start = prop.value.start;
if (prop.kind === "get") this.raiseRecoverable(start, "getter should have no params");
else this.raiseRecoverable(start, "setter should have exactly one param");
} else if (prop.kind === "set" && prop.value.params[0].type === "RestElement") this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
};
pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync$2, startPos, startLoc, refDestructuringErrors, containsEsc) {
if ((isGenerator || isAsync$2) && this.type === types$1$1.colon) this.unexpected();
if (this.eat(types$1$1.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === types$1$1.parenL) {
if (isPattern) this.unexpected();
prop.kind = "init";
prop.method = true;
prop.value = this.parseMethod(isGenerator, isAsync$2);
} else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type !== types$1$1.comma && this.type !== types$1$1.braceR && this.type !== types$1$1.eq) {
if (isGenerator || isAsync$2) this.unexpected();
this.parseGetterSetter(prop);
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (isGenerator || isAsync$2) this.unexpected();
this.checkUnreserved(prop.key);
if (prop.key.name === "await" && !this.awaitIdentPos) this.awaitIdentPos = startPos;
prop.kind = "init";
if (isPattern) prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
else if (this.type === types$1$1.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0) refDestructuringErrors.shorthandAssign = this.start;
prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
} else prop.value = this.copyNode(prop.key);
prop.shorthand = true;
} else this.unexpected();
};
pp$5.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) if (this.eat(types$1$1.bracketL)) {
prop.computed = true;
prop.key = this.parseMaybeAssign();
this.expect(types$1$1.bracketR);
return prop.key;
} else prop.computed = false;
return prop.key = this.type === types$1$1.num || this.type === types$1$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$5.initFunction = function(node) {
node.id = null;
if (this.options.ecmaVersion >= 6) node.generator = node.expression = false;
if (this.options.ecmaVersion >= 8) node.async = false;
};
pp$5.parseMethod = function(isGenerator, isAsync$2, allowDirectSuper) {
var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.initFunction(node);
if (this.options.ecmaVersion >= 6) node.generator = isGenerator;
if (this.options.ecmaVersion >= 8) node.async = !!isAsync$2;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(isAsync$2, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
this.expect(types$1$1.parenL);
node.params = this.parseBindingList(types$1$1.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
this.parseFunctionBody(node, false, true, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "FunctionExpression");
};
pp$5.parseArrowExpression = function(node, params, isAsync$2, forInit) {
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.enterScope(functionFlags(isAsync$2, false) | SCOPE_ARROW);
this.initFunction(node);
if (this.options.ecmaVersion >= 8) node.async = !!isAsync$2;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
node.params = this.toAssignableList(params, true);
this.parseFunctionBody(node, true, false, forInit);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "ArrowFunctionExpression");
};
pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
var isExpression = isArrowFunction && this.type !== types$1$1.braceL;
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign(forInit);
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
if (useStrict && nonSimple) this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
}
var oldLabels = this.labels;
this.labels = [];
if (useStrict) this.strict = true;
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
if (this.strict && node.id) this.checkLValSimple(node.id, BIND_OUTSIDE);
node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
node.expression = false;
this.adaptDirectivePrologue(node.body.body);
this.labels = oldLabels;
}
this.exitScope();
};
pp$5.isSimpleParamList = function(params) {
for (var i$1 = 0, list$1 = params; i$1 < list$1.length; i$1 += 1) if (list$1[i$1].type !== "Identifier") return false;
return true;
};
pp$5.checkParams = function(node, allowDuplicates) {
var nameHash = Object.create(null);
for (var i$1 = 0, list$1 = node.params; i$1 < list$1.length; i$1 += 1) {
var param = list$1[i$1];
this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
}
};
pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var elts = [], first = true;
while (!this.eat(close)) {
if (!first) {
this.expect(types$1$1.comma);
if (allowTrailingComma && this.afterTrailingComma(close)) break;
} else first = false;
var elt = void 0;
if (allowEmpty && this.type === types$1$1.comma) elt = null;
else if (this.type === types$1$1.ellipsis) {
elt = this.parseSpread(refDestructuringErrors);
if (refDestructuringErrors && this.type === types$1$1.comma && refDestructuringErrors.trailingComma < 0) refDestructuringErrors.trailingComma = this.start;
} else elt = this.parseMaybeAssign(false, refDestructuringErrors);
elts.push(elt);
}
return elts;
};
pp$5.checkUnreserved = function(ref$1) {
var start = ref$1.start;
var end = ref$1.end;
var name = ref$1.name;
if (this.inGenerator && name === "yield") this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
if (this.inAsync && name === "await") this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
if (this.currentThisScope().inClassFieldInit && name === "arguments") this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
if (this.inClassStaticBlock && (name === "arguments" || name === "await")) this.raise(start, "Cannot use " + name + " in class static initialization block");
if (this.keywords.test(name)) this.raise(start, "Unexpected keyword '" + name + "'");
if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) return;
if ((this.strict ? this.reservedWordsStrict : this.reservedWords).test(name)) {
if (!this.inAsync && name === "await") this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
}
};
pp$5.parseIdent = function(liberal) {
var node = this.parseIdentNode();
this.next(!!liberal);
this.finishNode(node, "Identifier");
if (!liberal) {
this.checkUnreserved(node);
if (node.name === "await" && !this.awaitIdentPos) this.awaitIdentPos = node.start;
}
return node;
};
pp$5.parseIdentNode = function() {
var node = this.startNode();
if (this.type === types$1$1.name) node.name = this.value;
else if (this.type.keyword) {
node.name = this.type.keyword;
if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) this.context.pop();
this.type = types$1$1.name;
} else this.unexpected();
return node;
};
pp$5.parsePrivateIdent = function() {
var node = this.startNode();
if (this.type === types$1$1.privateId) node.name = this.value;
else this.unexpected();
this.next();
this.finishNode(node, "PrivateIdentifier");
if (this.options.checkPrivateFields) if (this.privateNameStack.length === 0) this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
else this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
return node;
};
pp$5.parseYield = function(forInit) {
if (!this.yieldPos) this.yieldPos = this.start;
var node = this.startNode();
this.next();
if (this.type === types$1$1.semi || this.canInsertSemicolon() || this.type !== types$1$1.star && !this.type.startsExpr) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(types$1$1.star);
node.argument = this.parseMaybeAssign(forInit);
}
return this.finishNode(node, "YieldExpression");
};
pp$5.parseAwait = function(forInit) {
if (!this.awaitPos) this.awaitPos = this.start;
var node = this.startNode();
this.next();
node.argument = this.parseMaybeUnary(null, true, false, forInit);
return this.finishNode(node, "AwaitExpression");
};
var pp$4 = Parser.prototype;
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos);
message += " (" + loc.line + ":" + loc.column + ")";
var err = new SyntaxError(message);
err.pos = pos;
err.loc = loc;
err.raisedAt = this.pos;
throw err;
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
if (this.options.locations) return new Position(this.curLine, this.pos - this.lineStart);
};
var pp$3 = Parser.prototype;
var Scope = function Scope$1(flags) {
this.flags = flags;
this.var = [];
this.lexical = [];
this.functions = [];
this.inClassFieldInit = false;
};
pp$3.enterScope = function(flags) {
this.scopeStack.push(new Scope(flags));
};
pp$3.exitScope = function() {
this.scopeStack.pop();
};
pp$3.treatFunctionsAsVarInScope = function(scope) {
return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
};
pp$3.declareName = function(name, bindingType, pos) {
var redeclared = false;
if (bindingType === BIND_LEXICAL) {
var scope = this.currentScope();
redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
scope.lexical.push(name);
if (this.inModule && scope.flags & SCOPE_TOP) delete this.undefinedExports[name];
} else if (bindingType === BIND_SIMPLE_CATCH) this.currentScope().lexical.push(name);
else if (bindingType === BIND_FUNCTION) {
var scope$2 = this.currentScope();
if (this.treatFunctionsAsVar) redeclared = scope$2.lexical.indexOf(name) > -1;
else redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
scope$2.functions.push(name);
} else for (var i$1 = this.scopeStack.length - 1; i$1 >= 0; --i$1) {
var scope$3 = this.scopeStack[i$1];
if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
redeclared = true;
break;
}
scope$3.var.push(name);
if (this.inModule && scope$3.flags & SCOPE_TOP) delete this.undefinedExports[name];
if (scope$3.flags & SCOPE_VAR) break;
}
if (redeclared) this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
};
pp$3.checkLocalExport = function(id) {
if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) this.undefinedExports[id.name] = id;
};
pp$3.currentScope = function() {
return this.scopeStack[this.scopeStack.length - 1];
};
pp$3.currentVarScope = function() {
for (var i$1 = this.scopeStack.length - 1;; i$1--) {
var scope = this.scopeStack[i$1];
if (scope.flags & SCOPE_VAR) return scope;
}
};
pp$3.currentThisScope = function() {
for (var i$1 = this.scopeStack.length - 1;; i$1--) {
var scope = this.scopeStack[i$1];
if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) return scope;
}
};
var Node = function Node$1(parser, pos, loc) {
this.type = "";
this.start = pos;
this.end = 0;
if (parser.options.locations) this.loc = new SourceLocation(parser, loc);
if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
if (parser.options.ranges) this.range = [pos, 0];
};
var pp$2 = Parser.prototype;
pp$2.startNode = function() {
return new Node(this, this.start, this.startLoc);
};
pp$2.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc);
};
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations) node.loc.end = loc;
if (this.options.ranges) node.range[1] = pos;
return node;
}
pp$2.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
};
pp$2.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc);
};
pp$2.copyNode = function(node) {
var newNode = new Node(this, node.start, this.startLoc);
for (var prop in node) newNode[prop] = node[prop];
return newNode;
};
var scriptValuesAddedInUnicode = "Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz";
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var ecma13BinaryProperties = ecma12BinaryProperties;
var ecma14BinaryProperties = ecma13BinaryProperties;
var unicodeBinaryProperties = {
9: ecma9BinaryProperties,
10: ecma10BinaryProperties,
11: ecma11BinaryProperties,
12: ecma12BinaryProperties,
13: ecma13BinaryProperties,
14: ecma14BinaryProperties
};
var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
var unicodeBinaryPropertiesOfStrings = {
9: "",
10: "",
11: "",
12: "",
13: "",
14: ecma14BinaryPropertiesOfStrings
};
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var ecma14ScriptValues = ecma13ScriptValues + " " + scriptValuesAddedInUnicode;
var unicodeScriptValues = {
9: ecma9ScriptValues,
10: ecma10ScriptValues,
11: ecma11ScriptValues,
12: ecma12ScriptValues,
13: ecma13ScriptValues,
14: ecma14ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion$1) {
var d = data[ecmaVersion$1] = {
binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion$1] + " " + unicodeGeneralCategoryValues),
binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion$1]),
nonBinary: {
General_Category: wordsRegexp(unicodeGeneralCategoryValues),
Script: wordsRegexp(unicodeScriptValues[ecmaVersion$1])
}
};
d.nonBinary.Script_Extensions = d.nonBinary.Script;
d.nonBinary.gc = d.nonBinary.General_Category;
d.nonBinary.sc = d.nonBinary.Script;
d.nonBinary.scx = d.nonBinary.Script_Extensions;
}
for (var i = 0, list = [
9,
10,
11,
12,
13,
14
]; i < list.length; i += 1) {
var ecmaVersion = list[i];
buildUnicodeData(ecmaVersion);
}
var pp$1 = Parser.prototype;
var BranchID = function BranchID$1(parent, base) {
this.parent = parent;
this.base = base || this;
};
BranchID.prototype.separatedFrom = function separatedFrom(alt) {
for (var self = this; self; self = self.parent) for (var other = alt; other; other = other.parent) if (self.base === other.base && self !== other) return true;
return false;
};
BranchID.prototype.sibling = function sibling() {
return new BranchID(this.parent, this.base);
};
var RegExpValidationState = function RegExpValidationState$1(parser) {
this.parser = parser;
this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
this.source = "";
this.flags = "";
this.start = 0;
this.switchU = false;
this.switchV = false;
this.switchN = false;
this.pos = 0;
this.lastIntValue = 0;
this.lastStringValue = "";
this.lastAssertionIsQuantifiable = false;
this.numCapturingParens = 0;
this.maxBackReference = 0;
this.groupNames = Object.create(null);
this.backReferenceNames = [];
this.branchID = null;
};
RegExpValidationState.prototype.reset = function reset(start, pattern, flags) {
var unicodeSets = flags.indexOf("v") !== -1;
var unicode = flags.indexOf("u") !== -1;
this.start = start | 0;
this.source = pattern + "";
this.flags = flags;
if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
this.switchU = true;
this.switchV = true;
this.switchN = true;
} else {
this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
this.switchV = false;
this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
}
};
RegExpValidationState.prototype.raise = function raise(message) {
this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState.prototype.at = function at(i$1, forceU) {
if (forceU === void 0) forceU = false;
var s = this.source;
var l = s.length;
if (i$1 >= l) return -1;
var c = s.charCodeAt(i$1);
if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i$1 + 1 >= l) return c;
var next = s.charCodeAt(i$1 + 1);
return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i$1, forceU) {
if (forceU === void 0) forceU = false;
var s = this.source;
var l = s.length;
if (i$1 >= l) return l;
var c = s.charCodeAt(i$1), next;
if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i$1 + 1 >= l || (next = s.charCodeAt(i$1 + 1)) < 56320 || next > 57343) return i$1 + 1;
return i$1 + 2;
};
RegExpValidationState.prototype.current = function current(forceU) {
if (forceU === void 0) forceU = false;
return this.at(this.pos, forceU);
};
RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
if (forceU === void 0) forceU = false;
return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState.prototype.advance = function advance(forceU) {
if (forceU === void 0) forceU = false;
this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat(ch, forceU) {
if (forceU === void 0) forceU = false;
if (this.current(forceU) === ch) {
this.advance(forceU);
return true;
}
return false;
};
RegExpValidationState.prototype.eatChars = function eatChars(chs, forceU) {
if (forceU === void 0) forceU = false;
var pos = this.pos;
for (var i$1 = 0, list$1 = chs; i$1 < list$1.length; i$1 += 1) {
var ch = list$1[i$1];
var current = this.at(pos, forceU);
if (current === -1 || current !== ch) return false;
pos = this.nextIndex(pos, forceU);
}
this.pos = pos;
return true;
};
/**
* Validate the flags part of a given RegExpLiteral.
*
* @param {RegExpValidationState} state The state to validate RegExp.
* @returns {void}
*/
pp$1.validateRegExpFlags = function(state) {
var validFlags = state.validFlags;
var flags = state.flags;
var u = false;
var v = false;
for (var i$1 = 0; i$1 < flags.length; i$1++) {
var flag = flags.charAt(i$1);
if (validFlags.indexOf(flag) === -1) this.raise(state.start, "Invalid regular expression flag");
if (flags.indexOf(flag, i$1 + 1) > -1) this.raise(state.start, "Duplicate regular expression flag");
if (flag === "u") u = true;
if (flag === "v") v = true;
}
if (this.options.ecmaVersion >= 15 && u && v) this.raise(state.start, "Invalid regular expression flag");
};
function hasProp(obj) {
for (var _ in obj) return true;
return false;
}
/**
* Validate the pattern part of a given RegExpLiteral.
*
* @param {RegExpValidationState} state The state to validate RegExp.
* @returns {void}
*/
pp$1.validateRegExpPattern = function(state) {
this.regexp_pattern(state);
if (!state.switchN && this.options.ecmaVersion >= 9 && hasProp(state.groupNames)) {
state.switchN = true;
this.regexp_pattern(state);
}
};
pp$1.regexp_pattern = function(state) {
state.pos = 0;
state.lastIntValue = 0;
state.lastStringValue = "";
state.lastAssertionIsQuantifiable = false;
state.numCapturingParens = 0;
state.maxBackReference = 0;
state.groupNames = Object.create(null);
state.backReferenceNames.length = 0;
state.branchID = null;
this.regexp_disjunction(state);
if (state.pos !== state.source.length) {
if (state.eat(41)) state.raise("Unmatched ')'");
if (state.eat(93) || state.eat(125)) state.raise("Lone quantifier brackets");
}
if (state.maxBackReference > state.numCapturingParens) state.raise("Invalid escape");
for (var i$1 = 0, list$1 = state.backReferenceNames; i$1 < list$1.length; i$1 += 1) {
var name = list$1[i$1];
if (!state.groupNames[name]) state.raise("Invalid named capture referenced");
}
};
pp$1.regexp_disjunction = function(state) {
var trackDisjunction = this.options.ecmaVersion >= 16;
if (trackDisjunction) state.branchID = new BranchID(state.branchID, null);
this.regexp_alternative(state);
while (state.eat(124)) {
if (trackDisjunction) state.branchID = state.branchID.sibling();
this.regexp_alternative(state);
}
if (trackDisjunction) state.branchID = state.branchID.parent;
if (this.regexp_eatQuantifier(state, true)) state.raise("Nothing to repeat");
if (state.eat(123)) state.raise("Lone quantifier brackets");
};
pp$1.regexp_alternative = function(state) {
while (state.pos < state.source.length && this.regexp_eatTerm(state));
};
pp$1.regexp_eatTerm = function(state) {
if (this.regexp_eatAssertion(state)) {
if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
if (state.switchU) state.raise("Invalid quantifier");
}
return true;
}
if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
this.regexp_eatQuantifier(state);
return true;
}
return false;
};
pp$1.regexp_eatAssertion = function(state) {
var start = state.pos;
state.lastAssertionIsQuantifiable = false;
if (state.eat(94) || state.eat(36)) return true;
if (state.eat(92)) {
if (state.eat(66) || state.eat(98)) return true;
state.pos = start;
}
if (state.eat(40) && state.eat(63)) {
var lookbehind = false;
if (this.options.ecmaVersion >= 9) lookbehind = state.eat(60);
if (state.eat(61) || state.eat(33)) {
this.regexp_disjunction(state);
if (!state.eat(41)) state.raise("Unterminated group");
state.lastAssertionIsQuantifiable = !lookbehind;
return true;
}
}
state.pos = start;
return false;
};
pp$1.regexp_eatQuantifier = function(state, noError) {
if (noError === void 0) noError = false;
if (this.regexp_eatQuantifierPrefix(state, noError)) {
state.eat(63);
return true;
}
return false;
};
pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
return state.eat(42) || state.eat(43) || state.eat(63) || this.regexp_eatBracedQuantifier(state, noError);
};
pp$1.regexp_eatBracedQuantifier = function(state, noError) {
var start = state.pos;
if (state.eat(123)) {
var min = 0, max = -1;
if (this.regexp_eatDecimalDigits(state)) {
min = state.lastIntValue;
if (state.eat(44) && this.regexp_eatDecimalDigits(state)) max = state.lastIntValue;
if (state.eat(125)) {
if (max !== -1 && max < min && !noError) state.raise("numbers out of order in {} quantifier");
return true;
}
}
if (state.switchU && !noError) state.raise("Incomplete quantifier");
state.pos = start;
}
return false;
};
pp$1.regexp_eatAtom = function(state) {
return this.regexp_eatPatternCharacters(state) || state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
};
pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(92)) {
if (this.regexp_eatAtomEscape(state)) return true;
state.pos = start;
}
return false;
};
pp$1.regexp_eatUncapturingGroup = function(state) {
var start = state.pos;
if (state.eat(40)) {
if (state.eat(63)) {
if (this.options.ecmaVersion >= 16) {
var addModifiers = this.regexp_eatModifiers(state);
var hasHyphen = state.eat(45);
if (addModifiers || hasHyphen) {
for (var i$1 = 0; i$1 < addModifiers.length; i$1++) {
var modifier = addModifiers.charAt(i$1);
if (addModifiers.indexOf(modifier, i$1 + 1) > -1) state.raise("Duplicate regular expression modifiers");
}
if (hasHyphen) {
var removeModifiers = this.regexp_eatModifiers(state);
if (!addModifiers && !removeModifiers && state.current() === 58) state.raise("Invalid regular expression modifiers");
for (var i$1$1 = 0; i$1$1 < removeModifiers.length; i$1$1++) {
var modifier$1 = removeModifiers.charAt(i$1$1);
if (removeModifiers.indexOf(modifier$1, i$1$1 + 1) > -1 || addModifiers.indexOf(modifier$1) > -1) state.raise("Duplicate regular expression modifiers");
}
}
}
}
if (state.eat(58)) {
this.regexp_disjunction(state);
if (state.eat(41)) return true;
state.raise("Unterminated group");
}
}
state.pos = start;
}
return false;
};
pp$1.regexp_eatCapturingGroup = function(state) {
if (state.eat(40)) {
if (this.options.ecmaVersion >= 9) this.regexp_groupSpecifier(state);
else if (state.current() === 63) state.raise("Invalid group");
this.regexp_disjunction(state);
if (state.eat(41)) {
state.numCapturingParens += 1;
return true;
}
state.raise("Unterminated group");
}
return false;
};
pp$1.regexp_eatModifiers = function(state) {
var modifiers = "";
var ch = 0;
while ((ch = state.current()) !== -1 && isRegularExpressionModifier(ch)) {
modifiers += codePointToString(ch);
state.advance();
}
return modifiers;
};
function isRegularExpressionModifier(ch) {
return ch === 105 || ch === 109 || ch === 115;
}
pp$1.regexp_eatExtendedAtom = function(state) {
return state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
};
pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
if (this.regexp_eatBracedQuantifier(state, true)) state.raise("Nothing to repeat");
return false;
};
pp$1.regexp_eatSyntaxCharacter = function(state) {
var ch = state.current();
if (isSyntaxCharacter(ch)) {
state.lastIntValue = ch;
state.advance();
return true;
}
return false;
};
function isSyntaxCharacter(ch) {
return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatPatternCharacters = function(state) {
var start = state.pos;
var ch = 0;
while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) state.advance();
return state.pos !== start;
};
pp$1.regexp_eatExtendedPatternCharacter = function(state) {
var ch = state.current();
if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
state.advance();
return true;
}
return false;
};
pp$1.regexp_groupSpecifier = function(state) {
if (state.eat(63)) {
if (!this.regexp_eatGroupName(state)) state.raise("Invalid group");
var trackDisjunction = this.options.ecmaVersion >= 16;
var known = state.groupNames[state.lastStringValue];
if (known) if (trackDisjunction) {
for (var i$1 = 0, list$1 = known; i$1 < list$1.length; i$1 += 1) if (!list$1[i$1].separatedFrom(state.branchID)) state.raise("Duplicate capture group name");
} else state.raise("Duplicate capture group name");
if (trackDisjunction) (known || (state.groupNames[state.lastStringValue] = [])).push(state.branchID);
else state.groupNames[state.lastStringValue] = true;
}
};
pp$1.regexp_eatGroupName = function(state) {
state.lastStringValue = "";
if (state.eat(60)) {
if (this.regexp_eatRegExpIdentifierName(state) && state.eat(62)) return true;
state.raise("Invalid capture group name");
}
return false;
};
pp$1.regexp_eatRegExpIdentifierName = function(state) {
state.lastStringValue = "";
if (this.regexp_eatRegExpIdentifierStart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) state.lastStringValue += codePointToString(state.lastIntValue);
return true;
}
return false;
};
pp$1.regexp_eatRegExpIdentifierStart = function(state) {
var start = state.pos;
var forceU = this.options.ecmaVersion >= 11;
var ch = state.current(forceU);
state.advance(forceU);
if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) ch = state.lastIntValue;
if (isRegExpIdentifierStart(ch)) {
state.lastIntValue = ch;
return true;
}
state.pos = start;
return false;
};
function isRegExpIdentifierStart(ch) {
return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$1.regexp_eatRegExpIdentifierPart = function(state) {
var start = state.pos;
var forceU = this.options.ecmaVersion >= 11;
var ch = state.current(forceU);
state.advance(forceU);
if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) ch = state.lastIntValue;
if (isRegExpIdentifierPart(ch)) {
state.lastIntValue = ch;
return true;
}
state.pos = start;
return false;
};
function isRegExpIdentifierPart(ch) {
return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$1.regexp_eatAtomEscape = function(state) {
if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) return true;
if (state.switchU) {
if (state.current() === 99) state.raise("Invalid unicode escape");
state.raise("Invalid escape");
}
return false;
};
pp$1.regexp_eatBackReference = function(state) {
var start = state.pos;
if (this.regexp_eatDecimalEscape(state)) {
var n$1 = state.lastIntValue;
if (state.switchU) {
if (n$1 > state.maxBackReference) state.maxBackReference = n$1;
return true;
}
if (n$1 <= state.numCapturingParens) return true;
state.pos = start;
}
return false;
};
pp$1.regexp_eatKGroupName = function(state) {
if (state.eat(107)) {
if (this.regexp_eatGroupName(state)) {
state.backReferenceNames.push(state.lastStringValue);
return true;
}
state.raise("Invalid named reference");
}
return false;
};
pp$1.regexp_eatCharacterEscape = function(state) {
return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
};
pp$1.regexp_eatCControlLetter = function(state) {
var start = state.pos;
if (state.eat(99)) {
if (this.regexp_eatControlLetter(state)) return true;
state.pos = start;
}
return false;
};
pp$1.regexp_eatZero = function(state) {
if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {
state.lastIntValue = 0;
state.advance();
return true;
}
return false;
};
pp$1.regexp_eatControlEscape = function(state) {
var ch = state.current();
if (ch === 116) {
state.lastIntValue = 9;
state.advance();
return true;
}
if (ch === 110) {
state.lastIntValue = 10;
state.advance();
return true;
}
if (ch === 118) {
state.lastIntValue = 11;
state.advance();
return true;
}
if (ch === 102) {
state.lastIntValue = 12;
state.advance();
return true;
}
if (ch === 114) {
state.lastIntValue = 13;
state.advance();
return true;
}
return false;
};
pp$1.regexp_eatControlLetter = function(state) {
var ch = state.current();
if (isControlLetter(ch)) {
state.lastIntValue = ch % 32;
state.advance();
return true;
}
return false;
};
function isControlLetter(ch) {
return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
if (forceU === void 0) forceU = false;
var start = state.pos;
var switchU = forceU || state.switchU;
if (state.eat(117)) {
if (this.regexp_eatFixedHexDigits(state, 4)) {
var lead = state.lastIntValue;
if (switchU && lead >= 55296 && lead <= 56319) {
var leadSurrogateEnd = state.pos;
if (state.eat(92) && state.eat(117) && this.regexp_eatFixedHexDigits(state, 4)) {
var trail = state.lastIntValue;
if (trail >= 56320 && trail <= 57343) {
state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
return true;
}
}
state.pos = leadSurrogateEnd;
state.lastIntValue = lead;
}
return true;
}
if (switchU && state.eat(123) && this.regexp_eatHexDigits(state) && state.eat(125) && isValidUnicode(state.lastIntValue)) return true;
if (switchU) state.raise("Invalid unicode escape");
state.pos = start;
}
return false;
};
function isValidUnicode(ch) {
return ch >= 0 && ch <= 1114111;
}
pp$1.regexp_eatIdentityEscape = function(state) {
if (state.switchU) {
if (this.regexp_eatSyntaxCharacter(state)) return true;
if (state.eat(47)) {
state.lastIntValue = 47;
return true;
}
return false;
}
var ch = state.current();
if (ch !== 99 && (!state.switchN || ch !== 107)) {
state.lastIntValue = ch;
state.advance();
return true;
}
return false;
};
pp$1.regexp_eatDecimalEscape = function(state) {
state.lastIntValue = 0;
var ch = state.current();
if (ch >= 49 && ch <= 57) {
do {
state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
state.advance();
} while ((ch = state.current()) >= 48 && ch <= 57);
return true;
}
return false;
};
var CharSetNone = 0;
var CharSetOk = 1;
var CharSetString = 2;
pp$1.regexp_eatCharacterClassEscape = function(state) {
var ch = state.current();
if (isCharacterClassEscape(ch)) {
state.lastIntValue = -1;
state.advance();
return CharSetOk;
}
var negate = false;
if (state.switchU && this.options.ecmaVersion >= 9 && ((negate = ch === 80) || ch === 112)) {
state.lastIntValue = -1;
state.advance();
var result;
if (state.eat(123) && (result = this.regexp_eatUnicodePropertyValueExpression(state)) && state.eat(125)) {
if (negate && result === CharSetString) state.raise("Invalid property name");
return result;
}
state.raise("Invalid property name");
}
return CharSetNone;
};
function isCharacterClassEscape(ch) {
return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
var start = state.pos;
if (this.regexp_eatUnicodePropertyName(state) && state.eat(61)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return CharSetOk;
}
}
state.pos = start;
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
}
return CharSetNone;
};
pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
if (!hasOwn(state.unicodeProperties.nonBinary, name)) state.raise("Invalid property name");
if (!state.unicodeProperties.nonBinary[name].test(value)) state.raise("Invalid property value");
};
pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
if (state.unicodeProperties.binary.test(nameOrValue)) return CharSetOk;
if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) return CharSetString;
state.raise("Invalid property name");
};
pp$1.regexp_eatUnicodePropertyName = function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyNameCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
return isControlLetter(ch) || ch === 95;
}
pp$1.regexp_eatUnicodePropertyValue = function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyValueCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
return this.regexp_eatUnicodePropertyValue(state);
};
pp$1.regexp_eatCharacterClass = function(state) {
if (state.eat(91)) {
var negate = state.eat(94);
var result = this.regexp_classContents(state);
if (!state.eat(93)) state.raise("Unterminated character class");
if (negate && result === CharSetString) state.raise("Negated character class may contain strings");
return true;
}
return false;
};
pp$1.regexp_classContents = function(state) {
if (state.current() === 93) return CharSetOk;
if (state.switchV) return this.regexp_classSetExpression(state);
this.regexp_nonEmptyClassRanges(state);
return CharSetOk;
};
pp$1.regexp_nonEmptyClassRanges = function(state) {
while (this.regexp_eatClassAtom(state)) {
var left = state.lastIntValue;
if (state.eat(45) && this.regexp_eatClassAtom(state)) {
var right = state.lastIntValue;
if (state.switchU && (left === -1 || right === -1)) state.raise("Invalid character class");
if (left !== -1 && right !== -1 && left > right) state.raise("Range out of order in character class");
}
}
};
pp$1.regexp_eatClassAtom = function(state) {
var start = state.pos;
if (state.eat(92)) {
if (this.regexp_eatClassEscape(state)) return true;
if (state.switchU) {
var ch$1 = state.current();
if (ch$1 === 99 || isOctalDigit(ch$1)) state.raise("Invalid class escape");
state.raise("Invalid escape");
}
state.pos = start;
}
var ch = state.current();
if (ch !== 93) {
state.lastIntValue = ch;
state.advance();
return true;
}
return false;
};
pp$1.regexp_eatClassEscape = function(state) {
var start = state.pos;
if (state.eat(98)) {
state.lastIntValue = 8;
return true;
}
if (state.switchU && state.eat(45)) {
state.lastIntValue = 45;
return true;
}
if (!state.switchU && state.eat(99)) {
if (this.regexp_eatClassControlLetter(state)) return true;
state.pos = start;
}
return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
};
pp$1.regexp_classSetExpression = function(state) {
var result = CharSetOk, subResult;
if (this.regexp_eatClassSetRange(state));
else if (subResult = this.regexp_eatClassSetOperand(state)) {
if (subResult === CharSetString) result = CharSetString;
var start = state.pos;
while (state.eatChars([38, 38])) {
if (state.current() !== 38 && (subResult = this.regexp_eatClassSetOperand(state))) {
if (subResult !== CharSetString) result = CharSetOk;
continue;
}
state.raise("Invalid character in character class");
}
if (start !== state.pos) return result;
while (state.eatChars([45, 45])) {
if (this.regexp_eatClassSetOperand(state)) continue;
state.raise("Invalid character in character class");
}
if (start !== state.pos) return result;
} else state.raise("Invalid character in character class");
for (;;) {
if (this.regexp_eatClassSetRange(state)) continue;
subResult = this.regexp_eatClassSetOperand(state);
if (!subResult) return result;
if (subResult === CharSetString) result = CharSetString;
}
};
pp$1.regexp_eatClassSetRange = function(state) {
var start = state.pos;
if (this.regexp_eatClassSetCharacter(state)) {
var left = state.lastIntValue;
if (state.eat(45) && this.regexp_eatClassSetCharacter(state)) {
var right = state.lastIntValue;
if (left !== -1 && right !== -1 && left > right) state.raise("Range out of order in character class");
return true;
}
state.pos = start;
}
return false;
};
pp$1.regexp_eatClassSetOperand = function(state) {
if (this.regexp_eatClassSetCharacter(state)) return CharSetOk;
return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state);
};
pp$1.regexp_eatNestedClass = function(state) {
var start = state.pos;
if (state.eat(91)) {
var negate = state.eat(94);
var result = this.regexp_classContents(state);
if (state.eat(93)) {
if (negate && result === CharSetString) state.raise("Negated character class may contain strings");
return result;
}
state.pos = start;
}
if (state.eat(92)) {
var result$1 = this.regexp_eatCharacterClassEscape(state);
if (result$1) return result$1;
state.pos = start;
}
return null;
};
pp$1.regexp_eatClassStringDisjunction = function(state) {
var start = state.pos;
if (state.eatChars([92, 113])) {
if (state.eat(123)) {
var result = this.regexp_classStringDisjunctionContents(state);
if (state.eat(125)) return result;
} else state.raise("Invalid escape");
state.pos = start;
}
return null;
};
pp$1.regexp_classStringDisjunctionContents = function(state) {
var result = this.regexp_classString(state);
while (state.eat(124)) if (this.regexp_classString(state) === CharSetString) result = CharSetString;
return result;
};
pp$1.regexp_classString = function(state) {
var count = 0;
while (this.regexp_eatClassSetCharacter(state)) count++;
return count === 1 ? CharSetOk : CharSetString;
};
pp$1.regexp_eatClassSetCharacter = function(state) {
var start = state.pos;
if (state.eat(92)) {
if (this.regexp_eatCharacterEscape(state) || this.regexp_eatClassSetReservedPunctuator(state)) return true;
if (state.eat(98)) {
state.lastIntValue = 8;
return true;
}
state.pos = start;
return false;
}
var ch = state.current();
if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) return false;
if (isClassSetSyntaxCharacter(ch)) return false;
state.advance();
state.lastIntValue = ch;
return true;
};
function isClassSetReservedDoublePunctuatorCharacter(ch) {
return ch === 33 || ch >= 35 && ch <= 38 || ch >= 42 && ch <= 44 || ch === 46 || ch >= 58 && ch <= 64 || ch === 94 || ch === 96 || ch === 126;
}
function isClassSetSyntaxCharacter(ch) {
return ch === 40 || ch === 41 || ch === 45 || ch === 47 || ch >= 91 && ch <= 93 || ch >= 123 && ch <= 125;
}
pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
var ch = state.current();
if (isClassSetReservedPunctuator(ch)) {
state.lastIntValue = ch;
state.advance();
return true;
}
return false;
};
function isClassSetReservedPunctuator(ch) {
return ch === 33 || ch === 35 || ch === 37 || ch === 38 || ch === 44 || ch === 45 || ch >= 58 && ch <= 62 || ch === 64 || ch === 96 || ch === 126;
}
pp$1.regexp_eatClassControlLetter = function(state) {
var ch = state.current();
if (isDecimalDigit(ch) || ch === 95) {
state.lastIntValue = ch % 32;
state.advance();
return true;
}
return false;
};
pp$1.regexp_eatHexEscapeSequence = function(state) {
var start = state.pos;
if (state.eat(120)) {
if (this.regexp_eatFixedHexDigits(state, 2)) return true;
if (state.switchU) state.raise("Invalid escape");
state.pos = start;
}
return false;
};
pp$1.regexp_eatDecimalDigits = function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isDecimalDigit(ch = state.current())) {
state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
state.advance();
}
return state.pos !== start;
};
function isDecimalDigit(ch) {
return ch >= 48 && ch <= 57;
}
pp$1.regexp_eatHexDigits = function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isHexDigit(ch = state.current())) {
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return state.pos !== start;
};
function isHexDigit(ch) {
return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt(ch) {
if (ch >= 65 && ch <= 70) return 10 + (ch - 65);
if (ch >= 97 && ch <= 102) return 10 + (ch - 97);
return ch - 48;
}
pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
if (this.regexp_eatOctalDigit(state)) {
var n1 = state.lastIntValue;
if (this.regexp_eatOctalDigit(state)) {
var n2 = state.lastIntValue;
if (n1 <= 3 && this.regexp_eatOctalDigit(state)) state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
else state.lastIntValue = n1 * 8 + n2;
} else state.lastIntValue = n1;
return true;
}
return false;
};
pp$1.regexp_eatOctalDigit = function(state) {
var ch = state.current();
if (isOctalDigit(ch)) {
state.lastIntValue = ch - 48;
state.advance();
return true;
}
state.lastIntValue = 0;
return false;
};
function isOctalDigit(ch) {
return ch >= 48 && ch <= 55;
}
pp$1.regexp_eatFixedHexDigits = function(state, length) {
var start = state.pos;
state.lastIntValue = 0;
for (var i$1 = 0; i$1 < length; ++i$1) {
var ch = state.current();
if (!isHexDigit(ch)) {
state.pos = start;
return false;
}
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return true;
};
var Token = function Token$1(p$1) {
this.type = p$1.type;
this.value = p$1.value;
this.start = p$1.start;
this.end = p$1.end;
if (p$1.options.locations) this.loc = new SourceLocation(p$1, p$1.startLoc, p$1.endLoc);
if (p$1.options.ranges) this.range = [p$1.start, p$1.end];
};
var pp = Parser.prototype;
pp.next = function(ignoreEscapeSequenceInKeyword) {
if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
if (this.options.onToken) this.options.onToken(new Token(this));
this.lastTokEnd = this.end;
this.lastTokStart = this.start;
this.lastTokEndLoc = this.endLoc;
this.lastTokStartLoc = this.startLoc;
this.nextToken();
};
pp.getToken = function() {
this.next();
return new Token(this);
};
if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function() {
var this$1$1 = this;
return { next: function() {
var token = this$1$1.getToken();
return {
done: token.type === types$1$1.eof,
value: token
};
} };
};
pp.nextToken = function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) this.skipSpace();
this.start = this.pos;
if (this.options.locations) this.startLoc = this.curPosition();
if (this.pos >= this.input.length) return this.finishToken(types$1$1.eof);
if (curContext.override) return curContext.override(this);
else this.readToken(this.fullCharCodeAtPos());
};
pp.readToken = function(code) {
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) return this.readWord();
return this.getTokenFromCode(code);
};
pp.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 55295 || code >= 56320) return code;
var next = this.input.charCodeAt(this.pos + 1);
return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888;
};
pp.skipBlockComment = function() {
var startLoc = this.options.onComment && this.curPosition();
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
this.pos = end + 2;
if (this.options.locations) for (var nextBreak = void 0, pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
++this.curLine;
pos = this.lineStart = nextBreak;
}
if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
};
pp.skipLineComment = function(startSkip) {
var start = this.pos;
var startLoc = this.options.onComment && this.curPosition();
var ch = this.input.charCodeAt(this.pos += startSkip);
while (this.pos < this.input.length && !isNewLine(ch)) ch = this.input.charCodeAt(++this.pos);
if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
};
pp.skipSpace = function() {
loop: while (this.pos < this.input.length) {
var ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 32:
case 160:
++this.pos;
break;
case 13: if (this.input.charCodeAt(this.pos + 1) === 10) ++this.pos;
case 10:
case 8232:
case 8233:
++this.pos;
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
break;
case 47:
switch (this.input.charCodeAt(this.pos + 1)) {
case 42:
this.skipBlockComment();
break;
case 47:
this.skipLineComment(2);
break;
default: break loop;
}
break;
default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) ++this.pos;
else break loop;
}
}
};
pp.finishToken = function(type, val) {
this.end = this.pos;
if (this.options.locations) this.endLoc = this.curPosition();
var prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
};
pp.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1);
if (next >= 48 && next <= 57) return this.readNumber(true);
var next2 = this.input.charCodeAt(this.pos + 2);
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
this.pos += 3;
return this.finishToken(types$1$1.ellipsis);
} else {
++this.pos;
return this.finishToken(types$1$1.dot);
}
};
pp.readToken_slash = function() {
var next = this.input.charCodeAt(this.pos + 1);
if (this.exprAllowed) {
++this.pos;
return this.readRegexp();
}
if (next === 61) return this.finishOp(types$1$1.assign, 2);
return this.finishOp(types$1$1.slash, 1);
};
pp.readToken_mult_modulo_exp = function(code) {
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
var tokentype = code === 42 ? types$1$1.star : types$1$1.modulo;
if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
++size;
tokentype = types$1$1.starstar;
next = this.input.charCodeAt(this.pos + 2);
}
if (next === 61) return this.finishOp(types$1$1.assign, size + 1);
return this.finishOp(tokentype, size);
};
pp.readToken_pipe_amp = function(code) {
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (this.options.ecmaVersion >= 12) {
if (this.input.charCodeAt(this.pos + 2) === 61) return this.finishOp(types$1$1.assign, 3);
}
return this.finishOp(code === 124 ? types$1$1.logicalOR : types$1$1.logicalAND, 2);
}
if (next === 61) return this.finishOp(types$1$1.assign, 2);
return this.finishOp(code === 124 ? types$1$1.bitwiseOR : types$1$1.bitwiseAND, 1);
};
pp.readToken_caret = function() {
if (this.input.charCodeAt(this.pos + 1) === 61) return this.finishOp(types$1$1.assign, 2);
return this.finishOp(types$1$1.bitwiseXOR, 1);
};
pp.readToken_plus_min = function(code) {
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
this.skipLineComment(3);
this.skipSpace();
return this.nextToken();
}
return this.finishOp(types$1$1.incDec, 2);
}
if (next === 61) return this.finishOp(types$1$1.assign, 2);
return this.finishOp(types$1$1.plusMin, 1);
};
pp.readToken_lt_gt = function(code) {
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(types$1$1.assign, size + 1);
return this.finishOp(types$1$1.bitShift, size);
}
if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
this.skipLineComment(4);
this.skipSpace();
return this.nextToken();
}
if (next === 61) size = 2;
return this.finishOp(types$1$1.relational, size);
};
pp.readToken_eq_excl = function(code) {
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) return this.finishOp(types$1$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
this.pos += 2;
return this.finishToken(types$1$1.arrow);
}
return this.finishOp(code === 61 ? types$1$1.eq : types$1$1.prefix, 1);
};
pp.readToken_question = function() {
var ecmaVersion$1 = this.options.ecmaVersion;
if (ecmaVersion$1 >= 11) {
var next = this.input.charCodeAt(this.pos + 1);
if (next === 46) {
var next2 = this.input.charCodeAt(this.pos + 2);
if (next2 < 48 || next2 > 57) return this.finishOp(types$1$1.questionDot, 2);
}
if (next === 63) {
if (ecmaVersion$1 >= 12) {
if (this.input.charCodeAt(this.pos + 2) === 61) return this.finishOp(types$1$1.assign, 3);
}
return this.finishOp(types$1$1.coalesce, 2);
}
}
return this.finishOp(types$1$1.question, 1);
};
pp.readToken_numberSign = function() {
var ecmaVersion$1 = this.options.ecmaVersion;
var code = 35;
if (ecmaVersion$1 >= 13) {
++this.pos;
code = this.fullCharCodeAtPos();
if (isIdentifierStart(code, true) || code === 92) return this.finishToken(types$1$1.privateId, this.readWord1());
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.getTokenFromCode = function(code) {
switch (code) {
case 46: return this.readToken_dot();
case 40:
++this.pos;
return this.finishToken(types$1$1.parenL);
case 41:
++this.pos;
return this.finishToken(types$1$1.parenR);
case 59:
++this.pos;
return this.finishToken(types$1$1.semi);
case 44:
++this.pos;
return this.finishToken(types$1$1.comma);
case 91:
++this.pos;
return this.finishToken(types$1$1.bracketL);
case 93:
++this.pos;
return this.finishToken(types$1$1.bracketR);
case 123:
++this.pos;
return this.finishToken(types$1$1.braceL);
case 125:
++this.pos;
return this.finishToken(types$1$1.braceR);
case 58:
++this.pos;
return this.finishToken(types$1$1.colon);
case 96:
if (this.options.ecmaVersion < 6) break;
++this.pos;
return this.finishToken(types$1$1.backQuote);
case 48:
var next = this.input.charCodeAt(this.pos + 1);
if (next === 120 || next === 88) return this.readRadixNumber(16);
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) return this.readRadixNumber(8);
if (next === 98 || next === 66) return this.readRadixNumber(2);
}
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57: return this.readNumber(false);
case 34:
case 39: return this.readString(code);
case 47: return this.readToken_slash();
case 37:
case 42: return this.readToken_mult_modulo_exp(code);
case 124:
case 38: return this.readToken_pipe_amp(code);
case 94: return this.readToken_caret();
case 43:
case 45: return this.readToken_plus_min(code);
case 60:
case 62: return this.readToken_lt_gt(code);
case 61:
case 33: return this.readToken_eq_excl(code);
case 63: return this.readToken_question();
case 126: return this.finishOp(types$1$1.prefix, 1);
case 35: return this.readToken_numberSign();
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str);
};
pp.readRegexp = function() {
var escaped, inClass, start = this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
var ch = this.input.charAt(this.pos);
if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
if (!escaped) {
if (ch === "[") inClass = true;
else if (ch === "]" && inClass) inClass = false;
else if (ch === "/" && !inClass) break;
escaped = ch === "\\";
} else escaped = false;
++this.pos;
}
var pattern = this.input.slice(start, this.pos);
++this.pos;
var flagsStart = this.pos;
var flags = this.readWord1();
if (this.containsEsc) this.unexpected(flagsStart);
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
var value = null;
try {
value = new RegExp(pattern, flags);
} catch (e) {}
return this.finishToken(types$1$1.regexp, {
pattern,
flags,
value
});
};
pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
var start = this.pos, total = 0, lastCode = 0;
for (var i$1 = 0, e = len == null ? Infinity : len; i$1 < e; ++i$1, ++this.pos) {
var code = this.input.charCodeAt(this.pos), val = void 0;
if (allowSeparators && code === 95) {
if (isLegacyOctalNumericLiteral) this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
if (lastCode === 95) this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
if (i$1 === 0) this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
lastCode = code;
continue;
}
if (code >= 97) val = code - 97 + 10;
else if (code >= 65) val = code - 65 + 10;
else if (code >= 48 && code <= 57) val = code - 48;
else val = Infinity;
if (val >= radix) break;
lastCode = code;
total = total * radix + val;
}
if (allowSeparators && lastCode === 95) this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
if (this.pos === start || len != null && this.pos - start !== len) return null;
return total;
};
function stringToNumber(str, isLegacyOctalNumericLiteral) {
if (isLegacyOctalNumericLiteral) return parseInt(str, 8);
return parseFloat(str.replace(/_/g, ""));
}
function stringToBigInt(str) {
if (typeof BigInt !== "function") return null;
return BigInt(str.replace(/_/g, ""));
}
pp.readRadixNumber = function(radix) {
var start = this.pos;
this.pos += 2;
var val = this.readInt(radix);
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
val = stringToBigInt(this.input.slice(start, this.pos));
++this.pos;
} else if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
return this.finishToken(types$1$1.num, val);
};
pp.readNumber = function(startsWithDot) {
var start = this.pos;
if (!startsWithDot && this.readInt(10, void 0, true) === null) this.raise(start, "Invalid number");
var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
if (octal && this.strict) this.raise(start, "Invalid number");
var next = this.input.charCodeAt(this.pos);
if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
var val$1 = stringToBigInt(this.input.slice(start, this.pos));
++this.pos;
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
return this.finishToken(types$1$1.num, val$1);
}
if (octal && /[89]/.test(this.input.slice(start, this.pos))) octal = false;
if (next === 46 && !octal) {
++this.pos;
this.readInt(10);
next = this.input.charCodeAt(this.pos);
}
if ((next === 69 || next === 101) && !octal) {
next = this.input.charCodeAt(++this.pos);
if (next === 43 || next === 45) ++this.pos;
if (this.readInt(10) === null) this.raise(start, "Invalid number");
}
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
var val = stringToNumber(this.input.slice(start, this.pos), octal);
return this.finishToken(types$1$1.num, val);
};
pp.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected();
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 1114111) this.invalidStringToken(codePos, "Code point out of bounds");
} else code = this.readHexChar(4);
return code;
};
pp.readString = function(quote) {
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) break;
if (ch === 92) {
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(false);
chunkStart = this.pos;
} else if (ch === 8232 || ch === 8233) {
if (this.options.ecmaVersion < 10) this.raise(this.start, "Unterminated string constant");
++this.pos;
if (this.options.locations) {
this.curLine++;
this.lineStart = this.pos;
}
} else {
if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(types$1$1.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp.tryReadTemplateToken = function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) this.readInvalidTemplateToken();
else throw err;
}
this.inTemplateElement = false;
};
pp.invalidStringToken = function(position, message) {
if (this.inTemplateElement && this.options.ecmaVersion >= 9) throw INVALID_TEMPLATE_ESCAPE_ERROR;
else this.raise(position, message);
};
pp.readTmplToken = function() {
var out = "", chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
var ch = this.input.charCodeAt(this.pos);
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
if (this.pos === this.start && (this.type === types$1$1.template || this.type === types$1$1.invalidTemplate)) if (ch === 36) {
this.pos += 2;
return this.finishToken(types$1$1.dollarBraceL);
} else {
++this.pos;
return this.finishToken(types$1$1.backQuote);
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(types$1$1.template, out);
}
if (ch === 92) {
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(true);
chunkStart = this.pos;
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
++this.pos;
switch (ch) {
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
out += "\n";
break;
default:
out += String.fromCharCode(ch);
break;
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else ++this.pos;
}
};
pp.readInvalidTemplateToken = function() {
for (; this.pos < this.input.length; this.pos++) switch (this.input[this.pos]) {
case "\\":
++this.pos;
break;
case "$": if (this.input[this.pos + 1] !== "{") break;
case "`": return this.finishToken(types$1$1.invalidTemplate, this.input.slice(this.start, this.pos));
case "\r": if (this.input[this.pos + 1] === "\n") ++this.pos;
case "\n":
case "\u2028":
case "\u2029":
++this.curLine;
this.lineStart = this.pos + 1;
break;
}
this.raise(this.start, "Unterminated template");
};
pp.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos);
++this.pos;
switch (ch) {
case 110: return "\n";
case 114: return "\r";
case 120: return String.fromCharCode(this.readHexChar(2));
case 117: return codePointToString(this.readCodePoint());
case 116: return " ";
case 98: return "\b";
case 118: return "\v";
case 102: return "\f";
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
case 10:
if (this.options.locations) {
this.lineStart = this.pos;
++this.curLine;
}
return "";
case 56:
case 57:
if (this.strict) this.invalidStringToken(this.pos - 1, "Invalid escape sequence");
if (inTemplate) {
var codePos = this.pos - 1;
this.invalidStringToken(codePos, "Invalid escape sequence in template string");
}
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
var octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode");
return String.fromCharCode(octal);
}
if (isNewLine(ch)) {
if (this.options.locations) {
this.lineStart = this.pos;
++this.curLine;
}
return "";
}
return String.fromCharCode(ch);
}
};
pp.readHexChar = function(len) {
var codePos = this.pos;
var n$1 = this.readInt(16, len);
if (n$1 === null) this.invalidStringToken(codePos, "Bad character escape sequence");
return n$1;
};
pp.readWord1 = function() {
this.containsEsc = false;
var word = "", first = true, chunkStart = this.pos;
var astral = this.options.ecmaVersion >= 6;
while (this.pos < this.input.length) {
var ch = this.fullCharCodeAtPos();
if (isIdentifierChar(ch, astral)) this.pos += ch <= 65535 ? 1 : 2;
else if (ch === 92) {
this.containsEsc = true;
word += this.input.slice(chunkStart, this.pos);
var escStart = this.pos;
if (this.input.charCodeAt(++this.pos) !== 117) this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
++this.pos;
var esc = this.readCodePoint();
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.invalidStringToken(escStart, "Invalid Unicode escape");
word += codePointToString(esc);
chunkStart = this.pos;
} else break;
first = false;
}
return word + this.input.slice(chunkStart, this.pos);
};
pp.readWord = function() {
var word = this.readWord1();
var type = types$1$1.name;
if (this.keywords.test(word)) type = keywords[word];
return this.finishToken(type, word);
};
var version$1 = "8.14.0";
Parser.acorn = {
Parser,
version: version$1,
defaultOptions,
Position,
SourceLocation,
getLineInfo,
Node,
TokenType,
tokTypes: types$1$1,
keywordTypes: keywords,
TokContext,
tokContexts: types$2,
isIdentifierChar,
isIdentifierStart,
Token,
isNewLine,
lineBreak,
lineBreakG,
nonASCIIwhitespace
};
//#endregion
//#region ../../node_modules/.pnpm/ufo@1.5.4/node_modules/ufo/dist/index.mjs
const r = String.fromCharCode;
const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
const JOIN_LEADING_SLASH_RE = /^\.?\//;
function hasTrailingSlash(input = "", respectQueryAndFragment) {
if (!respectQueryAndFragment) return input.endsWith("/");
return TRAILING_SLASH_RE.test(input);
}
function withTrailingSlash$1(input = "", respectQueryAndFragment) {
if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
if (hasTrailingSlash(input, true)) return input || "/";
let path$2 = input;
let fragment = "";
const fragmentIndex = input.indexOf("#");
if (fragmentIndex >= 0) {
path$2 = input.slice(0, fragmentIndex);
fragment = input.slice(fragmentIndex);
if (!path$2) return fragment;
}
const [s0, ...s] = path$2.split("?");
return s0 + "/" + (s.length > 0 ? `?${s.join("?")}` : "") + fragment;
}
function isNonEmptyURL(url) {
return url && url !== "/";
}
function joinURL(base, ...input) {
let url = base || "";
for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
url = withTrailingSlash$1(url) + _segment;
} else url = segment;
return url;
}
const protocolRelative = Symbol.for("ufo:protocolRelative");
//#endregion
//#region ../../node_modules/.pnpm/pathe@2.0.1/node_modules/pathe/dist/shared/pathe.BLwDEnA5.mjs
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
const isAbsolute$1 = function(p$1) {
return _IS_ABSOLUTE_RE.test(p$1);
};
//#endregion
//#region ../../node_modules/.pnpm/mlly@1.7.4/node_modules/mlly/dist/index.mjs
const BUILTIN_MODULES = new Set(builtinModules);
function normalizeSlash(path$2) {
return path$2.replace(/\\/g, "/");
}
/**
* @typedef ErrnoExceptionFields
* @property {number | undefined} [errnode]
* @property {string | undefined} [code]
* @property {string | undefined} [path]
* @property {string | undefined} [syscall]
* @property {string | undefined} [url]
*
* @typedef {Error & ErrnoExceptionFields} ErrnoException
*/
const own$1 = {}.hasOwnProperty;
const classRegExp = /^([A-Z][a-z\d]*)+$/;
const kTypes = new Set([
"string",
"function",
"number",
"object",
"Function",
"Object",
"boolean",
"bigint",
"symbol"
]);
const codes = {};
/**
* Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
* We cannot use Intl.ListFormat because it's not available in
* --without-intl builds.
*
* @param {Array<string>} array
* An array of strings.
* @param {string} [type]
* The list type to be inserted before the last element.
* @returns {string}
*/
function formatList(array, type = "and") {
return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
}
/** @type {Map<string, MessageFunction | string>} */
const messages = /* @__PURE__ */ new Map();
const nodeInternalPrefix = "__node_internal_";
/** @type {number} */
let userStackTraceLimit;
codes.ERR_INVALID_ARG_TYPE = createError(
"ERR_INVALID_ARG_TYPE",
/**
* @param {string} name
* @param {Array<string> | string} expected
* @param {unknown} actual
*/
(name, expected, actual) => {
assert(typeof name === "string", "'name' must be a string");
if (!Array.isArray(expected)) expected = [expected];
let message = "The ";
if (name.endsWith(" argument")) message += `${name} `;
else {
const type = name.includes(".") ? "property" : "argument";
message += `"${name}" ${type} `;
}
message += "must be ";
/** @type {Array<string>} */
const types$4 = [];
/** @type {Array<string>} */
const instances = [];
/** @type {Array<string>} */
const other = [];
for (const value of expected) {
assert(typeof value === "string", "All expected entries have to be of type string");
if (kTypes.has(value)) types$4.push(value.toLowerCase());
else if (classRegExp.exec(value) === null) {
assert(value !== "object", "The value \"object\" should be written as \"Object\"");
other.push(value);
} else instances.push(value);
}
if (instances.length > 0) {
const pos = types$4.indexOf("object");
if (pos !== -1) {
types$4.slice(pos, 1);
instances.push("Object");
}
}
if (types$4.length > 0) {
message += `${types$4.length > 1 ? "one of type" : "of type"} ${formatList(types$4, "or")}`;
if (instances.length > 0 || other.length > 0) message += " or ";
}
if (instances.length > 0) {
message += `an instance of ${formatList(instances, "or")}`;
if (other.length > 0) message += " or ";
}
if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
else {
if (other[0].toLowerCase() !== other[0]) message += "an ";
message += `${other[0]}`;
}
message += `. Received ${determineSpecificType(actual)}`;
return message;
},
TypeError
);
codes.ERR_INVALID_MODULE_SPECIFIER = createError(
"ERR_INVALID_MODULE_SPECIFIER",
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request$2, reason, base = void 0) => {
return `Invalid module "${request$2}" ${reason}${base ? ` imported from ${base}` : ""}`;
},
TypeError
);
codes.ERR_INVALID_PACKAGE_CONFIG = createError(
"ERR_INVALID_PACKAGE_CONFIG",
/**
* @param {string} path
* @param {string} [base]
* @param {string} [message]
*/
(path$2, base, message) => {
return `Invalid package config ${path$2}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
},
Error
);
codes.ERR_INVALID_PACKAGE_TARGET = createError(
"ERR_INVALID_PACKAGE_TARGET",
/**
* @param {string} packagePath
* @param {string} key
* @param {unknown} target
* @param {boolean} [isImport=false]
* @param {string} [base]
*/
(packagePath, key, target$1, isImport = false, base = void 0) => {
const relatedError = typeof target$1 === "string" && !isImport && target$1.length > 0 && !target$1.startsWith("./");
if (key === ".") {
assert(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target$1)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
}
return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target$1)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`;
},
Error
);
codes.ERR_MODULE_NOT_FOUND = createError(
"ERR_MODULE_NOT_FOUND",
/**
* @param {string} path
* @param {string} base
* @param {boolean} [exactUrl]
*/
(path$2, base, exactUrl = false) => {
return `Cannot find ${exactUrl ? "module" : "package"} '${path$2}' imported from ${base}`;
},
Error
);
codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
/**
* @param {string} specifier
* @param {string} packagePath
* @param {string} base
*/
(specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
},
TypeError
);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
"ERR_PACKAGE_PATH_NOT_EXPORTED",
/**
* @param {string} packagePath
* @param {string} subpath
* @param {string} [base]
*/
(packagePath, subpath, base = void 0) => {
if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
},
Error
);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
"ERR_UNKNOWN_FILE_EXTENSION",
/**
* @param {string} extension
* @param {string} path
*/
(extension, path$2) => {
return `Unknown file extension "${extension}" for ${path$2}`;
},
TypeError
);
codes.ERR_INVALID_ARG_VALUE = createError(
"ERR_INVALID_ARG_VALUE",
/**
* @param {string} name
* @param {unknown} value
* @param {string} [reason='is invalid']
*/
(name, value, reason = "is invalid") => {
let inspected = inspect(value);
if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
},
TypeError
);
/**
* Utility function for registering the error codes. Only used here. Exported
* *only* to allow for testing.
* @param {string} sym
* @param {MessageFunction | string} value
* @param {ErrorConstructor} constructor
* @returns {new (...parameters: Array<any>) => Error}
*/
function createError(sym, value, constructor) {
messages.set(sym, value);
return makeNodeErrorWithCode(constructor, sym);
}
/**
* @param {ErrorConstructor} Base
* @param {string} key
* @returns {ErrorConstructor}
*/
function makeNodeErrorWithCode(Base, key) {
return NodeError;
/**
* @param {Array<unknown>} parameters
*/
function NodeError(...parameters) {
const limit = Error.stackTraceLimit;
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
const error = new Base();
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
const message = getMessage(key, parameters, error);
Object.defineProperties(error, {
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
}
});
captureLargerStackTrace(error);
error.code = key;
return error;
}
}
/**
* @returns {boolean}
*/
function isErrorStackTraceLimitWritable() {
try {
if (v8.startupSnapshot.isBuildingSnapshot()) return false;
} catch {}
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
if (desc === void 0) return Object.isExtensible(Error);
return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
}
/**
* This function removes unnecessary frames from Node.js core errors.
* @template {(...parameters: unknown[]) => unknown} T
* @param {T} wrappedFunction
* @returns {T}
*/
function hideStackFrames(wrappedFunction) {
const hidden = nodeInternalPrefix + wrappedFunction.name;
Object.defineProperty(wrappedFunction, "name", { value: hidden });
return wrappedFunction;
}
const captureLargerStackTrace = hideStackFrames(
/**
* @param {Error} error
* @returns {Error}
*/
function(error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
return error;
}
);
/**
* @param {string} key
* @param {Array<unknown>} parameters
* @param {Error} self
* @returns {string}
*/
function getMessage(key, parameters, self) {
const message = messages.get(key);
assert(message !== void 0, "expected `message` to be found");
if (typeof message === "function") {
assert(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
return Reflect.apply(message, self, parameters);
}
const regex = /%[dfijoOs]/g;
let expectedLength = 0;
while (regex.exec(message) !== null) expectedLength++;
assert(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
if (parameters.length === 0) return message;
parameters.unshift(message);
return Reflect.apply(format, null, parameters);
}
/**
* Determine the specific type of a value for type-mismatch errors.
* @param {unknown} value
* @returns {string}
*/
function determineSpecificType(value) {
if (value === null || value === void 0) return String(value);
if (typeof value === "function" && value.name) return `function ${value.name}`;
if (typeof value === "object") {
if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
return `${inspect(value, { depth: -1 })}`;
}
let inspected = inspect(value, { colors: false });
if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
return `type ${typeof value} (${inspected})`;
}
const hasOwnProperty$1 = {}.hasOwnProperty;
const { ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1 } = codes;
/** @type {Map<string, PackageConfig>} */
const cache = /* @__PURE__ */ new Map();
/**
* @param {string} jsonPath
* @param {{specifier: URL | string, base?: URL}} options
* @returns {PackageConfig}
*/
function read(jsonPath, { base, specifier }) {
const existing = cache.get(jsonPath);
if (existing) return existing;
/** @type {string | undefined} */
let string;
try {
string = fs.readFileSync(path.toNamespacedPath(jsonPath), "utf8");
} catch (error) {
const exception = error;
if (exception.code !== "ENOENT") throw exception;
}
/** @type {PackageConfig} */
const result = {
exists: false,
pjsonPath: jsonPath,
main: void 0,
name: void 0,
type: "none",
exports: void 0,
imports: void 0
};
if (string !== void 0) {
/** @type {Record<string, unknown>} */
let parsed;
try {
parsed = JSON.parse(string);
} catch (error_) {
const cause = error_;
const error = new ERR_INVALID_PACKAGE_CONFIG$1(jsonPath, (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier), cause.message);
error.cause = cause;
throw error;
}
result.exists = true;
if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") result.name = parsed.name;
if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") result.main = parsed.main;
if (hasOwnProperty$1.call(parsed, "exports")) result.exports = parsed.exports;
if (hasOwnProperty$1.call(parsed, "imports")) result.imports = parsed.imports;
if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) result.type = parsed.type;
}
cache.set(jsonPath, result);
return result;
}
/**
* @param {URL | string} resolved
* @returns {PackageConfig}
*/
function getPackageScopeConfig(resolved) {
let packageJSONUrl = new URL("package.json", resolved);
while (true) {
if (packageJSONUrl.pathname.endsWith("node_modules/package.json")) break;
const packageConfig = read(fileURLToPath(packageJSONUrl), { specifier: resolved });
if (packageConfig.exists) return packageConfig;
const lastPackageJSONUrl = packageJSONUrl;
packageJSONUrl = new URL("../package.json", packageJSONUrl);
if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
}
return {
pjsonPath: fileURLToPath(packageJSONUrl),
exists: false,
type: "none"
};
}
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
* @returns {PackageType}
*/
function getPackageType(url) {
return getPackageScopeConfig(url).type;
}
const { ERR_UNKNOWN_FILE_EXTENSION } = codes;
const hasOwnProperty = {}.hasOwnProperty;
/** @type {Record<string, string>} */
const extensionFormatMap = {
__proto__: null,
".cjs": "commonjs",
".js": "module",
".json": "json",
".mjs": "module"
};
/**
* @param {string | null} mime
* @returns {string | null}
*/
function mimeToFormat(mime) {
if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return "module";
if (mime === "application/json") return "json";
return null;
}
/**
* @callback ProtocolHandler
* @param {URL} parsed
* @param {{parentURL: string, source?: Buffer}} context
* @param {boolean} ignoreErrors
* @returns {string | null | void}
*/
/**
* @type {Record<string, ProtocolHandler>}
*/
const protocolHandlers = {
__proto__: null,
"data:": getDataProtocolModuleFormat,
"file:": getFileProtocolModuleFormat,
"http:": getHttpProtocolModuleFormat,
"https:": getHttpProtocolModuleFormat,
"node:"() {
return "builtin";
}
};
/**
* @param {URL} parsed
*/
function getDataProtocolModuleFormat(parsed) {
const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [
null,
null,
null
];
return mimeToFormat(mime);
}
/**
* Returns the file extension from a URL.
*
* Should give similar result to
* `require('node:path').extname(require('node:url').fileURLToPath(url))`
* when used with a `file:` URL.
*
* @param {URL} url
* @returns {string}
*/
function extname$1(url) {
const pathname = url.pathname;
let index = pathname.length;
while (index--) {
const code = pathname.codePointAt(index);
if (code === 47) return "";
if (code === 46) return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
}
return "";
}
/**
* @type {ProtocolHandler}
*/
function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
const value = extname$1(url);
if (value === ".js") {
const packageType = getPackageType(url);
if (packageType !== "none") return packageType;
return "commonjs";
}
if (value === "") {
const packageType = getPackageType(url);
if (packageType === "none" || packageType === "commonjs") return "commonjs";
return "module";
}
const format$2 = extensionFormatMap[value];
if (format$2) return format$2;
if (ignoreErrors) return;
throw new ERR_UNKNOWN_FILE_EXTENSION(value, fileURLToPath(url));
}
function getHttpProtocolModuleFormat() {}
/**
* @param {URL} url
* @param {{parentURL: string}} context
* @returns {string | null}
*/
function defaultGetFormatWithoutErrors(url, context) {
const protocol = url.protocol;
if (!hasOwnProperty.call(protocolHandlers, protocol)) return null;
return protocolHandlers[protocol](url, context, true) || null;
}
const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
const { ERR_NETWORK_IMPORT_DISALLOWED, ERR_INVALID_MODULE_SPECIFIER, ERR_INVALID_PACKAGE_CONFIG, ERR_INVALID_PACKAGE_TARGET, ERR_MODULE_NOT_FOUND, ERR_PACKAGE_IMPORT_NOT_DEFINED, ERR_PACKAGE_PATH_NOT_EXPORTED, ERR_UNSUPPORTED_DIR_IMPORT, ERR_UNSUPPORTED_RESOLVE_REQUEST } = codes;
const own = {}.hasOwnProperty;
const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i;
const deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;
const invalidPackageNameRegEx = /^\.|%|\\/;
const patternRegEx = /\*/g;
const encodedSeparatorRegEx = /%2f|%5c/i;
/** @type {Set<string>} */
const emittedPackageWarnings = /* @__PURE__ */ new Set();
const doubleSlashRegEx = /[/\\]{2}/;
/**
*
* @param {string} target
* @param {string} request
* @param {string} match
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} base
* @param {boolean} isTarget
*/
function emitInvalidSegmentDeprecation(target$1, request$2, match, packageJsonUrl, internal, base, isTarget) {
if (process$1.noDeprecation) return;
const pjsonPath = fileURLToPath(packageJsonUrl);
const double = doubleSlashRegEx.exec(isTarget ? target$1 : request$2) !== null;
process$1.emitWarning(`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target$1}" for module request "${request$2}" ${request$2 === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}.`, "DeprecationWarning", "DEP0166");
}
/**
* @param {URL} url
* @param {URL} packageJsonUrl
* @param {URL} base
* @param {string} [main]
* @returns {void}
*/
function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
if (process$1.noDeprecation) return;
if (defaultGetFormatWithoutErrors(url, { parentURL: base.href }) !== "module") return;
const urlPath = fileURLToPath(url.href);
const packagePath = fileURLToPath(new URL$1(".", packageJsonUrl));
const basePath = fileURLToPath(base);
if (!main) process$1.emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
else if (path.resolve(packagePath, main) !== urlPath) process$1.emitWarning(`Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`, "DeprecationWarning", "DEP0151");
}
/**
* @param {string} path
* @returns {Stats | undefined}
*/
function tryStatSync(path$2) {
try {
return statSync(path$2);
} catch {}
}
/**
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
* 2. TRY(M, M.js, M.json, M.node)
* 3. TRY(M/index.js, M/index.json, M/index.node)
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
* 5. NOT_FOUND
*
* @param {URL} url
* @returns {boolean}
*/
function fileExists(url) {
const stats = statSync(url, { throwIfNoEntry: false });
const isFile = stats ? stats.isFile() : void 0;
return isFile === null || isFile === void 0 ? false : isFile;
}
/**
* @param {URL} packageJsonUrl
* @param {PackageConfig} packageConfig
* @param {URL} base
* @returns {URL}
*/
function legacyMainResolve(packageJsonUrl, packageConfig, base) {
/** @type {URL | undefined} */
let guess;
if (packageConfig.main !== void 0) {
guess = new URL$1(packageConfig.main, packageJsonUrl);
if (fileExists(guess)) return guess;
const tries$1 = [
`./${packageConfig.main}.js`,
`./${packageConfig.main}.json`,
`./${packageConfig.main}.node`,
`./${packageConfig.main}/index.js`,
`./${packageConfig.main}/index.json`,
`./${packageConfig.main}/index.node`
];
let i$2 = -1;
while (++i$2 < tries$1.length) {
guess = new URL$1(tries$1[i$2], packageJsonUrl);
if (fileExists(guess)) break;
guess = void 0;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
}
const tries = [
"./index.js",
"./index.json",
"./index.node"
];
let i$1 = -1;
while (++i$1 < tries.length) {
guess = new URL$1(tries[i$1], packageJsonUrl);
if (fileExists(guess)) break;
guess = void 0;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
throw new ERR_MODULE_NOT_FOUND(fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
}
/**
* @param {URL} resolved
* @param {URL} base
* @param {boolean} [preserveSymlinks]
* @returns {URL}
*/
function finalizeResolution(resolved, base, preserveSymlinks) {
if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, "must not include encoded \"/\" or \"\\\" characters", fileURLToPath(base));
/** @type {string} */
let filePath;
try {
filePath = fileURLToPath(resolved);
} catch (error) {
const cause = error;
Object.defineProperty(cause, "input", { value: String(resolved) });
Object.defineProperty(cause, "module", { value: String(base) });
throw cause;
}
const stats = tryStatSync(filePath.endsWith("/") ? filePath.slice(-1) : filePath);
if (stats && stats.isDirectory()) {
const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base));
error.url = String(resolved);
throw error;
}
if (!stats || !stats.isFile()) {
const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && fileURLToPath(base), true);
error.url = String(resolved);
throw error;
}
{
const real = realpathSync(filePath);
const { search, hash } = resolved;
resolved = pathToFileURL(real + (filePath.endsWith(path.sep) ? "/" : ""));
resolved.search = search;
resolved.hash = hash;
}
return resolved;
}
/**
* @param {string} specifier
* @param {URL | undefined} packageJsonUrl
* @param {URL} base
* @returns {Error}
*/
function importNotDefined(specifier, packageJsonUrl, base) {
return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base));
}
/**
* @param {string} subpath
* @param {URL} packageJsonUrl
* @param {URL} base
* @returns {Error}
*/
function exportsNotFound(subpath, packageJsonUrl, base) {
return new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, base && fileURLToPath(base));
}
/**
* @param {string} request
* @param {string} match
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} [base]
* @returns {never}
*/
function throwInvalidSubpath(request$2, match, packageJsonUrl, internal, base) {
throw new ERR_INVALID_MODULE_SPECIFIER(request$2, `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJsonUrl)}`, base && fileURLToPath(base));
}
/**
* @param {string} subpath
* @param {unknown} target
* @param {URL} packageJsonUrl
* @param {boolean} internal
* @param {URL} [base]
* @returns {Error}
*/
function invalidPackageTarget(subpath, target$1, packageJsonUrl, internal, base) {
target$1 = typeof target$1 === "object" && target$1 !== null ? JSON.stringify(target$1, null, "") : `${target$1}`;
return new ERR_INVALID_PACKAGE_TARGET(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, target$1, internal, base && fileURLToPath(base));
}
/**
* @param {string} target
* @param {string} subpath
* @param {string} match
* @param {URL} packageJsonUrl
* @param {URL} base
* @param {boolean} pattern
* @param {boolean} internal
* @param {boolean} isPathMap
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function resolvePackageTargetString(target$1, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
if (subpath !== "" && !pattern && target$1[target$1.length - 1] !== "/") throw invalidPackageTarget(match, target$1, packageJsonUrl, internal, base);
if (!target$1.startsWith("./")) {
if (internal && !target$1.startsWith("../") && !target$1.startsWith("/")) {
let isURL = false;
try {
new URL$1(target$1);
isURL = true;
} catch {}
if (!isURL) return packageResolve(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target$1, () => subpath) : target$1 + subpath, packageJsonUrl, conditions);
}
throw invalidPackageTarget(match, target$1, packageJsonUrl, internal, base);
}
if (invalidSegmentRegEx.exec(target$1.slice(2)) !== null) if (deprecatedInvalidSegmentRegEx.exec(target$1.slice(2)) === null) {
if (!isPathMap) {
const request$2 = pattern ? match.replace("*", () => subpath) : match + subpath;
emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target$1, () => subpath) : target$1, request$2, match, packageJsonUrl, internal, base, true);
}
} else throw invalidPackageTarget(match, target$1, packageJsonUrl, internal, base);
const resolved = new URL$1(target$1, packageJsonUrl);
const resolvedPath = resolved.pathname;
const packagePath = new URL$1(".", packageJsonUrl).pathname;
if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target$1, packageJsonUrl, internal, base);
if (subpath === "") return resolved;
if (invalidSegmentRegEx.exec(subpath) !== null) {
const request$2 = pattern ? match.replace("*", () => subpath) : match + subpath;
if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
if (!isPathMap) emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target$1, () => subpath) : target$1, request$2, match, packageJsonUrl, internal, base, false);
} else throwInvalidSubpath(request$2, match, packageJsonUrl, internal, base);
}
if (pattern) return new URL$1(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath));
return new URL$1(subpath, resolved);
}
/**
* @param {string} key
* @returns {boolean}
*/
function isArrayIndex(key) {
const keyNumber = Number(key);
if (`${keyNumber}` !== key) return false;
return keyNumber >= 0 && keyNumber < 4294967295;
}
/**
* @param {URL} packageJsonUrl
* @param {unknown} target
* @param {string} subpath
* @param {string} packageSubpath
* @param {URL} base
* @param {boolean} pattern
* @param {boolean} internal
* @param {boolean} isPathMap
* @param {Set<string> | undefined} conditions
* @returns {URL | null}
*/
function resolvePackageTarget(packageJsonUrl, target$1, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
if (typeof target$1 === "string") return resolvePackageTargetString(target$1, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions);
if (Array.isArray(target$1)) {
/** @type {Array<unknown>} */
const targetList = target$1;
if (targetList.length === 0) return null;
/** @type {ErrnoException | null | undefined} */
let lastException;
let i$1 = -1;
while (++i$1 < targetList.length) {
const targetItem = targetList[i$1];
/** @type {URL | null} */
let resolveResult;
try {
resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
} catch (error) {
const exception = error;
lastException = exception;
if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
throw error;
}
if (resolveResult === void 0) continue;
if (resolveResult === null) {
lastException = null;
continue;
}
return resolveResult;
}
if (lastException === void 0 || lastException === null) return null;
throw lastException;
}
if (typeof target$1 === "object" && target$1 !== null) {
const keys = Object.getOwnPropertyNames(target$1);
let i$1 = -1;
while (++i$1 < keys.length) {
const key = keys[i$1];
if (isArrayIndex(key)) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain numeric property keys.");
}
i$1 = -1;
while (++i$1 < keys.length) {
const key = keys[i$1];
if (key === "default" || conditions && conditions.has(key)) {
const conditionalTarget = target$1[key];
const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions);
if (resolveResult === void 0) continue;
return resolveResult;
}
}
return null;
}
if (target$1 === null) return null;
throw invalidPackageTarget(packageSubpath, target$1, packageJsonUrl, internal, base);
}
/**
* @param {unknown} exports
* @param {URL} packageJsonUrl
* @param {URL} base
* @returns {boolean}
*/
function isConditionalExportsMainSugar(exports$1, packageJsonUrl, base) {
if (typeof exports$1 === "string" || Array.isArray(exports$1)) return true;
if (typeof exports$1 !== "object" || exports$1 === null) return false;
const keys = Object.getOwnPropertyNames(exports$1);
let isConditionalSugar = false;
let i$1 = 0;
let keyIndex = -1;
while (++keyIndex < keys.length) {
const key = keys[keyIndex];
const currentIsConditionalSugar = key === "" || key[0] !== ".";
if (i$1++ === 0) isConditionalSugar = currentIsConditionalSugar;
else if (isConditionalSugar !== currentIsConditionalSugar) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), base, "\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.");
}
return isConditionalSugar;
}
/**
* @param {string} match
* @param {URL} pjsonUrl
* @param {URL} base
*/
function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
if (process$1.noDeprecation) return;
const pjsonPath = fileURLToPath(pjsonUrl);
if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
emittedPackageWarnings.add(pjsonPath + "|" + match);
process$1.emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, "DeprecationWarning", "DEP0155");
}
/**
* @param {URL} packageJsonUrl
* @param {string} packageSubpath
* @param {Record<string, unknown>} packageConfig
* @param {URL} base
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
let exports$1 = packageConfig.exports;
if (isConditionalExportsMainSugar(exports$1, packageJsonUrl, base)) exports$1 = { ".": exports$1 };
if (own.call(exports$1, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
const target$1 = exports$1[packageSubpath];
const resolveResult = resolvePackageTarget(packageJsonUrl, target$1, "", packageSubpath, base, false, false, false, conditions);
if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
return resolveResult;
}
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(exports$1);
let i$1 = -1;
while (++i$1 < keys.length) {
const key = keys[i$1];
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
if (packageSubpath.endsWith("/")) emitTrailingSlashPatternDeprecation(packageSubpath, packageJsonUrl, base);
const patternTrailer = key.slice(patternIndex + 1);
if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = packageSubpath.slice(patternIndex, packageSubpath.length - patternTrailer.length);
}
}
}
if (bestMatch) {
const target$1 = exports$1[bestMatch];
const resolveResult = resolvePackageTarget(packageJsonUrl, target$1, bestMatchSubpath, bestMatch, base, true, false, packageSubpath.endsWith("/"), conditions);
if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base);
return resolveResult;
}
throw exportsNotFound(packageSubpath, packageJsonUrl, base);
}
/**
* @param {string} a
* @param {string} b
*/
function patternKeyCompare(a, b) {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
if (baseLengthA > baseLengthB) return -1;
if (baseLengthB > baseLengthA) return 1;
if (aPatternIndex === -1) return 1;
if (bPatternIndex === -1) return -1;
if (a.length > b.length) return -1;
if (b.length > a.length) return 1;
return 0;
}
/**
* @param {string} name
* @param {URL} base
* @param {Set<string>} [conditions]
* @returns {URL}
*/
function packageImportsResolve(name, base, conditions) {
if (name === "#" || name.startsWith("#/") || name.endsWith("/")) throw new ERR_INVALID_MODULE_SPECIFIER(name, "is not a valid internal imports specifier name", fileURLToPath(base));
/** @type {URL | undefined} */
let packageJsonUrl;
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) if (own.call(imports, name) && !name.includes("*")) {
const resolveResult = resolvePackageTarget(packageJsonUrl, imports[name], "", name, base, false, true, false, conditions);
if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
} else {
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(imports);
let i$1 = -1;
while (++i$1 < keys.length) {
const key = keys[i$1];
const patternIndex = key.indexOf("*");
if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
const patternTrailer = key.slice(patternIndex + 1);
if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
bestMatch = key;
bestMatchSubpath = name.slice(patternIndex, name.length - patternTrailer.length);
}
}
}
if (bestMatch) {
const target$1 = imports[bestMatch];
const resolveResult = resolvePackageTarget(packageJsonUrl, target$1, bestMatchSubpath, bestMatch, base, true, true, false, conditions);
if (resolveResult !== null && resolveResult !== void 0) return resolveResult;
}
}
}
throw importNotDefined(name, packageJsonUrl, base);
}
/**
* @param {string} specifier
* @param {URL} base
*/
function parsePackageName(specifier, base) {
let separatorIndex = specifier.indexOf("/");
let validPackageName = true;
let isScoped = false;
if (specifier[0] === "@") {
isScoped = true;
if (separatorIndex === -1 || specifier.length === 0) validPackageName = false;
else separatorIndex = specifier.indexOf("/", separatorIndex + 1);
}
const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
if (invalidPackageNameRegEx.exec(packageName) !== null) validPackageName = false;
if (!validPackageName) throw new ERR_INVALID_MODULE_SPECIFIER(specifier, "is not a valid package name", fileURLToPath(base));
return {
packageName,
packageSubpath: "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex)),
isScoped
};
}
/**
* @param {string} specifier
* @param {URL} base
* @param {Set<string> | undefined} conditions
* @returns {URL}
*/
function packageResolve(specifier, base, conditions) {
if (builtinModules.includes(specifier)) return new URL$1("node:" + specifier);
const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
const packageConfig = getPackageScopeConfig(base);
/* c8 ignore next 16 */
if (packageConfig.exists) {
const packageJsonUrl$1 = pathToFileURL(packageConfig.pjsonPath);
if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl$1, packageSubpath, packageConfig, base, conditions);
}
let packageJsonUrl = new URL$1("./node_modules/" + packageName + "/package.json", base);
let packageJsonPath = fileURLToPath(packageJsonUrl);
/** @type {string} */
let lastPath;
do {
const stat = tryStatSync(packageJsonPath.slice(0, -13));
if (!stat || !stat.isDirectory()) {
lastPath = packageJsonPath;
packageJsonUrl = new URL$1((isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json", packageJsonUrl);
packageJsonPath = fileURLToPath(packageJsonUrl);
continue;
}
const packageConfig$1 = read(packageJsonPath, {
base,
specifier
});
if (packageConfig$1.exports !== void 0 && packageConfig$1.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig$1, base, conditions);
if (packageSubpath === ".") return legacyMainResolve(packageJsonUrl, packageConfig$1, base);
return new URL$1(packageSubpath, packageJsonUrl);
} while (packageJsonPath.length !== lastPath.length);
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), false);
}
/**
* @param {string} specifier
* @returns {boolean}
*/
function isRelativeSpecifier(specifier) {
if (specifier[0] === ".") {
if (specifier.length === 1 || specifier[1] === "/") return true;
if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) return true;
}
return false;
}
/**
* @param {string} specifier
* @returns {boolean}
*/
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === "") return false;
if (specifier[0] === "/") return true;
return isRelativeSpecifier(specifier);
}
/**
* The “Resolver Algorithm Specification” as detailed in the Node docs (which is
* sync and slightly lower-level than `resolve`).
*
* @param {string} specifier
* `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
* @param {URL} base
* Full URL (to a file) that `specifier` is resolved relative from.
* @param {Set<string>} [conditions]
* Conditions.
* @param {boolean} [preserveSymlinks]
* Keep symlinks instead of resolving them.
* @returns {URL}
* A URL object to the found thing.
*/
function moduleResolve(specifier, base, conditions, preserveSymlinks) {
const protocol = base.protocol;
const isRemote = protocol === "data:" || protocol === "http:" || protocol === "https:";
/** @type {URL | undefined} */
let resolved;
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) try {
resolved = new URL$1(specifier, base);
} catch (error_) {
const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
error.cause = error_;
throw error;
}
else if (protocol === "file:" && specifier[0] === "#") resolved = packageImportsResolve(specifier, base, conditions);
else try {
resolved = new URL$1(specifier);
} catch (error_) {
if (isRemote && !builtinModules.includes(specifier)) {
const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
error.cause = error_;
throw error;
}
resolved = packageResolve(specifier, base, conditions);
}
assert(resolved !== void 0, "expected to be defined");
if (resolved.protocol !== "file:") return resolved;
return finalizeResolution(resolved, base);
}
function fileURLToPath$2(id) {
if (typeof id === "string" && !id.startsWith("file://")) return normalizeSlash(id);
return normalizeSlash(fileURLToPath(id));
}
function pathToFileURL$1(id) {
return pathToFileURL(fileURLToPath$2(id)).toString();
}
function normalizeid(id) {
if (typeof id !== "string") id = id.toString();
if (/(node|data|http|https|file):/.test(id)) return id;
if (BUILTIN_MODULES.has(id)) return "node:" + id;
return "file://" + encodeURI(normalizeSlash(id));
}
const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
const DEFAULT_EXTENSIONS = [
".mjs",
".cjs",
".js",
".json"
];
const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
"ERR_MODULE_NOT_FOUND",
"ERR_UNSUPPORTED_DIR_IMPORT",
"MODULE_NOT_FOUND",
"ERR_PACKAGE_PATH_NOT_EXPORTED"
]);
function _tryModuleResolve(id, url, conditions) {
try {
return moduleResolve(id, url, conditions);
} catch (error) {
if (!NOT_FOUND_ERRORS.has(error?.code)) throw error;
}
}
function _resolve(id, options = {}) {
if (typeof id !== "string") if (id instanceof URL) id = fileURLToPath$2(id);
else throw new TypeError("input must be a `string` or `URL`");
if (/(node|data|http|https):/.test(id)) return id;
if (BUILTIN_MODULES.has(id)) return "node:" + id;
if (id.startsWith("file://")) id = fileURLToPath$2(id);
if (isAbsolute$1(id)) try {
if (statSync(id).isFile()) return pathToFileURL$1(id);
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
if (_urls.length === 0) _urls.push(new URL(pathToFileURL$1(process.cwd())));
const urls = [..._urls];
for (const url of _urls) if (url.protocol === "file:") urls.push(new URL("./", url), new URL(joinURL(url.pathname, "_index.js"), url), new URL("node_modules", url));
let resolved;
for (const url of urls) {
resolved = _tryModuleResolve(id, url, conditionsSet);
if (resolved) break;
for (const prefix of ["", "/index"]) {
for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
resolved = _tryModuleResolve(joinURL(id, prefix) + extension, url, conditionsSet);
if (resolved) break;
}
if (resolved) break;
}
if (resolved) break;
}
if (!resolved) {
const error = /* @__PURE__ */ new Error(`Cannot find module ${id} imported from ${urls.join(", ")}`);
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
return pathToFileURL$1(resolved);
}
function resolveSync(id, options) {
return _resolve(id, options);
}
function resolvePathSync(id, options) {
return fileURLToPath$2(resolveSync(id, options));
}
//#endregion
//#region src/shared.ts
const UNKNOWN_HOST = "http://localhost";
const INIT_PATH = "/__vite_plugin_cloudflare_init__";
const GET_EXPORT_TYPES_PATH = "/__vite_plugin_cloudflare_get_export_types__";
const WORKER_ENTRY_PATH_HEADER = "__VITE_WORKER_ENTRY_PATH__";
const IS_ENTRY_WORKER_HEADER = "__VITE_IS_ENTRY_WORKER__";
const ENVIRONMENT_NAME_HEADER = "__VITE_ENVIRONMENT_NAME__";
const IS_PARENT_ENVIRONMENT_HEADER = "__VITE_IS_PARENT_ENVIRONMENT__";
const virtualPrefix = "virtual:cloudflare/";
const VIRTUAL_WORKER_ENTRY = `${virtualPrefix}worker-entry`;
const VIRTUAL_EXPORT_TYPES = `${virtualPrefix}export-types`;
//#endregion
//#region src/plugins/virtual-modules.ts
const VIRTUAL_USER_ENTRY = `${virtualPrefix}user-entry`;
const VIRTUAL_CLIENT_FALLBACK_ENTRY = `${virtualPrefix}client-fallback-entry`;
const VIRTUAL_NODEJS_GLOBAL_INJECT_PREFIX = `${virtualPrefix}nodejs-global-inject/`;
const virtualCloudflareResolveRE = /^virtual:cloudflare\//;
const virtualCloudflareLoadRE = /^\0virtual:cloudflare\//;
/**
* Plugin to provide virtual modules
*/
const virtualModulesPlugin = createPlugin("virtual-modules", (ctx) => {
return {
applyToEnvironment(environment) {
return !ctx.isChildEnvironment(environment.name) && ctx.getWorkerConfig(environment.name) !== void 0;
},
resolveId: {
filter: { id: virtualCloudflareResolveRE },
async handler(source) {
if (!virtualCloudflareResolveRE.test(source)) return;
if (source === VIRTUAL_USER_ENTRY) {
const workerConfig = ctx.getWorkerConfig(this.environment.name);
assert(workerConfig, "Expected `workerConfig` to be defined");
const main = await this.resolve(workerConfig.main);
if (!main) throw new Error(`Failed to resolve main entry file "${workerConfig.main}" for environment "${this.environment.name}"`);
return main;
}
return `\0${source}`;
}
},
load: {
filter: { id: virtualCloudflareLoadRE },
handler(id) {
if (id === `\0${VIRTUAL_WORKER_ENTRY}`) {
const nodeJsCompat = ctx.getNodeJsCompat(this.environment.name);
return `
${nodeJsCompat ? nodeJsCompat.injectGlobalCode() : ""}
import { getExportTypes } from "${VIRTUAL_EXPORT_TYPES}";
import * as mod from "${VIRTUAL_USER_ENTRY}";
export * from "${VIRTUAL_USER_ENTRY}";
export default mod.default ?? {};
if (import.meta.hot) {
import.meta.hot.accept((module) => {
const exportTypes = getExportTypes(module);
import.meta.hot.send("vite-plugin-cloudflare:worker-export-types", exportTypes);
});
}
`;
}
if (id === `\0${VIRTUAL_EXPORT_TYPES}`) return `
import {
WorkerEntrypoint,
DurableObject,
WorkflowEntrypoint,
} from "cloudflare:workers";
const baseClasses = new Map([
["WorkerEntrypoint", WorkerEntrypoint],
["DurableObject", DurableObject],
["WorkflowEntrypoint", WorkflowEntrypoint],
]);
export function getExportTypes(module) {
const exportTypes = {};
for (const [key, value] of Object.entries(module)) {
if (key === "default") {
continue;
}
let exportType;
if (typeof value === "function") {
for (const [type, baseClass] of baseClasses) {
if (baseClass.prototype.isPrototypeOf(value.prototype)) {
exportType = type;
break;
}
}
if (!exportType) {
exportType = "DurableObject";
}
} else if (typeof value === "object" && value !== null) {
exportType = "WorkerEntrypoint";
}
exportTypes[key] = exportType;
}
return exportTypes;
}
`;
if (id.startsWith(`\0${VIRTUAL_NODEJS_GLOBAL_INJECT_PREFIX}`)) {
const nodeJsCompat = ctx.getNodeJsCompat(this.environment.name);
assertHasNodeJsCompat(nodeJsCompat);
return nodeJsCompat.getGlobalVirtualModule(id.slice(1));
}
}
}
};
});
const virtualClientFallbackResolveRE = /^virtual:cloudflare\/client-fallback-entry$/;
const virtualClientFallbackLoadRE = /^\0virtual:cloudflare\/client-fallback-entry$/;
/**
* Plugin to provide a virtual fallback entry file for the `client` environment.
* This is used as the entry file for the client build when only the `public` directory is present.
*/
const virtualClientFallbackPlugin = createPlugin("virtual-client-fallback", () => {
return {
applyToEnvironment(environment) {
return environment.name === "client";
},
resolveId: {
filter: { id: virtualClientFallbackResolveRE },
handler(source) {
if (!virtualClientFallbackResolveRE.test(source)) return;
return `\0${VIRTUAL_CLIENT_FALLBACK_ENTRY}`;
}
},
load: {
filter: { id: virtualClientFallbackLoadRE },
handler(id) {
if (!virtualClientFallbackLoadRE.test(id)) return;
return "";
}
}
};
});
//#endregion
//#region src/nodejs-compat.ts
var NodeJsCompat = class {
externals;
entries;
#env;
/**
* Map of module identifiers to an array of:
* - `injectedName`: the name injected on `globalThis`
* - `exportName`: the export name from the module
* - `importName`: the imported name
*/
#injectsByModule;
/**
* Map of virtual module to injectable module ID,
* which then maps via `injectsByModule` to the global code to be injected.
*/
#virtualModulePathToSpecifier;
constructor(workerConfig) {
const { env: env$1 } = defineEnv({ presets: [getCloudflarePreset({
compatibilityDate: workerConfig.compatibility_date,
compatibilityFlags: workerConfig.compatibility_flags
})] });
this.#env = env$1;
this.externals = new Set(env$1.external);
this.entries = this.#getEntries();
const { injectsByModule, virtualModulePathToSpecifier } = this.#getInjects();
this.#injectsByModule = injectsByModule;
this.#virtualModulePathToSpecifier = virtualModulePathToSpecifier;
}
/**
* Gets a set of module specifiers for all possible Node.js compat polyfill entry-points
*/
#getEntries() {
const entries = new Set(Object.values(this.#env.alias));
for (const globalInject of Object.values(this.#env.inject)) if (typeof globalInject === "string") entries.add(globalInject);
else {
assert(globalInject[0] !== void 0, "Expected first element of globalInject to be defined");
entries.add(globalInject[0]);
}
this.#env.polyfill.forEach((polyfill) => entries.add(polyfill));
this.externals.forEach((external) => entries.delete(external));
return entries;
}
#getInjects() {
const injectsByModule = /* @__PURE__ */ new Map();
const virtualModulePathToSpecifier = /* @__PURE__ */ new Map();
for (const [injectedName, moduleSpecifier] of Object.entries(this.#env.inject)) {
const [module$1, exportName, importName] = Array.isArray(moduleSpecifier) ? [
moduleSpecifier[0],
moduleSpecifier[1],
moduleSpecifier[1]
] : [
moduleSpecifier,
"default",
"defaultExport"
];
if (!injectsByModule.has(module$1)) {
injectsByModule.set(module$1, []);
virtualModulePathToSpecifier.set(`${VIRTUAL_NODEJS_GLOBAL_INJECT_PREFIX}${module$1}`, module$1);
}
const injects = injectsByModule.get(module$1);
assert(injects, `expected injects for "${module$1}" to be defined`);
injects.push({
injectedName,
exportName,
importName
});
}
return {
injectsByModule,
virtualModulePathToSpecifier
};
}
/**
* Does the given module ID resolve to a virtual module corresponding to a global injection module?
*/
isGlobalVirtualModule(source) {
return this.#virtualModulePathToSpecifier.has(source);
}
/**
* Get the contents of the virtual module corresponding to a global injection module.
*/
getGlobalVirtualModule(source) {
const module$1 = this.#virtualModulePathToSpecifier.get(source);
if (!module$1) return;
const injects = this.#injectsByModule.get(module$1);
assert(injects, `expected injects for "${module$1}" to be defined`);
return [`import { ${injects.map(({ exportName, importName }) => importName === exportName ? exportName : `${exportName} as ${importName}`).join(", ")} } from "${module$1}";`, ...injects.map(({ injectedName, importName }) => `globalThis.${injectedName} = ${importName};`)].join("\n");
}
/**
* Gets the necessary global polyfills to inject into the entry-point of the user's code.
*/
injectGlobalCode() {
return `${Array.from(this.#virtualModulePathToSpecifier.keys()).map((moduleId) => `import "${moduleId}";`).join("\n")}${this.#env.polyfill.map((polyfillPath) => `import "${polyfillPath}";`).join("\n")}`;
}
/**
* Resolves the `source` to a Node.js compat alias if possible.
*
* If there is an alias, the return value is an object with:
* - `unresolved`: a bare import path to the polyfill (e.g. `unenv/runtime/node/crypto`)
* - `resolved`: an absolute path to the polyfill (e.g. `/path/to/project/node_modules/unenv/runtime/node/child_process/index.mjs`)
*/
resolveNodeJsImport(source) {
const alias = this.#env.alias[source];
if (alias && !this.externals.has(alias)) return {
unresolved: alias,
resolved: resolvePathSync(alias, { url: import.meta.url })
};
if (this.entries.has(source)) return {
unresolved: source,
resolved: resolvePathSync(source, { url: import.meta.url })
};
}
};
/**
* Returns `true` if the given combination of compat dates and flags enables Node.js compatibility.
*/
function hasNodeJsCompat(workerConfig) {
const nodeCompatMode = getNodeCompat(workerConfig.compatibility_date, workerConfig.compatibility_flags ?? []).mode;
if (nodeCompatMode === "v2") return true;
if (nodeCompatMode === "v1") throw new Error(`Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`);
return false;
}
/**
* Returns true if Node.js async local storage (ALS) is enabled (and not full Node.js compatibility mode).
*/
function hasNodeJsAls(workerConfig) {
return workerConfig !== void 0 && getNodeCompat(workerConfig.compatibility_date, workerConfig.compatibility_flags ?? []).mode === "als";
}
function isNodeAlsModule(modulePath) {
return /^(?:node:)?async_hooks$/.test(modulePath);
}
const nodeBuiltinsRE = /* @__PURE__ */ new RegExp(`^(${nonPrefixedNodeModules.join("|")}|node:.+)$`);
function assertHasNodeJsCompat(nodeJsCompat) {
assert(nodeJsCompat, `expected nodeJsCompat to be defined`);
}
var NodeJsCompatWarnings = class {
sources = /* @__PURE__ */ new Map();
timer;
constructor(environmentName, resolvedViteConfig) {
this.environmentName = environmentName;
this.resolvedViteConfig = resolvedViteConfig;
}
registerImport(source, importer = "<unknown>") {
const importers = this.sources.get(source) ?? /* @__PURE__ */ new Set();
this.sources.set(source, importers);
importers.add(importer);
this.renderWarningsOnIdle();
}
renderWarningsOnIdle() {
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.renderWarnings();
this.timer = void 0;
}, 500);
}
renderWarnings() {
if (this.sources.size > 0) {
let message = `Unexpected Node.js imports for environment "${this.environmentName}". Do you need to enable the "nodejs_compat" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.
`;
this.sources.forEach((importers, source) => {
importers.forEach((importer) => {
message += ` - "${source}" imported from "${nodePath.relative(this.resolvedViteConfig.root, importer)}"\n`;
});
});
this.resolvedViteConfig.logger.warn(message, { timestamp: true });
this.sources.clear();
}
}
};
//#endregion
//#region src/workers-configs.ts
/**
* Set of worker config options that are not applicable when using Vite
*/
const nonApplicableWorkerConfigs = {
replacedByVite: {
alias: {
viteReplacement: "resolve.alias",
viteDocs: "https://vite.dev/config/shared-options.html#resolve-alias"
},
define: {
viteReplacement: "define",
viteDocs: "https://vite.dev/config/shared-options.html#define"
},
minify: {
viteReplacement: "build.minify",
viteDocs: "https://vite.dev/config/build-options.html#build-minify"
}
},
notRelevant: [
"base_dir",
"build",
"find_additional_modules",
"no_bundle",
"preserve_file_names",
"rules",
"site",
"tsconfig"
],
notSupportedOnAuxiliary: ["assets"]
};
/**
* The non applicable configs that can be and default to `undefined`
*/
const nullableNonApplicable = [
"alias",
"base_dir",
"find_additional_modules",
"minify",
"no_bundle",
"preserve_file_names",
"site",
"tsconfig"
];
function readWorkerConfig(configPath, env$1) {
const nonApplicable = {
replacedByVite: /* @__PURE__ */ new Set(),
notRelevant: /* @__PURE__ */ new Set(),
notSupportedOnAuxiliary: /* @__PURE__ */ new Set()
};
const config = wrangler.unstable_readConfig({
config: configPath,
env: env$1
}, { preserveOriginalMain: true });
const raw = structuredClone(config);
nullableNonApplicable.forEach((prop) => {
if (config[prop] !== void 0) {
if (isReplacedByVite(prop)) nonApplicable.replacedByVite.add(prop);
if (isNotRelevant(prop)) nonApplicable.notRelevant.add(prop);
}
delete config[prop];
});
if (config.build && (config.build.command || config.build.cwd)) nonApplicable.notRelevant.add("build");
delete config["build"];
if (config.define && Object.keys(config.define).length > 0) nonApplicable.replacedByVite.add("define");
delete config["define"];
if (config.rules.length > 0) nonApplicable.notRelevant.add("rules");
return {
raw,
nonApplicable,
config
};
}
function getWarningForWorkersConfigs(configs) {
if (!("auxiliaryWorkers" in configs) || configs.auxiliaryWorkers.length === 0) {
const nonApplicableLines = getWorkerNonApplicableWarnLines(configs.entryWorker, ` - `);
if (nonApplicableLines.length === 0) return;
const lines$1 = [`\n\n\x1b[43mWARNING\x1b[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${nodePath.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`];
nonApplicableLines.forEach((line) => lines$1.push(line));
lines$1.push("");
return lines$1.join("\n");
}
const lines = [];
const processWorkerConfig = (workerConfig, isEntryWorker = false) => {
const nonApplicableLines = getWorkerNonApplicableWarnLines(workerConfig, ` - `, { isAuxiliary: !isEntryWorker });
if (nonApplicableLines.length > 0) {
lines.push(` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${nodePath.relative("", workerConfig.config.configPath)}\`)` : ""}`);
nonApplicableLines.forEach((line) => lines.push(line));
}
};
processWorkerConfig(configs.entryWorker, true);
configs.auxiliaryWorkers.forEach((config) => processWorkerConfig(config));
if (lines.length === 0) return;
return [
"\n\x1B[43mWARNING\x1B[0m: your workers configs contain configuration options which are ignored since they are not applicable when using Vite:",
...lines,
""
].join("\n");
}
function getWorkerNonApplicableWarnLines(workerConfig, linePrefix, options) {
const lines = [];
const { replacedByVite, notRelevant, notSupportedOnAuxiliary } = workerConfig.nonApplicable;
for (const config of replacedByVite) lines.push(`${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`);
if (notRelevant.size > 0) lines.push(`${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`);
if (options?.isAuxiliary && notSupportedOnAuxiliary.size > 0) lines.push(`${linePrefix}${[...notSupportedOnAuxiliary].map((config) => `\`${config}\``).join(", ")} which ${notSupportedOnAuxiliary.size > 1 ? "are" : "is"} not supported for auxiliary workers`);
return lines;
}
function isReplacedByVite(configName) {
return configName in nonApplicableWorkerConfigs["replacedByVite"];
}
function isNotRelevant(configName) {
return nonApplicableWorkerConfigs.notRelevant.includes(configName);
}
function missingFieldErrorMessage(field, configPath, env$1) {
return `No '${field}' field provided${configPath ? ` in '${configPath}'` : ""}${env$1 ? ` for '${env$1}' environment` : ""}`;
}
/**
* Reads and sanitizes a worker config from a wrangler config file.
*/
function readWorkerConfigFromFile(configPath, env$1, opts) {
if (opts?.visitedConfigPaths?.has(configPath)) throw new Error(`Duplicate Wrangler config path found: ${configPath}`);
const result = readWorkerConfig(configPath, env$1);
opts?.visitedConfigPaths?.add(configPath);
return result;
}
/**
* Validates required fields and determines whether the config represents
* an assets-only worker or a worker with server logic.
*
* @param config The sanitized worker config (after merging defaults, file config, and config())
* @param raw The raw config (before sanitization)
* @param nonApplicable The non-applicable config map
* @param opts Options for validation
*/
function resolveWorkerType(config, raw, nonApplicable, opts) {
if (!config.name) throw new Error(missingFieldErrorMessage("name", opts?.configPath, opts?.env));
if (!config.topLevelName) throw new Error(missingFieldErrorMessage("top-level name", opts?.configPath, opts?.env));
if (!config.compatibility_date) throw new Error(missingFieldErrorMessage("compatibility_date", opts?.configPath, opts?.env));
const requiredFields = {
topLevelName: config.topLevelName,
name: config.name,
compatibility_date: config.compatibility_date
};
if (opts?.isEntryWorker && !config.main) return {
type: "assets-only",
raw,
config: {
...config,
...requiredFields
},
nonApplicable
};
if (!config.main) throw new Error(missingFieldErrorMessage("main", opts?.configPath, opts?.env));
const resolvedMain = maybeResolveMain(config.main, opts?.configPath, opts?.root);
return {
type: "worker",
raw,
config: {
...config,
...requiredFields,
main: resolvedMain
},
nonApplicable
};
}
const ENTRY_MODULE_EXTENSIONS = [
".js",
".mjs",
".ts",
".mts",
".jsx",
".tsx"
];
/**
* If `main` ends with a valid file extension it is resolved to an absolute path.
* Else `main` is returned as is so that it can be resolved by Vite.
* This enables resolving entry modules relative to the Worker config while also supporting virtual modules and package exports.
*/
function maybeResolveMain(main, configPath, root) {
if (!ENTRY_MODULE_EXTENSIONS.some((extension) => main.endsWith(extension))) return main;
const baseDir = configPath ? nodePath.dirname(configPath) : root;
if (!baseDir) return main;
const resolvedMain = nodePath.resolve(baseDir, main);
if (!fs$2.existsSync(resolvedMain)) throw new Error(`The provided Wrangler config main field (${resolvedMain}) doesn't point to an existing file`);
return resolvedMain;
}
/**
* Returns the path to a wrangler config for a worker after having it validated
* (throws appropriate errors in case the validation fails)
*
* @param root the root of the vite project
* @param requestedConfigPath the requested config path, if any
* @param isForAuxiliaryWorker whether the config path is being requested for an auxiliary worker
* @returns a valid path to a config file, or undefined for entry workers when no config is found
*/
function getValidatedWranglerConfigPath(root, requestedConfigPath, isForAuxiliaryWorker = false) {
if (requestedConfigPath) {
const configPath = nodePath.resolve(root, requestedConfigPath);
const errorMessagePrefix = `The provided configPath (${configPath})${isForAuxiliaryWorker ? " requested for one of your auxiliary workers" : ""}`;
const fileExtension = nodePath.extname(configPath).slice(1);
if (!allowedWranglerConfigExtensions.includes(fileExtension)) {
const foundExtensionMessage = !fileExtension ? "no extension found" : `"${fileExtension}" found`;
throw new Error(`${errorMessagePrefix} doesn't point to a file with the correct file extension. It should point to a jsonc, json or toml file (${foundExtensionMessage} instead)`);
}
const mainStat = fs$2.statSync(configPath, { throwIfNoEntry: false });
if (!mainStat) throw new Error(`${errorMessagePrefix} doesn't point to an existing file`);
if (mainStat.isDirectory()) throw new Error(`${errorMessagePrefix} points to a directory. It should point to a file.`);
return configPath;
}
if (isForAuxiliaryWorker) return;
return findWranglerConfig(root);
}
function findWranglerConfig(root) {
for (const extension of allowedWranglerConfigExtensions) {
const configPath = nodePath.join(root, `wrangler.${extension}`);
if (fs$2.existsSync(configPath)) return configPath;
}
}
const allowedWranglerConfigExtensions = [
"jsonc",
"json",
"toml"
];
//#endregion
//#region src/plugin-config.ts
function filterEntryWorkerConfig(config) {
const { topLevelName: _topLevelName, name: _name,...filteredConfig } = config;
return filteredConfig;
}
function customizeWorkerConfig(options) {
const configResult = typeof options.configCustomizer === "function" ? "entryWorkerConfig" in options ? options.configCustomizer(options.workerConfig, { entryWorkerConfig: filterEntryWorkerConfig(options.entryWorkerConfig) }) : options.configCustomizer(options.workerConfig) : options.configCustomizer;
if (configResult) return defu(configResult, options.workerConfig);
return options.workerConfig;
}
/**
* Resolves the config for a single worker, applying defaults, file config, and config().
*/
function resolveWorkerConfig(options) {
const isEntryWorker = !("entryWorkerConfig" in options);
let workerConfig;
let raw;
let nonApplicable;
if (options.configPath) ({raw, config: workerConfig, nonApplicable} = readWorkerConfigFromFile(options.configPath, options.env, { visitedConfigPaths: options.visitedConfigPaths }));
else {
workerConfig = { ...wrangler.unstable_defaultWranglerConfig };
raw = structuredClone(workerConfig);
nonApplicable = {
replacedByVite: /* @__PURE__ */ new Set(),
notRelevant: /* @__PURE__ */ new Set(),
notSupportedOnAuxiliary: /* @__PURE__ */ new Set()
};
}
workerConfig = "entryWorkerConfig" in options ? customizeWorkerConfig({
workerConfig,
configCustomizer: options.configCustomizer,
entryWorkerConfig: options.entryWorkerConfig
}) : customizeWorkerConfig({
workerConfig,
configCustomizer: options.configCustomizer
});
workerConfig.compatibility_date ??= DEFAULT_COMPAT_DATE;
if (isEntryWorker) workerConfig.name ??= wrangler.unstable_getWorkerNameFromProject(options.root);
workerConfig.topLevelName ??= workerConfig.name;
return resolveWorkerType(workerConfig, raw, nonApplicable, {
isEntryWorker,
configPath: options.configPath,
root: options.root,
env: options.env
});
}
function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
const shared = {
persistState: pluginConfig.persistState ?? true,
inspectorPort: pluginConfig.inspectorPort,
tunnel: typeof pluginConfig.tunnel === "boolean" ? { autoStart: pluginConfig.tunnel } : {
autoStart: pluginConfig.tunnel?.autoStart ?? false,
name: pluginConfig.tunnel?.name
},
experimental: { headersAndRedirectsDevModeSupport: pluginConfig.experimental?.headersAndRedirectsDevModeSupport }
};
const root = userConfig.root ? nodePath.resolve(userConfig.root) : process.cwd();
const prefixedEnv = vite.loadEnv(viteEnv.mode, root, ["CLOUDFLARE_", "WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_"]);
Object.assign(process.env, prefixedEnv);
if (viteEnv.isPreview) return {
...shared,
remoteBindings: pluginConfig.remoteBindings ?? true,
type: "preview",
workers: getWorkerConfigs(root, !!process.env.CLOUDFLARE_VITE_BUILD)
};
const configPaths = /* @__PURE__ */ new Set();
const cloudflareEnv = prefixedEnv.CLOUDFLARE_ENV;
const validateAndAddEnvironmentName = createEnvironmentNameValidator();
const entryWorkerResolvedConfig = resolveWorkerConfig({
root,
configPath: getValidatedWranglerConfigPath(root, pluginConfig.configPath ?? prefixedEnv.CLOUDFLARE_VITE_WRANGLER_CONFIG_PATH),
env: cloudflareEnv,
configCustomizer: pluginConfig.config,
visitedConfigPaths: configPaths
});
const environmentNameToWorkerMap = /* @__PURE__ */ new Map();
const environmentNameToChildEnvironmentNamesMap = /* @__PURE__ */ new Map();
const prerenderWorkerConfig = pluginConfig.experimental?.prerenderWorker;
let prerenderWorkerEnvironmentName;
if (prerenderWorkerConfig && viteEnv.command === "build") {
const workerResolvedConfig = resolveWorkerConfig({
root,
configPath: getValidatedWranglerConfigPath(root, prerenderWorkerConfig.configPath, true),
env: cloudflareEnv,
configCustomizer: "config" in prerenderWorkerConfig ? prerenderWorkerConfig.config : void 0,
entryWorkerConfig: entryWorkerResolvedConfig.config,
visitedConfigPaths: configPaths
});
prerenderWorkerEnvironmentName = prerenderWorkerConfig.viteEnvironment?.name ?? workerNameToEnvironmentName(workerResolvedConfig.config.topLevelName);
validateAndAddEnvironmentName(prerenderWorkerEnvironmentName);
environmentNameToWorkerMap.set(prerenderWorkerEnvironmentName, resolveWorker(workerResolvedConfig.config));
const prerenderWorkerChildEnvironments = prerenderWorkerConfig.viteEnvironment?.childEnvironments;
if (prerenderWorkerChildEnvironments) {
for (const childName of prerenderWorkerChildEnvironments) validateAndAddEnvironmentName(childName);
environmentNameToChildEnvironmentNamesMap.set(prerenderWorkerEnvironmentName, prerenderWorkerChildEnvironments);
}
}
if (entryWorkerResolvedConfig.type === "assets-only") return {
...shared,
type: "assets-only",
cloudflareEnv,
config: entryWorkerResolvedConfig.config,
environmentNameToWorkerMap,
environmentNameToChildEnvironmentNamesMap,
prerenderWorkerEnvironmentName,
configPaths,
remoteBindings: pluginConfig.remoteBindings ?? true,
rawConfigs: { entryWorker: entryWorkerResolvedConfig }
};
let staticRouting;
if (Array.isArray(entryWorkerResolvedConfig.config.assets?.run_worker_first)) staticRouting = parseStaticRouting(entryWorkerResolvedConfig.config.assets.run_worker_first);
const entryWorkerEnvironmentName = pluginConfig.viteEnvironment?.name ?? workerNameToEnvironmentName(entryWorkerResolvedConfig.config.topLevelName);
validateAndAddEnvironmentName(entryWorkerEnvironmentName);
environmentNameToWorkerMap.set(entryWorkerEnvironmentName, resolveWorker(entryWorkerResolvedConfig.config));
const entryWorkerChildEnvironments = pluginConfig.viteEnvironment?.childEnvironments;
if (entryWorkerChildEnvironments) {
for (const childName of entryWorkerChildEnvironments) validateAndAddEnvironmentName(childName);
environmentNameToChildEnvironmentNamesMap.set(entryWorkerEnvironmentName, entryWorkerChildEnvironments);
}
const auxiliaryWorkersResolvedConfigs = [];
for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
const workerResolvedConfig = resolveWorkerConfig({
root,
configPath: getValidatedWranglerConfigPath(root, auxiliaryWorker.configPath, true),
env: cloudflareEnv,
configCustomizer: "config" in auxiliaryWorker ? auxiliaryWorker.config : void 0,
entryWorkerConfig: entryWorkerResolvedConfig.config,
visitedConfigPaths: configPaths
});
if (workerResolvedConfig.config.assets) workerResolvedConfig.nonApplicable.notSupportedOnAuxiliary.add("assets");
auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
const workerEnvironmentName = auxiliaryWorker.viteEnvironment?.name ?? workerNameToEnvironmentName(workerResolvedConfig.config.topLevelName);
validateAndAddEnvironmentName(workerEnvironmentName);
environmentNameToWorkerMap.set(workerEnvironmentName, resolveWorker(workerResolvedConfig.config));
const auxiliaryWorkerChildEnvironments = auxiliaryWorker.viteEnvironment?.childEnvironments;
if (auxiliaryWorkerChildEnvironments) {
for (const childName of auxiliaryWorkerChildEnvironments) validateAndAddEnvironmentName(childName);
environmentNameToChildEnvironmentNamesMap.set(workerEnvironmentName, auxiliaryWorkerChildEnvironments);
}
}
return {
...shared,
type: "workers",
cloudflareEnv,
configPaths,
environmentNameToWorkerMap,
environmentNameToChildEnvironmentNamesMap,
prerenderWorkerEnvironmentName,
entryWorkerEnvironmentName,
staticRouting,
remoteBindings: pluginConfig.remoteBindings ?? true,
rawConfigs: {
entryWorker: entryWorkerResolvedConfig,
auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
}
};
}
function workerNameToEnvironmentName(workerName) {
return workerName.replaceAll("-", "_");
}
function createEnvironmentNameValidator() {
const usedNames = /* @__PURE__ */ new Set();
return (name) => {
if (name === "client") throw new Error(`"client" is a reserved Vite environment name`);
if (usedNames.has(name)) throw new Error(`Duplicate Vite environment name: "${name}"`);
usedNames.add(name);
};
}
function resolveWorker(workerConfig) {
return {
config: workerConfig,
nodeJsCompat: hasNodeJsCompat(workerConfig) ? new NodeJsCompat(workerConfig) : void 0
};
}
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
const comma = ",".charCodeAt(0);
const semicolon = ";".charCodeAt(0);
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const intToChar = new Uint8Array(64);
const charToInt = new Uint8Array(128);
for (let i$1 = 0; i$1 < 64; i$1++) {
const c = chars.charCodeAt(i$1);
intToChar[i$1] = c;
charToInt[c] = i$1;
}
function encodeInteger(builder, num, relative$2) {
let delta = num - relative$2;
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
do {
let clamped = delta & 31;
delta >>>= 5;
if (delta > 0) clamped |= 32;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
const bufLength = 1024 * 16;
const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
} } : { decode(buf) {
let out = "";
for (let i$1 = 0; i$1 < buf.length; i$1++) out += String.fromCharCode(buf[i$1]);
return out;
} };
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer: buffer$1 } = this;
buffer$1[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer$1);
this.pos = 0;
}
}
flush() {
const { buffer: buffer$1, out, pos } = this;
return pos > 0 ? out + td.decode(buffer$1.subarray(0, pos)) : out;
}
};
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i$1 = 0; i$1 < decoded.length; i$1++) {
const line = decoded[i$1];
if (i$1 > 0) writer.write(semicolon);
if (line.length === 0) continue;
let genColumn = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (j > 0) writer.write(comma);
genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) continue;
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
sourceLine = encodeInteger(writer, segment[2], sourceLine);
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) continue;
namesIndex = encodeInteger(writer, segment[4], namesIndex);
}
}
return writer.flush();
}
//#endregion
//#region ../../node_modules/.pnpm/magic-string@0.30.17/node_modules/magic-string/dist/magic-string.es.mjs
var BitSet = class BitSet {
constructor(arg) {
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
}
add(n$1) {
this.bits[n$1 >> 5] |= 1 << (n$1 & 31);
}
has(n$1) {
return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31));
}
};
var Chunk = class Chunk {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
this.previous = null;
this.next = null;
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
reset() {
this.intro = "";
this.outro = "";
if (this.edited) {
this.content = this.original;
this.storeName = false;
this.edited = false;
}
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else this.content = originalBefore;
newChunk.next = this.next;
if (newChunk.next) newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", void 0, true);
if (this.edited) this.edit(trimmed, this.storeName, true);
}
return true;
} else {
this.edit("", void 0, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) newChunk.edit(trimmed, this.storeName, true);
this.edit("", void 0, true);
}
return true;
} else {
this.edit("", void 0, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
}
}
};
function getBtoa() {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
else return () => {
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
};
}
const btoa$1 = /* @__PURE__ */ getBtoa();
var SourceMap = class {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
}
};
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) return null;
if (tabbed.length >= spaced.length) return " ";
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i$1 = fromParts.length;
while (i$1--) fromParts[i$1] = "..";
}
return fromParts.concat(toParts).join("/");
}
const toString = Object.prototype.toString;
function isObject$1(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i$1 = 0, pos = 0; i$1 < originalLines.length; i$1++) {
lineOffsets.push(pos);
pos += originalLines[i$1].length + 1;
}
return function locate(index) {
let i$1 = 0;
let j = lineOffsets.length;
while (i$1 < j) {
const m = i$1 + j >> 1;
if (index < lineOffsets[m]) j = m;
else i$1 = m + 1;
}
const line = i$1 - 1;
return {
line,
column: index - lineOffsets[line]
};
};
}
const wordRegex = /\w/;
var Mappings = class {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const contentLengthMinusOne = content.length - 1;
let contentLineEnd = content.indexOf("\n", 0);
let previousContentLineEnd = -1;
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
const segment$1 = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment$1.push(nameIndex);
this.rawSegments.push(segment$1);
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
previousContentLineEnd = contentLineEnd;
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
}
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment.push(nameIndex);
this.rawSegments.push(segment);
this.advance(content.slice(previousContentLineEnd + 1));
} else if (this.pending) {
this.rawSegments.push(this.pending);
this.advance(content);
}
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
charInHiresBoundary = false;
} else {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
if (!charInHiresBoundary) {
this.rawSegments.push(segment);
charInHiresBoundary = true;
}
} else {
this.rawSegments.push(segment);
charInHiresBoundary = false;
}
else this.rawSegments.push(segment);
}
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str) return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i$1 = 0; i$1 < lines.length - 1; i$1++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
const n = "\n";
const warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class MagicString {
constructor(string, options = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: {
writable: true,
value: string
},
outro: {
writable: true,
value: ""
},
intro: {
writable: true,
value: ""
},
firstChunk: {
writable: true,
value: chunk
},
lastChunk: {
writable: true,
value: chunk
},
lastSearchedChunk: {
writable: true,
value: chunk
},
byStart: {
writable: true,
value: {}
},
byEnd: {
writable: true,
value: {}
},
filename: {
writable: true,
value: options.filename
},
indentExclusionRanges: {
writable: true,
value: options.indentExclusionRanges
},
sourcemapLocations: {
writable: true,
value: new BitSet()
},
storedNames: {
writable: true,
value: {}
},
indentStr: {
writable: true,
value: void 0
},
ignoreList: {
writable: true,
value: options.ignoreList
},
offset: {
writable: true,
value: options.offset || 0
}
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.appendLeft(content);
else this.intro += content;
return this;
}
appendRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.appendRight(content);
else this.outro += content;
return this;
}
clone() {
const cloned = new MagicString(this.original, {
filename: this.filename,
offset: this.offset
});
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options) {
options = options || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options.hires);
const locate = getLocator(this.original);
if (this.intro) mappings.advance(this.intro);
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length) mappings.advance(chunk.intro);
if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
if (chunk.outro.length) mappings.advance(chunk.outro);
});
return {
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
sourcesContent: options.includeContent ? [this.original] : void 0,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
};
}
generateMap(options) {
return new SourceMap(this.generateDecodedMap(options));
}
_ensureindentStr() {
if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
}
_getRawIndentString() {
this._ensureindentStr();
return this.indentStr;
}
getIndentString() {
this._ensureindentStr();
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options) {
const pattern = /^[^\r\n]/gm;
if (isObject$1(indentStr)) {
options = indentStr;
indentStr = void 0;
}
if (indentStr === void 0) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "") return this;
options = options || {};
const isExcluded = {};
if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
for (let i$1 = exclusion[0]; i$1 < exclusion[1]; i$1 += 1) isExcluded[i$1] = true;
});
let shouldIndentNextCharacter = options.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") shouldIndentNextCharacter = true;
else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) chunk.prependRight(indentStr);
else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
start = start + this.offset;
end = end + this.offset;
index = index + this.offset;
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk) return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft) oldLeft.next = oldRight;
if (oldRight) oldRight.previous = oldLeft;
if (newLeft) newLeft.next = first;
if (newRight) newRight.previous = last;
if (!first.previous) this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft) this.firstChunk = first;
if (!newRight) this.lastChunk = last;
return this;
}
overwrite(start, end, content, options) {
options = options || {};
return this.update(start, end, content, {
...options,
overwrite: !options.contentOnly
});
}
update(start, end, content, options) {
start = start + this.offset;
end = end + this.offset;
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (end > this.original.length) throw new Error("end is out of bounds");
if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
this._split(start);
this._split(end);
if (options === true) {
if (!warned.storeName) {
console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
warned.storeName = true;
}
options = { storeName: true };
}
const storeName = options !== void 0 ? options.storeName : false;
const overwrite = options !== void 0 ? options.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, !overwrite);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.prependLeft(content);
else this.intro = content + this.intro;
return this;
}
prependRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.prependRight(content);
else this.outro = content + this.outro;
return this;
}
remove(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
reset(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.reset();
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length) return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length) return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length - this.offset) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) return result;
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
if (containsEnd) break;
chunk = chunk.next;
}
return result;
}
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index]) return;
let chunk = this.lastSearchedChunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index)) return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk) this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = /* @__PURE__ */ new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = /* @__PURE__ */ new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
_replaceRegexp(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i$1) => {
if (i$1 === "$") return "$";
if (i$1 === "&") return match[0];
if (+i$1 < match.length) return match[+i$1];
return `$${i$1}`;
});
else return replacement(...match, match.index, str, match.groups);
}
function matchAll(re$5, str) {
let match;
const matches = [];
while (match = re$5.exec(str)) matches.push(match);
return matches;
}
if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
if (match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
});
else {
const match = this.original.match(searchValue);
if (match && match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
}
return this;
}
_replaceString(string, replacement) {
const { original } = this;
const index = original.indexOf(string);
if (index !== -1) this.overwrite(index, index + string.length, replacement);
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string, replacement) {
const { original } = this;
const stringLength = string.length;
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) if (original.slice(index, index + stringLength) !== replacement) this.overwrite(index, index + stringLength, replacement);
return this;
}
replaceAll(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
return this._replaceRegexp(searchValue, replacement);
}
};
//#endregion
//#region src/plugins/additional-modules.ts
/**
* Plugin to support additional module types (`CompiledWasm`, `Data` and `Text`)
*/
const additionalModulesPlugin = createPlugin("additional-modules", (ctx) => {
const additionalModulePaths = /* @__PURE__ */ new Set();
return {
enforce: "pre",
applyToEnvironment(environment) {
return ctx.getWorkerConfig(environment.name) !== void 0;
},
resolveId: {
filter: { id: moduleRuleFilters },
async handler(source, importer, options) {
const resolved = await this.resolve(source, importer, options);
if (!resolved) return;
const additionalModuleType = matchAdditionalModule(resolved.id);
if (!additionalModuleType) return resolved;
const filePath = cleanUrl(resolved.id);
additionalModulePaths.add(filePath);
return {
external: true,
id: createModuleReference(additionalModuleType, filePath)
};
}
},
hotUpdate(options) {
if (additionalModulePaths.has(options.file)) {
options.server.restart();
return [];
}
},
renderChunk: {
filter: { code: { include: additionalModuleRE } },
async handler(code, chunk) {
const matches = code.matchAll(additionalModuleGlobalRE);
let magicString;
for (const match of matches) {
magicString ??= new MagicString(code);
const [full, _, modulePath] = match;
assert(modulePath, `Unexpected error: module path not found in reference ${full}.`);
let source;
try {
source = await fsp.readFile(modulePath);
} catch {
throw new Error(`Import "${modulePath}" not found. Does the file exist?`);
}
const referenceId = this.emitFile({
type: "asset",
name: nodePath.basename(modulePath),
originalFileName: modulePath,
source
});
const emittedFileName = this.getFileName(referenceId);
const relativePath = vite.normalizePath(nodePath.relative(nodePath.dirname(chunk.fileName), emittedFileName));
const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
magicString.update(match.index, match.index + full.length, importPath);
}
if (magicString) return {
code: magicString.toString(),
map: this.environment.config.build.sourcemap ? magicString.generateMap({ hires: "boundary" }) : null
};
}
}
};
});
const ADDITIONAL_MODULE_PATTERN = `__CLOUDFLARE_MODULE__(${[
"CompiledWasm",
"Data",
"Text"
].join("|")})__(.*?)__CLOUDFLARE_MODULE__`;
const additionalModuleRE = new RegExp(ADDITIONAL_MODULE_PATTERN);
const additionalModuleGlobalRE = new RegExp(ADDITIONAL_MODULE_PATTERN, "g");
const moduleRules = [
{
type: "CompiledWasm",
pattern: /\.wasm(\?module)?$/
},
{
type: "Data",
pattern: /\.bin$/
},
{
type: "Text",
pattern: /\.(txt|html|sql)$/
}
];
const subpathImportRE = /^#/;
const moduleRuleFilters = [...moduleRules.map((rule) => rule.pattern), subpathImportRE];
function matchAdditionalModule(source) {
for (const rule of moduleRules) if (rule.pattern.test(source)) return rule.type;
return null;
}
function createModuleReference(type, id) {
return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__`;
}
//#endregion
//#region ../workers-shared/utils/configuration/constructConfiguration.ts
function constructRedirects({ redirects, redirectsFile, logger }) {
if (!redirects) return {};
const num_valid = redirects.rules.length;
const num_invalid = redirects.invalid.length;
const redirectsRelativePath = redirectsFile ? relative(process.cwd(), redirectsFile) : "";
logger.log(`✨ 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 += `▶︎ ${message}\n`;
if (line) invalidRedirectRulesList += ` at ${redirectsRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}\n\n`;
}
logger.warn(`Found ${num_invalid} invalid redirect rule${num_invalid === 1 ? "" : "s"}:\n${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 logger.info(`The redirect rule ${rule.from} → ${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 }) {
if (!headers) return {};
const num_valid = headers.rules.length;
const num_invalid = headers.invalid.length;
const headersRelativePath = headersFile ? relative(process.cwd(), headersFile) : "";
logger.log(`✨ 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 += `▶︎ ${message}\n`;
if (line) invalidHeaderRulesList += ` at ${headersRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}\n\n`;
}
logger.warn(`Found ${num_invalid} invalid header rule${num_invalid === 1 ? "" : "s"}:\n${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
} };
}
//#endregion
//#region ../workers-shared/utils/configuration/validateURL.ts
const extractPathname = (path$2 = "/", includeSearch, includeHash) => {
if (!path$2.startsWith("/")) path$2 = `/${path$2}`;
const url = new URL(`//${path$2}`, "relative://");
return `${url.pathname}${includeSearch ? url.search : ""}${includeHash ? url.hash : ""}`;
};
const URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
const HOST_WITH_PORT_REGEX = /.*:\d+$/;
const PATH_REGEX = /^\//;
const validateUrl = (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}`;
if (PATH_REGEX.exec(token)) 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://\")."];
};
function urlHasHost(token) {
const host = URL_REGEX.exec(token);
return Boolean(host && host.groups && host.groups.host);
}
//#endregion
//#region ../workers-shared/utils/configuration/parseHeaders.ts
const LINE_IS_PROBABLY_A_PATH = /* @__PURE__ */ new RegExp(/^([^\s]+:\/\/|^\/)/);
function parseHeaders(input, { maxRules = MAX_HEADER_RULES, maxLineLength = MAX_LINE_LENGTH } = {}) {
const lines = input.split("\n");
const rules = [];
const invalid = [];
let rule = void 0;
let skipUntilNextPath = false;
for (let i$1 = 0; i$1 < lines.length; i$1++) {
const line = (lines[i$1] || "").trim();
if (line.length === 0 || line.startsWith("#")) continue;
if (line.length > maxLineLength) {
invalid.push({ message: `Ignoring line ${i$1 + 1} as it exceeds the maximum allowed length of ${maxLineLength}.` });
continue;
}
if (LINE_IS_PROBABLY_A_PATH.test(line)) {
skipUntilNextPath = false;
if (rules.length >= maxRules) {
invalid.push({ message: `Maximum number of rules supported is ${maxRules}. Skipping remaining ${lines.length - i$1} 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: i$1 + 1,
message: "No headers specified"
});
const [path$2, pathError] = validateUrl(line, false, true);
if (pathError) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: pathError
});
rule = void 0;
skipUntilNextPath = true;
continue;
}
const wildcardError = validateNoMultipleWildcards(path$2);
if (wildcardError) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: wildcardError
});
rule = void 0;
skipUntilNextPath = true;
continue;
}
rule = {
path: path$2,
line,
headers: {},
unsetHeaders: []
};
continue;
}
if (skipUntilNextPath) continue;
if (!line.includes(HEADER_SEPARATOR)) {
if (!rule) invalid.push({
line,
lineNumber: i$1 + 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: i$1 + 1,
message: "Expected a colon-separated header pair (e.g. name: value)"
});
continue;
}
const [rawName, ...rawValue] = line.split(HEADER_SEPARATOR);
const name = (rawName || "").trim().toLowerCase();
if (name.includes(" ")) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: "Header name cannot include spaces"
});
continue;
}
const value = rawValue.join(HEADER_SEPARATOR).trim();
if (name === "") {
invalid.push({
line,
lineNumber: i$1 + 1,
message: "No header name specified"
});
continue;
}
if (value === "") {
invalid.push({
line,
lineNumber: i$1 + 1,
message: "No header value specified"
});
continue;
}
if (!rule) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: `Path should come before header (${name}: ${value})`
});
continue;
}
const existingValues = rule.headers[name];
rule.headers[name] = 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;
}
/**
* At runtime, `*` wildcards are converted to `:splat` placeholders. This means
* a path with multiple wildcards, or a wildcard combined with an explicit
* `:splat` placeholder, would result in duplicate `:splat` parameters which is
* unsupported.
*/
function validateNoMultipleWildcards(path$2) {
const wildcardCount = (path$2.match(SPLAT_REGEX) ?? []).length;
const hasSplatPlaceholder = /:splat(?!\w)/.test(path$2);
if (wildcardCount > 1) return `Only one wildcard is allowed per rule. Use a named placeholder (e.g. :project) instead. Skipping ${path$2}.`;
if (wildcardCount > 0 && hasSplatPlaceholder) return `Cannot combine a wildcard * with a :splat placeholder because wildcards are converted to :splat at runtime. Skipping ${path$2}.`;
}
//#endregion
//#region ../workers-shared/utils/configuration/parseRedirects.ts
function parseRedirects(input, { htmlHandling = void 0, 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 i$1 = 0; i$1 < lines.length; i$1++) {
const line = (lines[i$1] || "").trim();
if (line.length === 0 || line.startsWith("#")) continue;
if (line.length > maxLineLength) {
invalid.push({ message: `Ignoring line ${i$1 + 1} as it exceeds the maximum allowed length of ${maxLineLength}.` });
continue;
}
const tokens = line.replace(/\s+#.*$/, "").split(/\s+/);
if (tokens.length < 2 || tokens.length > 3) {
invalid.push({
line,
lineNumber: i$1 + 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: i$1 + 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 - i$1} lines of file.` });
break;
}
}
const toResult = validateUrl(str_to, false, false, true, true);
if (toResult[0] === void 0) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: toResult[1]
});
continue;
}
const to = toResult[0];
const status = Number(str_status);
if (isNaN(status) || !PERMITTED_STATUS_CODES.has(status)) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
});
continue;
}
const hasRelativePath = !urlHasHost(to);
const hasWildcardToIndex = from.endsWith("/*") && /\/index(.html)?$/.test(to);
const hasRootToIndex = from.endsWith("/") && /\/index(.html)?$/.test(to);
if (hasRelativePath && (hasWildcardToIndex || hasRootToIndex && htmlHandling !== "none")) {
invalid.push({
line,
lineNumber: i$1 + 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: i$1 + 1,
message: `Ignoring duplicate rule for path ${from}.`
});
continue;
}
seen_paths.add(from);
if (status === 200) {
if (urlHasHost(to)) {
invalid.push({
line,
lineNumber: i$1 + 1,
message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
});
continue;
}
}
rules.push({
from,
to,
status,
lineNumber: i$1 + 1
});
}
return {
rules,
invalid
};
}
//#endregion
//#region ../workers-shared/utils/constants.ts
/** manifest = [HEADER, [ entry = PATH_HASH, CONTENT_HASH, TAIL], [entry], ... , [entry] ] */
const PATH_HASH_SIZE = 16;
/** manifest = [HEADER, [ entry = PATH_HASH, CONTENT_HASH, TAIL], [entry], ... , [entry] ] */
const CONTENT_HASH_SIZE = 16;
/** manifest = [HEADER, [ entry = PATH_HASH, CONTENT_HASH, TAIL], [entry], ... , [entry] ] */
const TAIL_SIZE = 8;
/** manifest = [HEADER, [ entry = PATH_HASH, CONTENT_HASH, TAIL], [entry], ... , [entry] ] */
const ENTRY_SIZE = PATH_HASH_SIZE + CONTENT_HASH_SIZE + TAIL_SIZE;
/** Maximum size per asset that can be deployed with a Worker */
const MAX_ASSET_SIZE = 25 * 1024 * 1024;
const REDIRECTS_FILENAME = "_redirects";
const HEADERS_FILENAME = "_headers";
//#endregion
//#region ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
var require_ignore = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js": ((exports, module) => {
function makeArray(subject) {
return Array.isArray(subject) ? subject : [subject];
}
const EMPTY = "";
const SPACE = " ";
const ESCAPE = "\\";
const REGEX_TEST_BLANK_LINE = /^\s+$/;
const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
const REGEX_SPLITALL_CRLF = /\r?\n/g;
const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
const SLASH = "/";
let TMP_KEY_IGNORE = "node-ignore";
/* istanbul ignore else */
if (typeof Symbol !== "undefined") TMP_KEY_IGNORE = Symbol.for("node-ignore");
const KEY_IGNORE = TMP_KEY_IGNORE;
const define = (object, key, value) => Object.defineProperty(object, key, { value });
const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
const RETURN_FALSE = () => false;
const sanitizeRange = (range) => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY);
const cleanRangeBackSlash = (slashes) => {
const { length } = slashes;
return slashes.slice(0, length - length % 2);
};
const REPLACERS = [
[/^\uFEFF/, () => EMPTY],
[/\\?\s+$/, (match) => match.indexOf("\\") === 0 ? SPACE : EMPTY],
[/\\\s/g, () => SPACE],
[/[\\$.|*+(){^]/g, (match) => `\\${match}`],
[/(?!\\)\?/g, () => "[^/]"],
[/^\//, () => "^"],
[/\//g, () => "\\/"],
[/^\^*\\\*\\\*\\\//, () => "^(?:.*\\/)?"],
[/^(?=[^^])/, function startingReplacer() {
return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
}],
[/\\\/\\\*\\\*(?=\\\/|$)/g, (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"],
[/(^|[^\\]+)(\\\*)+(?=.+)/g, (_, p1, p2) => {
return p1 + p2.replace(/\\\*/g, "[^\\/]*");
}],
[/\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE],
[/\\\\/g, () => ESCAPE],
[/(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"],
[/(?:[^*])$/, (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`],
[/(\^|\\\/)?\\\*$/, (_, p1) => {
return `${p1 ? `${p1}[^/]+` : "[^/]*"}(?=$|\\/$)`;
}]
];
const regexCache = Object.create(null);
const makeRegex = (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);
};
const isString$1 = (subject) => typeof subject === "string";
const checkPattern = (pattern) => pattern && isString$1(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
const splitPattern$1 = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
var IgnoreRule = class {
constructor(origin, pattern, negative, regex) {
this.origin = origin;
this.pattern = pattern;
this.negative = negative;
this.regex = regex;
}
};
const createRule = (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 regex = makeRegex(pattern, ignoreCase);
return new IgnoreRule(origin, pattern, negative, regex);
};
const throwError = (message, Ctor) => {
throw new Ctor(message);
};
const checkPath = (path$2, originalPath, doThrow) => {
if (!isString$1(path$2)) return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
if (!path$2) return doThrow(`path must not be empty`, TypeError);
if (checkPath.isNotRelative(path$2)) return doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`, RangeError);
return true;
};
const isNotRelative = (path$2) => REGEX_TEST_INVALID_PATH.test(path$2);
checkPath.isNotRelative = isNotRelative;
checkPath.convert = (p$1) => p$1;
var Ignore = class {
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 = Object.create(null);
this._testCache = 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);
}
}
add(pattern) {
this._added = false;
makeArray(isString$1(pattern) ? splitPattern$1(pattern) : pattern).forEach(this._addPattern, this);
if (this._added) this._initCache();
return this;
}
addPattern(pattern) {
return this.add(pattern);
}
_testOne(path$2, checkUnignored) {
let ignored = false;
let unignored = false;
this._rules.forEach((rule) => {
const { negative } = rule;
if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) return;
if (rule.regex.test(path$2)) {
ignored = !negative;
unignored = negative;
}
});
return {
ignored,
unignored
};
}
_test(originalPath, cache$2, checkUnignored, slices) {
const path$2 = originalPath && checkPath.convert(originalPath);
checkPath(path$2, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
return this._t(path$2, cache$2, checkUnignored, slices);
}
_t(path$2, cache$2, checkUnignored, slices) {
if (path$2 in cache$2) return cache$2[path$2];
if (!slices) slices = path$2.split(SLASH);
slices.pop();
if (!slices.length) return cache$2[path$2] = this._testOne(path$2, checkUnignored);
const parent = this._t(slices.join(SLASH) + SLASH, cache$2, checkUnignored, slices);
return cache$2[path$2] = parent.ignored ? parent : this._testOne(path$2, checkUnignored);
}
ignores(path$2) {
return this._test(path$2, this._ignoreCache, false).ignored;
}
createFilter() {
return (path$2) => !this.ignores(path$2);
}
filter(paths) {
return makeArray(paths).filter(this.createFilter());
}
test(path$2) {
return this._test(path$2, this._testCache, true);
}
};
const factory = (options) => new Ignore(options);
const isPathValid = (path$2) => checkPath(path$2 && checkPath.convert(path$2), path$2, RETURN_FALSE);
factory.isPathValid = isPathValid;
factory.default = factory;
module.exports = factory;
/* istanbul ignore if */
if (typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")) {
const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
checkPath.convert = makePosix;
const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
checkPath.isNotRelative = (path$2) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path$2) || isNotRelative(path$2);
}
}) });
//#endregion
//#region ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/other.js
var import_ignore = /* @__PURE__ */ __toESM$1(require_ignore());
const types$1 = {
"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$1);
var other_default = types$1;
//#endregion
//#region ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/standard.js
const types = {
"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(types);
var standard_default = types;
//#endregion
//#region ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet = void 0 && (void 0).__classPrivateFieldGet || function(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;
var Mime = class {
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(path$2) {
if (typeof path$2 !== "string") return null;
const last = path$2.replace(/^.*[/\\]/s, "").toLowerCase();
const ext = last.replace(/^.*\./s, "").toLowerCase();
const hasPath = last.length < path$2.length;
if (!(ext.length < last.length - 1) && 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();
var Mime_default = Mime;
//#endregion
//#region ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/index.js
var src_default = new Mime_default(standard_default, other_default)._freeze();
//#endregion
//#region ../workers-shared/utils/helpers.ts
function thrownIsDoesNotExistError(thrown) {
return thrown instanceof Error && "code" in thrown && thrown.code === "ENOENT";
}
function maybeGetFile(filePath) {
try {
return readFileSync(filePath, "utf8");
} catch (e) {
if (!thrownIsDoesNotExistError(e)) throw e;
}
}
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js
var util;
(function(util$27) {
util$27.assertEqual = (_) => {};
function assertIs(_arg) {}
util$27.assertIs = assertIs;
function assertNever$1(_x) {
throw new Error();
}
util$27.assertNever = assertNever$1;
util$27.arrayToEnum = (items) => {
const obj = {};
for (const item of items) obj[item] = item;
return obj;
};
util$27.getValidEnumValues = (obj) => {
const validKeys = util$27.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) filtered[k] = obj[k];
return util$27.objectValues(filtered);
};
util$27.objectValues = (obj) => {
return util$27.objectKeys(obj).map(function(e) {
return obj[e];
});
};
util$27.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;
};
util$27.find = (arr, checker) => {
for (const item of arr) if (checker(item)) return item;
};
util$27.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
}
util$27.joinValues = joinValues;
util$27.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") return value.toString();
return value;
};
})(util || (util = {}));
var objectUtil;
(function(objectUtil$2) {
objectUtil$2.mergeShapes = (first, second) => {
return {
...first,
...second
};
};
})(objectUtil || (objectUtil = {}));
const ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
const getParsedType = (data$1) => {
switch (typeof data$1) {
case "undefined": return ZodParsedType.undefined;
case "string": return ZodParsedType.string;
case "number": return Number.isNaN(data$1) ? 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$1)) return ZodParsedType.array;
if (data$1 === null) return ZodParsedType.null;
if (data$1.then && typeof data$1.then === "function" && data$1.catch && typeof data$1.catch === "function") return ZodParsedType.promise;
if (typeof Map !== "undefined" && data$1 instanceof Map) return ZodParsedType.map;
if (typeof Set !== "undefined" && data$1 instanceof Set) return ZodParsedType.set;
if (typeof Date !== "undefined" && data$1 instanceof Date) return ZodParsedType.date;
return ZodParsedType.object;
default: return ZodParsedType.unknown;
}
};
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js
const 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"
]);
var ZodError = class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
else this.__proto__ = actualProto;
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.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 i$1 = 0;
while (i$1 < issue.path.length) {
const el = issue.path[i$1];
if (!(i$1 === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i$1++;
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
return new ZodError(issues);
};
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js
const errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) message = "Required";
else message = `Expected ${issue.expected}, received ${issue.received}`;
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
} else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
else util.assertNever(issue.validation);
else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
else message = "Invalid";
break;
case ZodIssueCode.too_small:
if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "bigint") 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 };
};
var en_default = errorMap;
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js
let overrideErrorMap = en_default;
function getErrorMap() {
return overrideErrorMap;
}
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js
const makeIssue = (params) => {
const { data: data$1, path: path$2, errorMaps, issueData } = params;
const fullPath = [...path$2, ...issueData.path || []];
const fullIssue = {
...issueData,
path: fullPath
};
if (issueData.message !== void 0) return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "";
const maps = errorMaps.filter((m) => !!m).slice().reverse();
for (const map of maps) errorMessage = map(fullIssue, {
data: data$1,
defaultError: errorMessage
}).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === en_default ? void 0 : en_default
].filter((x) => !!x)
});
ctx.common.issues.push(issue);
}
var ParseStatus = class ParseStatus {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid") this.value = "dirty";
}
abort() {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted") return INVALID;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return {
status: status.value,
value: arrayValue
};
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
}
return {
status: status.value,
value: finalObject
};
}
};
const INVALID = Object.freeze({ status: "aborted" });
const DIRTY = (value) => ({
status: "dirty",
value
});
const OK = (value) => ({
status: "valid",
value
});
const isAborted = (x) => x.status === "aborted";
const isDirty = (x) => x.status === "dirty";
const isValid = (x) => x.status === "valid";
const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil$2) {
errorUtil$2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
errorUtil$2.toString = (message) => typeof message === "string" ? message : message?.message;
})(errorUtil || (errorUtil = {}));
//#endregion
//#region ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
constructor(parent, value, path$2, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path$2;
this._key = key;
}
get path() {
if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
else this._cachedPath.push(...this._path, this._key);
return this._cachedPath;
}
};
const handleResult = (ctx, result) => {
if (isValid(result)) return {
success: true,
data: result.value
};
else {
if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
return {
success: false,
get error() {
if (this._error) return this._error;
this._error = new ZodError(ctx.common.issues);
return this._error;
}
};
}
};
function processCreateParams(params) {
if (!params) return {};
const { errorMap: errorMap$2, invalid_type_error, required_error, description } = params;
if (errorMap$2 && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
if (errorMap$2) return {
errorMap: errorMap$2,
description
};
const customMap = (iss, ctx) => {
const { message } = params;
if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
if (iss.code !== "invalid_type") return { message: ctx.defaultError };
return { message: message ?? invalid_type_error ?? ctx.defaultError };
};
return {
errorMap: customMap,
description
};
}
var ZodType = class {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data$1, params) {
const result = this.safeParse(data$1, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data$1, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: data$1,
parsedType: getParsedType(data$1)
};
return handleResult(ctx, this._parseSync({
data: data$1,
path: ctx.path,
parent: ctx
}));
}
"~validate"(data$1) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: data$1,
parsedType: getParsedType(data$1)
};
if (!this["~standard"].async) try {
const result = this._parseSync({
data: data$1,
path: [],
parent: ctx
});
return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
ctx.common = {
issues: [],
async: true
};
}
return this._parseAsync({
data: data$1,
path: [],
parent: ctx
}).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
}
async parseAsync(data$1, params) {
const result = await this.safeParseAsync(data$1, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data$1, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data: data$1,
parsedType: getParsedType(data$1)
};
const maybeAsyncResult = this._parse({
data: data$1,
path: ctx.path,
parent: ctx
});
return handleResult(ctx, await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)));
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") return { message };
else if (typeof message === "function") return message(val);
else return message;
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () => ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data$1) => {
if (!data$1) {
setError();
return false;
} else return true;
});
if (!result) {
setError();
return false;
} else return true;
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
return false;
} else return true;
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "refinement",
refinement
}
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def) {
/** Alias of safeParseAsync */
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data$1) => this["~validate"](data$1)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "transform",
transform
}
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target$1) {
return ZodPipeline.create(this, target$1);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const 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;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([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]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex = /* @__PURE__ */ new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = `[0-5]\\d`;
if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return /* @__PURE__ */ new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? `Z?` : `Z`);
if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
regex = `${regex}(${opts.join("|")})`;
return /* @__PURE__ */ new RegExp(`^${regex}$`);
}
function isValidIP(ip, version$2) {
if ((version$2 === "v4" || !version$2) && ipv4Regex.test(ip)) return true;
if ((version$2 === "v6" || !version$2) && ipv6Regex.test(ip)) return true;
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt)) return false;
try {
const [header] = jwt.split(".");
if (!header) return false;
const base64$1 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64$1));
if (typeof decoded !== "object" || decoded === null) return false;
if ("typ" in decoded && decoded?.typ !== "JWT") return false;
if (!decoded.alg) return false;
if (alg && decoded.alg !== alg) return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version$2) {
if ((version$2 === "v4" || !version$2) && ipv4CidrRegex.test(ip)) return true;
if ((version$2 === "v6" || !version$2) && ipv6CidrRegex.test(ip)) return true;
return false;
}
var ZodString = class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = String(input.data);
if (this._getType(input) !== ZodParsedType.string) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx$1.parsedType
});
return INVALID;
}
const status = 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
});
status.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
});
status.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
});
status.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
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.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
});
status.dirty();
}
} else if (check.kind === "nanoid") {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.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
});
status.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
});
status.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
});
status.dirty();
}
} else if (check.kind === "url") try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
else if (check.kind === "regex") {
check.regex.lastIndex = 0;
if (!check.regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.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
});
status.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
});
status.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
});
status.dirty();
}
} else if (check.kind === "datetime") {
if (!datetimeRegex(check).test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if (check.kind === "date") {
if (!dateRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if (check.kind === "time") {
if (!timeRegex(check).test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if (check.kind === "duration") {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.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
});
status.dirty();
}
} else if (check.kind === "jwt") {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "cidr") {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64") {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if (check.kind === "base64url") {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_regex(regex, validation, message) {
return this.refinement((data$1) => regex.test(data$1), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message)
});
}
_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)
});
}
nanoid(message) {
return this._addCheck({
kind: "nanoid",
...errorUtil.errToObj(message)
});
}
cuid(message) {
return this._addCheck({
kind: "cuid",
...errorUtil.errToObj(message)
});
}
cuid2(message) {
return this._addCheck({
kind: "cuid2",
...errorUtil.errToObj(message)
});
}
ulid(message) {
return this._addCheck({
kind: "ulid",
...errorUtil.errToObj(message)
});
}
base64(message) {
return this._addCheck({
kind: "base64",
...errorUtil.errToObj(message)
});
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({
kind: "jwt",
...errorUtil.errToObj(options)
});
}
ip(options) {
return this._addCheck({
kind: "ip",
...errorUtil.errToObj(options)
});
}
cidr(options) {
return this._addCheck({
kind: "cidr",
...errorUtil.errToObj(options)
});
}
datetime(options) {
if (typeof options === "string") return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
return this._addCheck({
kind: "datetime",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({
kind: "date",
message
});
}
time(options) {
if (typeof options === "string") return this._addCheck({
kind: "time",
precision: null,
message: options
});
return this._addCheck({
kind: "time",
precision: typeof options?.precision === "undefined" ? null : options?.precision,
...errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({
kind: "duration",
...errorUtil.errToObj(message)
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position: options?.position,
...errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message)
});
}
/**
* Equivalent to `.min(1)`
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }]
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isDate() {
return !!this._def.checks.find((ch) => ch.kind === "date");
}
get isTime() {
return !!this._def.checks.find((ch) => ch.kind === "time");
}
get isDuration() {
return !!this._def.checks.find((ch) => ch.kind === "duration");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isNANOID() {
return !!this._def.checks.find((ch) => ch.kind === "nanoid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get isCIDR() {
return !!this._def.checks.find((ch) => ch.kind === "cidr");
}
get isBase64() {
return !!this._def.checks.find((ch) => ch.kind === "base64");
}
get isBase64url() {
return !!this._def.checks.find((ch) => ch.kind === "base64url");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodString.create = (params) => {
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
}
var ZodNumber = class ZodNumber extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) input.data = Number(input.data);
if (this._getType(input) !== ZodParsedType.number) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx$1.parsedType
});
return INVALID;
}
let ctx = void 0;
const status = 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
});
status.dirty();
}
} else if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.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
});
status.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
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(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 ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
else if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
};
var ZodBigInt = class ZodBigInt extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
if (this._getType(input) !== ZodParsedType.bigint) return this._getInvalidInput(input);
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) if (check.kind === "min") {
if (check.inclusive ? input.data < check.value : input.data <= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if (check.kind === "max") {
if (check.inclusive ? input.data > check.value : input.data >= check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.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
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, {
kind,
value,
inclusive,
message: errorUtil.toString(message)
}]
});
}
_addCheck(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 ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max;
}
};
ZodBigInt.create = (params) => {
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = Boolean(input.data);
if (this._getType(input) !== 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?.coerce || false,
...processCreateParams(params)
});
};
var ZodDate = class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = new Date(input.data);
if (this._getType(input) !== ZodParsedType.date) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx$1.parsedType
});
return INVALID;
}
if (Number.isNaN(input.data.getTime())) {
addIssueToContext(this._getOrReturnCtx(input), { code: ZodIssueCode.invalid_date });
return INVALID;
}
const status = 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"
});
status.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"
});
status.dirty();
}
} else util.assertNever(check);
return {
status: status.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 ch of this._def.checks) if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
if (this._getType(input) !== 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)
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
if (this._getType(input) !== 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)
});
};
var ZodNull = class extends ZodType {
_parse(input) {
if (this._getType(input) !== 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)
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
if (this._getType(input) !== 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)
});
};
var ZodArray = class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) return Promise.all([...ctx.data].map((item, i$1) => {
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i$1));
})).then((result$1) => {
return ParseStatus.mergeArray(status, result$1);
});
const result = [...ctx.data].map((item, i$1) => {
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i$1));
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: {
value: minLength,
message: errorUtil.toString(message)
}
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: {
value: maxLength,
message: errorUtil.toString(message)
}
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: {
value: len,
message: errorUtil.toString(message)
}
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
};
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: () => newShape
});
} 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;
}
var ZodObject = class ZodObject extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
/**
* @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
* If you want to pass through unknown properties, use `.passthrough()` instead.
*/
this.nonstrict = this.passthrough;
/**
* @deprecated Use `.extend` instead
* */
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null) return this._cached;
const shape = this._def.shape();
this._cached = {
shape,
keys: util.objectKeys(shape)
};
return this._cached;
}
_parse(input) {
if (this._getType(input) !== ZodParsedType.object) {
const ctx$1 = this._getOrReturnCtx(input);
addIssueToContext(ctx$1, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx$1.parsedType
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
key: {
status: "valid",
value: key
},
value: {
status: "valid",
value: ctx.data[key]
}
});
else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) return Promise.resolve().then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
else return ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...message !== void 0 ? { errorMap: (issue, ctx) => {
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
return { message: defaultError };
} } : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation
})
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
return new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape()
}),
typeName: ZodFirstPartyTypeKind.ZodObject
});
}
setKey(key, schema) {
return this.augment({ [key]: schema });
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
omit(mask) {
const shape = {};
for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: () => shape
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) newShape[key] = fieldSchema;
else newShape[key] = fieldSchema.optional();
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
required(mask) {
const newShape = {};
for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
else {
let newField = this.shape[key];
while (newField instanceof ZodOptional) newField = newField._def.innerType;
newShape[key] = newField;
}
return new ZodObject({
...this._def,
shape: () => newShape
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) if (result.result.status === "valid") return result.result;
for (const result of results) if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
if (ctx.common.async) return Promise.all(options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if (result.status === "valid") return result;
else if (result.status === "dirty" && !dirty) dirty = {
result,
ctx: childCtx
};
if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues$1) => new ZodError(issues$1));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types$4, params) => {
return new ZodUnion({
options: types$4,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
};
const getDiscriminator = (type) => {
if (type instanceof ZodLazy) return getDiscriminator(type.schema);
else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
else if (type instanceof ZodLiteral) return [type.value];
else if (type instanceof ZodEnum) return type.options;
else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
else if (type instanceof ZodUndefined) return [void 0];
else if (type instanceof ZodNull) return [null];
else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
else return [];
};
var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator]
});
return INVALID;
}
if (ctx.common.async) return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
else return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
for (const value of discriminatorValues) {
if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) return {
valid: true,
data: a
};
else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) return { valid: false };
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) return { valid: false };
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return { valid: false };
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
} else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
valid: true,
data: a
};
else return { valid: false };
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
return {
status: status.value,
value: merged.data
};
};
if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})]).then(([left, right]) => handleParsed(left, right));
else return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
};
var ZodTuple = class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return INVALID;
}
if (!this._def.rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [...ctx.data].map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x) => !!x);
if (ctx.common.async) return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
else return ParseStatus.mergeArray(status, items);
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
};
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)
});
};
var ZodRecord = class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
else return ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") return INVALID;
if (key.status === "dirty" || value.status === "dirty") status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
};
var ZodSet = class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements$1) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements$1) {
if (element.status === "aborted") return INVALID;
if (element.status === "dirty") status.dirty();
parsedSet.add(element.value);
}
return {
status: status.value,
value: parsedSet
};
}
const elements = [...ctx.data.values()].map((item, i$1) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i$1)));
if (ctx.common.async) return Promise.all(elements).then((elements$1) => finalizeSet(elements$1));
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)
});
};
var ZodFunction = class ZodFunction extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
en_default
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
en_default
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
return await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
});
} else {
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
return this.parse(func);
}
strictImplement(func) {
return this.parse(func);
}
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)
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
return this._def.getter()._parse({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return INVALID;
}
return {
status: "valid",
value: input.data
};
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
var ZodEnum = class ZodEnum extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(this._def.values);
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) enumValues[val] = val;
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
...this._def,
...newDef
});
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return INVALID;
}
if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
if (!this._cache.has(input.data)) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return INVALID;
}
return OK((ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data)).then((data$1) => {
return this._def.type.parseAsync(data$1, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
});
}));
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) status.abort();
else status.dirty();
},
get path() {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) return Promise.resolve(processed).then(async (processed$1) => {
if (status.value === "aborted") return INVALID;
const result = await this._def.schema._parseAsync({
data: processed$1,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
});
else {
if (status.value === "aborted") return INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if (result.status === "aborted") return INVALID;
if (result.status === "dirty") return DIRTY(result.value);
if (status.value === "dirty") return DIRTY(result.value);
return result;
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) return Promise.resolve(result);
if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
executeRefinement(inner.value);
return {
status: status.value,
value: inner.value
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((inner) => {
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
return executeRefinement(inner.value).then(() => {
return {
status: status.value,
value: inner.value
};
});
});
}
if (effect.type === "transform") if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!isValid(base)) return INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
return {
status: status.value,
value: result
};
} else return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((base) => {
if (!isValid(base)) return INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
status: status.value,
value: result
}));
});
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: {
type: "preprocess",
transform: preprocess
},
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
if (this._getType(input) === 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)
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
if (this._getType(input) === 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)
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data$1 = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) data$1 = this._def.defaultValue();
return this._def.innerType._parse({
data: data$1,
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)
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: { ...newCtx }
});
if (isAsync(result)) return result.then((result$1) => {
return {
status: "valid",
value: result$1.status === "valid" ? result$1.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)
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
if (this._getType(input) !== 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)
});
};
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data$1 = ctx.data;
return this._def.type._parse({
data: data$1,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value
};
} else return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data$1) => {
if (isValid(data$1)) data$1.value = Object.freeze(data$1.value);
return data$1;
};
return isAsync(result) ? result.then((data$1) => freeze(data$1)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
};
const late = { object: ZodObject.lazycreate };
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind$2) {
ZodFirstPartyTypeKind$2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind$2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind$2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind$2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind$2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind$2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind$2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind$2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind$2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind$2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind$2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind$2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind$2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind$2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind$2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind$2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind$2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind$2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind$2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind$2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind$2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind$2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind$2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind$2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind$2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind$2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind$2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind$2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind$2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind$2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind$2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind$2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind$2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind$2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind$2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind$2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const stringType = ZodString.create;
const numberType = ZodNumber.create;
const nanType = ZodNaN.create;
const bigIntType = ZodBigInt.create;
const booleanType = ZodBoolean.create;
const dateType = ZodDate.create;
const symbolType = ZodSymbol.create;
const undefinedType = ZodUndefined.create;
const nullType = ZodNull.create;
const anyType = ZodAny.create;
const unknownType = ZodUnknown.create;
const neverType = ZodNever.create;
const voidType = ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
const strictObjectType = ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
const intersectionType = ZodIntersection.create;
const tupleType = ZodTuple.create;
const recordType = ZodRecord.create;
const mapType = ZodMap.create;
const setType = ZodSet.create;
const functionType = ZodFunction.create;
const lazyType = ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
const nativeEnumType = ZodNativeEnum.create;
const promiseType = ZodPromise.create;
const effectsType = ZodEffects.create;
const optionalType = ZodOptional.create;
const nullableType = ZodNullable.create;
const preprocessType = ZodEffects.createWithPreprocess;
const pipelineType = ZodPipeline.create;
//#endregion
//#region ../workers-shared/utils/types.ts
const InternalConfigSchema = objectType({
account_id: numberType().optional(),
script_id: numberType().optional(),
debug: booleanType().optional()
});
const StaticRoutingSchema = objectType({
user_worker: arrayType(stringType()),
asset_worker: arrayType(stringType()).optional()
});
const RouterConfigSchema = objectType({
invoke_user_worker_ahead_of_assets: booleanType().optional(),
static_routing: StaticRoutingSchema.optional(),
has_user_worker: booleanType().optional(),
...InternalConfigSchema.shape
});
const EyeballRouterConfigSchema = unionType([objectType({ limitedAssetsOnly: booleanType().optional() }), nullType()]);
const MetadataStaticRedirectEntry = objectType({
status: numberType(),
to: stringType(),
lineNumber: numberType()
});
const MetadataRedirectEntry = objectType({
status: numberType(),
to: stringType()
});
const MetadataStaticRedirects = recordType(MetadataStaticRedirectEntry);
const MetadataRedirects = recordType(MetadataRedirectEntry);
const MetadataHeaderEntry = objectType({
set: recordType(stringType()).optional(),
unset: arrayType(stringType()).optional()
});
const MetadataHeaders = recordType(MetadataHeaderEntry);
const RedirectsSchema = objectType({
version: literalType(1),
staticRules: MetadataStaticRedirects,
rules: MetadataRedirects
}).optional();
const HeadersSchema = objectType({
version: literalType(2),
rules: MetadataHeaders
}).optional();
const AssetConfigSchema = objectType({
compatibility_date: stringType().optional(),
compatibility_flags: arrayType(stringType()).optional(),
html_handling: enumType([
"auto-trailing-slash",
"force-trailing-slash",
"drop-trailing-slash",
"none"
]).optional(),
not_found_handling: enumType([
"single-page-application",
"404-page",
"none"
]).optional(),
redirects: RedirectsSchema,
headers: HeadersSchema,
has_static_routing: booleanType().optional(),
...InternalConfigSchema.shape
});
//#endregion
//#region src/asset-config.ts
/**
* Returns true if the `changedFile` matches one of the _headers or _redirects files,
* and the experimental support for these files is turned on.
*/
function hasAssetsConfigChanged(resolvedPluginConfig, resolvedViteConfig, changedFilePath) {
if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) return false;
return [getRedirectsConfigPath(resolvedViteConfig), getHeadersConfigPath(resolvedViteConfig)].includes(changedFilePath);
}
/**
* Computes the assets config that will be passed to Miniflare,
* taking into account whether experimental _headers and _redirects support is on.
*/
function getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedConfig) {
const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
const config = {
...resolvedPluginConfig.type === "assets-only" ? {
compatibility_date: resolvedPluginConfig.config.compatibility_date,
compatibility_flags: resolvedPluginConfig.config.compatibility_flags
} : {
...entryWorkerConfig?.compatibility_date ? { compatibility_date: entryWorkerConfig.compatibility_date } : {},
...entryWorkerConfig?.compatibility_flags ? { compatibility_flags: entryWorkerConfig.compatibility_flags } : {}
},
...assetsConfig,
has_static_routing: resolvedPluginConfig.type === "workers" && resolvedPluginConfig.staticRouting ? true : false
};
if (!resolvedPluginConfig.experimental?.headersAndRedirectsDevModeSupport) return config;
const logger = {
debug() {},
log(message) {
resolvedConfig.logger.info(message);
},
info(message) {
resolvedConfig.logger.info(message);
},
warn(message) {
resolvedConfig.logger.warn(message);
},
error(error) {
resolvedConfig.logger.error(error.message, { error });
}
};
const redirectsFile = getRedirectsConfigPath(resolvedConfig);
const redirectsContents = maybeGetFile(redirectsFile);
const redirects = redirectsContents && RedirectsSchema.parse(constructRedirects({
redirects: parseRedirects(redirectsContents, { htmlHandling: assetsConfig?.html_handling }),
redirectsFile,
logger
}).redirects);
const headersFile = getHeadersConfigPath(resolvedConfig);
const headersContents = maybeGetFile(headersFile);
const headers = headersContents && HeadersSchema.parse(constructHeaders({
headers: parseHeaders(headersContents),
headersFile,
logger
}).headers);
return {
...config,
...redirects ? { redirects } : {},
...headers ? { headers } : {}
};
}
function getRedirectsConfigPath(config) {
return nodePath.join(config.publicDir, REDIRECTS_FILENAME);
}
function getHeadersConfigPath(config) {
return nodePath.join(config.publicDir, HEADERS_FILENAME);
}
//#endregion
//#region src/build.ts
var import_picocolors$4 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
const CLIENT_FALLBACK_ENTRY_NAME = "__cloudflare_fallback_entry__";
function createBuildApp(resolvedPluginConfig) {
return async (builder) => {
const clientEnvironment = builder.environments.client;
assert(clientEnvironment, `No "client" environment`);
const defaultHtmlPath = nodePath.resolve(builder.config.root, "index.html");
const hasClientEntry = clientEnvironment.config.build.rollupOptions.input || fs$2.existsSync(defaultHtmlPath);
const workerEnvironments = [...resolvedPluginConfig.environmentNameToWorkerMap.keys()].map((environmentName) => {
const environment = builder.environments[environmentName];
assert(environment, `"${environmentName}" environment not found`);
return environment;
});
await Promise.all(workerEnvironments.map((environment) => builder.build(environment)));
if (resolvedPluginConfig.type === "assets-only") {
if (hasClientEntry) await builder.build(clientEnvironment);
else if (getHasPublicAssets(builder.config) || resolvedPluginConfig.prerenderWorkerEnvironmentName) await fallbackBuild(builder, clientEnvironment);
return;
}
const { entryWorkerEnvironmentName } = resolvedPluginConfig;
const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
assert(entryWorkerEnvironment, `No "${entryWorkerEnvironmentName}" environment`);
const entryWorkerBuildDirectory = nodePath.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir);
const importedAssetPaths = getImportedAssetPaths(loadViteManifest(entryWorkerBuildDirectory));
if (hasClientEntry) await builder.build(clientEnvironment);
else if (importedAssetPaths.size || getHasPublicAssets(builder.config) || resolvedPluginConfig.prerenderWorkerEnvironmentName) await fallbackBuild(builder, clientEnvironment);
else {
if (!satisfiesMinimumViteVersion("7.0.0")) removeAssetsField(entryWorkerBuildDirectory);
return;
}
const clientBuildDirectory = nodePath.resolve(builder.config.root, clientEnvironment.config.build.outDir);
const movedAssetPaths = [];
for (const assetPath of importedAssetPaths) {
const src$1 = nodePath.join(entryWorkerBuildDirectory, assetPath);
const dest = nodePath.join(clientBuildDirectory, assetPath);
if (!fs$2.existsSync(src$1)) continue;
if (fs$2.existsSync(dest)) fs$2.unlinkSync(src$1);
else {
const destDir = nodePath.dirname(dest);
fs$2.mkdirSync(destDir, { recursive: true });
fs$2.renameSync(src$1, dest);
movedAssetPaths.push(dest);
}
}
if (movedAssetPaths.length) builder.config.logger.info([`${import_picocolors$4.default.green("✓")} ${movedAssetPaths.length} asset${movedAssetPaths.length > 1 ? "s" : ""} moved from "${entryWorkerEnvironmentName}" to "client" build output.`, ...movedAssetPaths.map((assetPath) => import_picocolors$4.default.dim(nodePath.relative(builder.config.root, assetPath)))].join("\n"));
};
}
function getHasPublicAssets({ publicDir }) {
let hasPublicAssets = false;
if (publicDir) try {
if (fs$2.readdirSync(publicDir).length) hasPublicAssets = true;
} catch {}
return hasPublicAssets;
}
async function fallbackBuild(builder, environment) {
environment.config.build.rollupOptions = {
input: VIRTUAL_CLIENT_FALLBACK_ENTRY,
logLevel: "silent",
output: { entryFileNames: CLIENT_FALLBACK_ENTRY_NAME }
};
await builder.build(environment);
const fallbackEntryPath = nodePath.resolve(builder.config.root, environment.config.build.outDir, CLIENT_FALLBACK_ENTRY_NAME);
fs$2.unlinkSync(fallbackEntryPath);
}
function loadViteManifest(directory) {
const contents = fs$2.readFileSync(nodePath.resolve(directory, ".vite", "manifest.json"), "utf-8");
return JSON.parse(contents);
}
function getImportedAssetPaths(viteManifest) {
const assetPaths = Object.values(viteManifest).flatMap((chunk) => chunk.assets ?? []);
return new Set(assetPaths);
}
/**
* Used to remove the `assets` field from the entry Worker config if there are no assets
*/
function removeAssetsField(entryWorkerBuildDirectory) {
const entryWorkerConfigPath = nodePath.join(entryWorkerBuildDirectory, "wrangler.json");
const workerConfig = JSON.parse(fs$2.readFileSync(entryWorkerConfigPath, "utf-8"));
workerConfig.assets = void 0;
fs$2.writeFileSync(entryWorkerConfigPath, JSON.stringify(workerConfig));
}
//#endregion
//#region src/cloudflare-environment.ts
const MAIN_ENTRY_NAME = "index";
const webSocketUndefinedError = "The WebSocket is undefined";
function createHotChannel(webSocketContainer) {
const listenersMap = /* @__PURE__ */ new Map();
const client = { send(payload) {
const webSocket = webSocketContainer.webSocket;
assert(webSocket, webSocketUndefinedError);
webSocket.send(JSON.stringify(payload));
} };
function onMessage(event) {
const payload = JSON.parse(event.data.toString());
const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
for (const listener of listeners) listener(payload.data, client);
}
return {
send(payload) {
const webSocket = webSocketContainer.webSocket;
const message = JSON.stringify(payload);
if (!webSocket) {
webSocketContainer.messageBuffers ??= [];
webSocketContainer.messageBuffers.push(message);
return;
}
webSocket.send(message);
},
on(event, listener) {
const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
listeners.add(listener);
listenersMap.set(event, listeners);
},
off(event, listener) {
listenersMap.get(event)?.delete(listener);
},
listen() {
const webSocket = webSocketContainer.webSocket;
assert(webSocket, webSocketUndefinedError);
webSocket.addEventListener("message", onMessage);
},
close() {
const webSocket = webSocketContainer.webSocket;
assert(webSocket, webSocketUndefinedError);
webSocket.removeEventListener("message", onMessage);
}
};
}
var CloudflareDevEnvironment = class extends vite.DevEnvironment {
#webSocketContainer;
constructor(name, config) {
const webSocketContainer = {};
super(name, config, {
hot: true,
transport: createHotChannel(webSocketContainer)
});
this.#webSocketContainer = webSocketContainer;
}
async initRunner(miniflare, workerConfig, options) {
const response = await miniflare.dispatchFetch(new URL(INIT_PATH, UNKNOWN_HOST), { headers: {
[CoreHeaders.ROUTE_OVERRIDE]: workerConfig.name,
[WORKER_ENTRY_PATH_HEADER]: encodeURIComponent(workerConfig.main),
[IS_ENTRY_WORKER_HEADER]: String(options.isEntryWorker),
[ENVIRONMENT_NAME_HEADER]: this.name,
[IS_PARENT_ENVIRONMENT_HEADER]: String(options.isParentEnvironment),
upgrade: "websocket"
} });
assert(response.ok, `Failed to initialize module runner, error: ${await response.text()}`);
const webSocket = response.webSocket;
assert(webSocket, "Failed to establish WebSocket");
webSocket.accept();
this.#webSocketContainer.webSocket = webSocket;
if (this.#webSocketContainer.messageBuffers) {
for (const bufferedMessage of this.#webSocketContainer.messageBuffers) webSocket.send(bufferedMessage);
delete this.#webSocketContainer.messageBuffers;
}
}
async fetchWorkerExportTypes(miniflare, workerConfig) {
await this.depsOptimizer?.init();
return await (await miniflare.dispatchFetch(new URL(GET_EXPORT_TYPES_PATH, UNKNOWN_HOST), { headers: { [CoreHeaders.ROUTE_OVERRIDE]: workerConfig.name } })).json();
}
async fetchModule(id, importer, options) {
if (additionalModuleRE.test(id)) return {
externalize: id,
type: "module"
};
return super.fetchModule(id, importer, options);
}
};
const cloudflareBuiltInModules = [
"cloudflare:email",
"cloudflare:node",
"cloudflare:sockets",
"cloudflare:workers",
"cloudflare:workflows"
];
const defaultConditions = [
"workerd",
"worker",
"module",
"browser"
];
const target = "es2024";
const resolveExtensions = [
".mjs",
".js",
".mts",
".ts",
".jsx",
".tsx",
".json",
".cjs",
".cts",
".ctx"
];
function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, environmentName, isEntryWorker, isParentEnvironment, hasNodeJsCompat: hasNodeJsCompat$1 }) {
const rollupOptions = isParentEnvironment ? {
input: { [MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY },
preserveEntrySignatures: "strict"
} : {};
const define$1 = getProcessEnvReplacements(hasNodeJsCompat$1, mode);
return {
resolve: {
noExternal: true,
conditions: [...defaultConditions, "development|production"],
builtins: [...cloudflareBuiltInModules]
},
define: define$1,
dev: { createEnvironment(name, config) {
if (!config.plugins.some((plugin) => plugin.name === "vite-plugin-cloudflare:dev" && plugin.configureServer !== void 0)) return vite.createRunnableDevEnvironment(name, config);
return new CloudflareDevEnvironment(name, config);
} },
build: {
createEnvironment(name, config) {
return new vite.BuildEnvironment(name, config);
},
target,
emitAssets: true,
manifest: isEntryWorker,
outDir: getOutputDirectory(userConfig, environmentName),
copyPublicDir: false,
ssr: true,
...isRolldown ? { rolldownOptions: {
...rollupOptions,
platform: "neutral",
resolve: { extensions: resolveExtensions }
} } : { rollupOptions }
},
optimizeDeps: {
noDiscovery: false,
ignoreOutdatedRequests: true,
entries: vite.normalizePath(workerConfig.main),
exclude: [
...cloudflareBuiltInModules,
...nonPrefixedNodeModules,
...nonPrefixedNodeModules.map((module$1) => `node:${module$1}`),
...[
"node:sea",
"node:sqlite",
"node:test",
"node:test/reporters"
]
],
...isRolldown ? { rolldownOptions: {
platform: "neutral",
resolve: {
conditionNames: [...defaultConditions, "development"],
extensions: resolveExtensions
},
transform: {
target,
define: define$1
},
plugins: [vite.esmExternalRequirePlugin({
external: [nodeBuiltinsRE],
skipDuplicateCheck: true
})]
} } : { esbuildOptions: {
platform: "neutral",
conditions: [...defaultConditions, "development"],
resolveExtensions,
target,
define: define$1
} }
},
keepProcessEnv: true
};
}
/**
* Gets `process.env` replacement values.
* `process.env.NODE_ENV` is always replaced.
* `process.env` is replaced with an empty object if `nodejs_compat` is not enabled
* @param hasNodeJsCompat - whether `nodejs_compat` is enabled
* @param mode - the Vite mode
* @returns replacement values
*/
function getProcessEnvReplacements(hasNodeJsCompat$1, mode) {
const nodeEnv = process.env.NODE_ENV || mode;
const nodeEnvReplacements = {
"process.env.NODE_ENV": JSON.stringify(nodeEnv),
"global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
"globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
};
return hasNodeJsCompat$1 ? nodeEnvReplacements : {
...nodeEnvReplacements,
"process.env": "{}",
"global.process.env": "{}",
"globalThis.process.env": "{}"
};
}
function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
const initPromises = [...resolvedPluginConfig.environmentNameToWorkerMap].flatMap(([environmentName, worker]) => {
debuglog("Initializing worker:", worker.config.name);
const isEntryWorker = environmentName === resolvedPluginConfig.entryWorkerEnvironmentName;
const childEnvironmentNames = resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.get(environmentName) ?? [];
return [viteDevServer.environments[environmentName].initRunner(miniflare, worker.config, {
isEntryWorker,
isParentEnvironment: true
}), ...childEnvironmentNames.map((childEnvironmentName) => {
debuglog("Initializing child environment:", childEnvironmentName);
return viteDevServer.environments[childEnvironmentName].initRunner(miniflare, worker.config, {
isEntryWorker: false,
isParentEnvironment: false
});
})];
});
return Promise.all(initPromises);
}
//#endregion
//#region src/dev-vars.ts
/**
* Gets any variables with which to augment the Worker config in preview mode.
*
* Calls `unstable_getVarsForDev` with the current Cloudflare environment to get local dev variables from the .dev.vars/.env/process.env.
* When `secrets` is defined in the Worker config, only declared secrets are loaded.
*/
function getLocalDevVarsForPreview(config, cloudflareEnv) {
const dotDevDotVars = wrangler.unstable_getVarsForDev(config.configPath, void 0, {}, cloudflareEnv, false, config.secrets);
const dotDevDotVarsEntries = Array.from(Object.entries(dotDevDotVars));
if (dotDevDotVarsEntries.length > 0) return dotDevDotVarsEntries.map(([key, { value }]) => {
return `${key}=${quoteForDotenv(value?.toString() ?? "")}\n`;
}).join("");
}
/**
* Quote a value so that wrangler reads it back unchanged when it parses
* `dist/<env>/.dev.vars` at preview time.
*
* Strategy: To quote the string pick the first quote character that does not
* appear in the value (single → backtick → double). Throw if a value cannot
* be losslessly serialized rather than silently corrupting it.
*
* @internal exported for tests
*/
function quoteForDotenv(value) {
if (!value.includes("'")) return `'${value}'`;
if (!value.includes("`")) return `\`${value}\``;
if (!value.includes("\"") && !/[\\\n\r]/.test(value)) return `"${value}"`;
throw new Error("Unable to serialize value to .dev.vars: contains every supported quote character or unsafe escape sequence.");
}
/**
* Returns `true` if the `changedFile` matches a `.dev.vars` or `.env` file.
*/
function hasLocalDevVarsFileChanged({ configPaths, cloudflareEnv }, changedFilePath) {
return [...configPaths].some((configPath) => {
const configDir = nodePath.dirname(configPath);
return [
".dev.vars",
".env",
...cloudflareEnv ? [`.dev.vars.${cloudflareEnv}`, `.env.${cloudflareEnv}`] : []
].some((localDevFile) => changedFilePath === nodePath.join(configDir, localDevFile));
});
}
//#endregion
//#region src/vite-config.ts
/**
* Throws an error if Worker environments include configuration options that are incompatible with the plugin.
*/
function validateWorkerEnvironmentOptions(resolvedPluginConfig, resolvedViteConfig) {
const disallowedEnvironmentOptionsMap = /* @__PURE__ */ new Map();
for (const environmentName of resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
const environmentOptions = resolvedViteConfig.environments[environmentName];
assert(environmentOptions, `Missing environment config for "${environmentName}"`);
const { resolve: resolve$4 } = environmentOptions;
const disallowedEnvironmentOptions = {};
if (resolve$4.external === true || resolve$4.external.length) disallowedEnvironmentOptions.resolveExternal = resolve$4.external;
if (Object.keys(disallowedEnvironmentOptions).length) disallowedEnvironmentOptionsMap.set(environmentName, disallowedEnvironmentOptions);
}
if (disallowedEnvironmentOptionsMap.size) {
const errorMessage = `The following environment options are incompatible with the Cloudflare Vite plugin:\n${[...disallowedEnvironmentOptionsMap].map(([environmentName, disallowedEnvironmentOptions]) => disallowedEnvironmentOptions.resolveExternal && ` - "${environmentName}" environment: \`resolve.external\`: ${JSON.stringify(disallowedEnvironmentOptions.resolveExternal)}\n`).join("")}To resolve this issue, avoid setting \`resolve.external\` in your Cloudflare Worker environments.\n`;
throw new Error(errorMessage);
}
}
//#endregion
//#region src/plugins/config.ts
/**
* Plugin to handle configuration and config file watching
*/
const configPlugin = createPlugin("config", (ctx) => {
return {
config(userConfig, env$1) {
if (ctx.resolvedPluginConfig.type === "preview") return { appType: "custom" };
if (!ctx.hasShownWorkerConfigWarnings) {
ctx.setHasShownWorkerConfigWarnings(true);
const workerConfigWarnings = getWarningForWorkersConfigs(ctx.resolvedPluginConfig.rawConfigs);
if (workerConfigWarnings) console.warn(workerConfigWarnings);
}
return {
appType: "custom",
server: {
allowedHosts: getAllowedHosts(ctx.getTunnelHostnames(), userConfig.server?.allowedHosts),
fs: { deny: [...[
".env",
".env.*",
".npmrc",
".yarnrc",
".yarnrc.yml",
"*.{crt,pem,key,pfx,p12,p8,jks}",
"**/.git/**",
".dev.vars",
".dev.vars.*",
"**/.wrangler/**"
], ...Array.from(ctx.resolvedPluginConfig.configPaths, (configPath) => normalizePath(configPath))] }
},
environments: getEnvironmentsConfig(ctx, userConfig, env$1.mode),
builder: { buildApp: userConfig.builder?.buildApp ?? createBuildApp(ctx.resolvedPluginConfig) }
};
},
configResolved(resolvedViteConfig) {
ctx.setResolvedViteConfig(resolvedViteConfig);
if (ctx.resolvedPluginConfig.type !== "preview") validateWorkerEnvironmentOptions(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
},
buildStart() {
ctx.setHasShownWorkerConfigWarnings(false);
},
configureServer(viteDevServer) {
const configChangedHandler = async (changedFilePath) => {
assertIsNotPreview(ctx);
if (ctx.resolvedPluginConfig.configPaths.has(changedFilePath) || hasLocalDevVarsFileChanged(ctx.resolvedPluginConfig, changedFilePath) || hasAssetsConfigChanged(ctx.resolvedPluginConfig, ctx.resolvedViteConfig, changedFilePath)) {
debuglog("Config changed: " + changedFilePath);
viteDevServer.watcher.off("change", configChangedHandler);
debuglog("Restarting dev server and aborting previous setup");
await viteDevServer.restart();
}
};
viteDevServer.watcher.on("change", configChangedHandler);
},
buildApp: {
order: "post",
async handler(builder) {
if (ctx.resolvedPluginConfig.type !== "workers") return;
const workerEnvironments = [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.keys()].map((environmentName) => {
const environment = builder.environments[environmentName];
assert(environment, `"${environmentName}" environment not found`);
return environment;
});
await Promise.all(workerEnvironments.filter((environment) => !environment.isBuilt).map((environment) => builder.build(environment)));
const { entryWorkerEnvironmentName } = ctx.resolvedPluginConfig;
const entryWorkerEnvironment = builder.environments[entryWorkerEnvironmentName];
assert(entryWorkerEnvironment, `No "${entryWorkerEnvironmentName}" environment`);
const entryWorkerBuildDirectory = nodePath.resolve(builder.config.root, entryWorkerEnvironment.config.build.outDir);
if (!builder.environments.client?.isBuilt) removeAssetsField(entryWorkerBuildDirectory);
}
}
};
});
/**
* Generates the environment configuration for all Worker environments.
*/
function getEnvironmentsConfig(ctx, userConfig, mode) {
assertIsNotPreview(ctx);
if (!ctx.resolvedPluginConfig.environmentNameToWorkerMap.size) return;
return {
...Object.fromEntries([...ctx.resolvedPluginConfig.environmentNameToWorkerMap].flatMap(([environmentName, worker]) => {
const childEnvironmentNames = ctx.resolvedPluginConfig.environmentNameToChildEnvironmentNamesMap.get(environmentName) ?? [];
const sharedOptions = {
workerConfig: worker.config,
userConfig,
mode,
hasNodeJsCompat: ctx.getNodeJsCompat(environmentName) !== void 0
};
const isEntryWorker = environmentName === ctx.resolvedPluginConfig.prerenderWorkerEnvironmentName || ctx.resolvedPluginConfig.type === "workers" && environmentName === ctx.resolvedPluginConfig.entryWorkerEnvironmentName;
return [[environmentName, createCloudflareEnvironmentOptions({
...sharedOptions,
environmentName,
isEntryWorker,
isParentEnvironment: true
})], ...childEnvironmentNames.map((childEnvironmentName) => [childEnvironmentName, createCloudflareEnvironmentOptions({
...sharedOptions,
environmentName: childEnvironmentName,
isEntryWorker: false,
isParentEnvironment: false
})])];
})),
client: {
build: { outDir: getOutputDirectory(userConfig, "client") },
optimizeDeps: { exclude: [...cloudflareBuiltInModules] }
}
};
}
function getAllowedHosts(tunnelHostnames, userAllowedHosts) {
if (tunnelHostnames.length === 0 || userAllowedHosts === true) return userAllowedHosts;
return Array.from(new Set([...userAllowedHosts ?? [], ...tunnelHostnames]));
}
//#endregion
//#region src/debug.ts
var import_picocolors$3 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
const DEBUG_PATH = "/__debug";
const DEFAULT_INSPECTOR_PORT = 9229;
/**
* Gets the inspector port option that should be passed to Miniflare based on the user's plugin config
*/
async function getInputInspectorPort(ctx, viteServer) {
if (ctx.resolvedPluginConfig.inspectorPort === void 0 || ctx.resolvedPluginConfig.inspectorPort === 0) {
const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
if (resolvedInspectorPort !== null) return resolvedInspectorPort;
}
const inputInspectorPort = ctx.resolvedPluginConfig.inspectorPort ?? await getFirstAvailablePort(DEFAULT_INSPECTOR_PORT);
if (ctx.resolvedPluginConfig.inspectorPort === void 0 && inputInspectorPort !== DEFAULT_INSPECTOR_PORT) viteServer.config.logger.warn(import_picocolors$3.default.dim(`Default inspector port ${DEFAULT_INSPECTOR_PORT} not available, using ${inputInspectorPort} instead\n`));
return inputInspectorPort;
}
function getFirstAvailablePort(start) {
return getPorts({ port: portNumbers(start, 65535) });
}
/**
* Modifies the URL printing logic to also include a URL that developers can use to open DevTools to debug their Worker(s)
*/
function addDebugToVitePrintUrls(server) {
const originalPrintUrls = server.printUrls;
server.printUrls = () => {
originalPrintUrls();
const localUrl = server.resolvedUrls?.local[0];
if (localUrl) {
const { protocol, hostname, port } = new URL(localUrl);
const colorDebugUrl = (url) => import_picocolors$3.default.dim(import_picocolors$3.default.yellow(url.replace(/:(\d+)\//, (_, portNumber) => `:${import_picocolors$3.default.bold(portNumber)}/`)));
server.config.logger.info(` ${import_picocolors$3.default.green("➜")} ${import_picocolors$3.default.bold("Debug")}: ${colorDebugUrl(`${protocol}//${hostname}:${port}${DEBUG_PATH}`)}`);
}
};
}
/**
* Generate HTML that comprises a single script that:
* - redirects the page to the DevTools for debugging the first available Worker
* - opens tabs to the DevTools for all the remaining workers if any
*
* Note: this works based on the Miniflare inspector proxy logic (where Workers are available via
* their names)
*/
function getDebugPathHtml(workerNames, inspectorPort) {
assert(workerNames.length >= 1, "no workers present to debug");
const workerDevtoolsUrls = workerNames.map((workerName) => {
const localhost = `localhost:${inspectorPort}/${workerName}`;
return `https://devtools.devprod.cloudflare.dev/js_app?${new URLSearchParams({
theme: "systemPreferred",
debugger: "true",
ws: localhost,
domain: workerName
})}`;
});
return `
<script>
const workerUrls = ${JSON.stringify(workerDevtoolsUrls)};
const [firstUrl, ...rest] = workerUrls;
for (const workerUrl of rest) {
// open new tabs for the devtools of the various workers
window.open(workerUrl);
}
// redirect the current tab to the devtools of the first worker
window.location.replace(firstUrl);
<\/script>
`;
}
//#endregion
//#region src/plugins/debug.ts
/**
* Plugin to provide a `/__debug` path for debugging Workers
*/
const debugPlugin = createPlugin("debug", (ctx) => {
return {
enforce: "pre",
configureServer(viteDevServer) {
assertIsNotPreview(ctx);
if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
if (ctx.resolvedPluginConfig.type === "workers" && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(viteDevServer);
const workerNames = ctx.resolvedPluginConfig.type === "workers" ? [...ctx.resolvedPluginConfig.environmentNameToWorkerMap.values()].map((worker) => worker.config.name) : [];
viteDevServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
if (resolvedInspectorPort) {
const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
res.setHeader("Content-Type", "text/html");
res.end(html);
} else next();
});
},
async configurePreviewServer(vitePreviewServer) {
assertIsPreview(ctx);
if (!!process.env.VSCODE_INSPECTOR_OPTIONS) return;
if (ctx.resolvedPluginConfig.workers.length >= 1 && ctx.resolvedPluginConfig.inspectorPort !== false) addDebugToVitePrintUrls(vitePreviewServer);
const workerNames = ctx.resolvedPluginConfig.workers.map((worker) => {
assert(worker.name, "Expected the Worker to have a name");
return worker.name;
});
vitePreviewServer.middlewares.use(DEBUG_PATH, async (_, res, next) => {
const resolvedInspectorPort = await ctx.getResolvedInspectorPort();
if (resolvedInspectorPort) {
const html = getDebugPathHtml(workerNames, resolvedInspectorPort);
res.setHeader("Content-Type", "text/html");
res.end(html);
} else next();
});
}
};
});
//#endregion
//#region ../containers-shared/src/client/core/ApiError.ts
var ApiError = class extends Error {
url;
status;
statusText;
body;
request;
constructor(request$2, 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 = request$2;
}
};
//#endregion
//#region ../containers-shared/src/client/core/CancelablePromise.ts
/* istanbul ignore file */
var CancelError = class extends Error {
constructor(message) {
super(message);
this.name = "CancelError";
}
get isCancelled() {
return true;
}
};
var CancelablePromise = class {
#isResolved;
#isRejected;
#isCancelled;
#cancelHandlers;
#promise;
#resolve;
#reject;
constructor(executor) {
this.#isResolved = false;
this.#isRejected = false;
this.#isCancelled = false;
this.#cancelHandlers = [];
this.#promise = new Promise((resolve$4, reject) => {
this.#resolve = resolve$4;
this.#reject = reject;
const onResolve = (value) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) return;
this.#isResolved = true;
this.#resolve?.(value);
};
const onReject = (reason) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) return;
this.#isRejected = true;
this.#reject?.(reason);
};
const onCancel = (cancelHandler) => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) return;
this.#cancelHandlers.push(cancelHandler);
};
Object.defineProperty(onCancel, "isResolved", { get: () => this.#isResolved });
Object.defineProperty(onCancel, "isRejected", { get: () => this.#isRejected });
Object.defineProperty(onCancel, "isCancelled", { get: () => this.#isCancelled });
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 (error) {
console.warn("Cancellation threw an error", error);
return;
}
this.#cancelHandlers.length = 0;
this.#reject?.(new CancelError("Request aborted"));
}
get isCancelled() {
return this.#isCancelled;
}
};
//#endregion
//#region ../containers-shared/src/client/core/OpenAPI.ts
const 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
};
//#endregion
//#region ../containers-shared/src/client/core/request.ts
/* istanbul ignore file */
const isDefined = (value) => {
return value !== void 0 && value !== null;
};
const isString = (value) => {
return typeof value === "string";
};
const isStringWithValue = (value) => {
return isString(value) && value !== "";
};
const isBlob = (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]);
};
const base64 = (str) => {
try {
return btoa(str);
} catch (err) {
return Buffer.from(str).toString("base64");
}
};
const getQueryString = (params) => {
const qs = [];
const append = (key, value) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
};
const process$2 = (key, value) => {
if (isDefined(value)) if (Array.isArray(value)) value.forEach((v) => {
process$2(key, v);
});
else if (typeof value === "object") Object.entries(value).forEach(([k, v]) => {
process$2(`${key}[${k}]`, v);
});
else append(key, value);
};
Object.entries(params).forEach(([key, value]) => {
process$2(key, value);
});
if (qs.length > 0) return `?${qs.join("&")}`;
return "";
};
const getUrl = (config, options) => {
const encoder$1 = config.ENCODE_PATH || encodeURI;
const path$2 = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group) => {
if (options.path?.hasOwnProperty(group)) return encoder$1(String(options.path[group]));
return substring;
});
const url = `${config.BASE}${path$2}`;
if (options.query) return `${url}${getQueryString(options.query)}`;
return url;
};
const getFormData = (options) => {
if (options.formData) {
const formData = new FormData();
const process$2 = async (key, value) => {
if (isString(value)) formData.append(key, value);
else formData.append(key, JSON.stringify(value));
};
Object.entries(options.formData).filter(([_, value]) => isDefined(value)).forEach(([key, value]) => {
if (Array.isArray(value)) value.forEach((v) => process$2(key, v));
else process$2(key, value);
});
return formData;
}
};
const resolve$2 = async (options, resolver) => {
if (typeof resolver === "function") return resolver(options);
return resolver;
};
const getHeaders = async (config, options) => {
const token = await resolve$2(options, config.TOKEN);
const username = await resolve$2(options, config.USERNAME);
const password = await resolve$2(options, config.PASSWORD);
const additionalHeaders = await resolve$2(options, config.HEADERS);
const headers = Object.entries({
Accept: "application/json",
...additionalHeaders,
...options.headers
}).filter(([_, value]) => isDefined(value)).reduce((headers$1, [key, value]) => ({
...headers$1,
[key]: String(value)
}), {});
if (isStringWithValue(token)) headers["Authorization"] = `Bearer ${token}`;
if (isStringWithValue(username) && isStringWithValue(password)) headers["Authorization"] = `Basic ${base64(`${username}:${password}`)}`;
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);
};
const getRequestBody = (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);
};
const isResponseSchemaV4 = (config, _options) => {
return config.BASE.endsWith("/containers");
};
const parseResponseSchemaV4 = (url, response, responseHeader, responseBody) => {
const fetchResult = typeof responseBody === "object" ? responseBody : JSON.parse(responseBody);
const ok = response.ok && fetchResult.success;
let result;
if (ok) if (fetchResult.result !== void 0) result = fetchResult.result;
else result = {};
else result = { error: fetchResult.errors?.[0]?.message };
return {
url,
ok,
status: response.status,
statusText: response.statusText,
body: responseHeader ?? result
};
};
const sendRequest = async (config, options, url, body, formData, headers, onCancel) => {
const controller = new AbortController();
const request$2 = {
headers,
body: body ?? formData,
method: options.method,
signal: controller.signal
};
if (config.WITH_CREDENTIALS) request$2.credentials = config.CREDENTIALS;
onCancel(() => controller.abort());
return await fetch(url, request$2);
};
const getResponseHeader = (response, responseHeader) => {
if (responseHeader) {
const content = response.headers.get(responseHeader);
if (isString(content)) return content;
}
};
const getResponseBody = async (response) => {
if (response.status !== 204) try {
const contentType = response.headers.get("Content-Type");
if (contentType) if (["application/json", "application/problem+json"].some((type) => contentType.toLowerCase().startsWith(type))) return await response.json();
else return await response.text();
} catch (error) {
console.error(error);
}
};
const catchErrorCodes = (options, result) => {
const error = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable",
...options.errors
}[result.status];
if (error) throw new ApiError(options, result, error);
if (!result.ok) throw new ApiError(options, result, "Generic Error");
};
/**
* Shared HTTP execution: builds URL, headers, body, sends the request,
* and returns the raw response components for further processing.
* Returns null if the request was cancelled before sending.
*/
const executeRequest = async (config, options, onCancel) => {
const url = getUrl(config, options);
const formData = getFormData(options);
const body = getRequestBody(options);
const headers = await getHeaders(config, options);
debugLogRequest(config, url, headers, formData ?? body ?? {});
if (onCancel.isCancelled) return null;
const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
return {
url,
response,
responseBody: await getResponseBody(response),
responseHeader: getResponseHeader(response, options.responseHeader)
};
};
/**
* Build an ApiResult from the raw response, handling V4 schema parsing.
*/
const buildApiResult = (config, options, req) => {
if (isResponseSchemaV4(config, options)) return parseResponseSchemaV4(req.url, req.response, req.responseHeader, req.responseBody);
return {
url: req.url,
ok: req.response.ok,
status: req.response.status,
statusText: req.response.statusText,
body: req.responseHeader ?? req.responseBody
};
};
/**
* Request method
* @param config The OpenAPI configuration object
* @param options The request options from the service
* @returns CancelablePromise<T>
* @throws ApiError
*/
const request = (config, options) => {
return new CancelablePromise(async (resolve$4, reject, onCancel) => {
try {
const req = await executeRequest(config, options, onCancel);
if (!req) return;
const result = buildApiResult(config, options, req);
debugLogResponse(config, result);
catchErrorCodes(options, result);
resolve$4(result.body);
} catch (error) {
reject(error);
}
});
};
const debugLogRequest = async (config, url, headers, body) => {
config.LOGGER?.debug(`-- START CF API REQUEST: ${url}`);
const logHeaders = new Headers(headers);
logHeaders.delete("Authorization");
config.LOGGER?.debugWithSanitization("HEADERS:", JSON.stringify(logHeaders, 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");
};
const debugLogResponse = (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");
};
//#endregion
//#region ../containers-shared/src/client/models/ApplicationRollout.ts
let ApplicationRollout;
(function(_ApplicationRollout) {
_ApplicationRollout.kind = /* @__PURE__ */ function(kind) {
kind["FULL_AUTO"] = "full_auto";
kind["FULL_MANUAL"] = "full_manual";
kind["DURABLE_OBJECTS_AUTO"] = "durable_objects_auto";
return kind;
}({});
_ApplicationRollout.strategy = /* @__PURE__ */ function(strategy) {
strategy["ROLLING"] = "rolling";
return strategy;
}({});
_ApplicationRollout.status = /* @__PURE__ */ function(status) {
status["PENDING"] = "pending";
status["PROGRESSING"] = "progressing";
status["COMPLETED"] = "completed";
status["REVERTED"] = "reverted";
status["REPLACED"] = "replaced";
return status;
}({});
})(ApplicationRollout || (ApplicationRollout = {}));
//#endregion
//#region ../containers-shared/src/client/models/BadRequestWithCodeError.ts
let BadRequestWithCodeError;
(function(_BadRequestWithCodeError) {
_BadRequestWithCodeError.error = /* @__PURE__ */ function(error) {
error["VALIDATE_INPUT"] = "VALIDATE_INPUT";
return error;
}({});
})(BadRequestWithCodeError || (BadRequestWithCodeError = {}));
//#endregion
//#region ../containers-shared/src/client/models/CreateApplicationRolloutRequest.ts
let CreateApplicationRolloutRequest;
(function(_CreateApplicationRolloutRequest) {
_CreateApplicationRolloutRequest.strategy = /* @__PURE__ */ function(strategy) {
strategy["ROLLING"] = "rolling";
return strategy;
}({});
_CreateApplicationRolloutRequest.step_percentage = /* @__PURE__ */ function(step_percentage) {
step_percentage[step_percentage["_5"] = 5] = "_5";
step_percentage[step_percentage["_10"] = 10] = "_10";
step_percentage[step_percentage["_20"] = 20] = "_20";
step_percentage[step_percentage["_25"] = 25] = "_25";
step_percentage[step_percentage["_50"] = 50] = "_50";
step_percentage[step_percentage["_100"] = 100] = "_100";
return step_percentage;
}({});
_CreateApplicationRolloutRequest.kind = /* @__PURE__ */ function(kind) {
kind["FULL_AUTO"] = "full_auto";
kind["FULL_MANUAL"] = "full_manual";
return kind;
}({});
})(CreateApplicationRolloutRequest || (CreateApplicationRolloutRequest = {}));
//#endregion
//#region ../containers-shared/src/client/models/DeploymentNotFoundError.ts
let DeploymentNotFoundError;
(function(_DeploymentNotFoundError) {
_DeploymentNotFoundError.error = /* @__PURE__ */ function(error) {
error["DEPLOYMENT_NOT_FOUND"] = "DEPLOYMENT_NOT_FOUND";
return error;
}({});
})(DeploymentNotFoundError || (DeploymentNotFoundError = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryAlreadyExistsError.ts
let ImageRegistryAlreadyExistsError;
(function(_ImageRegistryAlreadyExistsError) {
_ImageRegistryAlreadyExistsError.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_ALREADY_EXISTS"] = "IMAGE_REGISTRY_ALREADY_EXISTS";
return error;
}({});
})(ImageRegistryAlreadyExistsError || (ImageRegistryAlreadyExistsError = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryIsPublic.ts
let ImageRegistryIsPublic;
(function(_ImageRegistryIsPublic) {
_ImageRegistryIsPublic.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_IS_PUBLIC"] = "IMAGE_REGISTRY_IS_PUBLIC";
return error;
}({});
})(ImageRegistryIsPublic || (ImageRegistryIsPublic = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryNotAllowedError.ts
let ImageRegistryNotAllowedError;
(function(_ImageRegistryNotAllowedError) {
_ImageRegistryNotAllowedError.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_NOT_ALLOWED"] = "IMAGE_REGISTRY_NOT_ALLOWED";
return error;
}({});
})(ImageRegistryNotAllowedError || (ImageRegistryNotAllowedError = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryNotFoundError.ts
let ImageRegistryNotFoundError;
(function(_ImageRegistryNotFoundError) {
_ImageRegistryNotFoundError.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_NOT_FOUND"] = "IMAGE_REGISTRY_NOT_FOUND";
return error;
}({});
})(ImageRegistryNotFoundError || (ImageRegistryNotFoundError = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryPermissions.ts
/* istanbul ignore file */
let ImageRegistryPermissions = /* @__PURE__ */ function(ImageRegistryPermissions$1) {
ImageRegistryPermissions$1["PULL"] = "pull";
ImageRegistryPermissions$1["PUSH"] = "push";
ImageRegistryPermissions$1["LIBRARY_PUSH"] = "library_push";
return ImageRegistryPermissions$1;
}({});
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryProtocolAlreadyExists.ts
let ImageRegistryProtocolAlreadyExists;
(function(_ImageRegistryProtocolAlreadyExists) {
_ImageRegistryProtocolAlreadyExists.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS"] = "IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS";
return error;
}({});
})(ImageRegistryProtocolAlreadyExists || (ImageRegistryProtocolAlreadyExists = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryProtocolIsReferencedError.ts
let ImageRegistryProtocolIsReferencedError;
(function(_ImageRegistryProtocolIsReferencedError) {
_ImageRegistryProtocolIsReferencedError.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_PROTO_IS_REFERENCED"] = "IMAGE_REGISTRY_PROTO_IS_REFERENCED";
return error;
}({});
})(ImageRegistryProtocolIsReferencedError || (ImageRegistryProtocolIsReferencedError = {}));
//#endregion
//#region ../containers-shared/src/client/models/ImageRegistryProtocolNotFound.ts
let ImageRegistryProtocolNotFound;
(function(_ImageRegistryProtocolNotFound) {
_ImageRegistryProtocolNotFound.error = /* @__PURE__ */ function(error) {
error["IMAGE_REGISTRY_PROTOCOL_NOT_FOUND"] = "IMAGE_REGISTRY_PROTOCOL_NOT_FOUND";
return error;
}({});
})(ImageRegistryProtocolNotFound || (ImageRegistryProtocolNotFound = {}));
//#endregion
//#region ../containers-shared/src/client/models/ProvisionerConfiguration.ts
let ProvisionerConfiguration;
(function(_ProvisionerConfiguration) {
_ProvisionerConfiguration.type = /* @__PURE__ */ function(type) {
type["NONE"] = "none";
type["CLOUDINIT"] = "cloudinit";
return type;
}({});
})(ProvisionerConfiguration || (ProvisionerConfiguration = {}));
//#endregion
//#region ../containers-shared/src/client/models/RolloutStep.ts
let RolloutStep;
(function(_RolloutStep) {
_RolloutStep.status = /* @__PURE__ */ function(status) {
status["PENDING"] = "pending";
status["PROGRESSING"] = "progressing";
status["REVERTING"] = "reverting";
status["COMPLETED"] = "completed";
status["REVERTED"] = "reverted";
return status;
}({});
})(RolloutStep || (RolloutStep = {}));
//#endregion
//#region ../containers-shared/src/client/models/SecretNameAlreadyExists.ts
let SecretNameAlreadyExists;
(function(_SecretNameAlreadyExists) {
_SecretNameAlreadyExists.error = /* @__PURE__ */ function(error) {
error["SECRET_NAME_ALREADY_EXISTS"] = "SECRET_NAME_ALREADY_EXISTS";
return error;
}({});
})(SecretNameAlreadyExists || (SecretNameAlreadyExists = {}));
//#endregion
//#region ../containers-shared/src/client/models/SecretNotFound.ts
let SecretNotFound;
(function(_SecretNotFound) {
_SecretNotFound.error = /* @__PURE__ */ function(error) {
error["SECRET_NAME_NOT_FOUND"] = "SECRET_NAME_NOT_FOUND";
return error;
}({});
})(SecretNotFound || (SecretNotFound = {}));
//#endregion
//#region ../containers-shared/src/client/models/SSHPublicKeyNotFoundError.ts
let SSHPublicKeyNotFoundError;
(function(_SSHPublicKeyNotFoundError) {
_SSHPublicKeyNotFoundError.error = /* @__PURE__ */ function(error) {
error["SSH_PUBLIC_KEY_NOT_FOUND"] = "SSH_PUBLIC_KEY_NOT_FOUND";
return error;
}({});
})(SSHPublicKeyNotFoundError || (SSHPublicKeyNotFoundError = {}));
//#endregion
//#region ../containers-shared/src/client/models/UpdateApplicationRolloutRequest.ts
let UpdateApplicationRolloutRequest;
(function(_UpdateApplicationRolloutRequest) {
_UpdateApplicationRolloutRequest.action = /* @__PURE__ */ function(action) {
action["NEXT"] = "next";
action["PREVIOUS"] = "previous";
action["REVERT"] = "revert";
return action;
}({});
})(UpdateApplicationRolloutRequest || (UpdateApplicationRolloutRequest = {}));
//#endregion
//#region ../containers-shared/src/client/services/ImageRegistriesService.ts
/* istanbul ignore file */
var ImageRegistriesService = class {
/**
* 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(proto) {
return request(OpenAPI, {
method: "DELETE",
url: "/registries/protos/{proto}",
path: { proto },
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(domain, requestBody) {
return request(OpenAPI, {
method: "POST",
url: "/registries/{domain}/credentials",
path: { domain },
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(domain) {
return request(OpenAPI, {
method: "DELETE",
url: "/registries/{domain}",
path: { domain },
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`
}
});
}
};
//#endregion
//#region ../containers-shared/src/build.ts
async function constructBuildCommand(options, logger) {
const platform$1 = options.platform ?? "linux/amd64";
const buildCmd = [
"build",
"--load",
"-t",
options.tag,
"--platform",
platform$1,
"--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 = readFileSync(options.pathToDockerfile, "utf-8");
buildCmd.push("-f", "-");
buildCmd.push(options.buildContext);
logger?.debug(`Building image with command: ${buildCmd.join(" ")}`);
return {
buildCmd,
dockerfile
};
}
function dockerBuild(dockerPath, options) {
let errorHandled = false;
let resolve$4;
let reject;
const ready = new Promise((res, rej) => {
resolve$4 = res;
reject = rej;
});
const child = spawn(dockerPath, options.buildCmd, {
stdio: [
"pipe",
"inherit",
"inherit"
],
detached: process.platform !== "win32",
windowsHide: true
});
if (child.stdin !== null) {
child.stdin.write(options.dockerfile);
child.stdin.end();
}
child.on("exit", (code) => {
if (code === 0) resolve$4();
else if (!errorHandled) {
errorHandled = true;
reject(new UserError(`Docker build exited with code: ${code}`, { telemetryMessage: false }));
}
});
child.on("error", (err) => {
if (!errorHandled) {
errorHandled = true;
reject(err);
}
});
return {
abort: () => {
child.unref();
if (child.pid !== void 0) if (process.platform === "win32") child.kill();
else process.kill(-child.pid);
},
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
});
}
//#endregion
//#region ../containers-shared/src/login.ts
function configureOpenAPIForContainerPull(accountId, apiToken, apiBase = "https://api.cloudflare.com/client/v4") {
OpenAPI.BASE = `${apiBase}/accounts/${accountId}/containers`;
OpenAPI.CREDENTIALS = "omit";
OpenAPI.HEADERS = {
...typeof OpenAPI.HEADERS === "object" ? OpenAPI.HEADERS : {},
Authorization: `Bearer ${apiToken}`
};
}
/**
* Gets push and pull credentials for a configured image registry
* and runs `docker login`, so subsequent image pushes or pulls are
* authenticated
*/
async function dockerLoginImageRegistry(pathToDocker, domain) {
const credentials = await ImageRegistriesService.generateImageRegistryCredentials(domain, {
expiration_minutes: 15,
permissions: [ImageRegistryPermissions.PUSH, ImageRegistryPermissions.PULL]
});
const child = spawn(pathToDocker, [
"login",
"--password-stdin",
"--username",
credentials.username,
domain
], { stdio: [
"pipe",
"inherit",
"inherit"
] }).on("error", (err) => {
throw err;
});
child.stdin.write(credentials.password);
child.stdin.end();
await new Promise((resolve$4, reject) => {
child.on("close", (code) => {
if (code === 0) resolve$4();
else reject(new UserError(`Login failed with code: ${code}`, { telemetryMessage: false }));
});
});
}
//#endregion
//#region ../containers-shared/src/registry.ts
const MF_DEV_CONTAINER_PREFIX = "cloudflare-dev";
//#endregion
//#region ../containers-shared/src/knobs.ts
const getCloudflareContainerRegistry = () => {
return process.env.CLOUDFLARE_CONTAINER_REGISTRY ?? (process.env.WRANGLER_API_ENVIRONMENT === "staging" ? "staging.registry.cloudflare.com" : "registry.cloudflare.com");
};
/** Prefixes with the cloudflare-dev namespace. The name should be the container's DO classname, and the tag a build uuid. */
const getDevContainerImageName = (name, tag) => {
return `${MF_DEV_CONTAINER_PREFIX}/${name.toLowerCase()}:${tag}`;
};
//#endregion
//#region ../containers-shared/src/inspect.ts
async function dockerImageInspect(dockerPath, options) {
return new Promise((resolve$4, reject) => {
const proc = spawn(dockerPath, [
"image",
"inspect",
options.imageTag,
"--format",
options.formatString
], { stdio: [
"ignore",
"pipe",
"pipe"
] });
let stdout = "";
let stderr = "";
proc.stdout.on("data", (chunk) => stdout += chunk);
proc.stderr.on("data", (chunk) => stderr += chunk);
proc.on("close", (code) => {
if (code !== 0) return reject(new UserError(`failed inspecting image locally: ${stderr.trim()}`, { telemetryMessage: false }));
resolve$4(stdout.trim());
});
proc.on("error", (err) => reject(err));
});
}
//#endregion
//#region ../containers-shared/src/utils.ts
/** helper for simple docker command call that don't require any io handling */
const runDockerCmd = (dockerPath, args, stdio) => {
let aborted = false;
let resolve$4;
let reject;
const ready = new Promise((res, rej) => {
resolve$4 = res;
reject = rej;
});
const child = spawn(dockerPath, args, {
stdio: stdio ?? "inherit",
detached: process.platform !== "win32",
windowsHide: true
});
let errorHandled = false;
child.on("close", (code) => {
if (code === 0 || aborted) resolve$4({ aborted });
else if (!errorHandled) {
errorHandled = true;
reject(new UserError(`Docker command exited with code: ${code}`, { telemetryMessage: false }));
}
});
child.on("error", (err) => {
if (!errorHandled) {
errorHandled = true;
reject(new UserError(`Docker command failed: ${err.message}`, { telemetryMessage: false }));
}
});
return {
abort: () => {
aborted = true;
child.unref();
if (child.pid !== void 0) if (process.platform === "win32") child.kill();
else process.kill(-child.pid);
},
ready,
then: async (onResolve, onReject) => ready.then(onResolve).catch(onReject)
};
};
const runDockerCmdWithOutput = (dockerPath, args) => {
try {
return execFileSync(dockerPath, args, { encoding: "utf8" }).trim();
} catch (error) {
throw new UserError(`Failed running docker command: ${error.message}. Command: ${dockerPath} ${args.join(" ")}`, { telemetryMessage: false });
}
};
/** Checks whether docker is running on the system */
const isDockerRunning = async (dockerPath) => {
try {
await runDockerCmd(dockerPath, ["info"], [
"inherit",
"pipe",
"pipe"
]);
} catch {
return false;
}
return true;
};
/** throws when docker is not installed */
const verifyDockerInstalled = async (dockerPath, isDev = true) => {
if (!await isDockerRunning(dockerPath)) throw new UserError(`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." : ""}`, { telemetryMessage: false });
};
/**
* Kills and removes any containers which come from the given image tag
*/
const cleanupContainers = (dockerPath, imageTags) => {
try {
const containerIds = getContainerIdsByImageTags(dockerPath, imageTags);
if (containerIds.length === 0) return true;
runDockerCmdWithOutput(dockerPath, [
"rm",
"--force",
...containerIds
]);
return true;
} catch {
return false;
}
};
/**
* See https://docs.docker.com/reference/cli/docker/container/ls/#ancestor
*
* @param dockerPath The path to the Docker executable
* @param imageTags A set of ancestor image tags
* @returns The ids of all containers that share the given image tags as ancestors.
*/
function getContainerIdsByImageTags(dockerPath, imageTags) {
const ids = /* @__PURE__ */ new Set();
for (const imageTag of imageTags) getContainerIdsFromImage(dockerPath, imageTag).forEach((id) => ids.add(id));
return Array.from(ids);
}
const getContainerIdsFromImage = (dockerPath, ancestorImage) => {
return runDockerCmdWithOutput(dockerPath, [
"ps",
"-a",
"--filter",
`ancestor=${ancestorImage}`,
"--format",
"{{.ID}}"
]).split("\n").filter((line) => line.trim());
};
/**
* While all ports are exposed in prod, a limitation of local dev with docker is that
* users will have to manually expose ports in their Dockerfile.
* We want to fail early and clearly if a user tries to develop with a container
* that has no ports exposed and is definitely not accessible.
*
* (A user could still use `getTCPPort()` on a port that is not exposed, but we leave that error for runtime.)
*/
async function checkExposedPorts(dockerPath, options) {
if (await dockerImageInspect(dockerPath, {
imageTag: options.image_tag,
formatString: "{{ len .Config.ExposedPorts }}"
}) === "0") throw new UserError(`The container "${options.class_name}" does not expose any ports. In your Dockerfile, please expose any ports you intend to connect to.\nFor additional information please see: https://developers.cloudflare.com/containers/local-dev/#exposing-ports.
`, { telemetryMessage: false });
}
/**
* Generates a random container build id
*/
function generateContainerBuildId() {
return randomUUID().slice(0, 8);
}
/**
* Run `docker context ls` to get the socket from the currently active Docker context
* @returns The socket path or null if we are not able to determine it
*/
function getDockerSocketFromContext(dockerPath) {
try {
const currentContext = runDockerCmdWithOutput(dockerPath, [
"context",
"ls",
"--format",
"json"
]).trim().split("\n").map((line) => JSON.parse(line)).find((context) => context.Current === true);
if (currentContext && currentContext.DockerEndpoint) return currentContext.DockerEndpoint;
} catch {}
return null;
}
/**
* Resolve Docker host as follows:
* 1. Check WRANGLER_DOCKER_HOST environment variable
* 2. Check DOCKER_HOST environment variable
* 3. Try to get socket from active Docker context
* 4. Fall back to platform-specific defaults
*/
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";
}
/**
* Get all repository tags for a given image
*/
async function getImageRepoTags(dockerPath, imageTag) {
try {
return (await dockerImageInspect(dockerPath, {
imageTag,
formatString: "{{ range .RepoTags }}{{ . }}\n{{ end }}"
})).split("\n").filter((tag) => tag.trim() !== "");
} catch {
return [];
}
}
/**
* Checks if the given image has any duplicate tags from previous dev sessions,
* and remove them if so.
*/
async function cleanupDuplicateImageTags(dockerPath, imageTag) {
try {
const tagsToRemove = (await getImageRepoTags(dockerPath, imageTag)).filter((tag) => tag !== imageTag && tag.startsWith("cloudflare-dev"));
if (tagsToRemove.length > 0) runDockerCmdWithOutput(dockerPath, ["rmi", ...tagsToRemove]);
} catch {}
}
//#endregion
//#region ../containers-shared/src/images.ts
const DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = "cloudflare/proxy-everything:3cb1195@sha256:0ef6716c52430096900b150d84a3302057d6cd2319dae7987128c85d0733e3c8";
function getEgressInterceptorImage() {
return process.env.MINIFLARE_CONTAINER_EGRESS_IMAGE ?? DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE;
}
async function pullEgressInterceptorImage(dockerPath) {
await runDockerCmd(dockerPath, [
"pull",
getEgressInterceptorImage(),
"--platform",
"linux/amd64"
]);
}
async function pullImage(dockerPath, options, logger) {
const domain = new URL(`http://${options.image_uri}`).hostname;
const isExternalRegistry = domain !== getCloudflareContainerRegistry();
try {
await dockerLoginImageRegistry(dockerPath, domain);
} catch (e) {
if (!isExternalRegistry) throw e;
logger?.warn("Unable to retrieve configured registry credentials from Cloudflare.\nUnless this is a public image, you will need to run `wrangler containers registries configure` before deploying.\nAttempting to pull image anyway...");
}
const pull = runDockerCmd(dockerPath, [
"pull",
options.image_uri,
"--platform",
"linux/amd64"
]);
return {
abort: () => {
pull.abort();
},
ready: pull.ready.then(async ({ aborted }) => {
if (!aborted) await runDockerCmd(dockerPath, [
"tag",
options.image_uri,
options.image_tag
]);
})
};
}
/**
*
* Builds or pulls the container images for local development. This
* will be called before starting the local development server, and by a rebuild
* hotkey during development.
*
* Because this runs when local dev starts, we also do some validation here,
* such as checking if the Docker CLI is installed, and if the container images
* expose any ports.
*/
async function prepareContainerImagesForDev(args) {
const { dockerPath, containerOptions, onContainerImagePreparationStart, onContainerImagePreparationEnd } = args;
let aborted = false;
if (process.platform === "win32") throw new UserError("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.", { telemetryMessage: false });
await verifyDockerInstalled(dockerPath);
for (const options of containerOptions) {
if ("dockerfile" in options) {
const build$8 = await buildImage(dockerPath, options);
onContainerImagePreparationStart({
containerOptions: options,
abort: () => {
aborted = true;
build$8.abort();
}
});
await build$8.ready;
onContainerImagePreparationEnd({ containerOptions: options });
} else {
const pull = await pullImage(dockerPath, options, args.logger);
onContainerImagePreparationStart({
containerOptions: options,
abort: () => {
aborted = true;
pull.abort();
}
});
await pull.ready;
onContainerImagePreparationEnd({ containerOptions: options });
}
if (!aborted) {
await cleanupDuplicateImageTags(dockerPath, options.image_tag);
await checkExposedPorts(dockerPath, options);
}
}
if (!aborted) await pullEgressInterceptorImage(dockerPath);
}
//#endregion
//#region ../workers-shared/asset-worker/src/utils/rules-engine.ts
const ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
const escapeRegex = (str) => {
return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
};
const generateGlobOnlyRuleRegExp = (rule) => {
rule = rule.split("*").map(escapeRegex).join(".*");
rule = "^" + rule + "$";
return RegExp(rule);
};
const generateStaticRoutingRuleMatcher = (rules) => ({ request: request$2 }) => {
const { pathname } = new URL(request$2.url);
for (const rule of rules) try {
if (generateGlobOnlyRuleRegExp(rule).test(pathname)) return true;
} catch {}
return false;
};
//#endregion
//#region src/containers.ts
/**
* Returns the path to the Docker executable as defined by the
* `WRANGLER_DOCKER_BIN` environment variable, or the default value
* `"docker"`
*/
function getDockerPath() {
return process.env["WRANGLER_DOCKER_BIN"] || "docker";
}
/**
* @returns Container options suitable for building or pulling images,
* with image tag set to well-known dev format, or undefined if
* containers are not enabled or not configured.
*/
function getContainerOptions(options) {
const { containersConfig, containerBuildId, configPath } = options;
if (!containersConfig?.length) return;
return containersConfig.map((container) => {
if (isDockerfile(container.image, configPath)) return {
dockerfile: container.image,
image_build_context: container.image_build_context ?? path.dirname(container.image),
image_vars: container.image_vars,
class_name: container.class_name,
image_tag: getDevContainerImageName(container.class_name, containerBuildId)
};
else return {
image_uri: container.image,
class_name: container.class_name,
image_tag: getDevContainerImageName(container.class_name, containerBuildId)
};
});
}
//#endregion
//#region ../../node_modules/.pnpm/fdir@6.5.0_picomatch@4.0.3/node_modules/fdir/dist/index.mjs
var __require = /* @__PURE__ */ createRequire$1(import.meta.url);
function cleanPath(path$2) {
let normalized = normalize(path$2);
if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
return normalized;
}
const SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path$2, separator) {
return path$2.replace(SLASHES_REGEX, separator);
}
const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
function isRootDirectory(path$2) {
return path$2 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$2);
}
function normalizePath$1(path$2, options) {
const { resolvePaths, normalizePath: normalizePath$1$1, pathSeparator } = options;
const pathNeedsCleaning = process.platform === "win32" && path$2.includes("/") || path$2.startsWith(".");
if (resolvePaths) path$2 = resolve$1(path$2);
if (normalizePath$1$1 || pathNeedsCleaning) path$2 = cleanPath(path$2);
if (path$2 === ".") return "";
return convertSlashes(path$2[path$2.length - 1] !== pathSeparator ? path$2 + pathSeparator : path$2, pathSeparator);
}
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
function joinPathWithRelativePath(root, options) {
return function(filename, directoryPath) {
if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename;
else return convertSlashes(relative$1(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
};
}
function joinPath(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
function build$7(root, options) {
const { relativePaths, includeBasePath } = options;
return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
}
function pushDirectoryWithRelativePath(root) {
return function(directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function(directoryPath, paths, filters) {
const relativePath = directoryPath.substring(root.length) || ".";
if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
};
}
const pushDirectory = (directoryPath, paths) => {
paths.push(directoryPath || ".");
};
const pushDirectoryFilter = (directoryPath, paths, filters) => {
const path$2 = directoryPath || ".";
if (filters.every((filter) => filter(path$2, true))) paths.push(path$2);
};
const empty$2 = () => {};
function build$6(root, options) {
const { includeDirs, filters, relativePaths } = options;
if (!includeDirs) return empty$2;
if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
return filters && filters.length ? pushDirectoryFilter : pushDirectory;
}
const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
if (filters.every((filter) => filter(filename, false))) counts.files++;
};
const pushFileFilter = (filename, paths, _counts, filters) => {
if (filters.every((filter) => filter(filename, false))) paths.push(filename);
};
const pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
};
const pushFile = (filename, paths) => {
paths.push(filename);
};
const empty$1 = () => {};
function build$5(options) {
const { excludeFiles, filters, onlyCounts } = options;
if (excludeFiles) return empty$1;
if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
else if (onlyCounts) return pushFileCount;
else return pushFile;
}
const getArray = (paths) => {
return paths;
};
const getArrayGroup = () => {
return [""].slice(0, 0);
};
function build$4(options) {
return options.group ? getArrayGroup : getArray;
}
const groupFiles = (groups, directory, files) => {
groups.push({
directory,
files,
dir: directory
});
};
const empty = () => {};
function build$3(options) {
return options.group ? groupFiles : empty;
}
const resolveSymlinksAsync = function(path$2, state, callback$1) {
const { queue, fs: fs$3, options: { suppressErrors } } = state;
queue.enqueue();
fs$3.realpath(path$2, (error, resolvedPath) => {
if (error) return queue.dequeue(suppressErrors ? null : error, state);
fs$3.stat(resolvedPath, (error$1, stat) => {
if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
if (stat.isDirectory() && isRecursive(path$2, resolvedPath, state)) return queue.dequeue(null, state);
callback$1(stat, resolvedPath);
queue.dequeue(null, state);
});
});
};
const resolveSymlinks = function(path$2, state, callback$1) {
const { queue, fs: fs$3, options: { suppressErrors } } = state;
queue.enqueue();
try {
const resolvedPath = fs$3.realpathSync(path$2);
const stat = fs$3.statSync(resolvedPath);
if (stat.isDirectory() && isRecursive(path$2, resolvedPath, state)) return;
callback$1(stat, resolvedPath);
} catch (e) {
if (!suppressErrors) throw e;
}
};
function build$2(options, isSynchronous) {
if (!options.resolveSymlinks || options.excludeSymlinks) return null;
return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
function isRecursive(path$2, resolved, state) {
if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
let parent = dirname$1(path$2);
let depth$1 = 1;
while (parent !== state.root && depth$1 < 2) {
const resolvedPath = state.symlinks.get(parent);
if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth$1++;
else parent = dirname$1(parent);
}
state.symlinks.set(path$2, resolved);
return depth$1 > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}
const onlyCountsSync = (state) => {
return state.counts;
};
const groupsSync = (state) => {
return state.groups;
};
const defaultSync = (state) => {
return state.paths;
};
const limitFilesSync = (state) => {
return state.paths.slice(0, state.options.maxFiles);
};
const onlyCountsAsync = (state, error, callback$1) => {
report(error, callback$1, state.counts, state.options.suppressErrors);
return null;
};
const defaultAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths, state.options.suppressErrors);
return null;
};
const limitFilesAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
return null;
};
const groupsAsync = (state, error, callback$1) => {
report(error, callback$1, state.groups, state.options.suppressErrors);
return null;
};
function report(error, callback$1, output, suppressErrors) {
if (error && !suppressErrors) callback$1(error, output);
else callback$1(null, output);
}
function build$1(options, isSynchronous) {
const { onlyCounts, group, maxFiles } = options;
if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
else if (group) return isSynchronous ? groupsSync : groupsAsync;
else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
else return isSynchronous ? defaultSync : defaultAsync;
}
const readdirOpts = { withFileTypes: true };
const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
state.queue.enqueue();
if (currentDepth < 0) return state.queue.dequeue(null, state);
const { fs: fs$3 } = state;
state.visited.push(crawlPath);
state.counts.directories++;
fs$3.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback$1(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
const { fs: fs$3 } = state;
if (currentDepth < 0) return;
state.visited.push(crawlPath);
state.counts.directories++;
let entries = [];
try {
entries = fs$3.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback$1(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
var Queue = class {
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
this.count++;
return this.count;
}
dequeue(error, output) {
if (this.onQueueEmpty && (--this.count <= 0 || error)) {
this.onQueueEmpty(error, output);
if (error) {
output.controller.abort();
this.onQueueEmpty = void 0;
}
}
}
};
var Counter = class {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
};
/**
* AbortController is not supported on Node 14 so we use this until we can drop
* support for Node 14.
*/
var Aborter = class {
aborted = false;
abort() {
this.aborted = true;
}
};
var Walker = class {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback$1) {
this.isSynchronous = !callback$1;
this.callbackInvoker = build$1(options, this.isSynchronous);
this.root = normalizePath$1(root, options);
this.state = {
root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
paths: [""].slice(0, 0),
groups: [],
counts: new Counter(),
options,
queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
symlinks: /* @__PURE__ */ new Map(),
visited: [""].slice(0, 0),
controller: new Aborter(),
fs: options.fs || nativeFs$1
};
this.joinPath = build$7(this.root, options);
this.pushDirectory = build$6(this.root, options);
this.pushFile = build$5(options);
this.getArray = build$4(options);
this.groupFiles = build$3(options);
this.resolveSymlink = build$2(options, this.isSynchronous);
this.walkDirectory = build(this.isSynchronous);
}
start() {
this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth$1) => {
const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
const files = this.getArray(this.state.paths);
for (let i$1 = 0; i$1 < entries.length; ++i$1) {
const entry = entries[i$1];
if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
const filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
} else if (entry.isDirectory()) {
let path$2 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path$2)) continue;
this.pushDirectory(path$2, paths, filters);
this.walkDirectory(this.state, path$2, path$2, depth$1 - 1, this.walk);
} else if (this.resolveSymlink && entry.isSymbolicLink()) {
let path$2 = joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path$2, this.state, (stat, resolvedPath) => {
if (stat.isDirectory()) {
resolvedPath = normalizePath$1(resolvedPath, this.state.options);
if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$2 + pathSeparator)) return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$2 + pathSeparator, depth$1 - 1, this.walk);
} else {
resolvedPath = useRealPaths ? resolvedPath : path$2;
const filename = basename(resolvedPath);
const directoryPath$1 = normalizePath$1(dirname$1(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath$1);
this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
};
function promise(root, options) {
return new Promise((resolve$1$1, reject) => {
callback(root, options, (err, output) => {
if (err) return reject(err);
resolve$1$1(output);
});
});
}
function callback(root, options, callback$1) {
new Walker(root, options, callback$1).start();
}
function sync(root, options) {
return new Walker(root, options).start();
}
var APIBuilder = class {
constructor(root, options) {
this.root = root;
this.options = options;
}
withPromise() {
return promise(this.root, this.options);
}
withCallback(cb) {
callback(this.root, this.options, cb);
}
sync() {
return sync(this.root, this.options);
}
};
let pm = null;
/* c8 ignore next 6 */
try {
__require.resolve("picomatch");
pm = __require("picomatch");
} catch {}
var Builder = class {
globCache = {};
options = {
maxDepth: Infinity,
suppressErrors: true,
pathSeparator: sep,
filters: []
};
globFunction;
constructor(options) {
this.options = {
...this.options,
...options
};
this.globFunction = this.options.globFunction;
}
group() {
this.options.group = true;
return this;
}
withPathSeparator(separator) {
this.options.pathSeparator = separator;
return this;
}
withBasePath() {
this.options.includeBasePath = true;
return this;
}
withRelativePaths() {
this.options.relativePaths = true;
return this;
}
withDirs() {
this.options.includeDirs = true;
return this;
}
withMaxDepth(depth$1) {
this.options.maxDepth = depth$1;
return this;
}
withMaxFiles(limit) {
this.options.maxFiles = limit;
return this;
}
withFullPaths() {
this.options.resolvePaths = true;
this.options.includeBasePath = true;
return this;
}
withErrors() {
this.options.suppressErrors = false;
return this;
}
withSymlinks({ resolvePaths = true } = {}) {
this.options.resolveSymlinks = true;
this.options.useRealPaths = resolvePaths;
return this.withFullPaths();
}
withAbortSignal(signal) {
this.options.signal = signal;
return this;
}
normalize() {
this.options.normalizePath = true;
return this;
}
filter(predicate) {
this.options.filters.push(predicate);
return this;
}
onlyDirs() {
this.options.excludeFiles = true;
this.options.includeDirs = true;
return this;
}
exclude(predicate) {
this.options.exclude = predicate;
return this;
}
onlyCounts() {
this.options.onlyCounts = true;
return this;
}
crawl(root) {
return new APIBuilder(root || ".", this.options);
}
withGlobFunction(fn) {
this.globFunction = fn;
return this;
}
/**
* @deprecated Pass options using the constructor instead:
* ```ts
* new fdir(options).crawl("/path/to/root");
* ```
* This method will be removed in v7.0
*/
/* c8 ignore next 4 */
crawlWithOptions(root, options) {
this.options = {
...this.options,
...options
};
return new APIBuilder(root || ".", this.options);
}
glob(...patterns) {
if (this.globFunction) return this.globWithOptions(patterns);
return this.globWithOptions(patterns, ...[{ dot: true }]);
}
globWithOptions(patterns, ...options) {
const globFn = this.globFunction || pm;
/* c8 ignore next 5 */
if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
var isMatch = this.globCache[patterns.join("\0")];
if (!isMatch) {
isMatch = globFn(patterns, ...options);
this.globCache[patterns.join("\0")] = isMatch;
}
this.options.filters.push((path$2) => isMatch(path$2));
return this;
}
};
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js
var require_constants = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js": ((exports, module) => {
const WIN_SLASH = "\\\\/";
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
* Posix glob regex
*/
const DOT_LITERAL = "\\.";
const PLUS_LITERAL = "\\+";
const QMARK_LITERAL = "\\?";
const SLASH_LITERAL = "\\/";
const ONE_CHAR = "(?=.)";
const QMARK = "[^/]";
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!${START_ANCHOR}${DOTS_SLASH})`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`,
NO_DOTS_SLASH: `(?!${DOTS_SLASH})`,
QMARK_NO_DOT: `[^.${SLASH_LITERAL}]`,
STAR: `${QMARK}*?`,
START_ANCHOR,
SEP: "/"
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: "\\"
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE$1 = {
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
REPLACEMENTS: {
__proto__: null,
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
CHAR_0: 48,
CHAR_9: 57,
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_LEFT_PARENTHESES: 40,
CHAR_RIGHT_PARENTHESES: 41,
CHAR_ASTERISK: 42,
CHAR_AMPERSAND: 38,
CHAR_AT: 64,
CHAR_BACKWARD_SLASH: 92,
CHAR_CARRIAGE_RETURN: 13,
CHAR_CIRCUMFLEX_ACCENT: 94,
CHAR_COLON: 58,
CHAR_COMMA: 44,
CHAR_DOT: 46,
CHAR_DOUBLE_QUOTE: 34,
CHAR_EQUAL: 61,
CHAR_EXCLAMATION_MARK: 33,
CHAR_FORM_FEED: 12,
CHAR_FORWARD_SLASH: 47,
CHAR_GRAVE_ACCENT: 96,
CHAR_HASH: 35,
CHAR_HYPHEN_MINUS: 45,
CHAR_LEFT_ANGLE_BRACKET: 60,
CHAR_LEFT_CURLY_BRACE: 123,
CHAR_LEFT_SQUARE_BRACKET: 91,
CHAR_LINE_FEED: 10,
CHAR_NO_BREAK_SPACE: 160,
CHAR_PERCENT: 37,
CHAR_PLUS: 43,
CHAR_QUESTION_MARK: 63,
CHAR_RIGHT_ANGLE_BRACKET: 62,
CHAR_RIGHT_CURLY_BRACE: 125,
CHAR_RIGHT_SQUARE_BRACKET: 93,
CHAR_SEMICOLON: 59,
CHAR_SINGLE_QUOTE: 39,
CHAR_SPACE: 32,
CHAR_TAB: 9,
CHAR_UNDERSCORE: 95,
CHAR_VERTICAL_LINE: 124,
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
extglobChars(chars$1) {
return {
"!": {
type: "negate",
open: "(?:(?!(?:",
close: `))${chars$1.STAR})`
},
"?": {
type: "qmark",
open: "(?:",
close: ")?"
},
"+": {
type: "plus",
open: "(?:",
close: ")+"
},
"*": {
type: "star",
open: "(?:",
close: ")*"
},
"@": {
type: "at",
open: "(?:",
close: ")"
}
};
},
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js
var require_utils = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js": ((exports) => {
const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports.isWindows = () => {
if (typeof navigator !== "undefined" && navigator.platform) {
const platform$1 = navigator.platform.toLowerCase();
return platform$1 === "win32" || platform$1 === "windows";
}
if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
return false;
};
exports.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
return match === "\\" ? "" : match;
});
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
let output = `${options.contains ? "" : "^"}(?:${input})${options.contains ? "" : "$"}`;
if (state.negated === true) output = `(?:^(?!${output}).*$)`;
return output;
};
exports.basename = (path$2, { windows } = {}) => {
const segs = path$2.split(windows ? /[\\/]/ : "/");
const last = segs[segs.length - 1];
if (last === "") return segs[segs.length - 2];
return last;
};
}) });
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js
var require_scan = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js": ((exports, module) => {
const utils$3 = require_utils();
const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
const isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = (token) => {
if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan$1 = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished$2 = false;
let braces = 0;
let prev;
let code;
let token = {
value: "",
depth: 0,
isGlob: false
};
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished$2 = true;
if (scanToEnd === true) continue;
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished$2 = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished$2 = true;
break;
}
}
}
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = {
value: "",
depth: 0,
isGlob: false
};
if (finished$2 === true) continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished$2 = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished$2 = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished$2 = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished$2 = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished$2 = true;
break;
}
}
if (scanToEnd === true) continue;
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished$2 = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished$2 = true;
if (scanToEnd === true) continue;
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = "";
let glob = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = "";
glob = str;
} else base = str;
if (base && base !== "" && base !== "/" && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
}
if (opts.unescape === true) {
if (glob) glob = utils$3.removeBackslashes(glob);
if (base && backslashes === true) base = utils$3.removeBackslashes(base);
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) tokens.push(token);
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n$1 = prevIndex ? prevIndex + 1 : start;
const i$1 = slashes[idx];
const value = input.slice(n$1, i$1);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else tokens[idx].value = value;
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") parts.push(value);
prevIndex = i$1;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js
var require_parse = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js": ((exports, module) => {
const constants$3 = require_constants();
const utils$2 = require_utils();
/**
* Constants
*/
const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$3;
/**
* Helpers
*/
const expandRange = (args, options) => {
if (typeof options.expandRange === "function") return options.expandRange(...args, options);
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v) => utils$2.escapeRegex(v)).join("..");
}
return value;
};
/**
* Create the message for a syntax error
*/
const syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
/**
* Parse the given input string.
* @param {String} input
* @param {Object} options
* @return {Object}
*/
const parse$1 = (input, options) => {
if (typeof input !== "string") throw new TypeError("Expected a string");
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
const bos = {
type: "bos",
value: "",
output: opts.prepend || ""
};
const tokens = [bos];
const capture = opts.capture ? "" : "?:";
const PLATFORM_CHARS = constants$3.globChars(opts.windows);
const EXTGLOB_CHARS = constants$3.extglobChars(PLATFORM_CHARS);
const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK: QMARK$1, QMARK_NO_DOT, STAR, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS;
const globstar = (opts$1) => {
return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
};
const nodot = opts.dot ? "" : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
if (opts.capture) star = `(${star})`;
if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
const state = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: "",
output: "",
prefix: "",
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
input = utils$2.removePrefix(input, state);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
/**
* Tokenizing helpers
*/
const eos = () => state.index === len - 1;
const peek = state.peek = (n$1 = 1) => input[state.index + n$1];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume$1 = (value$1 = "", num = 0) => {
state.consumed += value$1;
state.index += num;
};
const append = (token) => {
state.output += token.output != null ? token.output : token.value;
consume$1(token.value);
};
const negate = () => {
let count = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) return false;
state.negated = true;
state.start++;
return true;
};
const increment = (type) => {
state[type]++;
stack.push(type);
};
const decrement = (type) => {
state[type]--;
stack.pop();
};
/**
* Push tokens onto the tokens array. This helper speeds up
* tokenizing by 1) helping us avoid backtracking as much as possible,
* and 2) helping us avoid creating extra tokens when consecutive
* characters are plain text. This improves performance and simplifies
* lookbehinds.
*/
const push = (tok) => {
if (prev.type === "globstar") {
const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star;
state.output += prev.output;
}
}
if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
if (tok.value || tok.output) append(tok);
if (prev && prev.type === "text" && tok.type === "text") {
prev.output = (prev.output || prev.value) + tok.value;
prev.value += tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value$1) => {
const token = {
...EXTGLOB_CHARS[value$1],
conditions: 1,
inner: ""
};
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? "(" : "") + token.open;
increment("parens");
push({
type,
value: value$1,
output: state.output ? "" : ONE_CHAR$1
});
push({
type: "paren",
extglob: true,
value: advance(),
output
});
extglobs.push(token);
};
const extglobClose = (token) => {
let output = token.close + (opts.capture ? ")" : "");
let rest;
if (token.type === "negate") {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse$1(rest, {
...options,
fastpaths: false
}).output})${extglobStar})`;
if (token.prev.type === "bos") state.negatedExtglob = true;
}
push({
type: "paren",
extglob: true,
value,
output
});
decrement("parens");
};
/**
* Fast paths
*/
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars$1, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m;
}
if (first === "?") {
if (esc) return esc + first + (rest ? QMARK$1.repeat(rest.length) : "");
if (index === 0) return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "");
return QMARK$1.repeat(chars$1.length);
}
if (first === ".") return DOT_LITERAL$1.repeat(chars$1.length);
if (first === "*") {
if (esc) return esc + first + (rest ? star : "");
return star;
}
return esc ? m : `\\${m}`;
});
if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
else output = output.replace(/\\+/g, (m) => {
return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
});
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
state.output = utils$2.wrapOutput(output, state, options);
return state;
}
/**
* Tokenize input until we reach end-of-string
*/
while (!eos()) {
value = advance();
if (value === "\0") continue;
/**
* Escaped characters
*/
if (value === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) continue;
if (next === "." || next === ";") continue;
if (!next) {
value += "\\";
push({
type: "text",
value
});
continue;
}
const match = /^\\+/.exec(remaining());
let slashes = 0;
if (match && match[0].length > 2) {
slashes = match[0].length;
state.index += slashes;
if (slashes % 2 !== 0) value += "\\";
}
if (opts.unescape === true) value = advance();
else value += advance();
if (state.brackets === 0) {
push({
type: "text",
value
});
continue;
}
}
/**
* If we're inside a regex character class, continue
* until we reach the closing bracket.
*/
if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value === ":") {
const inner = prev.value.slice(1);
if (inner.includes("[")) {
prev.posix = true;
if (inner.includes(":")) {
const idx = prev.value.lastIndexOf("[");
const pre = prev.value.slice(0, idx);
const posix$1 = POSIX_REGEX_SOURCE[prev.value.slice(idx + 2)];
if (posix$1) {
prev.value = pre + posix$1;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1;
continue;
}
}
}
}
if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
prev.value += value;
append({ value });
continue;
}
/**
* If we're inside a quoted string, continue
* until we reach the closing double quote.
*/
if (state.quotes === 1 && value !== "\"") {
value = utils$2.escapeRegex(value);
prev.value += value;
append({ value });
continue;
}
/**
* Double quotes
*/
if (value === "\"") {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) push({
type: "text",
value
});
continue;
}
/**
* Parentheses
*/
if (value === "(") {
increment("parens");
push({
type: "paren",
value
});
continue;
}
if (value === ")") {
if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({
type: "paren",
value,
output: state.parens ? ")" : "\\)"
});
decrement("parens");
continue;
}
/**
* Square brackets
*/
if (value === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
value = `\\${value}`;
} else increment("brackets");
push({
type: "bracket",
value
});
continue;
}
if (value === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push({
type: "text",
value,
output: `\\${value}`
});
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
push({
type: "text",
value,
output: `\\${value}`
});
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
prev.value += value;
append({ value });
if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue;
const escaped = utils$2.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
/**
* Braces
*/
if (value === "{" && opts.nobrace !== true) {
increment("braces");
const open$1 = {
type: "brace",
value,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open$1);
push(open$1);
continue;
}
if (value === "}") {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({
type: "text",
value,
output: value
});
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i$1 = arr.length - 1; i$1 >= 0; i$1--) {
tokens.pop();
if (arr[i$1].type === "brace") break;
if (arr[i$1].type !== "dots") range.unshift(arr[i$1].value);
}
output = expandRange(range, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value = output = "\\}";
state.output = out;
for (const t$5 of toks) state.output += t$5.output || t$5.value;
}
push({
type: "brace",
value,
output
});
decrement("braces");
braces.pop();
continue;
}
/**
* Pipes
*/
if (value === "|") {
if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
push({
type: "text",
value
});
continue;
}
/**
* Commas
*/
if (value === ",") {
let output = value;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push({
type: "comma",
value,
output
});
continue;
}
/**
* Slashes
*/
if (value === "/") {
if (prev.type === "dot" && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = "";
state.output = "";
tokens.pop();
prev = bos;
continue;
}
push({
type: "slash",
value,
output: SLASH_LITERAL$1
});
continue;
}
/**
* Dots
*/
if (value === ".") {
if (state.braces > 0 && prev.type === "dot") {
if (prev.value === ".") prev.output = DOT_LITERAL$1;
const brace = braces[braces.length - 1];
prev.type = "dots";
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({
type: "text",
value,
output: DOT_LITERAL$1
});
continue;
}
push({
type: "dot",
value,
output: DOT_LITERAL$1
});
continue;
}
/**
* Question marks
*/
if (value === "?") {
if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value;
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
push({
type: "text",
value,
output
});
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push({
type: "qmark",
value,
output: QMARK_NO_DOT
});
continue;
}
push({
type: "qmark",
value,
output: QMARK$1
});
continue;
}
/**
* Exclamation
*/
if (value === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
/**
* Plus
*/
if (value === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push({
type: "plus",
value,
output: PLUS_LITERAL$1
});
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push({
type: "plus",
value
});
continue;
}
push({
type: "plus",
value: PLUS_LITERAL$1
});
continue;
}
/**
* Plain text
*/
if (value === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push({
type: "at",
extglob: true,
value,
output: ""
});
continue;
}
push({
type: "text",
value
});
continue;
}
/**
* Plain text
*/
if (value !== "*") {
if (value === "$" || value === "^") value = `\\${value}`;
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state.index += match[0].length;
}
push({
type: "text",
value
});
continue;
}
/**
* Stars
*/
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume$1(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume$1(value);
continue;
}
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === "slash" || prior.type === "bos";
const afterStar = before && (before.type === "star" || before.type === "globstar");
if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
push({
type: "star",
value,
output: ""
});
continue;
}
const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
push({
type: "star",
value,
output: ""
});
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state.index + 4];
if (after && after !== "/") break;
rest = rest.slice(3);
consume$1("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume$1(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume$1(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== void 0 ? "|$" : "";
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`;
prev.value += value;
state.output += prior.output + prev.output;
state.globstar = true;
consume$1(value + advance());
push({
type: "slash",
value: "/",
output: ""
});
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`;
state.output = prev.output;
state.globstar = true;
consume$1(value + advance());
push({
type: "slash",
value: "/",
output: ""
});
continue;
}
state.output = state.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value;
state.output += prev.output;
state.globstar = true;
consume$1(value);
continue;
}
const token = {
type: "star",
value,
output: star
};
if (opts.bash === true) {
token.output = ".*?";
if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
push(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
token.output = value;
push(token);
continue;
}
if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state.output += ONE_CHAR$1;
prev.output += ONE_CHAR$1;
}
}
push(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils$2.escapeLast(state.output, "[");
decrement("brackets");
}
while (state.parens > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils$2.escapeLast(state.output, "(");
decrement("parens");
}
while (state.braces > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils$2.escapeLast(state.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
type: "maybe_slash",
value: "",
output: `${SLASH_LITERAL$1}?`
});
if (state.backtrack === true) {
state.output = "";
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
if (token.suffix) state.output += token.suffix;
}
}
return state;
};
/**
* Fast paths for creating regular expressions for common glob patterns.
* This can significantly speed up processing and has very little downside
* impact when none of the fast paths match.
*/
parse$1.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
input = REPLACEMENTS[input] || input;
const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR: START_ANCHOR$1 } = constants$3.globChars(opts.windows);
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? "" : "?:";
const state = {
negated: false,
prefix: ""
};
let star = opts.bash === true ? ".*?" : STAR;
if (opts.capture) star = `(${star})`;
const globstar = (opts$1) => {
if (opts$1.noglobstar === true) return star;
return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
};
const create = (str) => {
switch (str) {
case "*": return `${nodot}${ONE_CHAR$1}${star}`;
case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
case "**": return nodot + globstar(opts);
case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match) return;
const source$1 = create(match[1]);
if (!source$1) return;
return source$1 + DOT_LITERAL$1 + match[2];
}
}
};
let source = create(utils$2.removePrefix(input, state));
if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`;
return source;
};
module.exports = parse$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js
var require_picomatch$1 = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js": ((exports, module) => {
const scan = require_scan();
const parse = require_parse();
const utils$1 = require_utils();
const constants$2 = require_constants();
const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
/**
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch(glob[, options]);
*
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
* @api public
*/
const picomatch$2 = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch$2(input, options, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state$1 = isMatch(str);
if (state$1) return state$1;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
const opts = options || {};
const posix$1 = opts.windows;
const regex = isState ? picomatch$2.compileRe(glob, options) : picomatch$2.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = {
...options,
ignore: null,
onMatch: null,
onResult: null
};
isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch$2.test(input, regex, options, {
glob,
posix: posix$1
});
const result = {
glob,
state,
regex,
posix: posix$1,
input,
output,
match,
isMatch
};
if (typeof opts.onResult === "function") opts.onResult(result);
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === "function") opts.onIgnore(result);
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === "function") opts.onMatch(result);
return returnObject ? result : true;
};
if (returnState) matcher.state = state;
return matcher;
};
/**
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
* ```
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
* @api public
*/
picomatch$2.test = (input, regex, options, { glob, posix: posix$1 } = {}) => {
if (typeof input !== "string") throw new TypeError("Expected input to be a string");
if (input === "") return {
isMatch: false,
output: ""
};
const opts = options || {};
const format$2 = opts.format || (posix$1 ? utils$1.toPosixSlashes : null);
let match = input === glob;
let output = match && format$2 ? format$2(input) : input;
if (match === false) {
output = format$2 ? format$2(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$2.matchBase(input, regex, options, posix$1);
else match = regex.exec(output);
return {
isMatch: Boolean(match),
match,
output
};
};
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
picomatch$2.matchBase = (input, glob, options) => {
return (glob instanceof RegExp ? glob : picomatch$2.makeRe(glob, options)).test(utils$1.basename(input));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
picomatch$2.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map((p$1) => picomatch$2.parse(p$1, options));
return parse(pattern, {
...options,
fastpaths: false
});
};
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
picomatch$2.scan = (input, options) => scan(input, options);
/**
* Compile a regular expression from the `state` object returned by the
* [parse()](#parse) method.
*
* @param {Object} `state`
* @param {Object} `options`
* @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
* @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* @return {RegExp}
* @api public
*/
picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) return state.output;
const opts = options || {};
const prepend = opts.contains ? "" : "^";
const append = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) source = `^(?!${source}).*$`;
const regex = picomatch$2.toRegex(source, options);
if (returnState === true) regex.state = state;
return regex;
};
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
let parsed = {
negated: false,
fastpaths: true
};
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
if (!parsed.output) parsed = parse(input, options);
return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
};
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
picomatch$2.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
/**
* Picomatch constants.
* @return {Object}
*/
picomatch$2.constants = constants$2;
/**
* Expose "picomatch"
*/
module.exports = picomatch$2;
}) });
//#endregion
//#region ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js
var require_picomatch = /* @__PURE__ */ __commonJS$1({ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js": ((exports, module) => {
const pico = require_picomatch$1();
const utils = require_utils();
function picomatch$1(glob, options, returnState = false) {
if (options && (options.windows === null || options.windows === void 0)) options = {
...options,
windows: utils.isWindows()
};
return pico(glob, options, returnState);
}
Object.assign(picomatch$1, pico);
module.exports = picomatch$1;
}) });
//#endregion
//#region ../../node_modules/.pnpm/tinyglobby@0.2.15/node_modules/tinyglobby/dist/index.mjs
var import_picomatch = /* @__PURE__ */ __toESM$1(require_picomatch(), 1);
const isReadonlyArray = Array.isArray;
const isWin = process.platform === "win32";
const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
function getPartialMatcher(patterns, options = {}) {
const patternsCount = patterns.length;
const patternsParts = Array(patternsCount);
const matchers = Array(patternsCount);
const globstarEnabled = !options.noglobstar;
for (let i$1 = 0; i$1 < patternsCount; i$1++) {
const parts = splitPattern(patterns[i$1]);
patternsParts[i$1] = parts;
const partsCount = parts.length;
const partMatchers = Array(partsCount);
for (let j = 0; j < partsCount; j++) partMatchers[j] = (0, import_picomatch.default)(parts[j], options);
matchers[i$1] = partMatchers;
}
return (input) => {
const inputParts = input.split("/");
if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
for (let i$1 = 0; i$1 < patterns.length; i$1++) {
const patternParts = patternsParts[i$1];
const matcher = matchers[i$1];
const inputPatternCount = inputParts.length;
const minParts = Math.min(inputPatternCount, patternParts.length);
let j = 0;
while (j < minParts) {
const part = patternParts[j];
if (part.includes("/")) return true;
if (!matcher[j](inputParts[j])) break;
if (globstarEnabled && part === "**") return true;
j++;
}
if (j === inputPatternCount) return true;
}
return false;
};
}
/* node:coverage ignore next 2 */
const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
const isRoot = isWin ? (p$1) => WIN32_ROOT_DIR.test(p$1) : (p$1) => p$1 === "/";
function buildFormat(cwd, root, absolute$1) {
if (cwd === root || root.startsWith(`${cwd}/`)) {
if (absolute$1) {
const start = isRoot(cwd) ? cwd.length : cwd.length + 1;
return (p$1, isDir) => p$1.slice(start, isDir ? -1 : void 0) || ".";
}
const prefix = root.slice(cwd.length + 1);
if (prefix) return (p$1, isDir) => {
if (p$1 === ".") return prefix;
const result = `${prefix}/${p$1}`;
return isDir ? result.slice(0, -1) : result;
};
return (p$1, isDir) => isDir && p$1 !== "." ? p$1.slice(0, -1) : p$1;
}
if (absolute$1) return (p$1) => posix.relative(cwd, p$1) || ".";
return (p$1) => posix.relative(cwd, `${root}/${p$1}`) || ".";
}
function buildRelative(cwd, root) {
if (root.startsWith(`${cwd}/`)) {
const prefix = root.slice(cwd.length + 1);
return (p$1) => `${prefix}/${p$1}`;
}
return (p$1) => {
const result = posix.relative(cwd, `${root}/${p$1}`);
if (p$1.endsWith("/") && result !== "") return `${result}/`;
return result || ".";
};
}
const splitPatternOptions = { parts: true };
function splitPattern(path$1$1) {
var _result$parts;
const result = import_picomatch.default.scan(path$1$1, splitPatternOptions);
return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1$1];
}
const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
const escapePosixPath = (path$1$1) => path$1$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
const escapeWin32Path = (path$1$1) => path$1$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
/**
* Escapes a path's special characters depending on the platform.
* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
*/
/* node:coverage ignore next */
const escapePath = isWin ? escapeWin32Path : escapePosixPath;
/**
* Checks if a pattern has dynamic parts.
*
* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
*
* - Doesn't necessarily return `false` on patterns that include `\`.
* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
*
* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
*/
function isDynamicPattern(pattern, options) {
if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
const scan$2 = import_picomatch.default.scan(pattern);
return scan$2.isGlob || scan$2.negated;
}
function log(...tasks) {
console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
}
const PARENT_DIRECTORY = /^(\/?\.\.)+/;
const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
const BACKSLASHES = /\\/g;
function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
let result = pattern;
if (pattern.endsWith("/")) result = pattern.slice(0, -1);
if (!result.endsWith("*") && expandDirectories) result += "/**";
const escapedCwd = escapePath(cwd);
if (path$1.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
else result = posix.normalize(result);
const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
const parts = splitPattern(result);
if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
const n$1 = (parentDirectoryMatch[0].length + 1) / 3;
let i$1 = 0;
const cwdParts = escapedCwd.split("/");
while (i$1 < n$1 && parts[i$1 + n$1] === cwdParts[cwdParts.length + i$1 - n$1]) {
result = result.slice(0, (n$1 - i$1 - 1) * 3) + result.slice((n$1 - i$1) * 3 + parts[i$1 + n$1].length + 1) || ".";
i$1++;
}
const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i$1 * 3));
if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
props.root = potentialRoot;
props.depthOffset = -n$1 + i$1;
}
}
if (!isIgnore && props.depthOffset >= 0) {
var _props$commonPath;
(_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
const newCommonPath = [];
const length = Math.min(props.commonPath.length, parts.length);
for (let i$1 = 0; i$1 < length; i$1++) {
const part = parts[i$1];
if (part === "**" && !parts[i$1 + 1]) {
newCommonPath.pop();
break;
}
if (part !== props.commonPath[i$1] || isDynamicPattern(part) || i$1 === parts.length - 1) break;
newCommonPath.push(part);
}
props.depthOffset = newCommonPath.length;
props.commonPath = newCommonPath;
props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
}
return result;
}
function processPatterns({ patterns = ["**/*"], ignore: ignore$1 = [], expandDirectories = true }, cwd, props) {
if (typeof patterns === "string") patterns = [patterns];
if (typeof ignore$1 === "string") ignore$1 = [ignore$1];
const matchPatterns = [];
const ignorePatterns = [];
for (const pattern of ignore$1) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
}
for (const pattern of patterns) {
if (!pattern) continue;
if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
}
return {
match: matchPatterns,
ignore: ignorePatterns
};
}
function formatPaths(paths, relative$2) {
for (let i$1 = paths.length - 1; i$1 >= 0; i$1--) {
const path$1$1 = paths[i$1];
paths[i$1] = relative$2(path$1$1);
}
return paths;
}
function normalizeCwd(cwd) {
if (!cwd) return process.cwd().replace(BACKSLASHES, "/");
if (cwd instanceof URL) return fileURLToPath$1(cwd).replace(BACKSLASHES, "/");
return path$1.resolve(cwd).replace(BACKSLASHES, "/");
}
function getCrawler(patterns, inputOptions = {}) {
const options = process.env.TINYGLOBBY_DEBUG ? {
...inputOptions,
debug: true
} : inputOptions;
const cwd = normalizeCwd(options.cwd);
if (options.debug) log("globbing with:", {
patterns,
options,
cwd
});
if (Array.isArray(patterns) && patterns.length === 0) return [{
sync: () => [],
withPromise: async () => []
}, false];
const props = {
root: cwd,
commonPath: null,
depthOffset: 0
};
const processed = processPatterns({
...options,
patterns
}, cwd, props);
if (options.debug) log("internal processing patterns:", processed);
const matchOptions = {
dot: options.dot,
nobrace: options.braceExpansion === false,
nocase: options.caseSensitiveMatch === false,
noextglob: options.extglob === false,
noglobstar: options.globstar === false,
posix: true
};
const matcher = (0, import_picomatch.default)(processed.match, {
...matchOptions,
ignore: processed.ignore
});
const ignore$1 = (0, import_picomatch.default)(processed.ignore, matchOptions);
const partialMatcher = getPartialMatcher(processed.match, matchOptions);
const format$2 = buildFormat(cwd, props.root, options.absolute);
const formatExclude = options.absolute ? format$2 : buildFormat(cwd, props.root, true);
const fdirOptions = {
filters: [options.debug ? (p$1, isDirectory$1) => {
const path$1$1 = format$2(p$1, isDirectory$1);
const matches = matcher(path$1$1);
if (matches) log(`matched ${path$1$1}`);
return matches;
} : (p$1, isDirectory$1) => matcher(format$2(p$1, isDirectory$1))],
exclude: options.debug ? (_, p$1) => {
const relativePath = formatExclude(p$1, true);
const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore$1(relativePath);
if (skipped) log(`skipped ${p$1}`);
else log(`crawling ${p$1}`);
return skipped;
} : (_, p$1) => {
const relativePath = formatExclude(p$1, true);
return relativePath !== "." && !partialMatcher(relativePath) || ignore$1(relativePath);
},
fs: options.fs ? {
readdir: options.fs.readdir || nativeFs.readdir,
readdirSync: options.fs.readdirSync || nativeFs.readdirSync,
realpath: options.fs.realpath || nativeFs.realpath,
realpathSync: options.fs.realpathSync || nativeFs.realpathSync,
stat: options.fs.stat || nativeFs.stat,
statSync: options.fs.statSync || nativeFs.statSync
} : void 0,
pathSeparator: "/",
relativePaths: true,
resolveSymlinks: true,
signal: options.signal
};
if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
if (options.absolute) {
fdirOptions.relativePaths = false;
fdirOptions.resolvePaths = true;
fdirOptions.includeBasePath = true;
}
if (options.followSymbolicLinks === false) {
fdirOptions.resolveSymlinks = false;
fdirOptions.excludeSymlinks = true;
}
if (options.onlyDirectories) {
fdirOptions.excludeFiles = true;
fdirOptions.includeDirs = true;
} else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
props.root = props.root.replace(BACKSLASHES, "");
const root = props.root;
if (options.debug) log("internal properties:", props);
const relative$2 = cwd !== root && !options.absolute && buildRelative(cwd, props.root);
return [new Builder(fdirOptions).crawl(root), relative$2];
}
function globSync(patternsOrOptions, options) {
if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
const opts = isModern ? options : patternsOrOptions;
const [crawler, relative$2] = getCrawler(isModern ? patternsOrOptions : patternsOrOptions.patterns, opts);
if (!relative$2) return crawler.sync();
return formatPaths(crawler.sync(), relative$2);
}
//#endregion
//#region src/miniflare-options.ts
const INTERNAL_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
const PUBLIC_DIR_PREFIX = "/__vite_public_dir__";
function getPersistenceRoot(root, persistState) {
if (persistState === false) return;
return nodePath.resolve(root, typeof persistState === "object" ? persistState.path : ".wrangler/state", "v3");
}
const miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
const ROUTER_WORKER_PATH = "./workers/router-worker/index.js";
const ASSET_WORKER_PATH = "./workers/asset-worker/index.js";
const VITE_PROXY_WORKER_PATH = "./workers/vite-proxy-worker/index.js";
const RUNNER_PATH = "./workers/runner-worker/index.js";
const MODULE_RUNNER_PATH = "./workers/runner-worker/module-runner.js";
const MODULE_RUNNER_LEGACY_PATH = "./workers/runner-worker/module-runner-legacy.js";
const WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
/** Map that maps worker configPaths to their existing remote proxy session data (if any) */
const remoteProxySessionsDataMap = /* @__PURE__ */ new Map();
async function getDevMiniflareOptions(ctx, viteDevServer) {
const inputInspectorPort = await getInputInspectorPort(ctx, viteDevServer);
const { resolvedPluginConfig, resolvedViteConfig, entryWorkerConfig } = ctx;
const assetsConfig = getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedViteConfig);
const assetWorkers = [
{
name: ROUTER_WORKER_NAME,
compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
compatibilityFlags: ["enable_ctx_exports"],
modulesRoot: miniflareModulesRoot,
modules: [{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
contents: fs$2.readFileSync(fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url)))
}],
bindings: { CONFIG: { has_user_worker: resolvedPluginConfig.type === "workers" } },
serviceBindings: {
ASSET_WORKER: ASSET_WORKER_NAME,
...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
}
},
{
name: ASSET_WORKER_NAME,
compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
modulesRoot: miniflareModulesRoot,
modules: [{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, ASSET_WORKER_PATH),
contents: fs$2.readFileSync(fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url)))
}],
bindings: {
CONFIG: assetsConfig,
__VITE_HEADERS__: JSON.stringify(viteDevServer.config.server.headers)
},
serviceBindings: {
__VITE_HTML_EXISTS__: async (request$2) => {
const { pathname } = new URL(request$2.url);
if (pathname.endsWith(".html")) {
const { root, publicDir } = resolvedViteConfig;
const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
const publicPath = withTrailingSlash(publicDir.slice(root.length));
if (publicDirInRoot && pathname.startsWith(publicPath)) return Response$1.json(null);
const publicDirFilePath = nodePath.join(publicDir, pathname);
const rootDirFilePath = nodePath.join(root, pathname);
for (const resolvedPath of [publicDirFilePath, rootDirFilePath]) try {
if ((await fsp.stat(resolvedPath)).isFile()) return Response$1.json(resolvedPath === publicDirFilePath ? `${PUBLIC_DIR_PREFIX}${pathname}` : pathname);
} catch {}
}
return Response$1.json(null);
},
__VITE_FETCH_HTML__: async (request$2) => {
const { pathname } = new URL(request$2.url);
const { root, publicDir } = resolvedViteConfig;
const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
const resolvedPath = isInPublicDir ? nodePath.join(publicDir, pathname.slice(20)) : nodePath.join(root, pathname);
try {
let html = await fsp.readFile(resolvedPath, "utf-8");
if (!isInPublicDir) html = await viteDevServer.transformIndexHtml(resolvedPath, html);
return new Response$1(html, { headers: { "Content-Type": "text/html" } });
} catch {
throw new Error(`Unexpected error. Failed to load "${pathname}".`);
}
}
}
},
{
name: VITE_PROXY_WORKER_NAME,
compatibilityDate: INTERNAL_WORKERS_COMPATIBILITY_DATE,
modulesRoot: miniflareModulesRoot,
modules: [{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, VITE_PROXY_WORKER_PATH),
contents: fs$2.readFileSync(fileURLToPath(new URL(VITE_PROXY_WORKER_PATH, import.meta.url)))
}],
serviceBindings: {
...entryWorkerConfig ? { ENTRY_USER_WORKER: entryWorkerConfig.name } : {},
__VITE_MIDDLEWARE__: { node: (req, res) => viteDevServer.middlewares(req, res) }
}
}
];
const containerTagToOptionsMap = /* @__PURE__ */ new Map();
const workersFromConfig = resolvedPluginConfig.type === "workers" ? await Promise.all([...resolvedPluginConfig.environmentNameToWorkerMap].map(async ([environmentName, worker]) => {
const bindings = wrangler.unstable_convertConfigBindingsToStartWorkerBindings(worker.config);
const preExistingRemoteProxySession = worker.config.configPath ? remoteProxySessionsDataMap.get(worker.config.configPath) : void 0;
const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await wrangler.maybeStartOrUpdateRemoteProxySession({
name: worker.config.name,
bindings: bindings ?? {},
account_id: worker.config.account_id
}, preExistingRemoteProxySession ?? null);
if (worker.config.configPath && remoteProxySessionData) remoteProxySessionsDataMap.set(worker.config.configPath, remoteProxySessionData);
let containerBuildId;
if (worker.config.containers?.length && worker.config.dev.enable_containers) {
const dockerPath = getDockerPath();
worker.config.dev.container_engine = resolveDockerHost(dockerPath);
containerBuildId = generateContainerBuildId();
const options = getContainerOptions({
containersConfig: worker.config.containers,
containerBuildId,
configPath: worker.config.configPath
});
for (const option of options ?? []) containerTagToOptionsMap.set(option.image_tag, option);
}
const { externalWorkers: externalWorkers$1, workerOptions } = wrangler.unstable_getMiniflareWorkerOptions({
...worker.config,
assets: void 0
}, resolvedPluginConfig.cloudflareEnv, {
remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
containerBuildId
});
if (workerOptions.browserRendering && getBrowserRenderingHeadfulFromEnv()) workerOptions.browserRendering.headful = true;
const wrappers = [
`import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from "${RUNNER_PATH}";`,
`export { __VITE_RUNNER_OBJECT__ } from "${RUNNER_PATH}";`,
`export default createWorkerEntrypointWrapper("default");`
];
const exportTypes = ctx.workerNameToExportTypesMap.get(worker.config.name);
assert(exportTypes, `Expected exportTypes to be defined`);
for (const [name, type] of Object.entries(exportTypes)) wrappers.push(`export const ${name} = create${type}Wrapper("${name}");`);
return {
externalWorkers: externalWorkers$1,
worker: {
...workerOptions,
name: worker.config.name,
modulesRoot: miniflareModulesRoot,
modules: [
{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, WRAPPER_PATH),
contents: wrappers.join("\n")
},
{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, RUNNER_PATH),
contents: fs$2.readFileSync(fileURLToPath(new URL(RUNNER_PATH, import.meta.url)))
},
{
type: "ESModule",
path: nodePath.join(miniflareModulesRoot, "workers/runner-worker/vite/module-runner"),
contents: fs$2.readFileSync(fileURLToPath(new URL(satisfiesMinimumViteVersion("7.2.0") ? MODULE_RUNNER_PATH : MODULE_RUNNER_LEGACY_PATH, import.meta.url)))
}
],
unsafeUseModuleFallbackService: true,
unsafeInspectorProxy: inputInspectorPort !== false,
...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && { unsafeOverrideFetchWorker: VITE_PROXY_WORKER_NAME },
unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
serviceBindings: {
...workerOptions.serviceBindings,
...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && worker.config.assets?.binding ? { [worker.config.assets.binding]: { node: (req, res) => {
req[kRequestType] = "asset";
viteDevServer.middlewares(req, res);
} } } : {},
__VITE_INVOKE_MODULE__: async (request$2) => {
const targetEnvironmentName = request$2.headers.get(ENVIRONMENT_NAME_HEADER);
assert(targetEnvironmentName, `Expected ${ENVIRONMENT_NAME_HEADER} header`);
const payload = await request$2.json();
const result = await viteDevServer.environments[targetEnvironmentName].hot.handleInvoke(payload);
return Response$1.json(result);
}
},
durableObjects: {
...workerOptions.durableObjects,
__VITE_RUNNER_OBJECT__: {
className: "__VITE_RUNNER_OBJECT__",
unsafeUniqueKey: kUnsafeEphemeralUniqueKey,
unsafePreventEviction: true
}
}
}
};
})) : [];
const userWorkers = workersFromConfig.map((options) => options.worker);
const externalWorkers = workersFromConfig.flatMap((options) => options.externalWorkers);
const logger = new ViteMiniflareLogger(resolvedViteConfig);
const serverConfig = viteDevServer.config.server;
return {
miniflareOptions: {
log: logger,
publicUrl: buildPublicUrl({
hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
port: serverConfig.port,
secure: !!serverConfig.https
}),
unsafeProxySharedSecret: PROXY_SHARED_SECRET,
logRequests: false,
inspectorPort: inputInspectorPort === false ? void 0 : inputInspectorPort,
unsafeDevRegistryPath: getDefaultDevRegistryPath(),
unsafeTriggerHandlers: true,
unsafeLocalExplorer: getLocalExplorerEnabledFromEnv(),
telemetry: { enabled: false },
handleStructuredLogs: getStructuredLogsLogger(logger),
defaultPersistRoot: getPersistenceRoot(resolvedViteConfig.root, resolvedPluginConfig.persistState),
workers: [
...assetWorkers,
...externalWorkers,
...userWorkers
],
async unsafeModuleFallbackService(request$2) {
const parsed = await parseModuleFallbackRequest(request$2);
if (!parsed) return new Response$1("Invalid module fallback request", { status: 400 });
const rawSpecifier = parsed.rawSpecifier;
assert(rawSpecifier, `Unexpected error: no specifier in request to module fallback service.`);
const match = additionalModuleRE.exec(rawSpecifier);
assert(match, `Unexpected error: no match for module: ${rawSpecifier}.`);
const [full, moduleType, modulePath] = match;
assert(moduleType, `Unexpected error: module type not found in reference: ${full}.`);
assert(modulePath, `Unexpected error: module path not found in reference: ${full}.`);
let contents;
try {
contents = await fsp.readFile(modulePath);
} catch {
throw new Error(`Import "${modulePath}" not found. Does the file exist?`);
}
switch (moduleType) {
case "CompiledWasm": return Response$1.json({ wasm: Array.from(contents) });
case "Data": return Response$1.json({ data: Array.from(contents) });
case "Text": return Response$1.json({ text: contents.toString() });
default: return Response$1.error();
}
}
},
containerTagToOptionsMap
};
}
function getPreviewModules(main, modulesRules) {
assert(modulesRules, `Unexpected error: 'modulesRules' is undefined`);
const rootPath = nodePath.dirname(main);
const entryPath = nodePath.basename(main);
return {
rootPath,
modules: [{
type: "ESModule",
path: entryPath
}, ...modulesRules.flatMap(({ type, include }) => globSync(include, {
cwd: rootPath,
ignore: entryPath
}).map((globPath) => ({
type,
path: globPath
})))]
};
}
async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
const inputInspectorPort = await getInputInspectorPort(ctx, vitePreviewServer);
const { resolvedPluginConfig, resolvedViteConfig } = ctx;
const containerTagToOptionsMap = /* @__PURE__ */ new Map();
const workers = (await Promise.all(resolvedPluginConfig.workers.map(async (workerConfig) => {
const bindings = wrangler.unstable_convertConfigBindingsToStartWorkerBindings(workerConfig);
const preExistingRemoteProxySessionData = workerConfig.configPath ? remoteProxySessionsDataMap.get(workerConfig.configPath) : void 0;
const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await wrangler.maybeStartOrUpdateRemoteProxySession({
name: workerConfig.name,
bindings: bindings ?? {},
account_id: workerConfig.account_id
}, preExistingRemoteProxySessionData ?? null);
if (workerConfig.configPath && remoteProxySessionData) remoteProxySessionsDataMap.set(workerConfig.configPath, remoteProxySessionData);
let containerBuildId;
if (workerConfig.containers?.length && workerConfig.dev.enable_containers) {
const dockerPath = getDockerPath();
workerConfig.dev.container_engine = resolveDockerHost(dockerPath);
containerBuildId = generateContainerBuildId();
const options = getContainerOptions({
containersConfig: workerConfig.containers,
containerBuildId,
configPath: workerConfig.configPath
});
for (const option of options ?? []) containerTagToOptionsMap.set(option.image_tag, option);
}
const miniflareWorkerOptions = wrangler.unstable_getMiniflareWorkerOptions(workerConfig, void 0, {
remoteProxyConnectionString: remoteProxySessionData?.session?.remoteProxyConnectionString,
containerBuildId
});
const { externalWorkers } = miniflareWorkerOptions;
const { modulesRules,...workerOptions } = miniflareWorkerOptions.workerOptions;
return [{
...workerOptions,
name: workerOptions.name ?? workerConfig.name,
unsafeInspectorProxy: inputInspectorPort !== false,
...miniflareWorkerOptions.main ? getPreviewModules(miniflareWorkerOptions.main, modulesRules) : {
modules: true,
script: ""
}
}, ...externalWorkers];
}))).flat();
const logger = new ViteMiniflareLogger(resolvedViteConfig);
const serverConfig = vitePreviewServer.config.preview;
return {
miniflareOptions: {
log: logger,
publicUrl: buildPublicUrl({
hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
port: serverConfig.port,
secure: !!serverConfig.https
}),
unsafeProxySharedSecret: PROXY_SHARED_SECRET,
inspectorPort: inputInspectorPort === false ? void 0 : inputInspectorPort,
unsafeDevRegistryPath: getDefaultDevRegistryPath(),
unsafeTriggerHandlers: true,
unsafeLocalExplorer: getLocalExplorerEnabledFromEnv(),
telemetry: { enabled: false },
handleStructuredLogs: getStructuredLogsLogger(logger),
defaultPersistRoot: getPersistenceRoot(resolvedViteConfig.root, resolvedPluginConfig.persistState),
workers
},
containerTagToOptionsMap
};
}
/**
* A Miniflare logger that forwards messages onto a Vite logger.
*/
var ViteMiniflareLogger = class extends Log {
logger;
constructor(config) {
super(miniflareLogLevelFromViteLogLevel(config.logLevel));
this.logger = config.logger;
}
logWithLevel(level, message) {
switch (level) {
case LogLevel.ERROR: return this.logger.error(message);
case LogLevel.WARN: return this.logger.warn(message);
case LogLevel.INFO: return this.logger.info(message);
}
}
logReady() {}
};
function miniflareLogLevelFromViteLogLevel(level = "info") {
switch (level) {
case "error": return LogLevel.ERROR;
case "warn": return LogLevel.WARN;
case "info": return LogLevel.INFO;
case "silent": return LogLevel.NONE;
}
}
/**
* Generates a log handler to be passed as the `handleStructuredLogs` option to miniflare
*
* @param logger the vite logger to use
* @returns the log handler to pass to miniflare
*/
function getStructuredLogsLogger(logger) {
return ({ level, message }) => {
if (level === "warn") return logger.warn(message);
if (level === "error") return logger.logWithLevel(LogLevel.ERROR, message);
return logger.info(message);
};
}
//#endregion
//#region src/websockets.ts
/**
* Handles 'upgrade' requests to the Vite HTTP server and forwards WebSocket events between the client and Worker environments.
*/
function handleWebSocket(httpServer, miniflare, entryWorkerName) {
const nodeWebSocket = new WebSocketServer({ noServer: true });
httpServer.on("upgrade", async (request$2, socket, head) => {
socket.on("error", () => socket.destroy());
const rawHost = request$2.headers.host ?? UNKNOWN_HOST;
const protocol = getForwardedProto(request$2) ?? "http:";
const base = /^https?:\/\//i.test(rawHost) ? rawHost : `${protocol}//${rawHost}`;
const url = new URL(request$2.url ?? "", base);
const isViteRequest = request$2.headers["sec-websocket-protocol"]?.startsWith("vite");
const isSandboxRequest = hasSandboxOrigin(url.origin);
if (isViteRequest && !isSandboxRequest) return;
const headers = createHeaders(request$2);
if (entryWorkerName) headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
const workerWebSocket = (await miniflare.dispatchFetch(url, {
headers,
method: request$2.method
})).webSocket;
if (!workerWebSocket) {
socket.destroy();
return;
}
nodeWebSocket.handleUpgrade(request$2, socket, head, async (clientWebSocket) => {
coupleWebSocket(clientWebSocket, workerWebSocket);
nodeWebSocket.emit("connection", clientWebSocket, request$2);
});
});
}
/**
* Matches the origin of a Sandbox SDK preview URL.
* See: https://developers.cloudflare.com/sandbox/concepts/preview-urls/
*
* Pattern: https?://<port(4+ digits)>-<id(no dots)>-<token>.localhost
*
* IMPORTANT: The token segment is [a-z0-9_]+ (no hyphens) to prevent ReDoS — two adjacent
* [^.]+ groups separated by - cause quadratic backtracking on hyphen-heavy input. Tokens are
* documented as letters/digits/underscores only.
*/
const SANDBOX_ORIGIN_REGEXP = /^https?:\/\/\d{4,}-[^.]+-[a-z0-9_]+\.localhost(:\d+)?$/i;
function hasSandboxOrigin(origin) {
return SANDBOX_ORIGIN_REGEXP.test(origin);
}
//#endregion
//#region src/plugins/dev.ts
var import_picocolors$2 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
let exitCallback$2 = () => {};
process.on("exit", () => {
exitCallback$2();
});
/**
* Plugin to provide core development functionality
*/
const devPlugin = createPlugin("dev", (ctx) => {
let containerImageTags = /* @__PURE__ */ new Set();
return {
async buildEnd() {
if (ctx.resolvedViteConfig.command === "serve" && containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
debuglog("buildEnd:", ctx.isRestartingDevServer ? "restarted" : "disposing");
if (!ctx.isRestartingDevServer) try {
await ctx.disposeMiniflare();
} catch (error) {
debuglog("Failed to dispose Miniflare instance:", error);
}
},
async configureServer(viteDevServer) {
assertIsNotPreview(ctx);
const initialOptions = await getDevMiniflareOptions(ctx, viteDevServer);
let containerTagToOptionsMap = initialOptions.containerTagToOptionsMap;
await ctx.startOrUpdateMiniflare(initialOptions.miniflareOptions);
if (viteDevServer.httpServer) viteDevServer.httpServer.on("listening", () => {
const addr = viteDevServer.httpServer?.address();
if (typeof addr === "object" && addr !== null) {
const serverConfig = viteDevServer.config.server;
ctx.miniflare.publicUrl = buildPublicUrl({
hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
port: addr.port,
secure: !!serverConfig.https
});
}
});
if (ctx.resolvedPluginConfig.type === "workers") {
debuglog("Initializing the Vite module runners");
await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
const currentWorkerNameToExportTypesMap = await getCurrentWorkerNameToExportTypesMap(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
if (compareWorkerNameToExportTypesMaps(ctx.workerNameToExportTypesMap, currentWorkerNameToExportTypesMap)) {
ctx.setWorkerNameToExportTypesMap(currentWorkerNameToExportTypesMap);
const updatedOptions = await getDevMiniflareOptions(ctx, viteDevServer);
containerTagToOptionsMap = updatedOptions.containerTagToOptionsMap;
await ctx.startOrUpdateMiniflare(updatedOptions.miniflareOptions);
await initRunners(ctx.resolvedPluginConfig, viteDevServer, ctx.miniflare);
}
for (const environmentName of ctx.resolvedPluginConfig.environmentNameToWorkerMap.keys()) {
const environment = viteDevServer.environments[environmentName];
assert(environment, `Expected environment "${environmentName}" to be defined`);
environment.hot.on("vite-plugin-cloudflare:worker-export-types", async (newExportTypes) => {
const workerConfig = ctx.getWorkerConfig(environmentName);
assert(workerConfig, `Expected workerConfig for environment "${environmentName}" to be defined`);
const oldExportTypes = ctx.workerNameToExportTypesMap.get(workerConfig.name);
assert(oldExportTypes, `Expected export types for Worker "${workerConfig.name}" to be defined`);
if (compareExportTypes(oldExportTypes, newExportTypes)) {
viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("Worker exports have changed. Restarting dev server.")));
await viteDevServer.restart();
}
});
}
const entryWorkerConfig = ctx.entryWorkerConfig;
assert(entryWorkerConfig, `No entry Worker config`);
const entryWorkerName = entryWorkerConfig.name;
if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName);
const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
if (staticRouting) {
const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
const includeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.user_worker);
const userWorkerHandler = createRequestHandler(async (request$2) => {
request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
});
viteDevServer.middlewares.use(async function cloudflarePreMiddleware(req, res, next) {
assert(req.url, `req.url not defined`);
const request$2 = new Request(new URL(req.url, UNKNOWN_HOST));
if (req[kRequestType] === "asset") next();
else if (excludeRulesMatcher({ request: request$2 })) {
req[kRequestType] = "asset";
next();
} else if (includeRulesMatcher({ request: request$2 })) userWorkerHandler(req, res, next);
else next();
});
}
if (containerTagToOptionsMap.size) {
viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("∷ Building container images for local development...\n")));
if ([...containerTagToOptionsMap.values()].some((opts) => "image_uri" in opts && new URL(`http://${opts.image_uri}`).hostname === getCloudflareContainerRegistry())) {
const apiToken = process.env.CLOUDFLARE_API_TOKEN;
const accountId = ctx.entryWorkerConfig?.account_id ?? process.env.CLOUDFLARE_ACCOUNT_ID;
if (!apiToken || !accountId) throw new UserError("To use images from the Cloudflare-managed registry with the Vite plugin, set the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID environment variables.\nThe API token requires Containers:Edit and Workers Scripts:Edit permissions.\nAlternatively, use a Dockerfile that references the image via FROM.", { telemetryMessage: false });
configureOpenAPIForContainerPull(accountId, apiToken);
}
await prepareContainerImagesForDev({
dockerPath: getDockerPath(),
containerOptions: [...containerTagToOptionsMap.values()],
onContainerImagePreparationStart: () => {},
onContainerImagePreparationEnd: () => {},
logger: viteDevServer.config.logger
});
containerImageTags = new Set(containerTagToOptionsMap.keys());
viteDevServer.config.logger.info(import_picocolors$2.default.dim(import_picocolors$2.default.yellow("\n⚡️ Containers successfully built. To rebuild your containers during development, restart the Vite dev server (r + enter).")));
exitCallback$2 = () => {
if (containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
};
}
}
return () => {
if (!satisfiesMinimumViteVersion("7.0.0")) {
const middlewareStack = viteDevServer.middlewares.stack;
const preMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "cloudflarePreMiddleware");
if (preMiddlewareIndex !== -1) {
const [preMiddleware] = middlewareStack.splice(preMiddlewareIndex, 1);
assert(preMiddleware, "Failed to remove cloudflarePreMiddleware from stack");
const cachedTransformMiddlewareIndex = middlewareStack.findIndex((middleware) => "name" in middleware.handle && middleware.handle.name === "viteCachedTransformMiddleware");
assert(cachedTransformMiddlewareIndex !== -1, "Failed to find viteCachedTransformMiddleware");
middlewareStack.splice(cachedTransformMiddlewareIndex, 0, preMiddleware);
}
}
viteDevServer.middlewares.use(createRequestHandler(async (request$2, req) => {
if (req[kRequestType] === "asset") {
request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ASSET_WORKER_NAME);
return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
} else {
request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, ROUTER_WORKER_NAME);
return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
}
}));
};
}
};
});
//#endregion
//#region src/plugins/nodejs-compat.ts
/**
* Plugin to support the `nodejs_als` compatibility flag
*/
const nodeJsAlsPlugin = createPlugin("nodejs-als", (ctx) => {
return { configEnvironment(name) {
if (hasNodeJsAls(ctx.getWorkerConfig(name))) return {
resolve: { builtins: ["async_hooks", "node:async_hooks"] },
optimizeDeps: { exclude: ["async_hooks", "node:async_hooks"] }
};
} };
});
/**
* Plugin to support the `nodejs_compat` compatibility flag
*/
const nodeJsCompatPlugin = createPlugin("nodejs-compat", (ctx) => {
return {
configEnvironment(name) {
const nodeJsCompat = ctx.getNodeJsCompat(name);
if (nodeJsCompat) return {
resolve: { builtins: [...nodeJsCompat.externals] },
...isRolldown ? { build: { rolldownOptions: { plugins: [vite.esmExternalRequirePlugin({
external: [...nodeJsCompat.externals],
skipDuplicateCheck: true
})] } } } : {}
};
},
applyToEnvironment(environment) {
return ctx.getNodeJsCompat(environment.name) !== void 0;
},
enforce: "pre",
resolveId: {
filter: { id: [
nodeBuiltinsRE,
/^unenv\//,
/^@cloudflare\/unenv-preset\//
] },
async handler(source, importer, options) {
const nodeJsCompat = ctx.getNodeJsCompat(this.environment.name);
assertHasNodeJsCompat(nodeJsCompat);
const result = nodeJsCompat.resolveNodeJsImport(source);
if (!result) return;
if (this.environment.mode === "dev") {
assert(this.environment.depsOptimizer, "depsOptimizer is required in dev mode");
const { id } = this.environment.depsOptimizer.registerMissingImport(result.unresolved, result.resolved);
return this.resolve(id, importer, options);
}
return this.resolve(result.resolved, importer, options);
}
},
async configureServer(viteDevServer) {
await Promise.all(Object.values(viteDevServer.environments).flatMap(async (environment) => {
const nodeJsCompat = ctx.getNodeJsCompat(environment.name);
if (nodeJsCompat) {
await environment.depsOptimizer?.init();
return Array.from(nodeJsCompat.entries).map((entry) => {
const result = nodeJsCompat.resolveNodeJsImport(entry);
if (result) return (environment.depsOptimizer?.registerMissingImport(result.unresolved, result.resolved))?.processing;
});
}
}));
}
};
});
let exitCallback$1 = () => {};
process.on("exit", () => {
exitCallback$1();
});
/**
* Plugin to warn if Node.js APIs are used without enabling the `nodejs_compat` compatibility flag
*/
const nodeJsCompatWarningsPlugin = createPlugin("nodejs-compat-warnings", (ctx) => {
const nodeJsCompatWarningsMap = /* @__PURE__ */ new Map();
exitCallback$1 = () => {
for (const nodeJsCompatWarnings of nodeJsCompatWarningsMap.values()) nodeJsCompatWarnings.renderWarnings();
};
return {
enforce: "pre",
configResolved(resolvedViteConfig) {
for (const environmentName of Object.keys(resolvedViteConfig.environments)) {
const workerConfig = ctx.getWorkerConfig(environmentName);
const nodeJsCompat = ctx.getNodeJsCompat(environmentName);
if (workerConfig && !nodeJsCompat) nodeJsCompatWarningsMap.set(workerConfig, new NodeJsCompatWarnings(environmentName, resolvedViteConfig));
}
},
applyToEnvironment(environment) {
return ctx.getWorkerConfig(environment.name) !== void 0 && !ctx.getNodeJsCompat(environment.name);
},
resolveId: {
filter: { id: nodeBuiltinsRE },
handler(source, importer) {
if (!nodeBuiltinsRE.test(source)) return;
const workerConfig = ctx.getWorkerConfig(this.environment.name);
assert(workerConfig, `expected workerConfig to be defined`);
if (hasNodeJsAls(workerConfig) && isNodeAlsModule(source)) return;
nodeJsCompatWarningsMap.get(workerConfig)?.registerImport(source, importer);
return {
id: source,
external: true
};
}
}
};
});
//#endregion
//#region src/plugins/output-config.ts
/**
* Plugin to generate additional output files as part of the build, including the output `wrangler.json` file.
*/
const outputConfigPlugin = createPlugin("output-config", (ctx) => {
return {
generateBundle(_, bundle) {
assertIsNotPreview(ctx);
if (ctx.isChildEnvironment(this.environment.name)) return;
let outputConfig;
const inputWorkerConfig = ctx.getWorkerConfig(this.environment.name);
if (inputWorkerConfig) {
const entryChunk = Object.values(bundle).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.name === MAIN_ENTRY_NAME);
assert(entryChunk, `Expected entry chunk with name "${MAIN_ENTRY_NAME}"`);
const isPrerenderWorker = this.environment.name === ctx.resolvedPluginConfig.prerenderWorkerEnvironmentName;
const isEntryWorker = ctx.resolvedPluginConfig.type === "workers" && this.environment.name === ctx.resolvedPluginConfig.entryWorkerEnvironmentName;
outputConfig = {
...inputWorkerConfig,
main: entryChunk.fileName,
no_bundle: true,
rules: [{
type: "ESModule",
globs: ["**/*.js", "**/*.mjs"]
}],
assets: isEntryWorker || isPrerenderWorker ? {
...inputWorkerConfig.assets,
directory: getAssetsDirectory(this.environment.config.build.outDir, ctx.resolvedViteConfig)
} : void 0
};
if (inputWorkerConfig.upload_source_maps === void 0 && this.environment.config.build.sourcemap) outputConfig.upload_source_maps = true;
if (inputWorkerConfig.configPath) {
const localDevVars = getLocalDevVarsForPreview(inputWorkerConfig, ctx.resolvedPluginConfig.cloudflareEnv);
if (localDevVars) this.emitFile({
type: "asset",
fileName: ".dev.vars",
source: localDevVars
});
}
} else if (this.environment.name === "client") {
const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
const existingAssetsIgnoreContent = ctx.resolvedViteConfig.publicDir.length > 0 ? readAssetsIgnoreFile(nodePath.join(ctx.resolvedViteConfig.publicDir, ".assetsignore")) : "";
this.emitFile({
type: "asset",
fileName: ".assetsignore",
source: `${existingAssetsIgnoreContent}${filesToAssetsIgnore.join("\n")}\n`
});
if (ctx.resolvedPluginConfig.type === "assets-only") {
const inputAssetsOnlyConfig = ctx.resolvedPluginConfig.config;
outputConfig = {
...inputAssetsOnlyConfig,
assets: {
...inputAssetsOnlyConfig.assets,
directory: "."
}
};
}
}
if (!outputConfig) return;
if (outputConfig.unsafe && Object.keys(outputConfig.unsafe).length === 0) outputConfig.unsafe = void 0;
this.emitFile({
type: "asset",
fileName: "wrangler.json",
source: JSON.stringify(outputConfig)
});
},
writeBundle() {
assertIsNotPreview(ctx);
if (this.environment.name === (ctx.resolvedPluginConfig.type === "workers" ? ctx.resolvedPluginConfig.entryWorkerEnvironmentName : "client")) writeDeployConfig(ctx.resolvedPluginConfig, ctx.resolvedViteConfig);
}
};
});
function readAssetsIgnoreFile(assetsIgnorePath) {
const content = existsSync(assetsIgnorePath) ? readFileSync(assetsIgnorePath, "utf-8") : "";
if (content.length === 0) return "";
return content.at(-1) === "\n" ? content : `${content}\n`;
}
function getAssetsDirectory(workerOutputDirectory, resolvedViteConfig) {
const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
assert(clientOutputDirectory, "Unexpected error: client output directory is undefined");
return vite.normalizePath(nodePath.relative(nodePath.resolve(resolvedViteConfig.root, workerOutputDirectory), nodePath.resolve(resolvedViteConfig.root, clientOutputDirectory)));
}
//#endregion
//#region src/plugins/preview.ts
var import_picocolors$1 = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
let exitCallback = () => {};
process.on("exit", () => {
exitCallback();
});
/**
* Plugin to provide core preview functionality
*/
const previewPlugin = createPlugin("preview", (ctx) => {
return { async configurePreviewServer(vitePreviewServer) {
assertIsPreview(ctx);
const closePreviewServer = vitePreviewServer.close.bind(vitePreviewServer);
vitePreviewServer.close = async () => {
await Promise.all([ctx.disposeMiniflare(), closePreviewServer()]);
};
const { miniflareOptions, containerTagToOptionsMap } = await getPreviewMiniflareOptions(ctx, vitePreviewServer);
await ctx.startOrUpdateMiniflare(miniflareOptions);
if (vitePreviewServer.httpServer) vitePreviewServer.httpServer.on("listening", () => {
const addr = vitePreviewServer.httpServer?.address();
if (typeof addr === "object" && addr !== null) {
const serverConfig = vitePreviewServer.config.preview;
ctx.miniflare.publicUrl = buildPublicUrl({
hostname: typeof serverConfig.host === "string" ? serverConfig.host : void 0,
port: addr.port,
secure: !!serverConfig.https
});
}
});
if (containerTagToOptionsMap.size) {
const dockerPath = getDockerPath();
vitePreviewServer.config.logger.info(import_picocolors$1.default.dim(import_picocolors$1.default.yellow("∷ Building container images for local preview...\n")));
if ([...containerTagToOptionsMap.values()].some((opts) => "image_uri" in opts && new URL(`http://${opts.image_uri}`).hostname === getCloudflareContainerRegistry())) {
const apiToken = process.env.CLOUDFLARE_API_TOKEN;
const accountId = ctx.allWorkerConfigs[0]?.account_id ?? process.env.CLOUDFLARE_ACCOUNT_ID;
if (!apiToken || !accountId) throw new UserError("To use images from the Cloudflare-managed registry with the Vite plugin, set the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID environment variables.\nThe API token requires Containers:Edit and Workers Scripts:Edit permissions.\nAlternatively, use a Dockerfile that references the image via FROM.", { telemetryMessage: false });
configureOpenAPIForContainerPull(accountId, apiToken);
}
await prepareContainerImagesForDev({
dockerPath: getDockerPath(),
containerOptions: [...containerTagToOptionsMap.values()],
onContainerImagePreparationStart: () => {},
onContainerImagePreparationEnd: () => {},
logger: vitePreviewServer.config.logger
});
const containerImageTags = new Set(containerTagToOptionsMap.keys());
vitePreviewServer.config.logger.info(import_picocolors$1.default.dim(import_picocolors$1.default.yellow("\n⚡️ Containers successfully built.\n")));
exitCallback = () => {
if (containerImageTags.size) cleanupContainers(dockerPath, containerImageTags);
};
}
handleWebSocket(vitePreviewServer.httpServer, ctx.miniflare);
vitePreviewServer.middlewares.use(createRequestHandler((request$2) => {
return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
}));
} };
});
//#endregion
//#region src/plugins/rsc.ts
/**
* Plugin to pass options to `@vitejs/plugin-rsc`
*/
const rscPlugin = createPlugin("rsc", () => {
return {
enforce: "pre",
config() {
return { rsc: { serverHandler: false } };
}
};
});
//#endregion
//#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
let isDockerCached;
function hasDockerEnv() {
try {
fs.statSync("/.dockerenv");
return true;
} catch {
return false;
}
}
function hasDockerCGroup() {
try {
return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
} catch {
return false;
}
}
function isDocker() {
if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
return isDockerCached;
}
//#endregion
//#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
let cachedResult;
const hasContainerEnv = () => {
try {
fs.statSync("/run/.containerenv");
return true;
} catch {
return false;
}
};
function isInsideContainer() {
if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
return cachedResult;
}
//#endregion
//#region ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
const isWsl = () => {
if (process$1.platform !== "linux") return false;
if (os.release().toLowerCase().includes("microsoft")) {
if (isInsideContainer()) return false;
return true;
}
try {
return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
} catch {
return false;
}
};
var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
//#endregion
//#region ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
const execFile$2 = promisify(childProcess.execFile);
const powerShellPath$1 = () => `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
const executePowerShell = async (command, options = {}) => {
const { powerShellPath: psPath,...execFileOptions } = options;
const encodedCommand = executePowerShell.encodeCommand(command);
return execFile$2(psPath ?? powerShellPath$1(), [...executePowerShell.argumentsPrefix, encodedCommand], {
encoding: "utf8",
...execFileOptions
});
};
executePowerShell.argumentsPrefix = [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand"
];
executePowerShell.encodeCommand = (command) => Buffer$1.from(command, "utf16le").toString("base64");
executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
//#endregion
//#region ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
function parseMountPointFromConfig(content) {
for (const line of content.split("\n")) {
if (/^\s*#/.test(line)) continue;
const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
if (!match) continue;
return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
}
}
//#endregion
//#region ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
const execFile$1 = promisify(childProcess.execFile);
const wslDrivesMountPoint = (() => {
const defaultMountPoint = "/mnt/";
let mountPoint;
return async function() {
if (mountPoint) return mountPoint;
const configFilePath = "/etc/wsl.conf";
let isConfigFileExists = false;
try {
await fs$1.access(configFilePath, constants$1.F_OK);
isConfigFileExists = true;
} catch {}
if (!isConfigFileExists) return defaultMountPoint;
const parsedMountPoint = parseMountPointFromConfig(await fs$1.readFile(configFilePath, { encoding: "utf8" }));
if (parsedMountPoint === void 0) return defaultMountPoint;
mountPoint = parsedMountPoint;
mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
return mountPoint;
};
})();
const powerShellPathFromWsl = async () => {
return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
};
const powerShellPath = is_wsl_default ? powerShellPathFromWsl : powerShellPath$1;
let canAccessPowerShellPromise;
const canAccessPowerShell = async () => {
canAccessPowerShellPromise ??= (async () => {
try {
const psPath = await powerShellPath();
await fs$1.access(psPath, constants$1.X_OK);
return true;
} catch {
return false;
}
})();
return canAccessPowerShellPromise;
};
const wslDefaultBrowser = async () => {
const psPath = await powerShellPath();
const { stdout } = await executePowerShell(String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`, { powerShellPath: psPath });
return stdout.trim();
};
const convertWslPathToWindows = async (path$2) => {
if (/^[a-z]+:\/\//i.test(path$2)) return path$2;
try {
const { stdout } = await execFile$1("wslpath", ["-aw", path$2], { encoding: "utf8" });
return stdout.trim();
} catch {
return path$2;
}
};
//#endregion
//#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
function defineLazyProperty(object, propertyName, valueGetter) {
const define$1 = (value) => Object.defineProperty(object, propertyName, {
value,
enumerable: true,
writable: true
});
Object.defineProperty(object, propertyName, {
configurable: true,
enumerable: true,
get() {
const result = valueGetter();
define$1(result);
return result;
},
set(value) {
define$1(value);
}
});
return object;
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
const execFileAsync$3 = promisify(execFile);
async function defaultBrowserId() {
if (process$1.platform !== "darwin") throw new Error("macOS only");
const { stdout } = await execFileAsync$3("defaults", [
"read",
"com.apple.LaunchServices/com.apple.launchservices.secure",
"LSHandlers"
]);
const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
if (browserId === "com.apple.safari") return "com.apple.Safari";
return browserId;
}
//#endregion
//#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
const execFileAsync$2 = promisify(execFile);
async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
if (process$1.platform !== "darwin") throw new Error("macOS only");
const outputArguments = humanReadableOutput ? [] : ["-ss"];
const execOptions = {};
if (signal) execOptions.signal = signal;
const { stdout } = await execFileAsync$2("osascript", [
"-e",
script,
outputArguments
], execOptions);
return stdout.trim();
}
//#endregion
//#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
async function bundleName(bundleId) {
return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser@5.4.0/node_modules/default-browser/windows.js
const execFileAsync$1 = promisify(execFile);
const windowsBrowserProgIds = {
MSEdgeHTM: {
name: "Edge",
id: "com.microsoft.edge"
},
MSEdgeBHTML: {
name: "Edge Beta",
id: "com.microsoft.edge.beta"
},
MSEdgeDHTML: {
name: "Edge Dev",
id: "com.microsoft.edge.dev"
},
AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
name: "Edge",
id: "com.microsoft.edge.old"
},
ChromeHTML: {
name: "Chrome",
id: "com.google.chrome"
},
ChromeBHTML: {
name: "Chrome Beta",
id: "com.google.chrome.beta"
},
ChromeDHTML: {
name: "Chrome Dev",
id: "com.google.chrome.dev"
},
ChromiumHTM: {
name: "Chromium",
id: "org.chromium.Chromium"
},
BraveHTML: {
name: "Brave",
id: "com.brave.Browser"
},
BraveBHTML: {
name: "Brave Beta",
id: "com.brave.Browser.beta"
},
BraveDHTML: {
name: "Brave Dev",
id: "com.brave.Browser.dev"
},
BraveSSHTM: {
name: "Brave Nightly",
id: "com.brave.Browser.nightly"
},
FirefoxURL: {
name: "Firefox",
id: "org.mozilla.firefox"
},
OperaStable: {
name: "Opera",
id: "com.operasoftware.Opera"
},
VivaldiHTM: {
name: "Vivaldi",
id: "com.vivaldi.Vivaldi"
},
"IE.HTTP": {
name: "Internet Explorer",
id: "com.microsoft.ie"
}
};
const _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
var UnknownBrowserError = class extends Error {};
async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
const { stdout } = await _execFileAsync("reg", [
"QUERY",
" HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
"/v",
"ProgId"
]);
const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
const { id } = match.groups;
const browser = windowsBrowserProgIds[id];
if (!browser) throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
return browser;
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser@5.4.0/node_modules/default-browser/index.js
const execFileAsync = promisify(execFile);
const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
async function defaultBrowser() {
if (process$1.platform === "darwin") {
const id = await defaultBrowserId();
return {
name: await bundleName(id),
id
};
}
if (process$1.platform === "linux") {
const { stdout } = await execFileAsync("xdg-mime", [
"query",
"default",
"x-scheme-handler/http"
]);
const id = stdout.trim();
return {
name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
id
};
}
if (process$1.platform === "win32") return defaultBrowser$1();
throw new Error("Only macOS, Linux, and Windows are supported");
}
//#endregion
//#region ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
const isInSsh = Boolean(process$1.env.SSH_CONNECTION || process$1.env.SSH_CLIENT || process$1.env.SSH_TTY);
var is_in_ssh_default = isInSsh;
//#endregion
//#region ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
const fallbackAttemptSymbol = Symbol("fallbackAttempt");
const __dirname = import.meta.url ? path.dirname(fileURLToPath(import.meta.url)) : "";
const localXdgOpenPath = path.join(__dirname, "xdg-open");
const { platform, arch: arch$1 } = process$1;
const tryEachApp = async (apps$1, opener) => {
if (apps$1.length === 0) return;
const errors$1 = [];
for (const app of apps$1) try {
return await opener(app);
} catch (error) {
errors$1.push(error);
}
throw new AggregateError(errors$1, "Failed to open in all supported apps");
};
const baseOpen = async (options) => {
options = {
wait: false,
background: false,
newInstance: false,
allowNonzeroExitCode: false,
...options
};
const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
delete options[fallbackAttemptSymbol];
if (Array.isArray(options.app)) return tryEachApp(options.app, (singleApp) => baseOpen({
...options,
app: singleApp,
[fallbackAttemptSymbol]: true
}));
let { name: app, arguments: appArguments = [] } = options.app ?? {};
appArguments = [...appArguments];
if (Array.isArray(app)) return tryEachApp(app, (appName) => baseOpen({
...options,
app: {
name: appName,
arguments: appArguments
},
[fallbackAttemptSymbol]: true
}));
if (app === "browser" || app === "browserPrivate") {
const ids = {
"com.google.chrome": "chrome",
"google-chrome.desktop": "chrome",
"com.brave.browser": "brave",
"org.mozilla.firefox": "firefox",
"firefox.desktop": "firefox",
"com.microsoft.msedge": "edge",
"com.microsoft.edge": "edge",
"com.microsoft.edgemac": "edge",
"microsoft-edge.desktop": "edge",
"com.apple.safari": "safari"
};
const flags = {
chrome: "--incognito",
brave: "--incognito",
firefox: "--private-window",
edge: "--inPrivate"
};
let browser;
if (is_wsl_default) {
const progId = await wslDefaultBrowser();
browser = _windowsBrowserProgIdMap.get(progId) ?? {};
} else browser = await defaultBrowser();
if (browser.id in ids) {
const browserName = ids[browser.id.toLowerCase()];
if (app === "browserPrivate") {
if (browserName === "safari") throw new Error("Safari doesn't support opening in private mode via command line");
appArguments.push(flags[browserName]);
}
return baseOpen({
...options,
app: {
name: apps[browserName],
arguments: appArguments
}
});
}
throw new Error(`${browser.name} is not supported as a default browser`);
}
let command;
const cliArguments = [];
const childProcessOptions = {};
let shouldUseWindowsInWsl = false;
if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) shouldUseWindowsInWsl = await canAccessPowerShell();
if (platform === "darwin") {
command = "open";
if (options.wait) cliArguments.push("--wait-apps");
if (options.background) cliArguments.push("--background");
if (options.newInstance) cliArguments.push("--new");
if (app) cliArguments.push("-a", app);
} else if (platform === "win32" || shouldUseWindowsInWsl) {
command = await powerShellPath();
cliArguments.push(...executePowerShell.argumentsPrefix);
if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
if (is_wsl_default && options.target) options.target = await convertWslPathToWindows(options.target);
const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
if (options.wait) encodedArguments.push("-Wait");
if (app) {
encodedArguments.push(executePowerShell.escapeArgument(app));
if (options.target) appArguments.push(options.target);
} else if (options.target) encodedArguments.push(executePowerShell.escapeArgument(options.target));
if (appArguments.length > 0) {
appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
encodedArguments.push("-ArgumentList", appArguments.join(","));
}
options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
if (!options.wait) childProcessOptions.stdio = "ignore";
} else {
if (app) command = app;
else {
const isBundled = !__dirname || __dirname === "/";
let exeLocalXdgOpen = false;
try {
await fs$1.access(localXdgOpenPath, constants$1.X_OK);
exeLocalXdgOpen = true;
} catch {}
command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
}
if (appArguments.length > 0) cliArguments.push(...appArguments);
if (!options.wait) {
childProcessOptions.stdio = "ignore";
childProcessOptions.detached = true;
}
}
if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
if (options.target) cliArguments.push(options.target);
const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
if (options.wait) return new Promise((resolve$4, reject) => {
subprocess.once("error", reject);
subprocess.once("close", (exitCode) => {
if (!options.allowNonzeroExitCode && exitCode !== 0) {
reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
return;
}
resolve$4(subprocess);
});
});
if (isFallbackAttempt) return new Promise((resolve$4, reject) => {
subprocess.once("error", reject);
subprocess.once("spawn", () => {
subprocess.once("close", (exitCode) => {
subprocess.off("error", reject);
if (exitCode !== 0) {
reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
return;
}
subprocess.unref();
resolve$4(subprocess);
});
});
});
subprocess.unref();
return new Promise((resolve$4, reject) => {
subprocess.once("error", reject);
subprocess.once("spawn", () => {
subprocess.off("error", reject);
resolve$4(subprocess);
});
});
};
const open = (target$1, options) => {
if (typeof target$1 !== "string") throw new TypeError("Expected a `target`");
return baseOpen({
...options,
target: target$1
});
};
function detectArchBinary(binary) {
if (typeof binary === "string" || Array.isArray(binary)) return binary;
const { [arch$1]: archBinary } = binary;
if (!archBinary) throw new Error(`${arch$1} is not supported`);
return archBinary;
}
function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
if (wsl && is_wsl_default) return detectArchBinary(wsl);
if (!platformBinary) throw new Error(`${platform} is not supported`);
return detectArchBinary(platformBinary);
}
const apps = {
browser: "browser",
browserPrivate: "browserPrivate"
};
defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
darwin: "google chrome",
win32: "chrome",
linux: [
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser"
]
}, { 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, "brave", () => detectPlatformBinary({
darwin: "brave browser",
win32: "brave",
linux: ["brave-browser", "brave"]
}, { wsl: {
ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
} }));
defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
darwin: "firefox",
win32: String.raw`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" }));
defineLazyProperty(apps, "safari", () => detectPlatformBinary({ darwin: "Safari" }));
var open_default = open;
//#endregion
//#region src/plugins/shortcuts.ts
var import_picocolors = /* @__PURE__ */ __toESM$1(require_picocolors(), 1);
const shortcutsPlugin = createPlugin("shortcuts", (ctx) => {
const isCustomShortcutsSupported = satisfiesMinimumViteVersion("7.2.7");
return {
async configureServer(viteDevServer) {
if (!isCustomShortcutsSupported) return;
assertIsNotPreview(ctx);
addShortcuts(viteDevServer, ctx);
},
async configurePreviewServer(vitePreviewServer) {
if (!isCustomShortcutsSupported) return;
assertIsPreview(ctx);
addShortcuts(vitePreviewServer, ctx);
}
};
});
function addShortcuts(server, ctx) {
if (!process.stdin.isTTY) return;
const registryPath = getDefaultDevRegistryPath();
const printBindingsShortcut = {
key: "b",
description: "list configured Cloudflare bindings",
action: (viteServer) => {
viteServer.config.logger.info("");
const workerConfigs = ctx.allWorkerConfigs;
for (const workerConfig of workerConfigs) {
const bindings = wrangler.unstable_convertConfigBindingsToStartWorkerBindings(workerConfig);
wrangler.unstable_printBindings(bindings, workerConfig.tail_consumers, workerConfig.streaming_tail_consumers, workerConfig.containers, {
warnIfNoBindings: true,
isMultiWorker: workerConfigs.length > 1,
name: workerConfig.name ?? "Your Worker",
registry: getWorkerRegistry(registryPath),
log: (message) => viteServer.config.logger.info(message)
});
}
}
};
const openExplorerShortcut = {
key: "e",
description: "open local explorer",
action: async (viteServer) => {
const url = viteServer.resolvedUrls?.local[0];
if (!url) {
viteServer.config.logger.warn("No local URL available");
return;
}
const explorerUrl = new URL(CorePaths.EXPLORER, url).href;
(await open_default(explorerUrl)).on("error", () => {
viteServer.config.logger.warn("Failed to open browser, the local explorer can be accessed at " + explorerUrl);
});
}
};
const toggleTunnelShortcut = {
key: "t",
description: "start or close tunnel",
action: () => {
toggleTunnel(server, ctx).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
server.config.logger.error(import_picocolors.default.red(`Error: ${message}`));
});
}
};
const extendTunnelExpiryShortcut = {
key: "a",
description: "extend tunnel by 1 hour",
action: () => {
extendTunnelExpiry();
}
};
const bindCLIShortcuts = server.bindCLIShortcuts.bind(server);
server.bindCLIShortcuts = (options) => {
if (server.httpServer && process.stdin.isTTY && !process.env.CI && options?.print) {
if (ctx.allWorkerConfigs.length > 0) server.config.logger.info(import_picocolors.default.dim(import_picocolors.default.green(" ➜")) + import_picocolors.default.dim(" press ") + import_picocolors.default.bold(`${printBindingsShortcut.key} + enter`) + import_picocolors.default.dim(` to ${printBindingsShortcut.description}`));
server.config.logger.info(import_picocolors.default.dim(import_picocolors.default.green(" ➜")) + import_picocolors.default.dim(" press ") + import_picocolors.default.bold(`${openExplorerShortcut.key} + enter`) + import_picocolors.default.dim(` to ${openExplorerShortcut.description}`));
server.config.logger.info(import_picocolors.default.dim(import_picocolors.default.green(" ➜")) + import_picocolors.default.dim(" press ") + import_picocolors.default.bold(`${toggleTunnelShortcut.key} + enter`) + import_picocolors.default.dim(` to ${isTunnelOpen() ? "close tunnel" : "start tunnel"}`));
}
bindCLIShortcuts(options);
};
server.bindCLIShortcuts({ customShortcuts: [
printBindingsShortcut,
openExplorerShortcut,
toggleTunnelShortcut,
extendTunnelExpiryShortcut
] });
}
//#endregion
//#region src/plugins/trigger-handlers.ts
/**
* Plugin to forward `/cdn-cgi/handler/*` routes to trigger handlers in development
*/
const triggerHandlersPlugin = createPlugin("trigger-handlers", (ctx) => {
return {
enforce: "pre",
async configureServer(viteDevServer) {
const entryWorkerConfig = ctx.entryWorkerConfig;
if (!entryWorkerConfig) return;
const entryWorkerName = entryWorkerConfig.name;
const requestHandler = createRequestHandler((request$2) => {
request$2.headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
return ctx.miniflare.dispatchFetch(request$2, { redirect: "manual" });
});
viteDevServer.middlewares.use("/cdn-cgi/handler/", requestHandler);
}
};
});
//#endregion
//#region src/plugins/wasm.ts
const wasmInitRE = /\.wasm\?init$/;
/**
* Plugin to support the `.wasm?init` extension
*/
const wasmHelperPlugin = createPlugin("wasm-helper", (ctx) => {
return {
enforce: "pre",
applyToEnvironment(environment) {
return ctx.getWorkerConfig(environment.name) !== void 0;
},
load: {
filter: { id: wasmInitRE },
handler(id) {
if (!wasmInitRE.test(id)) return;
return `
import wasm from "${cleanUrl(id)}";
export default function(opts = {}) {
return WebAssembly.instantiate(wasm, opts);
}
`;
}
}
};
});
//#endregion
//#region src/index.ts
/**
* @deprecated Use today's date instead (as `YYYY-MM-DD`)
*
* Gets the compatibility date to use with the local workerd version.
*
* Note: the function's signature is as is because it needs to be backward compatibly with
* a previous iteration of this, it will be simplified in the next major version of this package.
*
* @param _options Unused argument (present only for backward compatibility)
* @returns Object containing the compatibility date (this is not the date directly for backward compatibility)
*/
function getLocalWorkerdCompatibilityDate(_options) {
return {
date: DEFAULT_COMPAT_DATE,
source: "workerd"
};
}
const sharedContext = {
hasShownWorkerConfigWarnings: false,
restartingDevServerCount: 0,
tunnelHostnames: /* @__PURE__ */ new Set()
};
await assertWranglerVersion();
/**
* Vite plugin that enables a full-featured integration between Vite and the Cloudflare Workers runtime.
*
* See the [README](https://github.com/cloudflare/workers-sdk/tree/main/packages/vite-plugin-cloudflare#readme) for more details.
*
* @param pluginConfig An optional {@link PluginConfig} object.
*/
function cloudflare(pluginConfig = {}) {
const ctx = new PluginContext(sharedContext);
return [
{
name: "vite-plugin-cloudflare",
sharedDuringBuild: true,
config(userConfig, env$1) {
ctx.setResolvedPluginConfig(resolvePluginConfig(pluginConfig, userConfig, env$1));
if (env$1.command === "build") process.env.CLOUDFLARE_VITE_BUILD = "true";
},
async configureServer(viteDevServer) {
const restartServer = viteDevServer.restart.bind(viteDevServer);
viteDevServer.restart = async () => {
try {
ctx.beginRestartingDevServer();
debuglog("From server.restart(): Restarting server...");
await restartServer();
debuglog("From server.restart(): Restarted server...");
} finally {
ctx.endRestartingDevServer();
}
};
}
},
configPlugin(ctx),
rscPlugin(ctx),
devPlugin(ctx),
tunnelPlugin(ctx),
previewPlugin(ctx),
shortcutsPlugin(ctx),
debugPlugin(ctx),
triggerHandlersPlugin(ctx),
virtualModulesPlugin(ctx),
virtualClientFallbackPlugin(ctx),
outputConfigPlugin(ctx),
wasmHelperPlugin(ctx),
additionalModulesPlugin(ctx),
nodeJsAlsPlugin(ctx),
nodeJsCompatPlugin(ctx),
nodeJsCompatWarningsPlugin(ctx)
];
}
//#endregion
export { cloudflare, getLocalWorkerdCompatibilityDate };
//# sourceMappingURL=index.mjs.map