Files
METH_Transcendence/site/game/node_modules/.vite/deps/chunk-UIZRH6IJ.js
edbernar 7c3378ed41 Game
- Added request when w or s pressed
2024-08-07 16:22:47 +02:00

57971 lines
1.9 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
require_url
} from "./chunk-MPVQUUHK.js";
import {
require_events,
require_node_os,
require_os,
require_stream,
require_util
} from "./chunk-KPGLAEFU.js";
import {
require_fs
} from "./chunk-I5RSIQOR.js";
import {
parseAst,
parseAstAsync,
require_native,
require_node_fs,
require_node_perf_hooks,
require_promises,
require_tty
} from "./chunk-I6YKGN4K.js";
import {
require_path
} from "./chunk-4XRL7ZXG.js";
import {
require_node_http
} from "./chunk-X45QO7DX.js";
import {
require_node_https
} from "./chunk-OZBCPRVH.js";
import {
require_node_module,
require_node_url
} from "./chunk-G2ZEZZAJ.js";
import {
require_node_path
} from "./chunk-M2MSWSHF.js";
import {
__commonJS,
__privateAdd,
__privateGet,
__privateMethod,
__privateSet,
__privateWrapper,
__publicField,
__require,
__toESM
} from "./chunk-ZSMWDLMK.js";
// browser-external:node:util
var require_node_util = __commonJS({
"browser-external:node:util"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:util" has been externalized for browser compatibility. Cannot access "node:util.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:child_process
var require_child_process = __commonJS({
"browser-external:child_process"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "child_process" has been externalized for browser compatibility. Cannot access "child_process.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:crypto
var require_crypto = __commonJS({
"browser-external:crypto"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "crypto" has been externalized for browser compatibility. Cannot access "crypto.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:worker_threads
var require_worker_threads = __commonJS({
"browser-external:worker_threads"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "worker_threads" has been externalized for browser compatibility. Cannot access "worker_threads.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// node_modules/esbuild/lib/main.js
var require_main = __commonJS({
"node_modules/esbuild/lib/main.js"(exports2, module) {
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var node_exports = {};
__export(node_exports, {
analyzeMetafile: () => analyzeMetafile,
analyzeMetafileSync: () => analyzeMetafileSync,
build: () => build2,
buildSync: () => buildSync,
context: () => context,
default: () => node_default,
formatMessages: () => formatMessages2,
formatMessagesSync: () => formatMessagesSync,
initialize: () => initialize,
stop: () => stop,
transform: () => transform2,
transformSync: () => transformSync,
version: () => version3
});
module.exports = __toCommonJS(node_exports);
function encodePacket(packet) {
let visit2 = (value2) => {
if (value2 === null) {
bb.write8(0);
} else if (typeof value2 === "boolean") {
bb.write8(1);
bb.write8(+value2);
} else if (typeof value2 === "number") {
bb.write8(2);
bb.write32(value2 | 0);
} else if (typeof value2 === "string") {
bb.write8(3);
bb.write(encodeUTF8(value2));
} else if (value2 instanceof Uint8Array) {
bb.write8(4);
bb.write(value2);
} else if (value2 instanceof Array) {
bb.write8(5);
bb.write32(value2.length);
for (let item of value2) {
visit2(item);
}
} else {
let keys = Object.keys(value2);
bb.write8(6);
bb.write32(keys.length);
for (let key of keys) {
bb.write(encodeUTF8(key));
visit2(value2[key]);
}
}
};
let bb = new ByteBuffer();
bb.write32(0);
bb.write32(packet.id << 1 | +!packet.isRequest);
visit2(packet.value);
writeUInt32LE(bb.buf, bb.len - 4, 0);
return bb.buf.subarray(0, bb.len);
}
function decodePacket(bytes) {
let visit2 = () => {
switch (bb.read8()) {
case 0:
return null;
case 1:
return !!bb.read8();
case 2:
return bb.read32();
case 3:
return decodeUTF8(bb.read());
case 4:
return bb.read();
case 5: {
let count = bb.read32();
let value22 = [];
for (let i = 0; i < count; i++) {
value22.push(visit2());
}
return value22;
}
case 6: {
let count = bb.read32();
let value22 = {};
for (let i = 0; i < count; i++) {
value22[decodeUTF8(bb.read())] = visit2();
}
return value22;
}
default:
throw new Error("Invalid packet");
}
};
let bb = new ByteBuffer(bytes);
let id = bb.read32();
let isRequest = (id & 1) === 0;
id >>>= 1;
let value2 = visit2();
if (bb.ptr !== bytes.length) {
throw new Error("Invalid packet");
}
return { id, isRequest, value: value2 };
}
var ByteBuffer = class {
constructor(buf = new Uint8Array(1024)) {
this.buf = buf;
this.len = 0;
this.ptr = 0;
}
_write(delta) {
if (this.len + delta > this.buf.length) {
let clone2 = new Uint8Array((this.len + delta) * 2);
clone2.set(this.buf);
this.buf = clone2;
}
this.len += delta;
return this.len - delta;
}
write8(value2) {
let offset2 = this._write(1);
this.buf[offset2] = value2;
}
write32(value2) {
let offset2 = this._write(4);
writeUInt32LE(this.buf, value2, offset2);
}
write(bytes) {
let offset2 = this._write(4 + bytes.length);
writeUInt32LE(this.buf, bytes.length, offset2);
this.buf.set(bytes, offset2 + 4);
}
_read(delta) {
if (this.ptr + delta > this.buf.length) {
throw new Error("Invalid packet");
}
this.ptr += delta;
return this.ptr - delta;
}
read8() {
return this.buf[this._read(1)];
}
read32() {
return readUInt32LE(this.buf, this._read(4));
}
read() {
let length = this.read32();
let bytes = new Uint8Array(length);
let ptr = this._read(bytes.length);
bytes.set(this.buf.subarray(ptr, ptr + length));
return bytes;
}
};
var encodeUTF8;
var decodeUTF8;
var encodeInvariant;
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
let encoder = new TextEncoder();
let decoder2 = new TextDecoder();
encodeUTF8 = (text) => encoder.encode(text);
decodeUTF8 = (bytes) => decoder2.decode(bytes);
encodeInvariant = 'new TextEncoder().encode("")';
} else if (typeof Buffer !== "undefined") {
encodeUTF8 = (text) => Buffer.from(text);
decodeUTF8 = (bytes) => {
let { buffer, byteOffset, byteLength } = bytes;
return Buffer.from(buffer, byteOffset, byteLength).toString();
};
encodeInvariant = 'Buffer.from("")';
} else {
throw new Error("No UTF-8 codec found");
}
if (!(encodeUTF8("") instanceof Uint8Array))
throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
`);
function readUInt32LE(buffer, offset2) {
return buffer[offset2++] | buffer[offset2++] << 8 | buffer[offset2++] << 16 | buffer[offset2++] << 24;
}
function writeUInt32LE(buffer, value2, offset2) {
buffer[offset2++] = value2;
buffer[offset2++] = value2 >> 8;
buffer[offset2++] = value2 >> 16;
buffer[offset2++] = value2 >> 24;
}
var quote3 = JSON.stringify;
var buildLogLevelDefault = "warning";
var transformLogLevelDefault = "silent";
function validateTarget(target) {
validateStringValue(target, "target");
if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`);
return target;
}
var canBeAnything = () => null;
var mustBeBoolean = (value2) => typeof value2 === "boolean" ? null : "a boolean";
var mustBeString = (value2) => typeof value2 === "string" ? null : "a string";
var mustBeRegExp = (value2) => value2 instanceof RegExp ? null : "a RegExp object";
var mustBeInteger = (value2) => typeof value2 === "number" && value2 === (value2 | 0) ? null : "an integer";
var mustBeFunction = (value2) => typeof value2 === "function" ? null : "a function";
var mustBeArray = (value2) => Array.isArray(value2) ? null : "an array";
var mustBeObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2) ? null : "an object";
var mustBeEntryPoints = (value2) => typeof value2 === "object" && value2 !== null ? null : "an array or an object";
var mustBeWebAssemblyModule = (value2) => value2 instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
var mustBeObjectOrNull = (value2) => typeof value2 === "object" && !Array.isArray(value2) ? null : "an object or null";
var mustBeStringOrBoolean = (value2) => typeof value2 === "string" || typeof value2 === "boolean" ? null : "a string or a boolean";
var mustBeStringOrObject = (value2) => typeof value2 === "string" || typeof value2 === "object" && value2 !== null && !Array.isArray(value2) ? null : "a string or an object";
var mustBeStringOrArray = (value2) => typeof value2 === "string" || Array.isArray(value2) ? null : "a string or an array";
var mustBeStringOrUint8Array = (value2) => typeof value2 === "string" || value2 instanceof Uint8Array ? null : "a string or a Uint8Array";
var mustBeStringOrURL = (value2) => typeof value2 === "string" || value2 instanceof URL ? null : "a string or a URL";
function getFlag(object, keys, key, mustBeFn) {
let value2 = object[key];
keys[key + ""] = true;
if (value2 === void 0) return void 0;
let mustBe = mustBeFn(value2);
if (mustBe !== null) throw new Error(`${quote3(key)} must be ${mustBe}`);
return value2;
}
function checkForInvalidFlags(object, keys, where) {
for (let key in object) {
if (!(key in keys)) {
throw new Error(`Invalid option ${where}: ${quote3(key)}`);
}
}
}
function validateInitializeOptions(options2) {
let keys = /* @__PURE__ */ Object.create(null);
let wasmURL = getFlag(options2, keys, "wasmURL", mustBeStringOrURL);
let wasmModule = getFlag(options2, keys, "wasmModule", mustBeWebAssemblyModule);
let worker = getFlag(options2, keys, "worker", mustBeBoolean);
checkForInvalidFlags(options2, keys, "in initialize() call");
return {
wasmURL,
wasmModule,
worker
};
}
function validateMangleCache(mangleCache) {
let validated;
if (mangleCache !== void 0) {
validated = /* @__PURE__ */ Object.create(null);
for (let key in mangleCache) {
let value2 = mangleCache[key];
if (typeof value2 === "string" || value2 === false) {
validated[key] = value2;
} else {
throw new Error(`Expected ${quote3(key)} in mangle cache to map to either a string or false`);
}
}
}
return validated;
}
function pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault) {
let color = getFlag(options2, keys, "color", mustBeBoolean);
let logLevel = getFlag(options2, keys, "logLevel", mustBeString);
let logLimit = getFlag(options2, keys, "logLimit", mustBeInteger);
if (color !== void 0) flags.push(`--color=${color}`);
else if (isTTY2) flags.push(`--color=true`);
flags.push(`--log-level=${logLevel || logLevelDefault}`);
flags.push(`--log-limit=${logLimit || 0}`);
}
function validateStringValue(value2, what, key) {
if (typeof value2 !== "string") {
throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote3(key) : ""} to be a string, got ${typeof value2} instead`);
}
return value2;
}
function pushCommonFlags(flags, options2, keys) {
let legalComments = getFlag(options2, keys, "legalComments", mustBeString);
let sourceRoot = getFlag(options2, keys, "sourceRoot", mustBeString);
let sourcesContent = getFlag(options2, keys, "sourcesContent", mustBeBoolean);
let target = getFlag(options2, keys, "target", mustBeStringOrArray);
let format2 = getFlag(options2, keys, "format", mustBeString);
let globalName = getFlag(options2, keys, "globalName", mustBeString);
let mangleProps = getFlag(options2, keys, "mangleProps", mustBeRegExp);
let reserveProps = getFlag(options2, keys, "reserveProps", mustBeRegExp);
let mangleQuoted = getFlag(options2, keys, "mangleQuoted", mustBeBoolean);
let minify = getFlag(options2, keys, "minify", mustBeBoolean);
let minifySyntax = getFlag(options2, keys, "minifySyntax", mustBeBoolean);
let minifyWhitespace = getFlag(options2, keys, "minifyWhitespace", mustBeBoolean);
let minifyIdentifiers = getFlag(options2, keys, "minifyIdentifiers", mustBeBoolean);
let lineLimit = getFlag(options2, keys, "lineLimit", mustBeInteger);
let drop = getFlag(options2, keys, "drop", mustBeArray);
let dropLabels = getFlag(options2, keys, "dropLabels", mustBeArray);
let charset = getFlag(options2, keys, "charset", mustBeString);
let treeShaking = getFlag(options2, keys, "treeShaking", mustBeBoolean);
let ignoreAnnotations = getFlag(options2, keys, "ignoreAnnotations", mustBeBoolean);
let jsx = getFlag(options2, keys, "jsx", mustBeString);
let jsxFactory = getFlag(options2, keys, "jsxFactory", mustBeString);
let jsxFragment = getFlag(options2, keys, "jsxFragment", mustBeString);
let jsxImportSource = getFlag(options2, keys, "jsxImportSource", mustBeString);
let jsxDev = getFlag(options2, keys, "jsxDev", mustBeBoolean);
let jsxSideEffects = getFlag(options2, keys, "jsxSideEffects", mustBeBoolean);
let define = getFlag(options2, keys, "define", mustBeObject);
let logOverride = getFlag(options2, keys, "logOverride", mustBeObject);
let supported = getFlag(options2, keys, "supported", mustBeObject);
let pure = getFlag(options2, keys, "pure", mustBeArray);
let keepNames = getFlag(options2, keys, "keepNames", mustBeBoolean);
let platform2 = getFlag(options2, keys, "platform", mustBeString);
let tsconfigRaw = getFlag(options2, keys, "tsconfigRaw", mustBeStringOrObject);
if (legalComments) flags.push(`--legal-comments=${legalComments}`);
if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
if (target) {
if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`);
else flags.push(`--target=${validateTarget(target)}`);
}
if (format2) flags.push(`--format=${format2}`);
if (globalName) flags.push(`--global-name=${globalName}`);
if (platform2) flags.push(`--platform=${platform2}`);
if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
if (minify) flags.push("--minify");
if (minifySyntax) flags.push("--minify-syntax");
if (minifyWhitespace) flags.push("--minify-whitespace");
if (minifyIdentifiers) flags.push("--minify-identifiers");
if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
if (charset) flags.push(`--charset=${charset}`);
if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
if (ignoreAnnotations) flags.push(`--ignore-annotations`);
if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`);
if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`);
if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`);
if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
if (jsx) flags.push(`--jsx=${jsx}`);
if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
if (jsxDev) flags.push(`--jsx-dev`);
if (jsxSideEffects) flags.push(`--jsx-side-effects`);
if (define) {
for (let key in define) {
if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
}
}
if (logOverride) {
for (let key in logOverride) {
if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
}
}
if (supported) {
for (let key in supported) {
if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
const value2 = supported[key];
if (typeof value2 !== "boolean") throw new Error(`Expected value for supported ${quote3(key)} to be a boolean, got ${typeof value2} instead`);
flags.push(`--supported:${key}=${value2}`);
}
}
if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
if (keepNames) flags.push(`--keep-names`);
}
function flagsForBuildOptions(callName, options2, isTTY2, logLevelDefault, writeDefault) {
var _a22;
let flags = [];
let entries = [];
let keys = /* @__PURE__ */ Object.create(null);
let stdinContents = null;
let stdinResolveDir = null;
pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault);
pushCommonFlags(flags, options2, keys);
let sourcemap = getFlag(options2, keys, "sourcemap", mustBeStringOrBoolean);
let bundle = getFlag(options2, keys, "bundle", mustBeBoolean);
let splitting = getFlag(options2, keys, "splitting", mustBeBoolean);
let preserveSymlinks = getFlag(options2, keys, "preserveSymlinks", mustBeBoolean);
let metafile = getFlag(options2, keys, "metafile", mustBeBoolean);
let outfile = getFlag(options2, keys, "outfile", mustBeString);
let outdir = getFlag(options2, keys, "outdir", mustBeString);
let outbase = getFlag(options2, keys, "outbase", mustBeString);
let tsconfig = getFlag(options2, keys, "tsconfig", mustBeString);
let resolveExtensions2 = getFlag(options2, keys, "resolveExtensions", mustBeArray);
let nodePathsInput = getFlag(options2, keys, "nodePaths", mustBeArray);
let mainFields = getFlag(options2, keys, "mainFields", mustBeArray);
let conditions = getFlag(options2, keys, "conditions", mustBeArray);
let external = getFlag(options2, keys, "external", mustBeArray);
let packages = getFlag(options2, keys, "packages", mustBeString);
let alias2 = getFlag(options2, keys, "alias", mustBeObject);
let loader = getFlag(options2, keys, "loader", mustBeObject);
let outExtension = getFlag(options2, keys, "outExtension", mustBeObject);
let publicPath = getFlag(options2, keys, "publicPath", mustBeString);
let entryNames = getFlag(options2, keys, "entryNames", mustBeString);
let chunkNames = getFlag(options2, keys, "chunkNames", mustBeString);
let assetNames = getFlag(options2, keys, "assetNames", mustBeString);
let inject = getFlag(options2, keys, "inject", mustBeArray);
let banner = getFlag(options2, keys, "banner", mustBeObject);
let footer = getFlag(options2, keys, "footer", mustBeObject);
let entryPoints = getFlag(options2, keys, "entryPoints", mustBeEntryPoints);
let absWorkingDir = getFlag(options2, keys, "absWorkingDir", mustBeString);
let stdin = getFlag(options2, keys, "stdin", mustBeObject);
let write = (_a22 = getFlag(options2, keys, "write", mustBeBoolean)) != null ? _a22 : writeDefault;
let allowOverwrite = getFlag(options2, keys, "allowOverwrite", mustBeBoolean);
let mangleCache = getFlag(options2, keys, "mangleCache", mustBeObject);
keys.plugins = true;
checkForInvalidFlags(options2, keys, `in ${callName}() call`);
if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
if (bundle) flags.push("--bundle");
if (allowOverwrite) flags.push("--allow-overwrite");
if (splitting) flags.push("--splitting");
if (preserveSymlinks) flags.push("--preserve-symlinks");
if (metafile) flags.push(`--metafile`);
if (outfile) flags.push(`--outfile=${outfile}`);
if (outdir) flags.push(`--outdir=${outdir}`);
if (outbase) flags.push(`--outbase=${outbase}`);
if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
if (packages) flags.push(`--packages=${packages}`);
if (resolveExtensions2) {
let values = [];
for (let value2 of resolveExtensions2) {
validateStringValue(value2, "resolve extension");
if (value2.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value2}`);
values.push(value2);
}
flags.push(`--resolve-extensions=${values.join(",")}`);
}
if (publicPath) flags.push(`--public-path=${publicPath}`);
if (entryNames) flags.push(`--entry-names=${entryNames}`);
if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
if (assetNames) flags.push(`--asset-names=${assetNames}`);
if (mainFields) {
let values = [];
for (let value2 of mainFields) {
validateStringValue(value2, "main field");
if (value2.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value2}`);
values.push(value2);
}
flags.push(`--main-fields=${values.join(",")}`);
}
if (conditions) {
let values = [];
for (let value2 of conditions) {
validateStringValue(value2, "condition");
if (value2.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value2}`);
values.push(value2);
}
flags.push(`--conditions=${values.join(",")}`);
}
if (external) for (let name2 of external) flags.push(`--external:${validateStringValue(name2, "external")}`);
if (alias2) {
for (let old in alias2) {
if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
flags.push(`--alias:${old}=${validateStringValue(alias2[old], "alias", old)}`);
}
}
if (banner) {
for (let type in banner) {
if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
}
}
if (footer) {
for (let type in footer) {
if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
}
}
if (inject) for (let path32 of inject) flags.push(`--inject:${validateStringValue(path32, "inject")}`);
if (loader) {
for (let ext2 in loader) {
if (ext2.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext2}`);
flags.push(`--loader:${ext2}=${validateStringValue(loader[ext2], "loader", ext2)}`);
}
}
if (outExtension) {
for (let ext2 in outExtension) {
if (ext2.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext2}`);
flags.push(`--out-extension:${ext2}=${validateStringValue(outExtension[ext2], "out extension", ext2)}`);
}
}
if (entryPoints) {
if (Array.isArray(entryPoints)) {
for (let i = 0, n2 = entryPoints.length; i < n2; i++) {
let entryPoint = entryPoints[i];
if (typeof entryPoint === "object" && entryPoint !== null) {
let entryPointKeys = /* @__PURE__ */ Object.create(null);
let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i);
if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i);
entries.push([output, input]);
} else {
entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
}
}
} else {
for (let key in entryPoints) {
entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
}
}
}
if (stdin) {
let stdinKeys = /* @__PURE__ */ Object.create(null);
let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object');
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
if (loader2) flags.push(`--loader=${loader2}`);
if (resolveDir) stdinResolveDir = resolveDir;
if (typeof contents === "string") stdinContents = encodeUTF8(contents);
else if (contents instanceof Uint8Array) stdinContents = contents;
}
let nodePaths = [];
if (nodePathsInput) {
for (let value2 of nodePathsInput) {
value2 += "";
nodePaths.push(value2);
}
}
return {
entries,
flags,
write,
stdinContents,
stdinResolveDir,
absWorkingDir,
nodePaths,
mangleCache: validateMangleCache(mangleCache)
};
}
function flagsForTransformOptions(callName, options2, isTTY2, logLevelDefault) {
let flags = [];
let keys = /* @__PURE__ */ Object.create(null);
pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault);
pushCommonFlags(flags, options2, keys);
let sourcemap = getFlag(options2, keys, "sourcemap", mustBeStringOrBoolean);
let sourcefile = getFlag(options2, keys, "sourcefile", mustBeString);
let loader = getFlag(options2, keys, "loader", mustBeString);
let banner = getFlag(options2, keys, "banner", mustBeString);
let footer = getFlag(options2, keys, "footer", mustBeString);
let mangleCache = getFlag(options2, keys, "mangleCache", mustBeObject);
checkForInvalidFlags(options2, keys, `in ${callName}() call`);
if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
if (loader) flags.push(`--loader=${loader}`);
if (banner) flags.push(`--banner=${banner}`);
if (footer) flags.push(`--footer=${footer}`);
return {
flags,
mangleCache: validateMangleCache(mangleCache)
};
}
function createChannel(streamIn) {
const requestCallbacksByKey = {};
const closeData = { didClose: false, reason: "" };
let responseCallbacks = {};
let nextRequestID = 0;
let nextBuildKey = 0;
let stdout = new Uint8Array(16 * 1024);
let stdoutUsed = 0;
let readFromStdout = (chunk) => {
let limit = stdoutUsed + chunk.length;
if (limit > stdout.length) {
let swap = new Uint8Array(limit * 2);
swap.set(stdout);
stdout = swap;
}
stdout.set(chunk, stdoutUsed);
stdoutUsed += chunk.length;
let offset2 = 0;
while (offset2 + 4 <= stdoutUsed) {
let length = readUInt32LE(stdout, offset2);
if (offset2 + 4 + length > stdoutUsed) {
break;
}
offset2 += 4;
handleIncomingPacket(stdout.subarray(offset2, offset2 + length));
offset2 += length;
}
if (offset2 > 0) {
stdout.copyWithin(0, offset2, stdoutUsed);
stdoutUsed -= offset2;
}
};
let afterClose = (error2) => {
closeData.didClose = true;
if (error2) closeData.reason = ": " + (error2.message || error2);
const text = "The service was stopped" + closeData.reason;
for (let id in responseCallbacks) {
responseCallbacks[id](text, null);
}
responseCallbacks = {};
};
let sendRequest = (refs, value2, callback) => {
if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
let id = nextRequestID++;
responseCallbacks[id] = (error2, response) => {
try {
callback(error2, response);
} finally {
if (refs) refs.unref();
}
};
if (refs) refs.ref();
streamIn.writeToStdin(encodePacket({ id, isRequest: true, value: value2 }));
};
let sendResponse = (id, value2) => {
if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
streamIn.writeToStdin(encodePacket({ id, isRequest: false, value: value2 }));
};
let handleRequest = async (id, request) => {
try {
if (request.command === "ping") {
sendResponse(id, {});
return;
}
if (typeof request.key === "number") {
const requestCallbacks = requestCallbacksByKey[request.key];
if (!requestCallbacks) {
return;
}
const callback = requestCallbacks[request.command];
if (callback) {
await callback(id, request);
return;
}
}
throw new Error(`Invalid command: ` + request.command);
} catch (e2) {
const errors = [extractErrorMessageV8(e2, streamIn, null, void 0, "")];
try {
sendResponse(id, { errors });
} catch {
}
}
};
let isFirstPacket = true;
let handleIncomingPacket = (bytes) => {
if (isFirstPacket) {
isFirstPacket = false;
let binaryVersion = String.fromCharCode(...bytes);
if (binaryVersion !== "0.21.5") {
throw new Error(`Cannot start service: Host version "${"0.21.5"}" does not match binary version ${quote3(binaryVersion)}`);
}
return;
}
let packet = decodePacket(bytes);
if (packet.isRequest) {
handleRequest(packet.id, packet.value);
} else {
let callback = responseCallbacks[packet.id];
delete responseCallbacks[packet.id];
if (packet.value.error) callback(packet.value.error, {});
else callback(null, packet.value);
}
};
let buildOrContext = ({ callName, refs, options: options2, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
let refCount = 0;
const buildKey = nextBuildKey++;
const requestCallbacks = {};
const buildRefs = {
ref() {
if (++refCount === 1) {
if (refs) refs.ref();
}
},
unref() {
if (--refCount === 0) {
delete requestCallbacksByKey[buildKey];
if (refs) refs.unref();
}
}
};
requestCallbacksByKey[buildKey] = requestCallbacks;
buildRefs.ref();
buildOrContextImpl(
callName,
buildKey,
sendRequest,
sendResponse,
buildRefs,
streamIn,
requestCallbacks,
options2,
isTTY2,
defaultWD2,
(err2, res) => {
try {
callback(err2, res);
} finally {
buildRefs.unref();
}
}
);
};
let transform22 = ({ callName, refs, input, options: options2, isTTY: isTTY2, fs: fs3, callback }) => {
const details = createObjectStash();
let start = (inputPath) => {
try {
if (typeof input !== "string" && !(input instanceof Uint8Array))
throw new Error('The input to "transform" must be a string or a Uint8Array');
let {
flags,
mangleCache
} = flagsForTransformOptions(callName, options2, isTTY2, transformLogLevelDefault);
let request = {
command: "transform",
flags,
inputFS: inputPath !== null,
input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
};
if (mangleCache) request.mangleCache = mangleCache;
sendRequest(refs, request, (error2, response) => {
if (error2) return callback(new Error(error2), null);
let errors = replaceDetailsInMessages(response.errors, details);
let warnings = replaceDetailsInMessages(response.warnings, details);
let outstanding = 1;
let next = () => {
if (--outstanding === 0) {
let result = {
warnings,
code: response.code,
map: response.map,
mangleCache: void 0,
legalComments: void 0
};
if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
callback(null, result);
}
};
if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
if (response.codeFS) {
outstanding++;
fs3.readFile(response.code, (err2, contents) => {
if (err2 !== null) {
callback(err2, null);
} else {
response.code = contents;
next();
}
});
}
if (response.mapFS) {
outstanding++;
fs3.readFile(response.map, (err2, contents) => {
if (err2 !== null) {
callback(err2, null);
} else {
response.map = contents;
next();
}
});
}
next();
});
} catch (e2) {
let flags = [];
try {
pushLogFlags(flags, options2, {}, isTTY2, transformLogLevelDefault);
} catch {
}
const error2 = extractErrorMessageV8(e2, streamIn, details, void 0, "");
sendRequest(refs, { command: "error", flags, error: error2 }, () => {
error2.detail = details.load(error2.detail);
callback(failureErrorWithLog("Transform failed", [error2], []), null);
});
}
};
if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
let next = start;
start = () => fs3.writeFile(input, next);
}
start(null);
};
let formatMessages22 = ({ callName, refs, messages: messages2, options: options2, callback }) => {
if (!options2) throw new Error(`Missing second argument in ${callName}() call`);
let keys = {};
let kind = getFlag(options2, keys, "kind", mustBeString);
let color = getFlag(options2, keys, "color", mustBeBoolean);
let terminalWidth = getFlag(options2, keys, "terminalWidth", mustBeInteger);
checkForInvalidFlags(options2, keys, `in ${callName}() call`);
if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
let request = {
command: "format-msgs",
messages: sanitizeMessages(messages2, "messages", null, "", terminalWidth),
isWarning: kind === "warning"
};
if (color !== void 0) request.color = color;
if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
sendRequest(refs, request, (error2, response) => {
if (error2) return callback(new Error(error2), null);
callback(null, response.messages);
});
};
let analyzeMetafile2 = ({ callName, refs, metafile, options: options2, callback }) => {
if (options2 === void 0) options2 = {};
let keys = {};
let color = getFlag(options2, keys, "color", mustBeBoolean);
let verbose = getFlag(options2, keys, "verbose", mustBeBoolean);
checkForInvalidFlags(options2, keys, `in ${callName}() call`);
let request = {
command: "analyze-metafile",
metafile
};
if (color !== void 0) request.color = color;
if (verbose !== void 0) request.verbose = verbose;
sendRequest(refs, request, (error2, response) => {
if (error2) return callback(new Error(error2), null);
callback(null, response.result);
});
};
return {
readFromStdout,
afterClose,
service: {
buildOrContext,
transform: transform22,
formatMessages: formatMessages22,
analyzeMetafile: analyzeMetafile2
}
};
}
function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options2, isTTY2, defaultWD2, callback) {
const details = createObjectStash();
const isContext = callName === "context";
const handleError = (e2, pluginName) => {
const flags = [];
try {
pushLogFlags(flags, options2, {}, isTTY2, buildLogLevelDefault);
} catch {
}
const message = extractErrorMessageV8(e2, streamIn, details, void 0, pluginName);
sendRequest(refs, { command: "error", flags, error: message }, () => {
message.detail = details.load(message.detail);
callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
});
};
let plugins2;
if (typeof options2 === "object") {
const value2 = options2.plugins;
if (value2 !== void 0) {
if (!Array.isArray(value2)) return handleError(new Error(`"plugins" must be an array`), "");
plugins2 = value2;
}
}
if (plugins2 && plugins2.length > 0) {
if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), "");
handlePlugins(
buildKey,
sendRequest,
sendResponse,
refs,
streamIn,
requestCallbacks,
options2,
plugins2,
details
).then(
(result) => {
if (!result.ok) return handleError(result.error, result.pluginName);
try {
buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
} catch (e2) {
handleError(e2, "");
}
},
(e2) => handleError(e2, "")
);
return;
}
try {
buildOrContextContinue(null, (result, done) => done([], []), () => {
});
} catch (e2) {
handleError(e2, "");
}
function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
const writeDefault = streamIn.hasFS;
const {
entries,
flags,
write,
stdinContents,
stdinResolveDir,
absWorkingDir,
nodePaths,
mangleCache
} = flagsForBuildOptions(callName, options2, isTTY2, buildLogLevelDefault, writeDefault);
if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
const request = {
command: "build",
key: buildKey,
entries,
flags,
write,
stdinContents,
stdinResolveDir,
absWorkingDir: absWorkingDir || defaultWD2,
nodePaths,
context: isContext
};
if (requestPlugins) request.plugins = requestPlugins;
if (mangleCache) request.mangleCache = mangleCache;
const buildResponseToResult = (response, callback2) => {
const result = {
errors: replaceDetailsInMessages(response.errors, details),
warnings: replaceDetailsInMessages(response.warnings, details),
outputFiles: void 0,
metafile: void 0,
mangleCache: void 0
};
const originalErrors = result.errors.slice();
const originalWarnings = result.warnings.slice();
if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
if (response.metafile) result.metafile = JSON.parse(response.metafile);
if (response.mangleCache) result.mangleCache = response.mangleCache;
if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
if (originalErrors.length > 0 || onEndErrors.length > 0) {
const error2 = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings));
return callback2(error2, null, onEndErrors, onEndWarnings);
}
callback2(null, result, onEndErrors, onEndWarnings);
});
};
let latestResultPromise;
let provideLatestResult;
if (isContext)
requestCallbacks["on-end"] = (id, request2) => new Promise((resolve3) => {
buildResponseToResult(request2, (err2, result, onEndErrors, onEndWarnings) => {
const response = {
errors: onEndErrors,
warnings: onEndWarnings
};
if (provideLatestResult) provideLatestResult(err2, result);
latestResultPromise = void 0;
provideLatestResult = void 0;
sendResponse(id, response);
resolve3();
});
});
sendRequest(refs, request, (error2, response) => {
if (error2) return callback(new Error(error2), null);
if (!isContext) {
return buildResponseToResult(response, (err2, res) => {
scheduleOnDisposeCallbacks();
return callback(err2, res);
});
}
if (response.errors.length > 0) {
return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
}
let didDispose = false;
const result = {
rebuild: () => {
if (!latestResultPromise) latestResultPromise = new Promise((resolve3, reject) => {
let settlePromise;
provideLatestResult = (err2, result2) => {
if (!settlePromise) settlePromise = () => err2 ? reject(err2) : resolve3(result2);
};
const triggerAnotherBuild = () => {
const request2 = {
command: "rebuild",
key: buildKey
};
sendRequest(refs, request2, (error22, response2) => {
if (error22) {
reject(new Error(error22));
} else if (settlePromise) {
settlePromise();
} else {
triggerAnotherBuild();
}
});
};
triggerAnotherBuild();
});
return latestResultPromise;
},
watch: (options22 = {}) => new Promise((resolve3, reject) => {
if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
const keys = {};
checkForInvalidFlags(options22, keys, `in watch() call`);
const request2 = {
command: "watch",
key: buildKey
};
sendRequest(refs, request2, (error22) => {
if (error22) reject(new Error(error22));
else resolve3(void 0);
});
}),
serve: (options22 = {}) => new Promise((resolve3, reject) => {
if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
const keys = {};
const port = getFlag(options22, keys, "port", mustBeInteger);
const host = getFlag(options22, keys, "host", mustBeString);
const servedir = getFlag(options22, keys, "servedir", mustBeString);
const keyfile = getFlag(options22, keys, "keyfile", mustBeString);
const certfile = getFlag(options22, keys, "certfile", mustBeString);
const fallback = getFlag(options22, keys, "fallback", mustBeString);
const onRequest = getFlag(options22, keys, "onRequest", mustBeFunction);
checkForInvalidFlags(options22, keys, `in serve() call`);
const request2 = {
command: "serve",
key: buildKey,
onRequest: !!onRequest
};
if (port !== void 0) request2.port = port;
if (host !== void 0) request2.host = host;
if (servedir !== void 0) request2.servedir = servedir;
if (keyfile !== void 0) request2.keyfile = keyfile;
if (certfile !== void 0) request2.certfile = certfile;
if (fallback !== void 0) request2.fallback = fallback;
sendRequest(refs, request2, (error22, response2) => {
if (error22) return reject(new Error(error22));
if (onRequest) {
requestCallbacks["serve-request"] = (id, request3) => {
onRequest(request3.args);
sendResponse(id, {});
};
}
resolve3(response2);
});
}),
cancel: () => new Promise((resolve3) => {
if (didDispose) return resolve3();
const request2 = {
command: "cancel",
key: buildKey
};
sendRequest(refs, request2, () => {
resolve3();
});
}),
dispose: () => new Promise((resolve3) => {
if (didDispose) return resolve3();
didDispose = true;
const request2 = {
command: "dispose",
key: buildKey
};
sendRequest(refs, request2, () => {
resolve3();
scheduleOnDisposeCallbacks();
refs.unref();
});
})
};
refs.ref();
callback(null, result);
});
}
}
var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins2, details) => {
let onStartCallbacks = [];
let onEndCallbacks = [];
let onResolveCallbacks = {};
let onLoadCallbacks = {};
let onDisposeCallbacks = [];
let nextCallbackID = 0;
let i = 0;
let requestPlugins = [];
let isSetupDone = false;
plugins2 = [...plugins2];
for (let item of plugins2) {
let keys = {};
if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
const name2 = getFlag(item, keys, "name", mustBeString);
if (typeof name2 !== "string" || name2 === "") throw new Error(`Plugin at index ${i} is missing a name`);
try {
let setup = getFlag(item, keys, "setup", mustBeFunction);
if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
checkForInvalidFlags(item, keys, `on plugin ${quote3(name2)}`);
let plugin = {
name: name2,
onStart: false,
onEnd: false,
onResolve: [],
onLoad: []
};
i++;
let resolve3 = (path32, options2 = {}) => {
if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed');
if (typeof path32 !== "string") throw new Error(`The path to resolve must be a string`);
let keys2 = /* @__PURE__ */ Object.create(null);
let pluginName = getFlag(options2, keys2, "pluginName", mustBeString);
let importer = getFlag(options2, keys2, "importer", mustBeString);
let namespace = getFlag(options2, keys2, "namespace", mustBeString);
let resolveDir = getFlag(options2, keys2, "resolveDir", mustBeString);
let kind = getFlag(options2, keys2, "kind", mustBeString);
let pluginData = getFlag(options2, keys2, "pluginData", canBeAnything);
let importAttributes = getFlag(options2, keys2, "with", mustBeObject);
checkForInvalidFlags(options2, keys2, "in resolve() call");
return new Promise((resolve22, reject) => {
const request = {
command: "resolve",
path: path32,
key: buildKey,
pluginName: name2
};
if (pluginName != null) request.pluginName = pluginName;
if (importer != null) request.importer = importer;
if (namespace != null) request.namespace = namespace;
if (resolveDir != null) request.resolveDir = resolveDir;
if (kind != null) request.kind = kind;
else throw new Error(`Must specify "kind" when calling "resolve"`);
if (pluginData != null) request.pluginData = details.store(pluginData);
if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
sendRequest(refs, request, (error2, response) => {
if (error2 !== null) reject(new Error(error2));
else resolve22({
errors: replaceDetailsInMessages(response.errors, details),
warnings: replaceDetailsInMessages(response.warnings, details),
path: response.path,
external: response.external,
sideEffects: response.sideEffects,
namespace: response.namespace,
suffix: response.suffix,
pluginData: details.load(response.pluginData)
});
});
});
};
let promise2 = setup({
initialOptions,
resolve: resolve3,
onStart(callback) {
let registeredText = `This error came from the "onStart" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart");
onStartCallbacks.push({ name: name2, callback, note: registeredNote });
plugin.onStart = true;
},
onEnd(callback) {
let registeredText = `This error came from the "onEnd" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd");
onEndCallbacks.push({ name: name2, callback, note: registeredNote });
plugin.onEnd = true;
},
onResolve(options2, callback) {
let registeredText = `This error came from the "onResolve" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve");
let keys2 = {};
let filter2 = getFlag(options2, keys2, "filter", mustBeRegExp);
let namespace = getFlag(options2, keys2, "namespace", mustBeString);
checkForInvalidFlags(options2, keys2, `in onResolve() call for plugin ${quote3(name2)}`);
if (filter2 == null) throw new Error(`onResolve() call is missing a filter`);
let id = nextCallbackID++;
onResolveCallbacks[id] = { name: name2, callback, note: registeredNote };
plugin.onResolve.push({ id, filter: filter2.source, namespace: namespace || "" });
},
onLoad(options2, callback) {
let registeredText = `This error came from the "onLoad" callback registered here:`;
let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad");
let keys2 = {};
let filter2 = getFlag(options2, keys2, "filter", mustBeRegExp);
let namespace = getFlag(options2, keys2, "namespace", mustBeString);
checkForInvalidFlags(options2, keys2, `in onLoad() call for plugin ${quote3(name2)}`);
if (filter2 == null) throw new Error(`onLoad() call is missing a filter`);
let id = nextCallbackID++;
onLoadCallbacks[id] = { name: name2, callback, note: registeredNote };
plugin.onLoad.push({ id, filter: filter2.source, namespace: namespace || "" });
},
onDispose(callback) {
onDisposeCallbacks.push(callback);
},
esbuild: streamIn.esbuild
});
if (promise2) await promise2;
requestPlugins.push(plugin);
} catch (e2) {
return { ok: false, error: e2, pluginName: name2 };
}
}
requestCallbacks["on-start"] = async (id, request) => {
let response = { errors: [], warnings: [] };
await Promise.all(onStartCallbacks.map(async ({ name: name2, callback, note }) => {
try {
let result = await callback();
if (result != null) {
if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote3(name2)} to return an object`);
let keys = {};
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote3(name2)}`);
if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name2, void 0));
if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name2, void 0));
}
} catch (e2) {
response.errors.push(extractErrorMessageV8(e2, streamIn, details, note && note(), name2));
}
}));
sendResponse(id, response);
};
requestCallbacks["on-resolve"] = async (id, request) => {
let response = {}, name2 = "", callback, note;
for (let id2 of request.ids) {
try {
({ name: name2, callback, note } = onResolveCallbacks[id2]);
let result = await callback({
path: request.path,
importer: request.importer,
namespace: request.namespace,
resolveDir: request.resolveDir,
kind: request.kind,
pluginData: details.load(request.pluginData),
with: request.with
});
if (result != null) {
if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote3(name2)} to return an object`);
let keys = {};
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
let path32 = getFlag(result, keys, "path", mustBeString);
let namespace = getFlag(result, keys, "namespace", mustBeString);
let suffix = getFlag(result, keys, "suffix", mustBeString);
let external = getFlag(result, keys, "external", mustBeBoolean);
let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote3(name2)}`);
response.id = id2;
if (pluginName != null) response.pluginName = pluginName;
if (path32 != null) response.path = path32;
if (namespace != null) response.namespace = namespace;
if (suffix != null) response.suffix = suffix;
if (external != null) response.external = external;
if (sideEffects != null) response.sideEffects = sideEffects;
if (pluginData != null) response.pluginData = details.store(pluginData);
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name2, void 0);
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name2, void 0);
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
break;
}
} catch (e2) {
response = { id: id2, errors: [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)] };
break;
}
}
sendResponse(id, response);
};
requestCallbacks["on-load"] = async (id, request) => {
let response = {}, name2 = "", callback, note;
for (let id2 of request.ids) {
try {
({ name: name2, callback, note } = onLoadCallbacks[id2]);
let result = await callback({
path: request.path,
namespace: request.namespace,
suffix: request.suffix,
pluginData: details.load(request.pluginData),
with: request.with
});
if (result != null) {
if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote3(name2)} to return an object`);
let keys = {};
let pluginName = getFlag(result, keys, "pluginName", mustBeString);
let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
let loader = getFlag(result, keys, "loader", mustBeString);
let errors = getFlag(result, keys, "errors", mustBeArray);
let warnings = getFlag(result, keys, "warnings", mustBeArray);
let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray);
let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray);
checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote3(name2)}`);
response.id = id2;
if (pluginName != null) response.pluginName = pluginName;
if (contents instanceof Uint8Array) response.contents = contents;
else if (contents != null) response.contents = encodeUTF8(contents);
if (resolveDir != null) response.resolveDir = resolveDir;
if (pluginData != null) response.pluginData = details.store(pluginData);
if (loader != null) response.loader = loader;
if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name2, void 0);
if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name2, void 0);
if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
break;
}
} catch (e2) {
response = { id: id2, errors: [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)] };
break;
}
}
sendResponse(id, response);
};
let runOnEndCallbacks = (result, done) => done([], []);
if (onEndCallbacks.length > 0) {
runOnEndCallbacks = (result, done) => {
(async () => {
const onEndErrors = [];
const onEndWarnings = [];
for (const { name: name2, callback, note } of onEndCallbacks) {
let newErrors;
let newWarnings;
try {
const value2 = await callback(result);
if (value2 != null) {
if (typeof value2 !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote3(name2)} to return an object`);
let keys = {};
let errors = getFlag(value2, keys, "errors", mustBeArray);
let warnings = getFlag(value2, keys, "warnings", mustBeArray);
checkForInvalidFlags(value2, keys, `from onEnd() callback in plugin ${quote3(name2)}`);
if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name2, void 0);
if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name2, void 0);
}
} catch (e2) {
newErrors = [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)];
}
if (newErrors) {
onEndErrors.push(...newErrors);
try {
result.errors.push(...newErrors);
} catch {
}
}
if (newWarnings) {
onEndWarnings.push(...newWarnings);
try {
result.warnings.push(...newWarnings);
} catch {
}
}
}
done(onEndErrors, onEndWarnings);
})();
};
}
let scheduleOnDisposeCallbacks = () => {
for (const cb of onDisposeCallbacks) {
setTimeout(() => cb(), 0);
}
};
isSetupDone = true;
return {
ok: true,
requestPlugins,
runOnEndCallbacks,
scheduleOnDisposeCallbacks
};
};
function createObjectStash() {
const map2 = /* @__PURE__ */ new Map();
let nextID = 0;
return {
load(id) {
return map2.get(id);
},
store(value2) {
if (value2 === void 0) return -1;
const id = nextID++;
map2.set(id, value2);
return id;
}
};
}
function extractCallerV8(e2, streamIn, ident) {
let note;
let tried = false;
return () => {
if (tried) return note;
tried = true;
try {
let lines = (e2.stack + "").split("\n");
lines.splice(1, 1);
let location2 = parseStackLinesV8(streamIn, lines, ident);
if (location2) {
note = { text: e2.message, location: location2 };
return note;
}
} catch {
}
};
}
function extractErrorMessageV8(e2, streamIn, stash, note, pluginName) {
let text = "Internal error";
let location2 = null;
try {
text = (e2 && e2.message || e2) + "";
} catch {
}
try {
location2 = parseStackLinesV8(streamIn, (e2.stack + "").split("\n"), "");
} catch {
}
return { id: "", pluginName, text, location: location2, notes: note ? [note] : [], detail: stash ? stash.store(e2) : -1 };
}
function parseStackLinesV8(streamIn, lines, ident) {
let at = " at ";
if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) {
for (let i = 1; i < lines.length; i++) {
let line = lines[i];
if (!line.startsWith(at)) continue;
line = line.slice(at.length);
while (true) {
let match2 = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
if (match2) {
line = match2[1];
continue;
}
match2 = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
if (match2) {
line = match2[1];
continue;
}
match2 = /^(\S+):(\d+):(\d+)$/.exec(line);
if (match2) {
let contents;
try {
contents = streamIn.readFileSync(match2[1], "utf8");
} catch {
break;
}
let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match2[2] - 1] || "";
let column = +match2[3] - 1;
let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
return {
file: match2[1],
namespace: "file",
line: +match2[2],
column: encodeUTF8(lineText.slice(0, column)).length,
length: encodeUTF8(lineText.slice(column, column + length)).length,
lineText: lineText + "\n" + lines.slice(1).join("\n"),
suggestion: ""
};
}
break;
}
}
}
return null;
}
function failureErrorWithLog(text, errors, warnings) {
let limit = 5;
text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e2, i) => {
if (i === limit) return "\n...";
if (!e2.location) return `
error: ${e2.text}`;
let { file, line, column } = e2.location;
let pluginText = e2.pluginName ? `[plugin: ${e2.pluginName}] ` : "";
return `
${file}:${line}:${column}: ERROR: ${pluginText}${e2.text}`;
}).join("");
let error2 = new Error(text);
for (const [key, value2] of [["errors", errors], ["warnings", warnings]]) {
Object.defineProperty(error2, key, {
configurable: true,
enumerable: true,
get: () => value2,
set: (value22) => Object.defineProperty(error2, key, {
configurable: true,
enumerable: true,
value: value22
})
});
}
return error2;
}
function replaceDetailsInMessages(messages2, stash) {
for (const message of messages2) {
message.detail = stash.load(message.detail);
}
return messages2;
}
function sanitizeLocation(location2, where, terminalWidth) {
if (location2 == null) return null;
let keys = {};
let file = getFlag(location2, keys, "file", mustBeString);
let namespace = getFlag(location2, keys, "namespace", mustBeString);
let line = getFlag(location2, keys, "line", mustBeInteger);
let column = getFlag(location2, keys, "column", mustBeInteger);
let length = getFlag(location2, keys, "length", mustBeInteger);
let lineText = getFlag(location2, keys, "lineText", mustBeString);
let suggestion = getFlag(location2, keys, "suggestion", mustBeString);
checkForInvalidFlags(location2, keys, where);
if (lineText) {
const relevantASCII = lineText.slice(
0,
(column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80)
);
if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) {
lineText = relevantASCII;
}
}
return {
file: file || "",
namespace: namespace || "",
line: line || 0,
column: column || 0,
length: length || 0,
lineText: lineText || "",
suggestion: suggestion || ""
};
}
function sanitizeMessages(messages2, property, stash, fallbackPluginName, terminalWidth) {
let messagesClone = [];
let index = 0;
for (const message of messages2) {
let keys = {};
let id = getFlag(message, keys, "id", mustBeString);
let pluginName = getFlag(message, keys, "pluginName", mustBeString);
let text = getFlag(message, keys, "text", mustBeString);
let location2 = getFlag(message, keys, "location", mustBeObjectOrNull);
let notes = getFlag(message, keys, "notes", mustBeArray);
let detail = getFlag(message, keys, "detail", canBeAnything);
let where = `in element ${index} of "${property}"`;
checkForInvalidFlags(message, keys, where);
let notesClone = [];
if (notes) {
for (const note of notes) {
let noteKeys = {};
let noteText = getFlag(note, noteKeys, "text", mustBeString);
let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
checkForInvalidFlags(note, noteKeys, where);
notesClone.push({
text: noteText || "",
location: sanitizeLocation(noteLocation, where, terminalWidth)
});
}
}
messagesClone.push({
id: id || "",
pluginName: pluginName || fallbackPluginName,
text: text || "",
location: sanitizeLocation(location2, where, terminalWidth),
notes: notesClone,
detail: stash ? stash.store(detail) : -1
});
index++;
}
return messagesClone;
}
function sanitizeStringArray(values, property) {
const result = [];
for (const value2 of values) {
if (typeof value2 !== "string") throw new Error(`${quote3(property)} must be an array of strings`);
result.push(value2);
}
return result;
}
function sanitizeStringMap(map2, property) {
const result = /* @__PURE__ */ Object.create(null);
for (const key in map2) {
const value2 = map2[key];
if (typeof value2 !== "string") throw new Error(`key ${quote3(key)} in object ${quote3(property)} must be a string`);
result[key] = value2;
}
return result;
}
function convertOutputFiles({ path: path32, contents, hash: hash2 }) {
let text = null;
return {
path: path32,
contents,
hash: hash2,
get text() {
const binary2 = this.contents;
if (text === null || binary2 !== contents) {
contents = binary2;
text = decodeUTF8(binary2);
}
return text;
}
};
}
var fs2 = require_fs();
var os2 = require_os();
var path3 = require_path();
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
var packageDarwin_arm64 = "@esbuild/darwin-arm64";
var packageDarwin_x64 = "@esbuild/darwin-x64";
var knownWindowsPackages = {
"win32 arm64 LE": "@esbuild/win32-arm64",
"win32 ia32 LE": "@esbuild/win32-ia32",
"win32 x64 LE": "@esbuild/win32-x64"
};
var knownUnixlikePackages = {
"aix ppc64 BE": "@esbuild/aix-ppc64",
"android arm64 LE": "@esbuild/android-arm64",
"darwin arm64 LE": "@esbuild/darwin-arm64",
"darwin x64 LE": "@esbuild/darwin-x64",
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
"freebsd x64 LE": "@esbuild/freebsd-x64",
"linux arm LE": "@esbuild/linux-arm",
"linux arm64 LE": "@esbuild/linux-arm64",
"linux ia32 LE": "@esbuild/linux-ia32",
"linux mips64el LE": "@esbuild/linux-mips64el",
"linux ppc64 LE": "@esbuild/linux-ppc64",
"linux riscv64 LE": "@esbuild/linux-riscv64",
"linux s390x BE": "@esbuild/linux-s390x",
"linux x64 LE": "@esbuild/linux-x64",
"linux loong64 LE": "@esbuild/linux-loong64",
"netbsd x64 LE": "@esbuild/netbsd-x64",
"openbsd x64 LE": "@esbuild/openbsd-x64",
"sunos x64 LE": "@esbuild/sunos-x64"
};
var knownWebAssemblyFallbackPackages = {
"android arm LE": "@esbuild/android-arm",
"android x64 LE": "@esbuild/android-x64"
};
function pkgAndSubpathForCurrentPlatform() {
let pkg;
let subpath;
let isWASM = false;
let platformKey = `${process.platform} ${os2.arch()} ${os2.endianness()}`;
if (platformKey in knownWindowsPackages) {
pkg = knownWindowsPackages[platformKey];
subpath = "esbuild.exe";
} else if (platformKey in knownUnixlikePackages) {
pkg = knownUnixlikePackages[platformKey];
subpath = "bin/esbuild";
} else if (platformKey in knownWebAssemblyFallbackPackages) {
pkg = knownWebAssemblyFallbackPackages[platformKey];
subpath = "bin/esbuild";
isWASM = true;
} else {
throw new Error(`Unsupported platform: ${platformKey}`);
}
return { pkg, subpath, isWASM };
}
function pkgForSomeOtherPlatform() {
const libMainJS = __require.resolve("esbuild");
const nodeModulesDirectory = path3.dirname(path3.dirname(path3.dirname(libMainJS)));
if (path3.basename(nodeModulesDirectory) === "node_modules") {
for (const unixKey in knownUnixlikePackages) {
try {
const pkg = knownUnixlikePackages[unixKey];
if (fs2.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg;
} catch {
}
}
for (const windowsKey in knownWindowsPackages) {
try {
const pkg = knownWindowsPackages[windowsKey];
if (fs2.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg;
} catch {
}
}
}
return null;
}
function downloadedBinPath(pkg, subpath) {
const esbuildLibDir = path3.dirname(__require.resolve("esbuild"));
return path3.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path3.basename(subpath)}`);
}
function generateBinPath() {
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
} else {
return { binPath: ESBUILD_BINARY_PATH, isWASM: false };
}
}
const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
let binPath;
try {
binPath = __require.resolve(`${pkg}/${subpath}`);
} catch (e2) {
binPath = downloadedBinPath(pkg, subpath);
if (!fs2.existsSync(binPath)) {
try {
__require.resolve(pkg);
} catch {
const otherPkg = pkgForSomeOtherPlatform();
if (otherPkg) {
let suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild on Windows or macOS and copying "node_modules"
into a Docker image that runs Linux, or by copying "node_modules" between
Windows and WSL environments.
If you are installing with npm, you can try not copying the "node_modules"
directory when you copy the files over, and running "npm ci" or "npm install"
on the destination platform after the copy. Or you could consider using yarn
instead of npm which has built-in support for installing a package on multiple
platforms simultaneously.
If you are installing with yarn, you can try listing both this platform and the
other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) {
suggestions = `
Specifically the "${otherPkg}" package is present but this platform
needs the "${pkg}" package instead. People often get into this
situation by installing esbuild with npm running inside of Rosetta 2 and then
trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2 is Apple's on-the-fly x86_64-to-arm64 translation service).
If you are installing with npm, you can try ensuring that both npm and node are
not running under Rosetta 2 and then reinstalling esbuild. This likely involves
changing how you installed npm and/or node. For example, installing node with
the universal installer here should work: https://nodejs.org/en/download/. Or
you could consider using yarn instead of npm which has built-in support for
installing a package on multiple platforms simultaneously.
If you are installing with yarn, you can try listing both "arm64" and "x64"
in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
Keep in mind that this means multiple copies of esbuild will be present.
`;
}
throw new Error(`
You installed esbuild for another platform than the one you're currently using.
This won't work because esbuild is written with native code and needs to
install a platform-specific binary executable.
${suggestions}
Another alternative is to use the "esbuild-wasm" package instead, which works
the same way on all platforms. But it comes with a heavy performance cost and
can sometimes be 10x slower than the "esbuild" package, so you may also not
want to do that.
`);
}
throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
If you are installing esbuild with npm, make sure that you don't specify the
"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
of "package.json" is used by esbuild to install the correct binary executable
for your current platform.`);
}
throw e2;
}
}
if (/\.zip\//.test(binPath)) {
let pnpapi;
try {
pnpapi = __require("pnpapi");
} catch (e2) {
}
if (pnpapi) {
const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
const binTargetPath = path3.join(
root,
"node_modules",
".cache",
"esbuild",
`pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path3.basename(subpath)}`
);
if (!fs2.existsSync(binTargetPath)) {
fs2.mkdirSync(path3.dirname(binTargetPath), { recursive: true });
fs2.copyFileSync(binPath, binTargetPath);
fs2.chmodSync(binTargetPath, 493);
}
return { binPath: binTargetPath, isWASM };
}
}
return { binPath, isWASM };
}
var child_process = require_child_process();
var crypto2 = require_crypto();
var path22 = require_path();
var fs22 = require_fs();
var os22 = require_os();
var tty = require_tty();
var worker_threads;
if (process.env.ESBUILD_WORKER_THREADS !== "0") {
try {
worker_threads = require_worker_threads();
} catch {
}
let [major, minor] = process.versions.node.split(".");
if (
// <v12.17.0 does not work
+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13
) {
worker_threads = void 0;
}
}
var _a4;
var isInternalWorkerThread = ((_a4 = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a4.esbuildVersion) === "0.21.5";
var esbuildCommandAndArgs = () => {
if ((!ESBUILD_BINARY_PATH || false) && (path22.basename(__filename) !== "main.js" || path22.basename(__dirname) !== "lib")) {
throw new Error(
`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`
);
}
if (false) {
return ["node", [path22.join(__dirname, "..", "bin", "esbuild")]];
} else {
const { binPath, isWASM } = generateBinPath();
if (isWASM) {
return ["node", [binPath]];
} else {
return [binPath, []];
}
}
};
var isTTY = () => tty.isatty(2);
var fsSync = {
readFile(tempFile, callback) {
try {
let contents = fs22.readFileSync(tempFile, "utf8");
try {
fs22.unlinkSync(tempFile);
} catch {
}
callback(null, contents);
} catch (err2) {
callback(err2, null);
}
},
writeFile(contents, callback) {
try {
let tempFile = randomFileName();
fs22.writeFileSync(tempFile, contents);
callback(tempFile);
} catch {
callback(null);
}
}
};
var fsAsync = {
readFile(tempFile, callback) {
try {
fs22.readFile(tempFile, "utf8", (err2, contents) => {
try {
fs22.unlink(tempFile, () => callback(err2, contents));
} catch {
callback(err2, contents);
}
});
} catch (err2) {
callback(err2, null);
}
},
writeFile(contents, callback) {
try {
let tempFile = randomFileName();
fs22.writeFile(tempFile, contents, (err2) => err2 !== null ? callback(null) : callback(tempFile));
} catch {
callback(null);
}
}
};
var version3 = "0.21.5";
var build2 = (options2) => ensureServiceIsRunning().build(options2);
var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
var transform2 = (input, options2) => ensureServiceIsRunning().transform(input, options2);
var formatMessages2 = (messages2, options2) => ensureServiceIsRunning().formatMessages(messages2, options2);
var analyzeMetafile = (messages2, options2) => ensureServiceIsRunning().analyzeMetafile(messages2, options2);
var buildSync = (options2) => {
if (worker_threads && !isInternalWorkerThread) {
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
return workerThreadService.buildSync(options2);
}
let result;
runServiceSync((service) => service.buildOrContext({
callName: "buildSync",
refs: null,
options: options2,
isTTY: isTTY(),
defaultWD,
callback: (err2, res) => {
if (err2) throw err2;
result = res;
}
}));
return result;
};
var transformSync = (input, options2) => {
if (worker_threads && !isInternalWorkerThread) {
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
return workerThreadService.transformSync(input, options2);
}
let result;
runServiceSync((service) => service.transform({
callName: "transformSync",
refs: null,
input,
options: options2 || {},
isTTY: isTTY(),
fs: fsSync,
callback: (err2, res) => {
if (err2) throw err2;
result = res;
}
}));
return result;
};
var formatMessagesSync = (messages2, options2) => {
if (worker_threads && !isInternalWorkerThread) {
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
return workerThreadService.formatMessagesSync(messages2, options2);
}
let result;
runServiceSync((service) => service.formatMessages({
callName: "formatMessagesSync",
refs: null,
messages: messages2,
options: options2,
callback: (err2, res) => {
if (err2) throw err2;
result = res;
}
}));
return result;
};
var analyzeMetafileSync = (metafile, options2) => {
if (worker_threads && !isInternalWorkerThread) {
if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
return workerThreadService.analyzeMetafileSync(metafile, options2);
}
let result;
runServiceSync((service) => service.analyzeMetafile({
callName: "analyzeMetafileSync",
refs: null,
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
options: options2,
callback: (err2, res) => {
if (err2) throw err2;
result = res;
}
}));
return result;
};
var stop = () => {
if (stopService) stopService();
if (workerThreadService) workerThreadService.stop();
return Promise.resolve();
};
var initializeWasCalled = false;
var initialize = (options2) => {
options2 = validateInitializeOptions(options2 || {});
if (options2.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
if (options2.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
if (options2.worker) throw new Error(`The "worker" option only works in the browser`);
if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once');
ensureServiceIsRunning();
initializeWasCalled = true;
return Promise.resolve();
};
var defaultWD = process.cwd();
var longLivedService;
var stopService;
var ensureServiceIsRunning = () => {
if (longLivedService) return longLivedService;
let [command, args] = esbuildCommandAndArgs();
let child = child_process.spawn(command, args.concat(`--service=${"0.21.5"}`, "--ping"), {
windowsHide: true,
stdio: ["pipe", "pipe", "inherit"],
cwd: defaultWD
});
let { readFromStdout, afterClose, service } = createChannel({
writeToStdin(bytes) {
child.stdin.write(bytes, (err2) => {
if (err2) afterClose(err2);
});
},
readFileSync: fs22.readFileSync,
isSync: false,
hasFS: true,
esbuild: node_exports
});
child.stdin.on("error", afterClose);
child.on("error", afterClose);
const stdin = child.stdin;
const stdout = child.stdout;
stdout.on("data", readFromStdout);
stdout.on("end", afterClose);
stopService = () => {
stdin.destroy();
stdout.destroy();
child.kill();
initializeWasCalled = false;
longLivedService = void 0;
stopService = void 0;
};
let refCount = 0;
child.unref();
if (stdin.unref) {
stdin.unref();
}
if (stdout.unref) {
stdout.unref();
}
const refs = {
ref() {
if (++refCount === 1) child.ref();
},
unref() {
if (--refCount === 0) child.unref();
}
};
longLivedService = {
build: (options2) => new Promise((resolve3, reject) => {
service.buildOrContext({
callName: "build",
refs,
options: options2,
isTTY: isTTY(),
defaultWD,
callback: (err2, res) => err2 ? reject(err2) : resolve3(res)
});
}),
context: (options2) => new Promise((resolve3, reject) => service.buildOrContext({
callName: "context",
refs,
options: options2,
isTTY: isTTY(),
defaultWD,
callback: (err2, res) => err2 ? reject(err2) : resolve3(res)
})),
transform: (input, options2) => new Promise((resolve3, reject) => service.transform({
callName: "transform",
refs,
input,
options: options2 || {},
isTTY: isTTY(),
fs: fsAsync,
callback: (err2, res) => err2 ? reject(err2) : resolve3(res)
})),
formatMessages: (messages2, options2) => new Promise((resolve3, reject) => service.formatMessages({
callName: "formatMessages",
refs,
messages: messages2,
options: options2,
callback: (err2, res) => err2 ? reject(err2) : resolve3(res)
})),
analyzeMetafile: (metafile, options2) => new Promise((resolve3, reject) => service.analyzeMetafile({
callName: "analyzeMetafile",
refs,
metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
options: options2,
callback: (err2, res) => err2 ? reject(err2) : resolve3(res)
}))
};
return longLivedService;
};
var runServiceSync = (callback) => {
let [command, args] = esbuildCommandAndArgs();
let stdin = new Uint8Array();
let { readFromStdout, afterClose, service } = createChannel({
writeToStdin(bytes) {
if (stdin.length !== 0) throw new Error("Must run at most one command");
stdin = bytes;
},
isSync: true,
hasFS: true,
esbuild: node_exports
});
callback(service);
let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.21.5"}`), {
cwd: defaultWD,
windowsHide: true,
input: stdin,
// We don't know how large the output could be. If it's too large, the
// command will fail with ENOBUFS. Reserve 16mb for now since that feels
// like it should be enough. Also allow overriding this with an environment
// variable.
maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
});
readFromStdout(stdout);
afterClose(null);
};
var randomFileName = () => {
return path22.join(os22.tmpdir(), `esbuild-${crypto2.randomBytes(32).toString("hex")}`);
};
var workerThreadService = null;
var startWorkerThreadService = (worker_threads2) => {
let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
let worker = new worker_threads2.Worker(__filename, {
workerData: { workerPort, defaultWD, esbuildVersion: "0.21.5" },
transferList: [workerPort],
// From node's documentation: https://nodejs.org/api/worker_threads.html
//
// Take care when launching worker threads from preload scripts (scripts loaded
// and run using the `-r` command line flag). Unless the `execArgv` option is
// explicitly set, new Worker threads automatically inherit the command line flags
// from the running process and will preload the same preload scripts as the main
// thread. If the preload script unconditionally launches a worker thread, every
// thread spawned will spawn another until the application crashes.
//
execArgv: []
});
let nextID = 0;
let fakeBuildError = (text) => {
let error2 = new Error(`Build failed with 1 error:
error: ${text}`);
let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }];
error2.errors = errors;
error2.warnings = [];
return error2;
};
let validateBuildSyncOptions = (options2) => {
if (!options2) return;
let plugins2 = options2.plugins;
if (plugins2 && plugins2.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
};
let applyProperties = (object, properties) => {
for (let key in properties) {
object[key] = properties[key];
}
};
let runCallSync = (command, args) => {
let id = nextID++;
let sharedBuffer = new SharedArrayBuffer(8);
let sharedBufferView = new Int32Array(sharedBuffer);
let msg = { sharedBuffer, id, command, args };
worker.postMessage(msg);
let status2 = Atomics.wait(sharedBufferView, 0, 0);
if (status2 !== "ok" && status2 !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status2);
let { message: { id: id2, resolve: resolve3, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
if (reject) {
applyProperties(reject, properties);
throw reject;
}
return resolve3;
};
worker.unref();
return {
buildSync(options2) {
validateBuildSyncOptions(options2);
return runCallSync("build", [options2]);
},
transformSync(input, options2) {
return runCallSync("transform", [input, options2]);
},
formatMessagesSync(messages2, options2) {
return runCallSync("formatMessages", [messages2, options2]);
},
analyzeMetafileSync(metafile, options2) {
return runCallSync("analyzeMetafile", [metafile, options2]);
},
stop() {
worker.terminate();
workerThreadService = null;
}
};
};
var startSyncServiceWorker = () => {
let workerPort = worker_threads.workerData.workerPort;
let parentPort = worker_threads.parentPort;
let extractProperties = (object) => {
let properties = {};
if (object && typeof object === "object") {
for (let key in object) {
properties[key] = object[key];
}
}
return properties;
};
try {
let service = ensureServiceIsRunning();
defaultWD = worker_threads.workerData.defaultWD;
parentPort.on("message", (msg) => {
(async () => {
let { sharedBuffer, id, command, args } = msg;
let sharedBufferView = new Int32Array(sharedBuffer);
try {
switch (command) {
case "build":
workerPort.postMessage({ id, resolve: await service.build(args[0]) });
break;
case "transform":
workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) });
break;
case "formatMessages":
workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) });
break;
case "analyzeMetafile":
workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) });
break;
default:
throw new Error(`Invalid command: ${command}`);
}
} catch (reject) {
workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
}
Atomics.add(sharedBufferView, 0, 1);
Atomics.notify(sharedBufferView, 0, Infinity);
})();
});
} catch (reject) {
parentPort.on("message", (msg) => {
let { sharedBuffer, id } = msg;
let sharedBufferView = new Int32Array(sharedBuffer);
workerPort.postMessage({ id, reject, properties: extractProperties(reject) });
Atomics.add(sharedBufferView, 0, 1);
Atomics.notify(sharedBufferView, 0, Infinity);
});
}
};
if (isInternalWorkerThread) {
startSyncServiceWorker();
}
var node_default = node_exports;
}
});
// browser-external:node:events
var require_node_events = __commonJS({
"browser-external:node:events"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:events" has been externalized for browser compatibility. Cannot access "node:events.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:stream
var require_node_stream = __commonJS({
"browser-external:node:stream"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:stream" has been externalized for browser compatibility. Cannot access "node:stream.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:string_decoder
var require_node_string_decoder = __commonJS({
"browser-external:node:string_decoder"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:string_decoder" has been externalized for browser compatibility. Cannot access "node:string_decoder.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:child_process
var require_node_child_process = __commonJS({
"browser-external:node:child_process"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:child_process" has been externalized for browser compatibility. Cannot access "node:child_process.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:net
var require_net = __commonJS({
"browser-external:net"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "net" has been externalized for browser compatibility. Cannot access "net.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:http
var require_http = __commonJS({
"browser-external:http"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "http" has been externalized for browser compatibility. Cannot access "http.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:crypto
var require_node_crypto = __commonJS({
"browser-external:node:crypto"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:crypto" has been externalized for browser compatibility. Cannot access "node:crypto.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:dns
var require_node_dns = __commonJS({
"browser-external:node:dns"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:dns" has been externalized for browser compatibility. Cannot access "node:dns.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:module
var require_module = __commonJS({
"browser-external:module"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "module" has been externalized for browser compatibility. Cannot access "module.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:assert
var require_node_assert = __commonJS({
"browser-external:node:assert"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:assert" has been externalized for browser compatibility. Cannot access "node:assert.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:v8
var require_node_v8 = __commonJS({
"browser-external:node:v8"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:v8" has been externalized for browser compatibility. Cannot access "node:v8.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:worker_threads
var require_node_worker_threads = __commonJS({
"browser-external:node:worker_threads"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:worker_threads" has been externalized for browser compatibility. Cannot access "node:worker_threads.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:buffer
var require_node_buffer = __commonJS({
"browser-external:node:buffer"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:buffer" has been externalized for browser compatibility. Cannot access "node:buffer.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:querystring
var require_querystring = __commonJS({
"browser-external:querystring"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "querystring" has been externalized for browser compatibility. Cannot access "querystring.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:readline
var require_node_readline = __commonJS({
"browser-external:node:readline"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:readline" has been externalized for browser compatibility. Cannot access "node:readline.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:zlib
var require_zlib = __commonJS({
"browser-external:zlib"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "zlib" has been externalized for browser compatibility. Cannot access "zlib.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:buffer
var require_buffer = __commonJS({
"browser-external:buffer"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:https
var require_https = __commonJS({
"browser-external:https"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "https" has been externalized for browser compatibility. Cannot access "https.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:tls
var require_tls = __commonJS({
"browser-external:tls"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "tls" has been externalized for browser compatibility. Cannot access "tls.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:assert
var require_assert = __commonJS({
"browser-external:assert"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "assert" has been externalized for browser compatibility. Cannot access "assert.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// browser-external:node:zlib
var require_node_zlib = __commonJS({
"browser-external:node:zlib"(exports2, module) {
module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") {
console.warn(`Module "node:zlib" has been externalized for browser compatibility. Cannot access "node:zlib.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
}
}
}));
}
});
// node_modules/rollup/dist/es/parseAst.js
var import_native = __toESM(require_native());
var import_node_path = __toESM(require_node_path());
// node_modules/vite/dist/node/constants.js
var import_node_path2 = __toESM(require_node_path(), 1);
var import_node_url = __toESM(require_node_url(), 1);
var import_node_fs = __toESM(require_node_fs(), 1);
var { version } = JSON.parse(
(0, import_node_fs.readFileSync)(new URL("../../package.json", import.meta.url)).toString()
);
var VERSION = version;
var DEFAULT_MAIN_FIELDS = [
"browser",
"module",
"jsnext:main",
// moment still uses this...
"jsnext"
];
var ESBUILD_MODULES_TARGET = [
"es2020",
// support import.meta.url
"edge88",
"firefox78",
"chrome87",
"safari14"
];
var DEFAULT_EXTENSIONS = [
".mjs",
".js",
".mts",
".ts",
".jsx",
".tsx",
".json"
];
var DEFAULT_CONFIG_FILES = [
"vite.config.js",
"vite.config.mjs",
"vite.config.ts",
"vite.config.cjs",
"vite.config.mts",
"vite.config.cts"
];
var JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/;
var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
var FS_PREFIX = `/@fs/`;
var CLIENT_PUBLIC_PATH = `/@vite/client`;
var ENV_PUBLIC_PATH = `/@vite/env`;
var VITE_PACKAGE_DIR = (0, import_node_path2.resolve)(
// import.meta.url is `dist/node/constants.js` after bundle
(0, import_node_url.fileURLToPath)(import.meta.url),
"../../.."
);
var CLIENT_ENTRY = (0, import_node_path2.resolve)(VITE_PACKAGE_DIR, "dist/client/client.mjs");
var ENV_ENTRY = (0, import_node_path2.resolve)(VITE_PACKAGE_DIR, "dist/client/env.mjs");
var CLIENT_DIR = import_node_path2.default.dirname(CLIENT_ENTRY);
var KNOWN_ASSET_TYPES = [
// images
"apng",
"bmp",
"png",
"jpe?g",
"jfif",
"pjpeg",
"pjp",
"gif",
"svg",
"ico",
"webp",
"avif",
// media
"mp4",
"webm",
"ogg",
"mp3",
"wav",
"flac",
"aac",
"opus",
"mov",
"m4a",
"vtt",
// fonts
"woff2?",
"eot",
"ttf",
"otf",
// other
"webmanifest",
"pdf",
"txt"
];
var DEFAULT_ASSETS_RE = new RegExp(
`\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$`
);
var DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/;
var loopbackHosts = /* @__PURE__ */ new Set([
"localhost",
"127.0.0.1",
"::1",
"0000:0000:0000:0000:0000:0000:0000:0001"
]);
var wildcardHosts = /* @__PURE__ */ new Set([
"0.0.0.0",
"::",
"0000:0000:0000:0000:0000:0000:0000:0000"
]);
var DEFAULT_DEV_PORT = 5173;
var DEFAULT_PREVIEW_PORT = 4173;
var DEFAULT_ASSETS_INLINE_LIMIT = 4096;
var METADATA_FILENAME = "_metadata.json";
// node_modules/vite/dist/node/chunks/dep-mCdpKltl.js
var fs$j = __toESM(require_node_fs(), 1);
var import_node_fs2 = __toESM(require_node_fs(), 1);
var import_promises = __toESM(require_promises(), 1);
var import_node_path3 = __toESM(require_node_path(), 1);
var import_node_url2 = __toESM(require_node_url(), 1);
var import_node_util = __toESM(require_node_util(), 1);
var import_node_perf_hooks = __toESM(require_node_perf_hooks(), 1);
var import_node_module = __toESM(require_node_module(), 1);
var import_tty = __toESM(require_tty(), 1);
var import_path = __toESM(require_path(), 1);
var import_esbuild = __toESM(require_main(), 1);
var require$$0$2 = __toESM(require_fs(), 1);
var import_fs = __toESM(require_fs(), 1);
var import_node_events = __toESM(require_node_events(), 1);
var import_node_stream = __toESM(require_node_stream(), 1);
var import_node_string_decoder = __toESM(require_node_string_decoder(), 1);
var import_node_child_process = __toESM(require_node_child_process(), 1);
var import_node_http = __toESM(require_node_http(), 1);
var import_node_https = __toESM(require_node_https(), 1);
var import_util = __toESM(require_util(), 1);
var import_net = __toESM(require_net(), 1);
var import_events = __toESM(require_events(), 1);
var import_url = __toESM(require_url(), 1);
var import_http = __toESM(require_http(), 1);
var import_stream = __toESM(require_stream(), 1);
var import_os = __toESM(require_os(), 1);
var import_child_process = __toESM(require_child_process(), 1);
var import_node_os = __toESM(require_node_os(), 1);
var import_node_crypto = __toESM(require_node_crypto(), 1);
var import_node_dns = __toESM(require_node_dns(), 1);
var import_crypto = __toESM(require_crypto(), 1);
var import_module = __toESM(require_module(), 1);
var import_node_assert = __toESM(require_node_assert(), 1);
var import_node_v8 = __toESM(require_node_v8(), 1);
var import_node_worker_threads = __toESM(require_node_worker_threads(), 1);
var import_node_buffer = __toESM(require_node_buffer(), 1);
var qs = __toESM(require_querystring(), 1);
var import_node_readline = __toESM(require_node_readline(), 1);
var import_zlib = __toESM(require_zlib(), 1);
var import_buffer = __toESM(require_buffer(), 1);
var import_https = __toESM(require_https(), 1);
var import_tls = __toESM(require_tls(), 1);
var import_assert = __toESM(require_assert(), 1);
var import_node_zlib = __toESM(require_node_zlib(), 1);
var import_node_url3 = __toESM(require_node_url(), 1);
var import_node_path4 = __toESM(require_node_path(), 1);
var import_node_module2 = __toESM(require_node_module(), 1);
var __filename2 = (0, import_node_url3.fileURLToPath)(import.meta.url);
var __dirname2 = (0, import_node_path4.dirname)(__filename2);
var require2 = (0, import_node_module2.createRequire)(import.meta.url);
var __require2 = require2;
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function getAugmentedNamespace(n2) {
if (n2.__esModule) return n2;
var f2 = n2.default;
if (typeof f2 == "function") {
var a = function a2() {
if (this instanceof a2) {
return Reflect.construct(f2, arguments, this.constructor);
}
return f2.apply(this, arguments);
};
a.prototype = f2.prototype;
} else a = {};
Object.defineProperty(a, "__esModule", { value: true });
Object.keys(n2).forEach(function(k) {
var d = Object.getOwnPropertyDescriptor(n2, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function() {
return n2[k];
}
});
});
return a;
}
function commonjsRequire(path3) {
throw new Error('Could not dynamically require "' + path3 + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var picocolors = { exports: {} };
var argv = process.argv || [];
var env$1 = process.env;
var isColorSupported = !("NO_COLOR" in env$1 || argv.includes("--no-color")) && ("FORCE_COLOR" in env$1 || argv.includes("--color") || process.platform === "win32" || commonjsRequire != null && import_tty.default.isatty(1) && env$1.TERM !== "dumb" || "CI" in env$1);
var formatter = (open2, close2, replace = open2) => (input) => {
let string2 = "" + input;
let index = string2.indexOf(close2, open2.length);
return ~index ? open2 + replaceClose(string2, close2, replace, index) + close2 : open2 + string2 + close2;
};
var replaceClose = (string2, close2, replace, index) => {
let result = "";
let cursor = 0;
do {
result += string2.substring(cursor, index) + replace;
cursor = index + close2.length;
index = string2.indexOf(close2, cursor);
} while (~index);
return result + string2.substring(cursor);
};
var createColors = (enabled = isColorSupported) => {
let init2 = enabled ? formatter : () => String;
return {
isColorSupported: enabled,
reset: init2("\x1B[0m", "\x1B[0m"),
bold: init2("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
dim: init2("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
italic: init2("\x1B[3m", "\x1B[23m"),
underline: init2("\x1B[4m", "\x1B[24m"),
inverse: init2("\x1B[7m", "\x1B[27m"),
hidden: init2("\x1B[8m", "\x1B[28m"),
strikethrough: init2("\x1B[9m", "\x1B[29m"),
black: init2("\x1B[30m", "\x1B[39m"),
red: init2("\x1B[31m", "\x1B[39m"),
green: init2("\x1B[32m", "\x1B[39m"),
yellow: init2("\x1B[33m", "\x1B[39m"),
blue: init2("\x1B[34m", "\x1B[39m"),
magenta: init2("\x1B[35m", "\x1B[39m"),
cyan: init2("\x1B[36m", "\x1B[39m"),
white: init2("\x1B[37m", "\x1B[39m"),
gray: init2("\x1B[90m", "\x1B[39m"),
bgBlack: init2("\x1B[40m", "\x1B[49m"),
bgRed: init2("\x1B[41m", "\x1B[49m"),
bgGreen: init2("\x1B[42m", "\x1B[49m"),
bgYellow: init2("\x1B[43m", "\x1B[49m"),
bgBlue: init2("\x1B[44m", "\x1B[49m"),
bgMagenta: init2("\x1B[45m", "\x1B[49m"),
bgCyan: init2("\x1B[46m", "\x1B[49m"),
bgWhite: init2("\x1B[47m", "\x1B[49m")
};
};
picocolors.exports = createColors();
picocolors.exports.createColors = createColors;
var picocolorsExports = picocolors.exports;
var colors$1 = getDefaultExportFromCjs(picocolorsExports);
function matches$1(pattern2, importee) {
if (pattern2 instanceof RegExp) {
return pattern2.test(importee);
}
if (importee.length < pattern2.length) {
return false;
}
if (importee === pattern2) {
return true;
}
return importee.startsWith(pattern2 + "/");
}
function getEntries({ entries, customResolver }) {
if (!entries) {
return [];
}
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) {
return entries.map((entry2) => {
return {
find: entry2.find,
replacement: entry2.replacement,
resolverFunction: resolveCustomResolver(entry2.customResolver) || resolverFunctionFromOptions
};
});
}
return Object.entries(entries).map(([key, value2]) => {
return { find: key, replacement: value2, resolverFunction: resolverFunctionFromOptions };
});
}
function getHookFunction(hook) {
if (typeof hook === "function") {
return hook;
}
if (hook && "handler" in hook && typeof hook.handler === "function") {
return hook.handler;
}
return null;
}
function resolveCustomResolver(customResolver) {
if (typeof customResolver === "function") {
return customResolver;
}
if (customResolver) {
return getHookFunction(customResolver.resolveId);
}
return null;
}
function alias$1(options2 = {}) {
const entries = getEntries(options2);
if (entries.length === 0) {
return {
name: "alias",
resolveId: () => null
};
}
return {
name: "alias",
async buildStart(inputOptions) {
await Promise.all([...Array.isArray(options2.entries) ? options2.entries : [], options2].map(({ customResolver }) => {
var _a4;
return customResolver && ((_a4 = getHookFunction(customResolver.buildStart)) === null || _a4 === void 0 ? void 0 : _a4.call(this, inputOptions));
}));
},
resolveId(importee, importer, resolveOptions) {
const matchedEntry = entries.find((entry2) => matches$1(entry2.find, importee));
if (!matchedEntry) {
return null;
}
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) {
return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
}
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
if (resolved)
return resolved;
if (!import_path.default.isAbsolute(updatedId)) {
this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`);
}
return { id: updatedId };
});
}
};
}
var VALID_ID_PREFIX = `/@id/`;
var NULL_BYTE_PLACEHOLDER = `__x00__`;
var SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
var VITE_RUNTIME_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-runtime";
var isWindows$3 = typeof process !== "undefined" && process.platform === "win32";
function wrapId$1(id) {
return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
}
function unwrapId$1(id) {
return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
}
var windowsSlashRE = /\\/g;
function slash$1(p) {
return p.replace(windowsSlashRE, "/");
}
var postfixRE = /[?#].*$/;
function cleanUrl(url2) {
return url2.replace(postfixRE, "");
}
function withTrailingSlash(path3) {
if (path3[path3.length - 1] !== "/") {
return `${path3}/`;
}
return path3;
}
var AsyncFunction = (async function() {
}).constructor;
var asyncFunctionDeclarationPaddingLineCount = (() => {
const body = "/*code*/";
const source = new AsyncFunction("a", "b", body).toString();
return source.slice(0, source.indexOf(body)).split("\n").length - 1;
})();
var WalkerBase$1 = class WalkerBase {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node2) => this.replacement = node2
};
}
/**
*
* @param {any} parent
* @param {string} prop
* @param {number} index
* @param {BaseNode} node
*/
replace(parent, prop, index, node2) {
if (parent) {
if (index !== null) {
parent[prop][index] = node2;
} else {
parent[prop] = node2;
}
}
}
/**
*
* @param {any} parent
* @param {string} prop
* @param {number} index
*/
remove(parent, prop, index) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
var SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
/**
*
* @param {SyncHandler} enter
* @param {SyncHandler} leave
*/
constructor(enter, leave) {
super();
this.enter = enter;
this.leave = leave;
}
/**
*
* @param {BaseNode} node
* @param {BaseNode} parent
* @param {string} [prop]
* @param {number} [index]
* @returns {BaseNode}
*/
visit(node2, parent, prop, index) {
if (node2) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node2, parent, prop, index);
if (this.replacement) {
node2 = this.replacement;
this.replace(parent, prop, index, node2);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node2;
if (removed) return null;
}
for (const key in node2) {
const value2 = node2[key];
if (typeof value2 !== "object") {
continue;
} else if (Array.isArray(value2)) {
for (let i = 0; i < value2.length; i += 1) {
if (value2[i] !== null && typeof value2[i].type === "string") {
if (!this.visit(value2[i], node2, key, i)) {
i--;
}
}
}
} else if (value2 !== null && typeof value2.type === "string") {
this.visit(value2, node2, key, null);
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node2, parent, prop, index);
if (this.replacement) {
node2 = this.replacement;
this.replace(parent, prop, index, node2);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node2;
}
};
function walk$3(ast, { enter, leave }) {
const instance = new SyncWalker$1(enter, leave);
return instance.visit(ast, null);
}
var utils$k = {};
var path$m = import_path.default;
var WIN_SLASH = "\\\\/";
var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
var DOT_LITERAL = "\\.";
var PLUS_LITERAL = "\\+";
var QMARK_LITERAL = "\\?";
var SLASH_LITERAL = "\\/";
var ONE_CHAR = "(?=.)";
var QMARK = "[^/]";
var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
var NO_DOT = `(?!${DOT_LITERAL})`;
var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
var STAR$1 = `${QMARK}*?`;
var POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR: STAR$1,
START_ANCHOR
};
var WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
};
var POSIX_REGEX_SOURCE$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"
};
var constants$6 = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
// Digits
CHAR_0: 48,
/* 0 */
CHAR_9: 57,
/* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65,
/* A */
CHAR_LOWERCASE_A: 97,
/* a */
CHAR_UPPERCASE_Z: 90,
/* Z */
CHAR_LOWERCASE_Z: 122,
/* z */
CHAR_LEFT_PARENTHESES: 40,
/* ( */
CHAR_RIGHT_PARENTHESES: 41,
/* ) */
CHAR_ASTERISK: 42,
/* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38,
/* & */
CHAR_AT: 64,
/* @ */
CHAR_BACKWARD_SLASH: 92,
/* \ */
CHAR_CARRIAGE_RETURN: 13,
/* \r */
CHAR_CIRCUMFLEX_ACCENT: 94,
/* ^ */
CHAR_COLON: 58,
/* : */
CHAR_COMMA: 44,
/* , */
CHAR_DOT: 46,
/* . */
CHAR_DOUBLE_QUOTE: 34,
/* " */
CHAR_EQUAL: 61,
/* = */
CHAR_EXCLAMATION_MARK: 33,
/* ! */
CHAR_FORM_FEED: 12,
/* \f */
CHAR_FORWARD_SLASH: 47,
/* / */
CHAR_GRAVE_ACCENT: 96,
/* ` */
CHAR_HASH: 35,
/* # */
CHAR_HYPHEN_MINUS: 45,
/* - */
CHAR_LEFT_ANGLE_BRACKET: 60,
/* < */
CHAR_LEFT_CURLY_BRACE: 123,
/* { */
CHAR_LEFT_SQUARE_BRACKET: 91,
/* [ */
CHAR_LINE_FEED: 10,
/* \n */
CHAR_NO_BREAK_SPACE: 160,
/* \u00A0 */
CHAR_PERCENT: 37,
/* % */
CHAR_PLUS: 43,
/* + */
CHAR_QUESTION_MARK: 63,
/* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62,
/* > */
CHAR_RIGHT_CURLY_BRACE: 125,
/* } */
CHAR_RIGHT_SQUARE_BRACKET: 93,
/* ] */
CHAR_SEMICOLON: 59,
/* ; */
CHAR_SINGLE_QUOTE: 39,
/* ' */
CHAR_SPACE: 32,
/* */
CHAR_TAB: 9,
/* \t */
CHAR_UNDERSCORE: 95,
/* _ */
CHAR_VERTICAL_LINE: 124,
/* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
/* \uFEFF */
SEP: path$m.sep,
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars2) {
return {
"!": { type: "negate", open: "(?:(?!(?:", close: `))${chars2.STAR})` },
"?": { type: "qmark", open: "(?:", close: ")?" },
"+": { type: "plus", open: "(?:", close: ")+" },
"*": { type: "star", open: "(?:", close: ")*" },
"@": { type: "at", open: "(?:", close: ")" }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win322) {
return win322 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
(function(exports2) {
const path3 = import_path.default;
const win322 = process.platform === "win32";
const {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = constants$6;
exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
exports2.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports2.isRegexChar = (str) => str.length === 1 && exports2.hasRegexChars(str);
exports2.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports2.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports2.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match2) => {
return match2 === "\\" ? "" : match2;
});
};
exports2.supportsLookbehinds = () => {
const segs = process.version.slice(1).split(".").map(Number);
if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
return true;
}
return false;
};
exports2.isWindows = (options2) => {
if (options2 && typeof options2.windows === "boolean") {
return options2.windows;
}
return win322 === true || path3.sep === "\\";
};
exports2.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports2.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports2.wrapOutput = (input, state = {}, options2 = {}) => {
const prepend = options2.contains ? "" : "^";
const append2 = options2.contains ? "" : "$";
let output = `${prepend}(?:${input})${append2}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
})(utils$k);
var utils$j = utils$k;
var {
CHAR_ASTERISK,
/* * */
CHAR_AT,
/* @ */
CHAR_BACKWARD_SLASH,
/* \ */
CHAR_COMMA: CHAR_COMMA$1,
/* , */
CHAR_DOT: CHAR_DOT$1,
/* . */
CHAR_EXCLAMATION_MARK,
/* ! */
CHAR_FORWARD_SLASH,
/* / */
CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
/* { */
CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
/* ( */
CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
/* [ */
CHAR_PLUS,
/* + */
CHAR_QUESTION_MARK,
/* ? */
CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
/* } */
CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
/* ) */
CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
/* ] */
} = constants$6;
var isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
var depth = (token) => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
var scan$2 = (input, options2) => {
const opts = options2 || {};
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 isGlob3 = false;
let isExtglob3 = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces2 = 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$1) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
braces2++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE$1) {
braces2++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
isBrace = token.isBrace = true;
isGlob3 = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA$1) {
isBrace = token.isBrace = true;
isGlob3 = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE$1) {
braces2--;
if (braces2 === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: "", depth: 0, isGlob: false };
if (finished === true) continue;
if (prev === CHAR_DOT$1 && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
isGlob3 = token.isGlob = true;
isExtglob3 = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES$1) {
isGlob3 = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob3 = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob3 = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
isBracket = token.isBracket = true;
isGlob3 = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
isGlob3 = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES$1) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES$1) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob3 === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob3 = false;
isGlob3 = false;
}
let base = str;
let prefix = "";
let glob2 = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob3 === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob2 = str.slice(lastIndex);
} else if (isGlob3 === true) {
base = "";
glob2 = 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 (glob2) glob2 = utils$j.removeBackslashes(glob2);
if (base && backslashes === true) {
base = utils$j.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
glob: glob2,
isBrace,
isBracket,
isGlob: isGlob3,
isExtglob: isExtglob3,
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 n2 = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value2 = input.slice(n2, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value2;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value2 !== "") {
parts.push(value2);
}
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value2 = input.slice(prevIndex + 1);
parts.push(value2);
if (opts.tokens) {
tokens[tokens.length - 1].value = value2;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
var scan_1 = scan$2;
var constants$5 = constants$6;
var utils$i = utils$k;
var {
MAX_LENGTH: MAX_LENGTH$1,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants$5;
var expandRange = (args, options2) => {
if (typeof options2.expandRange === "function") {
return options2.expandRange(...args, options2);
}
args.sort();
const value2 = `[${args.join("-")}]`;
return value2;
};
var syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
var parse$g = (input, options2) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
input = REPLACEMENTS[input] || input;
const opts = { ...options2 };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
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 win322 = utils$i.isWindows(options2);
const PLATFORM_CHARS = constants$5.globChars(win322);
const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS);
const {
DOT_LITERAL: DOT_LITERAL2,
PLUS_LITERAL: PLUS_LITERAL2,
SLASH_LITERAL: SLASH_LITERAL2,
ONE_CHAR: ONE_CHAR2,
DOTS_SLASH: DOTS_SLASH2,
NO_DOT: NO_DOT2,
NO_DOT_SLASH: NO_DOT_SLASH2,
NO_DOTS_SLASH: NO_DOTS_SLASH2,
QMARK: QMARK2,
QMARK_NO_DOT: QMARK_NO_DOT2,
STAR: STAR2,
START_ANCHOR: START_ANCHOR2
} = PLATFORM_CHARS;
const globstar = (opts2) => {
return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`;
};
const nodot = opts.dot ? "" : NO_DOT2;
const qmarkNoDot = opts.dot ? QMARK2 : QMARK_NO_DOT2;
let star2 = opts.bash === true ? globstar(opts) : STAR2;
if (opts.capture) {
star2 = `(${star2})`;
}
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$i.removePrefix(input, state);
len = input.length;
const extglobs = [];
const braces2 = [];
const stack = [];
let prev = bos;
let value2;
const eos = () => state.index === len - 1;
const peek = state.peek = (n2 = 1) => input[state.index + n2];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume = (value3 = "", num = 0) => {
state.consumed += value3;
state.index += num;
};
const append2 = (token) => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) {
return false;
}
state.negated = true;
state.start++;
return true;
};
const increment = (type) => {
state[type]++;
stack.push(type);
};
const decrement = (type) => {
state[type]--;
stack.pop();
};
const push2 = (tok) => {
if (prev.type === "globstar") {
const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
const isExtglob3 = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob3) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star2;
state.output += prev.output;
}
}
if (extglobs.length && tok.type !== "paren") {
extglobs[extglobs.length - 1].inner += tok.value;
}
if (tok.value || tok.output) append2(tok);
if (prev && prev.type === "text" && tok.type === "text") {
prev.value += tok.value;
prev.output = (prev.output || "") + tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value3) => {
const token = { ...EXTGLOB_CHARS[value3], conditions: 1, inner: "" };
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? "(" : "") + token.open;
increment("parens");
push2({ type, value: value3, output: state.output ? "" : ONE_CHAR2 });
push2({ 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 = star2;
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
extglobStar = globstar(opts);
}
if (extglobStar !== star2 || eos() || /^\)+$/.test(remaining())) {
output = token.close = `)$))${extglobStar}`;
}
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
const expression = parse$g(rest, { ...options2, fastpaths: false }).output;
output = token.close = `)${expression})${extglobStar})`;
}
if (token.prev.type === "bos") {
state.negatedExtglob = true;
}
}
push2({ type: "paren", extglob: true, value: value2, output });
decrement("parens");
};
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars2, first2, rest, index) => {
if (first2 === "\\") {
backslashes = true;
return m;
}
if (first2 === "?") {
if (esc) {
return esc + first2 + (rest ? QMARK2.repeat(rest.length) : "");
}
if (index === 0) {
return qmarkNoDot + (rest ? QMARK2.repeat(rest.length) : "");
}
return QMARK2.repeat(chars2.length);
}
if (first2 === ".") {
return DOT_LITERAL2.repeat(chars2.length);
}
if (first2 === "*") {
if (esc) {
return esc + first2 + (rest ? star2 : "");
}
return star2;
}
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$i.wrapOutput(output, state, options2);
return state;
}
while (!eos()) {
value2 = advance();
if (value2 === "\0") {
continue;
}
if (value2 === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) {
continue;
}
if (next === "." || next === ";") {
continue;
}
if (!next) {
value2 += "\\";
push2({ type: "text", value: value2 });
continue;
}
const match2 = /^\\+/.exec(remaining());
let slashes = 0;
if (match2 && match2[0].length > 2) {
slashes = match2[0].length;
state.index += slashes;
if (slashes % 2 !== 0) {
value2 += "\\";
}
}
if (opts.unescape === true) {
value2 = advance();
} else {
value2 += advance();
}
if (state.brackets === 0) {
push2({ type: "text", value: value2 });
continue;
}
}
if (state.brackets > 0 && (value2 !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value2 === ":") {
const inner = prev.value.slice(1);
if (inner.includes("[")) {
prev.posix = true;
if (inner.includes(":")) {
const idx = prev.value.lastIndexOf("[");
const pre = prev.value.slice(0, idx);
const rest2 = prev.value.slice(idx + 2);
const posix2 = POSIX_REGEX_SOURCE[rest2];
if (posix2) {
prev.value = pre + posix2;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR2;
}
continue;
}
}
}
}
if (value2 === "[" && peek() !== ":" || value2 === "-" && peek() === "]") {
value2 = `\\${value2}`;
}
if (value2 === "]" && (prev.value === "[" || prev.value === "[^")) {
value2 = `\\${value2}`;
}
if (opts.posix === true && value2 === "!" && prev.value === "[") {
value2 = "^";
}
prev.value += value2;
append2({ value: value2 });
continue;
}
if (state.quotes === 1 && value2 !== '"') {
value2 = utils$i.escapeRegex(value2);
prev.value += value2;
append2({ value: value2 });
continue;
}
if (value2 === '"') {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push2({ type: "text", value: value2 });
}
continue;
}
if (value2 === "(") {
increment("parens");
push2({ type: "paren", value: value2 });
continue;
}
if (value2 === ")") {
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;
}
push2({ type: "paren", value: value2, output: state.parens ? ")" : "\\)" });
decrement("parens");
continue;
}
if (value2 === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("closing", "]"));
}
value2 = `\\${value2}`;
} else {
increment("brackets");
}
push2({ type: "bracket", value: value2 });
continue;
}
if (value2 === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push2({ type: "text", value: value2, output: `\\${value2}` });
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "["));
}
push2({ type: "text", value: value2, output: `\\${value2}` });
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
value2 = `/${value2}`;
}
prev.value += value2;
append2({ value: value2 });
if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) {
continue;
}
const escaped2 = utils$i.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state.output += escaped2;
prev.value = escaped2;
continue;
}
prev.value = `(${capture}${escaped2}|${prev.value})`;
state.output += prev.value;
continue;
}
if (value2 === "{" && opts.nobrace !== true) {
increment("braces");
const open2 = {
type: "brace",
value: value2,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces2.push(open2);
push2(open2);
continue;
}
if (value2 === "}") {
const brace = braces2[braces2.length - 1];
if (opts.nobrace === true || !brace) {
push2({ type: "text", value: value2, output: value2 });
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range2 = [];
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === "brace") {
break;
}
if (arr[i].type !== "dots") {
range2.unshift(arr[i].value);
}
}
output = expandRange(range2, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out2 = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value2 = output = "\\}";
state.output = out2;
for (const t2 of toks) {
state.output += t2.output || t2.value;
}
}
push2({ type: "brace", value: value2, output });
decrement("braces");
braces2.pop();
continue;
}
if (value2 === "|") {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push2({ type: "text", value: value2 });
continue;
}
if (value2 === ",") {
let output = value2;
const brace = braces2[braces2.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push2({ type: "comma", value: value2, output });
continue;
}
if (value2 === "/") {
if (prev.type === "dot" && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = "";
state.output = "";
tokens.pop();
prev = bos;
continue;
}
push2({ type: "slash", value: value2, output: SLASH_LITERAL2 });
continue;
}
if (value2 === ".") {
if (state.braces > 0 && prev.type === "dot") {
if (prev.value === ".") prev.output = DOT_LITERAL2;
const brace = braces2[braces2.length - 1];
prev.type = "dots";
prev.output += value2;
prev.value += value2;
brace.dots = true;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push2({ type: "text", value: value2, output: DOT_LITERAL2 });
continue;
}
push2({ type: "dot", value: value2, output: DOT_LITERAL2 });
continue;
}
if (value2 === "?") {
const isGroup = prev && prev.value === "(";
if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value2);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value2;
if (next === "<" && !utils$i.supportsLookbehinds()) {
throw new Error("Node.js v10 or higher is required for regex lookbehinds");
}
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
output = `\\${value2}`;
}
push2({ type: "text", value: value2, output });
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push2({ type: "qmark", value: value2, output: QMARK_NO_DOT2 });
continue;
}
push2({ type: "qmark", value: value2, output: QMARK2 });
continue;
}
if (value2 === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value2);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
if (value2 === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value2);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push2({ type: "plus", value: value2, output: PLUS_LITERAL2 });
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push2({ type: "plus", value: value2 });
continue;
}
push2({ type: "plus", value: PLUS_LITERAL2 });
continue;
}
if (value2 === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push2({ type: "at", extglob: true, value: value2, output: "" });
continue;
}
push2({ type: "text", value: value2 });
continue;
}
if (value2 !== "*") {
if (value2 === "$" || value2 === "^") {
value2 = `\\${value2}`;
}
const match2 = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match2) {
value2 += match2[0];
state.index += match2[0].length;
}
push2({ type: "text", value: value2 });
continue;
}
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value2;
prev.output = star2;
state.backtrack = true;
state.globstar = true;
consume(value2);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value2);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume(value2);
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] !== "/")) {
push2({ type: "star", value: value2, output: "" });
continue;
}
const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
const isExtglob3 = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob3) {
push2({ type: "star", value: value2, output: "" });
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state.index + 4];
if (after && after !== "/") {
break;
}
rest = rest.slice(3);
consume("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value2;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value2);
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 += value2;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value2);
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_LITERAL2}|${SLASH_LITERAL2}${end})`;
prev.value += value2;
state.output += prior.output + prev.output;
state.globstar = true;
consume(value2 + advance());
push2({ type: "slash", value: "/", output: "" });
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value2;
prev.output = `(?:^|${SLASH_LITERAL2}|${globstar(opts)}${SLASH_LITERAL2})`;
state.output = prev.output;
state.globstar = true;
consume(value2 + advance());
push2({ type: "slash", value: "/", output: "" });
continue;
}
state.output = state.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value2;
state.output += prev.output;
state.globstar = true;
consume(value2);
continue;
}
const token = { type: "star", value: value2, output: star2 };
if (opts.bash === true) {
token.output = ".*?";
if (prev.type === "bos" || prev.type === "slash") {
token.output = nodot + token.output;
}
push2(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
token.output = value2;
push2(token);
continue;
}
if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state.output += NO_DOT_SLASH2;
prev.output += NO_DOT_SLASH2;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH2;
prev.output += NO_DOTS_SLASH2;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state.output += ONE_CHAR2;
prev.output += ONE_CHAR2;
}
}
push2(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils$i.escapeLast(state.output, "[");
decrement("brackets");
}
while (state.parens > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils$i.escapeLast(state.output, "(");
decrement("parens");
}
while (state.braces > 0) {
if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils$i.escapeLast(state.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
push2({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL2}?` });
}
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;
};
parse$g.fastpaths = (input, options2) => {
const opts = { ...options2 };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
const len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
input = REPLACEMENTS[input] || input;
const win322 = utils$i.isWindows(options2);
const {
DOT_LITERAL: DOT_LITERAL2,
SLASH_LITERAL: SLASH_LITERAL2,
ONE_CHAR: ONE_CHAR2,
DOTS_SLASH: DOTS_SLASH2,
NO_DOT: NO_DOT2,
NO_DOTS: NO_DOTS2,
NO_DOTS_SLASH: NO_DOTS_SLASH2,
STAR: STAR2,
START_ANCHOR: START_ANCHOR2
} = constants$5.globChars(win322);
const nodot = opts.dot ? NO_DOTS2 : NO_DOT2;
const slashDot = opts.dot ? NO_DOTS_SLASH2 : NO_DOT2;
const capture = opts.capture ? "" : "?:";
const state = { negated: false, prefix: "" };
let star2 = opts.bash === true ? ".*?" : STAR2;
if (opts.capture) {
star2 = `(${star2})`;
}
const globstar = (opts2) => {
if (opts2.noglobstar === true) return star2;
return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`;
};
const create = (str) => {
switch (str) {
case "*":
return `${nodot}${ONE_CHAR2}${star2}`;
case ".*":
return `${DOT_LITERAL2}${ONE_CHAR2}${star2}`;
case "*.*":
return `${nodot}${star2}${DOT_LITERAL2}${ONE_CHAR2}${star2}`;
case "*/*":
return `${nodot}${star2}${SLASH_LITERAL2}${ONE_CHAR2}${slashDot}${star2}`;
case "**":
return nodot + globstar(opts);
case "**/*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${ONE_CHAR2}${star2}`;
case "**/*.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${star2}${DOT_LITERAL2}${ONE_CHAR2}${star2}`;
case "**/.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${DOT_LITERAL2}${ONE_CHAR2}${star2}`;
default: {
const match2 = /^(.*?)\.(\w+)$/.exec(str);
if (!match2) return;
const source2 = create(match2[1]);
if (!source2) return;
return source2 + DOT_LITERAL2 + match2[2];
}
}
};
const output = utils$i.removePrefix(input, state);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL2}?`;
}
return source;
};
var parse_1$3 = parse$g;
var path$l = import_path.default;
var scan$1 = scan_1;
var parse$f = parse_1$3;
var utils$h = utils$k;
var constants$4 = constants$6;
var isObject$3 = (val) => val && typeof val === "object" && !Array.isArray(val);
var picomatch$5 = (glob2, options2, returnState = false) => {
if (Array.isArray(glob2)) {
const fns = glob2.map((input) => picomatch$5(input, options2, returnState));
const arrayMatcher = (str) => {
for (const isMatch2 of fns) {
const state2 = isMatch2(str);
if (state2) return state2;
}
return false;
};
return arrayMatcher;
}
const isState = isObject$3(glob2) && glob2.tokens && glob2.input;
if (glob2 === "" || typeof glob2 !== "string" && !isState) {
throw new TypeError("Expected pattern to be a non-empty string");
}
const opts = options2 || {};
const posix2 = utils$h.isWindows(options2);
const regex2 = isState ? picomatch$5.compileRe(glob2, options2) : picomatch$5.makeRe(glob2, options2, false, true);
const state = regex2.state;
delete regex2.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options2, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState);
}
const matcher2 = (input, returnObject = false) => {
const { isMatch: isMatch2, match: match2, output } = picomatch$5.test(input, regex2, options2, { glob: glob2, posix: posix2 });
const result = { glob: glob2, state, regex: regex2, posix: posix2, input, output, match: match2, isMatch: isMatch2 };
if (typeof opts.onResult === "function") {
opts.onResult(result);
}
if (isMatch2 === 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) {
matcher2.state = state;
}
return matcher2;
};
picomatch$5.test = (input, regex2, options2, { glob: glob2, posix: posix2 } = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected input to be a string");
}
if (input === "") {
return { isMatch: false, output: "" };
}
const opts = options2 || {};
const format2 = opts.format || (posix2 ? utils$h.toPosixSlashes : null);
let match2 = input === glob2;
let output = match2 && format2 ? format2(input) : input;
if (match2 === false) {
output = format2 ? format2(input) : input;
match2 = output === glob2;
}
if (match2 === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match2 = picomatch$5.matchBase(input, regex2, options2, posix2);
} else {
match2 = regex2.exec(output);
}
}
return { isMatch: Boolean(match2), match: match2, output };
};
picomatch$5.matchBase = (input, glob2, options2, posix2 = utils$h.isWindows(options2)) => {
const regex2 = glob2 instanceof RegExp ? glob2 : picomatch$5.makeRe(glob2, options2);
return regex2.test(path$l.basename(input));
};
picomatch$5.isMatch = (str, patterns, options2) => picomatch$5(patterns, options2)(str);
picomatch$5.parse = (pattern2, options2) => {
if (Array.isArray(pattern2)) return pattern2.map((p) => picomatch$5.parse(p, options2));
return parse$f(pattern2, { ...options2, fastpaths: false });
};
picomatch$5.scan = (input, options2) => scan$1(input, options2);
picomatch$5.compileRe = (state, options2, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options2 || {};
const prepend = opts.contains ? "" : "^";
const append2 = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append2}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex2 = picomatch$5.toRegex(source, options2);
if (returnState === true) {
regex2.state = state;
}
return regex2;
};
picomatch$5.makeRe = (input, options2 = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") {
throw new TypeError("Expected a non-empty string");
}
let parsed = { negated: false, fastpaths: true };
if (options2.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
parsed.output = parse$f.fastpaths(input, options2);
}
if (!parsed.output) {
parsed = parse$f(input, options2);
}
return picomatch$5.compileRe(parsed, options2, returnOutput, returnState);
};
picomatch$5.toRegex = (source, options2) => {
try {
const opts = options2 || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err2) {
if (options2 && options2.debug === true) throw err2;
return /$^/;
}
};
picomatch$5.constants = constants$4;
var picomatch_1 = picomatch$5;
var picomatch$3 = picomatch_1;
var picomatch$4 = getDefaultExportFromCjs(picomatch$3);
var extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() {
},
ObjectPattern(names, param) {
for (const prop of param.properties) {
if (prop.type === "RestElement") {
extractors.RestElement(names, prop);
} else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
var extractAssignedNames = function extractAssignedNames2(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
var blockDeclarations = {
const: true,
let: true
};
var Scope = class {
constructor(options2 = {}) {
this.parent = options2.parent;
this.isBlockScope = !!options2.block;
this.declarations = /* @__PURE__ */ Object.create(null);
if (options2.params) {
options2.params.forEach((param) => {
extractAssignedNames(param).forEach((name2) => {
this.declarations[name2] = true;
});
});
}
}
addDeclaration(node2, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
this.parent.addDeclaration(node2, isBlockDeclaration, isVar);
} else if (node2.id) {
extractAssignedNames(node2.id).forEach((name2) => {
this.declarations[name2] = true;
});
}
}
contains(name2) {
return this.declarations[name2] || (this.parent ? this.parent.contains(name2) : false);
}
};
var attachScopes = function attachScopes2(ast, propertyName = "scope") {
let scope = new Scope();
walk$3(ast, {
enter(n2, parent) {
const node2 = n2;
if (/(Function|Class)Declaration/.test(node2.type)) {
scope.addDeclaration(node2, false, false);
}
if (node2.type === "VariableDeclaration") {
const { kind } = node2;
const isBlockDeclaration = blockDeclarations[kind];
node2.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
if (/Function/.test(node2.type)) {
const func = node2;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
if (func.type === "FunctionExpression" && func.id) {
newScope.addDeclaration(func, false, false);
}
}
if (/For(In|Of)?Statement/.test(node2.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
if (node2.type === "BlockStatement" && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
if (node2.type === "CatchClause") {
newScope = new Scope({
parent: scope,
params: node2.param ? [node2.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node2, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n2) {
const node2 = n2;
if (node2[propertyName])
scope = scope.parent;
}
});
return scope;
};
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
var normalizePath$5 = function normalizePath(filename) {
return filename.split(import_path.win32.sep).join(import_path.posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || (0, import_path.isAbsolute)(id) || id.startsWith("**")) {
return normalizePath$5(id);
}
const basePath = normalizePath$5((0, import_path.resolve)(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
return import_path.posix.join(basePath, normalizePath$5(id));
}
var createFilter$1 = function createFilter(include, exclude, options2) {
const resolutionBase = options2 && options2.resolve;
const getMatcher = (id) => id instanceof RegExp ? id : {
test: (what) => {
const pattern2 = getMatcherString(id, resolutionBase);
const fn = picomatch$4(pattern2, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id) {
if (typeof id !== "string")
return false;
if (/\0/.test(id))
return false;
const pathId = normalizePath$5(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher2 = excludeMatchers[i];
if (matcher2.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher2 = includeMatchers[i];
if (matcher2.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
var reservedWords = "break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public";
var builtins = "arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl";
var forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(" "));
forbiddenIdentifiers.add("");
var makeLegalIdentifier = function makeLegalIdentifier2(str) {
let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_");
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || "_";
};
function stringify$8(obj) {
return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = "[";
const separator = indent ? `
${baseIndent}${indent}` : "";
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `
${baseIndent}` : ""}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = "{";
const separator = indent ? `
${baseIndent}${indent}` : "";
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value2] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key);
output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value2, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `
${baseIndent}` : ""}}`;
}
function serialize(obj, indent, baseIndent) {
if (typeof obj === "object" && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === "number") {
if (obj === Infinity)
return "Infinity";
if (obj === -Infinity)
return "-Infinity";
if (obj === 0)
return 1 / obj === Infinity ? "0" : "-0";
if (obj !== obj)
return "NaN";
}
if (typeof obj === "symbol") {
const key = Symbol.keyFor(obj);
if (key !== void 0)
return `Symbol.for(${stringify$8(key)})`;
}
if (typeof obj === "bigint")
return `${obj}n`;
return stringify$8(obj);
}
var hasStringIsWellFormed = "isWellFormed" in String.prototype;
function isWellFormedString(input) {
if (hasStringIsWellFormed)
return input.isWellFormed();
return !new RegExp("\\p{Surrogate}", "u").test(input);
}
var dataToEsm = function dataToEsm2(data, options2 = {}) {
var _a4, _b3;
const t2 = options2.compact ? "" : "indent" in options2 ? options2.indent : " ";
const _ = options2.compact ? "" : " ";
const n2 = options2.compact ? "" : "\n";
const declarationType = options2.preferConst ? "const" : "var";
if (options2.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
const code = serialize(data, options2.compact ? null : t2, "");
const magic = _ || (/^[{[\-\/]/.test(code) ? "" : " ");
return `export default${magic}${code};`;
}
let maxUnderbarPrefixLength = 0;
for (const key of Object.keys(data)) {
const underbarPrefixLength = (_b3 = (_a4 = key.match(/^(_+)/)) === null || _a4 === void 0 ? void 0 : _a4[0].length) !== null && _b3 !== void 0 ? _b3 : 0;
if (underbarPrefixLength > maxUnderbarPrefixLength) {
maxUnderbarPrefixLength = underbarPrefixLength;
}
}
const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
let namedExportCode = "";
const defaultExportRows = [];
const arbitraryNameExportRows = [];
for (const [key, value2] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options2.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value2, options2.compact ? null : t2, "")};${n2}`;
} else {
defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value2, options2.compact ? null : t2, "")}`);
if (options2.includeArbitraryNames && isWellFormedString(key)) {
const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value2, options2.compact ? null : t2, "")};${n2}`;
arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
}
}
}
const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n2}${t2}${arbitraryNameExportRows.join(`,${n2}${t2}`)}${n2}};${n2}` : "";
const defaultExportCode = `export default${_}{${n2}${t2}${defaultExportRows.join(`,${n2}${t2}`)}${n2}};${n2}`;
return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
};
var path$k = import_path.default;
var commondir = function(basedir, relfiles) {
if (relfiles) {
var files = relfiles.map(function(r2) {
return path$k.resolve(basedir, r2);
});
} else {
var files = basedir;
}
var res = files.slice(1).reduce(function(ps, file) {
if (!file.match(/^([A-Za-z]:)?\/|\\/)) {
throw new Error("relative path without a basedir");
}
var xs = file.split(/\/+|\\+/);
for (var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++) ;
return ps.slice(0, i);
}, files[0].split(/\/+|\\+/));
return res.length > 1 ? res.join("/") : "/";
};
var getCommonDir = getDefaultExportFromCjs(commondir);
var balancedMatch = balanced$1;
function balanced$1(a, b, str) {
if (a instanceof RegExp) a = maybeMatch(a, str);
if (b instanceof RegExp) b = maybeMatch(b, str);
var r2 = range$1(a, b, str);
return r2 && {
start: r2[0],
end: r2[1],
pre: str.slice(0, r2[0]),
body: str.slice(r2[0] + a.length, r2[1]),
post: str.slice(r2[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m = str.match(reg);
return m ? m[0] : null;
}
balanced$1.range = range$1;
function range$1(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i == ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length == 1) {
result = [begs.pop(), bi];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [left, right];
}
}
return result;
}
var balanced = balancedMatch;
var braceExpansion = expandTop;
var escSlash = "\0SLASH" + Math.random() + "\0";
var escOpen = "\0OPEN" + Math.random() + "\0";
var escClose = "\0CLOSE" + Math.random() + "\0";
var escComma = "\0COMMA" + Math.random() + "\0";
var escPeriod = "\0PERIOD" + Math.random() + "\0";
function numeric(str) {
return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
}
function parseCommaParts(str) {
if (!str)
return [""];
var parts = [];
var m = balanced("{", "}", str);
if (!m)
return str.split(",");
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(",");
p[p.length - 1] += "{" + body + "}";
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length - 1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
if (str.substr(0, 2) === "{}") {
str = "\\{\\}" + str.substr(2);
}
return expand$3(escapeBraces(str), true).map(unescapeBraces);
}
function embrace(str) {
return "{" + str + "}";
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand$3(str, isTop) {
var expansions = [];
var m = balanced("{", "}", str);
if (!m) return [str];
var pre = m.pre;
var post = m.post.length ? expand$3(m.post, false) : [""];
if (/\$$/.test(m.pre)) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + "{" + m.body + "}" + post[k];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(",") >= 0;
if (!isSequence && !isOptions) {
if (m.post.match(/,.*\}/)) {
str = m.pre + "{" + m.body + escClose + m.post;
return expand$3(str);
}
return [str];
}
var n2;
if (isSequence) {
n2 = m.body.split(/\.\./);
} else {
n2 = parseCommaParts(m.body);
if (n2.length === 1) {
n2 = expand$3(n2[0], false).map(embrace);
if (n2.length === 1) {
return post.map(function(p) {
return m.pre + n2[0] + p;
});
}
}
}
var N;
if (isSequence) {
var x = numeric(n2[0]);
var y = numeric(n2[1]);
var width = Math.max(n2[0].length, n2[1].length);
var incr = n2.length == 3 ? Math.abs(numeric(n2[2])) : 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad2 = n2.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === "\\")
c = "";
} else {
c = String(i);
if (pad2) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join("0");
if (i < 0)
c = "-" + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = [];
for (var j = 0; j < n2.length; j++) {
N.push.apply(N, expand$3(n2[j], false));
}
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}
var expand$4 = getDefaultExportFromCjs(braceExpansion);
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = (pattern2) => {
if (typeof pattern2 !== "string") {
throw new TypeError("invalid pattern");
}
if (pattern2.length > MAX_PATTERN_LENGTH) {
throw new TypeError("pattern is too long");
}
};
var posixClasses = {
"[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
"[:alpha:]": ["\\p{L}\\p{Nl}", true],
"[:ascii:]": ["\\x00-\\x7f", false],
"[:blank:]": ["\\p{Zs}\\t", true],
"[:cntrl:]": ["\\p{Cc}", true],
"[:digit:]": ["\\p{Nd}", true],
"[:graph:]": ["\\p{Z}\\p{C}", true, true],
"[:lower:]": ["\\p{Ll}", true],
"[:print:]": ["\\p{C}", true],
"[:punct:]": ["\\p{P}", true],
"[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
"[:upper:]": ["\\p{Lu}", true],
"[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
"[:xdigit:]": ["A-Fa-f0-9", false]
};
var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var rangesToString = (ranges) => ranges.join("");
var parseClass = (glob2, position) => {
const pos = position;
if (glob2.charAt(pos) !== "[") {
throw new Error("not in a brace expression");
}
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = "";
WHILE: while (i < glob2.length) {
const c = glob2.charAt(i);
if ((c === "!" || c === "^") && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === "]" && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === "\\") {
if (!escaping) {
escaping = true;
i++;
continue;
}
}
if (c === "[" && !escaping) {
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob2.startsWith(cls, i)) {
if (rangeStart) {
return ["$.", false, glob2.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
escaping = false;
if (rangeStart) {
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
} else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = "";
i++;
continue;
}
if (glob2.startsWith("-]", i + 1)) {
ranges.push(braceEscape(c + "-"));
i += 2;
continue;
}
if (glob2.startsWith("-", i + 1)) {
rangeStart = c;
i += 2;
continue;
}
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
return ["", false, 0, false];
}
if (!ranges.length && !negs.length) {
return ["$.", false, glob2.length - pos, true];
}
if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
const r2 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r2), false, endPos - pos, false];
}
const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
return [comb, uflag, endPos - pos, true];
};
var unescape$1 = (s, { windowsPathsNoEscape = false } = {}) => {
return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
};
var types$1 = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
var isExtglobType = (c) => types$1.has(c);
var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))";
var startNoDot = "(?!\\.)";
var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
var justDots = /* @__PURE__ */ new Set(["..", "."]);
var reSpecials = new Set("().*{}+?[]^$\\!");
var regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var qmark$1 = "[^/]";
var star$1 = qmark$1 + "*?";
var starNoEmpty = qmark$1 + "+?";
var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, partsToRegExp_fn, parseGlob_fn;
var _AST = class _AST {
constructor(type, parent, options2 = {}) {
__privateAdd(this, _AST_instances);
__publicField(this, "type");
__privateAdd(this, _root);
__privateAdd(this, _hasMagic);
__privateAdd(this, _uflag, false);
__privateAdd(this, _parts, []);
__privateAdd(this, _parent);
__privateAdd(this, _parentIndex);
__privateAdd(this, _negs);
__privateAdd(this, _filledNegs, false);
__privateAdd(this, _options);
__privateAdd(this, _toString);
// set to true if it's an extglob with no children
// (which really means one child of '')
__privateAdd(this, _emptyExt, false);
this.type = type;
if (type)
__privateSet(this, _hasMagic, true);
__privateSet(this, _parent, parent);
__privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
__privateSet(this, _options, __privateGet(this, _root) === this ? options2 : __privateGet(__privateGet(this, _root), _options));
__privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
if (type === "!" && !__privateGet(__privateGet(this, _root), _filledNegs))
__privateGet(this, _negs).push(this);
__privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
}
get hasMagic() {
if (__privateGet(this, _hasMagic) !== void 0)
return __privateGet(this, _hasMagic);
for (const p of __privateGet(this, _parts)) {
if (typeof p === "string")
continue;
if (p.type || p.hasMagic)
return __privateSet(this, _hasMagic, true);
}
return __privateGet(this, _hasMagic);
}
// reconstructs the pattern
toString() {
if (__privateGet(this, _toString) !== void 0)
return __privateGet(this, _toString);
if (!this.type) {
return __privateSet(this, _toString, __privateGet(this, _parts).map((p) => String(p)).join(""));
} else {
return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((p) => String(p)).join("|") + ")");
}
}
push(...parts) {
for (const p of parts) {
if (p === "")
continue;
if (typeof p !== "string" && !(p instanceof _AST && __privateGet(p, _parent) === this)) {
throw new Error("invalid part: " + p);
}
__privateGet(this, _parts).push(p);
}
}
toJSON() {
var _a4;
const ret = this.type === null ? __privateGet(this, _parts).slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...__privateGet(this, _parts).map((p) => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && ((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!")) {
ret.push({});
}
return ret;
}
isStart() {
var _a4;
if (__privateGet(this, _root) === this)
return true;
if (!((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.isStart()))
return false;
if (__privateGet(this, _parentIndex) === 0)
return true;
const p = __privateGet(this, _parent);
for (let i = 0; i < __privateGet(this, _parentIndex); i++) {
const pp = __privateGet(p, _parts)[i];
if (!(pp instanceof _AST && pp.type === "!")) {
return false;
}
}
return true;
}
isEnd() {
var _a4, _b3, _c2;
if (__privateGet(this, _root) === this)
return true;
if (((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!")
return true;
if (!((_b3 = __privateGet(this, _parent)) == null ? void 0 : _b3.isEnd()))
return false;
if (!this.type)
return (_c2 = __privateGet(this, _parent)) == null ? void 0 : _c2.isEnd();
const pl = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
return __privateGet(this, _parentIndex) === pl - 1;
}
copyIn(part) {
if (typeof part === "string")
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new _AST(this.type, parent);
for (const p of __privateGet(this, _parts)) {
c.copyIn(p);
}
return c;
}
static fromGlob(pattern2, options2 = {}) {
var _a4;
const ast = new _AST(null, void 0, options2);
__privateMethod(_a4 = _AST, _AST_static, parseAST_fn).call(_a4, pattern2, ast, 0, options2);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
if (this !== __privateGet(this, _root))
return __privateGet(this, _root).toMMPattern();
const glob2 = this.toString();
const [re, body, hasMagic2, uflag] = this.toRegExpSource();
const anyMagic = hasMagic2 || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase();
if (!anyMagic) {
return body;
}
const flags = (__privateGet(this, _options).nocase ? "i" : "") + (uflag ? "u" : "");
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob2
});
}
get options() {
return __privateGet(this, _options);
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
var _a4;
const dot = allowDot ?? !!__privateGet(this, _options).dot;
if (__privateGet(this, _root) === this)
__privateMethod(this, _AST_instances, fillNegs_fn).call(this);
if (!this.type) {
const noEmpty = this.isStart() && this.isEnd();
const src2 = __privateGet(this, _parts).map((p) => {
var _a5;
const [re, _, hasMagic2, uflag] = typeof p === "string" ? __privateMethod(_a5 = _AST, _AST_static, parseGlob_fn).call(_a5, p, __privateGet(this, _hasMagic), noEmpty) : p.toRegExpSource(allowDot);
__privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || hasMagic2);
__privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
return re;
}).join("");
let start2 = "";
if (this.isStart()) {
if (typeof __privateGet(this, _parts)[0] === "string") {
const dotTravAllowed = __privateGet(this, _parts).length === 1 && justDots.has(__privateGet(this, _parts)[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
const needNoTrav = (
// dots are allowed, and the pattern starts with [ or .
dot && aps.has(src2.charAt(0)) || // the pattern starts with \., and then [ or .
src2.startsWith("\\.") && aps.has(src2.charAt(2)) || // the pattern starts with \.\., and then [ or .
src2.startsWith("\\.\\.") && aps.has(src2.charAt(4))
);
const needNoDot = !dot && !allowDot && aps.has(src2.charAt(0));
start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
}
}
}
let end = "";
if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && ((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!") {
end = "(?:$|\\/)";
}
const final2 = start2 + src2 + end;
return [
final2,
unescape$1(src2),
__privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
__privateGet(this, _uflag)
];
}
const repeated = this.type === "*" || this.type === "+";
const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
let body = __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, dot);
if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
const s = this.toString();
__privateSet(this, _parts, [s]);
this.type = null;
__privateSet(this, _hasMagic, void 0);
return [s, unescape$1(this.toString()), false, false];
}
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, true);
if (bodyDotAllowed === body) {
bodyDotAllowed = "";
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
let final = "";
if (this.type === "!" && __privateGet(this, _emptyExt)) {
final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;
} else {
const close2 = this.type === "!" ? (
// !() must match something,but !(x) can match ''
"))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star$1 + ")"
) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;
final = start + body + close2;
}
return [
final,
unescape$1(body),
__privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
__privateGet(this, _uflag)
];
}
};
_root = new WeakMap();
_hasMagic = new WeakMap();
_uflag = new WeakMap();
_parts = new WeakMap();
_parent = new WeakMap();
_parentIndex = new WeakMap();
_negs = new WeakMap();
_filledNegs = new WeakMap();
_options = new WeakMap();
_toString = new WeakMap();
_emptyExt = new WeakMap();
_AST_instances = new WeakSet();
fillNegs_fn = function() {
if (this !== __privateGet(this, _root))
throw new Error("should only call on root");
if (__privateGet(this, _filledNegs))
return this;
this.toString();
__privateSet(this, _filledNegs, true);
let n2;
while (n2 = __privateGet(this, _negs).pop()) {
if (n2.type !== "!")
continue;
let p = n2;
let pp = __privateGet(p, _parent);
while (pp) {
for (let i = __privateGet(p, _parentIndex) + 1; !pp.type && i < __privateGet(pp, _parts).length; i++) {
for (const part of __privateGet(n2, _parts)) {
if (typeof part === "string") {
throw new Error("string part in extglob AST??");
}
part.copyIn(__privateGet(pp, _parts)[i]);
}
}
p = pp;
pp = __privateGet(p, _parent);
}
}
return this;
};
_AST_static = new WeakSet();
parseAST_fn = function(str, ast, pos, opt) {
var _a4, _b3;
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
let i2 = pos;
let acc2 = "";
while (i2 < str.length) {
const c = str.charAt(i2++);
if (escaping || c === "\\") {
escaping = !escaping;
acc2 += c;
continue;
}
if (inBrace) {
if (i2 === braceStart + 1) {
if (c === "^" || c === "!") {
braceNeg = true;
}
} else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc2 += c;
continue;
} else if (c === "[") {
inBrace = true;
braceStart = i2;
braceNeg = false;
acc2 += c;
continue;
}
if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") {
ast.push(acc2);
acc2 = "";
const ext2 = new _AST(c, ast);
i2 = __privateMethod(_a4 = _AST, _AST_static, parseAST_fn).call(_a4, str, ext2, i2, opt);
ast.push(ext2);
continue;
}
acc2 += c;
}
ast.push(acc2);
return i2;
}
let i = pos + 1;
let part = new _AST(null, ast);
const parts = [];
let acc = "";
while (i < str.length) {
const c = str.charAt(i++);
if (escaping || c === "\\") {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === "^" || c === "!") {
braceNeg = true;
}
} else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
} else if (c === "[") {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (isExtglobType(c) && str.charAt(i) === "(") {
part.push(acc);
acc = "";
const ext2 = new _AST(c, part);
part.push(ext2);
i = __privateMethod(_b3 = _AST, _AST_static, parseAST_fn).call(_b3, str, ext2, i, opt);
continue;
}
if (c === "|") {
part.push(acc);
acc = "";
parts.push(part);
part = new _AST(null, ast);
continue;
}
if (c === ")") {
if (acc === "" && __privateGet(ast, _parts).length === 0) {
__privateSet(ast, _emptyExt, true);
}
part.push(acc);
acc = "";
ast.push(...parts, part);
return i;
}
acc += c;
}
ast.type = null;
__privateSet(ast, _hasMagic, void 0);
__privateSet(ast, _parts, [str.substring(pos - 1)]);
return i;
};
partsToRegExp_fn = function(dot) {
return __privateGet(this, _parts).map((p) => {
if (typeof p === "string") {
throw new Error("string type in extglob ast??");
}
const [re, _, _hasMagic2, uflag] = p.toRegExpSource(dot);
__privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
return re;
}).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
};
parseGlob_fn = function(glob2, hasMagic2, noEmpty = false) {
let escaping = false;
let re = "";
let uflag = false;
for (let i = 0; i < glob2.length; i++) {
const c = glob2.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? "\\" : "") + c;
continue;
}
if (c === "\\") {
if (i === glob2.length - 1) {
re += "\\\\";
} else {
escaping = true;
}
continue;
}
if (c === "[") {
const [src2, needUflag, consumed, magic] = parseClass(glob2, i);
if (consumed) {
re += src2;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic2 = hasMagic2 || magic;
continue;
}
}
if (c === "*") {
if (noEmpty && glob2 === "*")
re += starNoEmpty;
else
re += star$1;
hasMagic2 = true;
continue;
}
if (c === "?") {
re += qmark$1;
hasMagic2 = true;
continue;
}
re += regExpEscape$1(c);
}
return [re, unescape$1(glob2), !!hasMagic2, uflag];
};
__privateAdd(_AST, _AST_static);
var AST = _AST;
var escape$2 = (s, { windowsPathsNoEscape = false } = {}) => {
return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
};
var minimatch = (p, pattern2, options2 = {}) => {
assertValidPattern(pattern2);
if (!options2.nocomment && pattern2.charAt(0) === "#") {
return false;
}
return new Minimatch(pattern2, options2).match(p);
};
var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
var starDotExtTest = (ext2) => (f2) => !f2.startsWith(".") && f2.endsWith(ext2);
var starDotExtTestDot = (ext2) => (f2) => f2.endsWith(ext2);
var starDotExtTestNocase = (ext2) => {
ext2 = ext2.toLowerCase();
return (f2) => !f2.startsWith(".") && f2.toLowerCase().endsWith(ext2);
};
var starDotExtTestNocaseDot = (ext2) => {
ext2 = ext2.toLowerCase();
return (f2) => f2.toLowerCase().endsWith(ext2);
};
var starDotStarRE = /^\*+\.\*+$/;
var starDotStarTest = (f2) => !f2.startsWith(".") && f2.includes(".");
var starDotStarTestDot = (f2) => f2 !== "." && f2 !== ".." && f2.includes(".");
var dotStarRE = /^\.\*+$/;
var dotStarTest = (f2) => f2 !== "." && f2 !== ".." && f2.startsWith(".");
var starRE = /^\*+$/;
var starTest = (f2) => f2.length !== 0 && !f2.startsWith(".");
var starTestDot = (f2) => f2.length !== 0 && f2 !== "." && f2 !== "..";
var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
var qmarksTestNocase = ([$0, ext2 = ""]) => {
const noext = qmarksTestNoExt([$0]);
if (!ext2)
return noext;
ext2 = ext2.toLowerCase();
return (f2) => noext(f2) && f2.toLowerCase().endsWith(ext2);
};
var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
const noext = qmarksTestNoExtDot([$0]);
if (!ext2)
return noext;
ext2 = ext2.toLowerCase();
return (f2) => noext(f2) && f2.toLowerCase().endsWith(ext2);
};
var qmarksTestDot = ([$0, ext2 = ""]) => {
const noext = qmarksTestNoExtDot([$0]);
return !ext2 ? noext : (f2) => noext(f2) && f2.endsWith(ext2);
};
var qmarksTest = ([$0, ext2 = ""]) => {
const noext = qmarksTestNoExt([$0]);
return !ext2 ? noext : (f2) => noext(f2) && f2.endsWith(ext2);
};
var qmarksTestNoExt = ([$0]) => {
const len = $0.length;
return (f2) => f2.length === len && !f2.startsWith(".");
};
var qmarksTestNoExtDot = ([$0]) => {
const len = $0.length;
return (f2) => f2.length === len && f2 !== "." && f2 !== "..";
};
var defaultPlatform$2 = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
var path$j = {
win32: { sep: "\\" },
posix: { sep: "/" }
};
var sep = defaultPlatform$2 === "win32" ? path$j.win32.sep : path$j.posix.sep;
minimatch.sep = sep;
var GLOBSTAR$2 = Symbol("globstar **");
minimatch.GLOBSTAR = GLOBSTAR$2;
var qmark = "[^/]";
var star = qmark + "*?";
var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
var filter$1 = (pattern2, options2 = {}) => (p) => minimatch(p, pattern2, options2);
minimatch.filter = filter$1;
var ext = (a, b = {}) => Object.assign({}, a, b);
var defaults = (def) => {
if (!def || typeof def !== "object" || !Object.keys(def).length) {
return minimatch;
}
const orig = minimatch;
const m = (p, pattern2, options2 = {}) => orig(p, pattern2, ext(def, options2));
return Object.assign(m, {
Minimatch: class Minimatch extends orig.Minimatch {
constructor(pattern2, options2 = {}) {
super(pattern2, ext(def, options2));
}
static defaults(options2) {
return orig.defaults(ext(def, options2)).Minimatch;
}
},
AST: class AST extends orig.AST {
/* c8 ignore start */
constructor(type, parent, options2 = {}) {
super(type, parent, ext(def, options2));
}
/* c8 ignore stop */
static fromGlob(pattern2, options2 = {}) {
return orig.AST.fromGlob(pattern2, ext(def, options2));
}
},
unescape: (s, options2 = {}) => orig.unescape(s, ext(def, options2)),
escape: (s, options2 = {}) => orig.escape(s, ext(def, options2)),
filter: (pattern2, options2 = {}) => orig.filter(pattern2, ext(def, options2)),
defaults: (options2) => orig.defaults(ext(def, options2)),
makeRe: (pattern2, options2 = {}) => orig.makeRe(pattern2, ext(def, options2)),
braceExpand: (pattern2, options2 = {}) => orig.braceExpand(pattern2, ext(def, options2)),
match: (list, pattern2, options2 = {}) => orig.match(list, pattern2, ext(def, options2)),
sep: orig.sep,
GLOBSTAR: GLOBSTAR$2
});
};
minimatch.defaults = defaults;
var braceExpand = (pattern2, options2 = {}) => {
assertValidPattern(pattern2);
if (options2.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern2)) {
return [pattern2];
}
return expand$4(pattern2);
};
minimatch.braceExpand = braceExpand;
var makeRe$1 = (pattern2, options2 = {}) => new Minimatch(pattern2, options2).makeRe();
minimatch.makeRe = makeRe$1;
var match = (list, pattern2, options2 = {}) => {
const mm = new Minimatch(pattern2, options2);
list = list.filter((f2) => mm.match(f2));
if (mm.options.nonull && !list.length) {
list.push(pattern2);
}
return list;
};
minimatch.match = match;
var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var Minimatch = class {
constructor(pattern2, options2 = {}) {
__publicField(this, "options");
__publicField(this, "set");
__publicField(this, "pattern");
__publicField(this, "windowsPathsNoEscape");
__publicField(this, "nonegate");
__publicField(this, "negate");
__publicField(this, "comment");
__publicField(this, "empty");
__publicField(this, "preserveMultipleSlashes");
__publicField(this, "partial");
__publicField(this, "globSet");
__publicField(this, "globParts");
__publicField(this, "nocase");
__publicField(this, "isWindows");
__publicField(this, "platform");
__publicField(this, "windowsNoMagicRoot");
__publicField(this, "regexp");
assertValidPattern(pattern2);
options2 = options2 || {};
this.options = options2;
this.pattern = pattern2;
this.platform = options2.platform || defaultPlatform$2;
this.isWindows = this.platform === "win32";
this.windowsPathsNoEscape = !!options2.windowsPathsNoEscape || options2.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, "/");
}
this.preserveMultipleSlashes = !!options2.preserveMultipleSlashes;
this.regexp = null;
this.negate = false;
this.nonegate = !!options2.nonegate;
this.comment = false;
this.empty = false;
this.partial = !!options2.partial;
this.nocase = !!this.options.nocase;
this.windowsNoMagicRoot = options2.windowsNoMagicRoot !== void 0 ? options2.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
this.globSet = [];
this.globParts = [];
this.set = [];
this.make();
}
hasMagic() {
if (this.options.magicalBraces && this.set.length > 1) {
return true;
}
for (const pattern2 of this.set) {
for (const part of pattern2) {
if (typeof part !== "string")
return true;
}
}
return false;
}
debug(..._) {
}
make() {
const pattern2 = this.pattern;
const options2 = this.options;
if (!options2.nocomment && pattern2.charAt(0) === "#") {
this.comment = true;
return;
}
if (!pattern2) {
this.empty = true;
return;
}
this.parseNegate();
this.globSet = [...new Set(this.braceExpand())];
if (options2.debug) {
this.debug = (...args) => console.error(...args);
}
this.debug(this.pattern, this.globSet);
const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
this.globParts = this.preprocess(rawGlobParts);
this.debug(this.pattern, this.globParts);
let set2 = this.globParts.map((s, _, __) => {
if (this.isWindows && this.windowsNoMagicRoot) {
const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
const isDrive = /^[a-z]:/i.test(s[0]);
if (isUNC) {
return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
} else if (isDrive) {
return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
}
}
return s.map((ss) => this.parse(ss));
});
this.debug(this.pattern, set2);
this.set = set2.filter((s) => s.indexOf(false) === -1);
if (this.isWindows) {
for (let i = 0; i < this.set.length; i++) {
const p = this.set[i];
if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
p[2] = "?";
}
}
}
this.debug(this.pattern, this.set);
}
// various transforms to equivalent pattern sets that are
// faster to process in a filesystem walk. The goal is to
// eliminate what we can, and push all ** patterns as far
// to the right as possible, even if it increases the number
// of patterns that we have to process.
preprocess(globParts) {
if (this.options.noglobstar) {
for (let i = 0; i < globParts.length; i++) {
for (let j = 0; j < globParts[i].length; j++) {
if (globParts[i][j] === "**") {
globParts[i][j] = "*";
}
}
}
}
const { optimizationLevel = 1 } = this.options;
if (optimizationLevel >= 2) {
globParts = this.firstPhasePreProcess(globParts);
globParts = this.secondPhasePreProcess(globParts);
} else if (optimizationLevel >= 1) {
globParts = this.levelOneOptimize(globParts);
} else {
globParts = this.adjascentGlobstarOptimize(globParts);
}
return globParts;
}
// just get rid of adjascent ** portions
adjascentGlobstarOptimize(globParts) {
return globParts.map((parts) => {
let gs = -1;
while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
let i = gs;
while (parts[i + 1] === "**") {
i++;
}
if (i !== gs) {
parts.splice(gs, i - gs);
}
}
return parts;
});
}
// get rid of adjascent ** and resolve .. portions
levelOneOptimize(globParts) {
return globParts.map((parts) => {
parts = parts.reduce((set2, part) => {
const prev = set2[set2.length - 1];
if (part === "**" && prev === "**") {
return set2;
}
if (part === "..") {
if (prev && prev !== ".." && prev !== "." && prev !== "**") {
set2.pop();
return set2;
}
}
set2.push(part);
return set2;
}, []);
return parts.length === 0 ? [""] : parts;
});
}
levelTwoFileOptimize(parts) {
if (!Array.isArray(parts)) {
parts = this.slashSplit(parts);
}
let didSomething = false;
do {
didSomething = false;
if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
if (i === 1 && p === "" && parts[0] === "")
continue;
if (p === "." || p === "") {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
didSomething = true;
parts.pop();
}
}
let dd = 0;
while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
const p = parts[dd - 1];
if (p && p !== "." && p !== ".." && p !== "**") {
didSomething = true;
parts.splice(dd - 1, 2);
dd -= 2;
}
}
} while (didSomething);
return parts.length === 0 ? [""] : parts;
}
// First phase: single-pattern processing
// <pre> is 1 or more portions
// <rest> is 1 or more portions
// <p> is any portion other than ., .., '', or **
// <e> is . or ''
//
// **/.. is *brutal* for filesystem walking performance, because
// it effectively resets the recursive walk each time it occurs,
// and ** cannot be reduced out by a .. pattern part like a regexp
// or most strings (other than .., ., and '') can be.
//
// <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
// <pre>/<e>/<rest> -> <pre>/<rest>
// <pre>/<p>/../<rest> -> <pre>/<rest>
// **/**/<rest> -> **/<rest>
//
// **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
// this WOULD be allowed if ** did follow symlinks, or * didn't
firstPhasePreProcess(globParts) {
let didSomething = false;
do {
didSomething = false;
for (let parts of globParts) {
let gs = -1;
while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
let gss = gs;
while (parts[gss + 1] === "**") {
gss++;
}
if (gss > gs) {
parts.splice(gs + 1, gss - gs);
}
let next = parts[gs + 1];
const p = parts[gs + 2];
const p2 = parts[gs + 3];
if (next !== "..")
continue;
if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
continue;
}
didSomething = true;
parts.splice(gs, 1);
const other = parts.slice(0);
other[gs] = "**";
globParts.push(other);
gs--;
}
if (!this.preserveMultipleSlashes) {
for (let i = 1; i < parts.length - 1; i++) {
const p = parts[i];
if (i === 1 && p === "" && parts[0] === "")
continue;
if (p === "." || p === "") {
didSomething = true;
parts.splice(i, 1);
i--;
}
}
if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
didSomething = true;
parts.pop();
}
}
let dd = 0;
while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
const p = parts[dd - 1];
if (p && p !== "." && p !== ".." && p !== "**") {
didSomething = true;
const needDot = dd === 1 && parts[dd + 1] === "**";
const splin = needDot ? ["."] : [];
parts.splice(dd - 1, 2, ...splin);
if (parts.length === 0)
parts.push("");
dd -= 2;
}
}
}
} while (didSomething);
return globParts;
}
// second phase: multi-pattern dedupes
// {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
// {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
// {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
//
// {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
// ^-- not valid because ** doens't follow symlinks
secondPhasePreProcess(globParts) {
for (let i = 0; i < globParts.length - 1; i++) {
for (let j = i + 1; j < globParts.length; j++) {
const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
if (matched) {
globParts[i] = [];
globParts[j] = matched;
break;
}
}
}
return globParts.filter((gs) => gs.length);
}
partsMatch(a, b, emptyGSMatch = false) {
let ai = 0;
let bi = 0;
let result = [];
let which2 = "";
while (ai < a.length && bi < b.length) {
if (a[ai] === b[bi]) {
result.push(which2 === "b" ? b[bi] : a[ai]);
ai++;
bi++;
} else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
result.push(a[ai]);
ai++;
} else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
result.push(b[bi]);
bi++;
} else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
if (which2 === "b")
return false;
which2 = "a";
result.push(a[ai]);
ai++;
bi++;
} else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
if (which2 === "a")
return false;
which2 = "b";
result.push(b[bi]);
ai++;
bi++;
} else {
return false;
}
}
return a.length === b.length && result;
}
parseNegate() {
if (this.nonegate)
return;
const pattern2 = this.pattern;
let negate = false;
let negateOffset = 0;
for (let i = 0; i < pattern2.length && pattern2.charAt(i) === "!"; i++) {
negate = !negate;
negateOffset++;
}
if (negateOffset)
this.pattern = pattern2.slice(negateOffset);
this.negate = negate;
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne(file, pattern2, partial2 = false) {
const options2 = this.options;
if (this.isWindows) {
const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
const patternDrive = typeof pattern2[0] === "string" && /^[a-z]:$/i.test(pattern2[0]);
const patternUNC = !patternDrive && pattern2[0] === "" && pattern2[1] === "" && pattern2[2] === "?" && typeof pattern2[3] === "string" && /^[a-z]:$/i.test(pattern2[3]);
const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
if (typeof fdi === "number" && typeof pdi === "number") {
const [fd, pd] = [file[fdi], pattern2[pdi]];
if (fd.toLowerCase() === pd.toLowerCase()) {
pattern2[pdi] = fd;
if (pdi > fdi) {
pattern2 = pattern2.slice(pdi);
} else if (fdi > pdi) {
file = file.slice(fdi);
}
}
}
}
const { optimizationLevel = 1 } = this.options;
if (optimizationLevel >= 2) {
file = this.levelTwoFileOptimize(file);
}
this.debug("matchOne", this, { file, pattern: pattern2 });
this.debug("matchOne", file.length, pattern2.length);
for (var fi = 0, pi = 0, fl = file.length, pl = pattern2.length; fi < fl && pi < pl; fi++, pi++) {
this.debug("matchOne loop");
var p = pattern2[pi];
var f2 = file[fi];
this.debug(pattern2, p, f2);
if (p === false) {
return false;
}
if (p === GLOBSTAR$2) {
this.debug("GLOBSTAR", [pattern2, p, f2]);
var fr = fi;
var pr = pi + 1;
if (pr === pl) {
this.debug("** at the end");
for (; fi < fl; fi++) {
if (file[fi] === "." || file[fi] === ".." || !options2.dot && file[fi].charAt(0) === ".")
return false;
}
return true;
}
while (fr < fl) {
var swallowee = file[fr];
this.debug("\nglobstar while", file, fr, pattern2, pr, swallowee);
if (this.matchOne(file.slice(fr), pattern2.slice(pr), partial2)) {
this.debug("globstar found match!", fr, fl, swallowee);
return true;
} else {
if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") {
this.debug("dot detected!", file, fr, pattern2, pr);
break;
}
this.debug("globstar swallow a segment, and continue");
fr++;
}
}
if (partial2) {
this.debug("\n>>> no match, partial?", file, fr, pattern2, pr);
if (fr === fl) {
return true;
}
}
return false;
}
let hit;
if (typeof p === "string") {
hit = f2 === p;
this.debug("string match", p, f2, hit);
} else {
hit = p.test(f2);
this.debug("pattern match", p, f2, hit);
}
if (!hit)
return false;
}
if (fi === fl && pi === pl) {
return true;
} else if (fi === fl) {
return partial2;
} else if (pi === pl) {
return fi === fl - 1 && file[fi] === "";
} else {
throw new Error("wtf?");
}
}
braceExpand() {
return braceExpand(this.pattern, this.options);
}
parse(pattern2) {
assertValidPattern(pattern2);
const options2 = this.options;
if (pattern2 === "**")
return GLOBSTAR$2;
if (pattern2 === "")
return "";
let m;
let fastTest = null;
if (m = pattern2.match(starRE)) {
fastTest = options2.dot ? starTestDot : starTest;
} else if (m = pattern2.match(starDotExtRE)) {
fastTest = (options2.nocase ? options2.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options2.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
} else if (m = pattern2.match(qmarksRE)) {
fastTest = (options2.nocase ? options2.dot ? qmarksTestNocaseDot : qmarksTestNocase : options2.dot ? qmarksTestDot : qmarksTest)(m);
} else if (m = pattern2.match(starDotStarRE)) {
fastTest = options2.dot ? starDotStarTestDot : starDotStarTest;
} else if (m = pattern2.match(dotStarRE)) {
fastTest = dotStarTest;
}
const re = AST.fromGlob(pattern2, this.options).toMMPattern();
if (fastTest && typeof re === "object") {
Reflect.defineProperty(re, "test", { value: fastTest });
}
return re;
}
makeRe() {
if (this.regexp || this.regexp === false)
return this.regexp;
const set2 = this.set;
if (!set2.length) {
this.regexp = false;
return this.regexp;
}
const options2 = this.options;
const twoStar = options2.noglobstar ? star : options2.dot ? twoStarDot : twoStarNoDot;
const flags = new Set(options2.nocase ? ["i"] : []);
let re = set2.map((pattern2) => {
const pp = pattern2.map((p) => {
if (p instanceof RegExp) {
for (const f2 of p.flags.split(""))
flags.add(f2);
}
return typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR$2 ? GLOBSTAR$2 : p._src;
});
pp.forEach((p, i) => {
const next = pp[i + 1];
const prev = pp[i - 1];
if (p !== GLOBSTAR$2 || prev === GLOBSTAR$2) {
return;
}
if (prev === void 0) {
if (next !== void 0 && next !== GLOBSTAR$2) {
pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
} else {
pp[i] = twoStar;
}
} else if (next === void 0) {
pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
} else if (next !== GLOBSTAR$2) {
pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
pp[i + 1] = GLOBSTAR$2;
}
});
return pp.filter((p) => p !== GLOBSTAR$2).join("/");
}).join("|");
const [open2, close2] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
re = "^" + open2 + re + close2 + "$";
if (this.negate)
re = "^(?!" + re + ").+$";
try {
this.regexp = new RegExp(re, [...flags].join(""));
} catch (ex) {
this.regexp = false;
}
return this.regexp;
}
slashSplit(p) {
if (this.preserveMultipleSlashes) {
return p.split("/");
} else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
return ["", ...p.split(/\/+/)];
} else {
return p.split(/\/+/);
}
}
match(f2, partial2 = this.partial) {
this.debug("match", f2, this.pattern);
if (this.comment) {
return false;
}
if (this.empty) {
return f2 === "";
}
if (f2 === "/" && partial2) {
return true;
}
const options2 = this.options;
if (this.isWindows) {
f2 = f2.split("\\").join("/");
}
const ff = this.slashSplit(f2);
this.debug(this.pattern, "split", ff);
const set2 = this.set;
this.debug(this.pattern, "set", set2);
let filename = ff[ff.length - 1];
if (!filename) {
for (let i = ff.length - 2; !filename && i >= 0; i--) {
filename = ff[i];
}
}
for (let i = 0; i < set2.length; i++) {
const pattern2 = set2[i];
let file = ff;
if (options2.matchBase && pattern2.length === 1) {
file = [filename];
}
const hit = this.matchOne(file, pattern2, partial2);
if (hit) {
if (options2.flipNegate) {
return true;
}
return !this.negate;
}
}
if (options2.flipNegate) {
return false;
}
return this.negate;
}
static defaults(def) {
return minimatch.defaults(def).Minimatch;
}
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape$2;
minimatch.unescape = unescape$1;
var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
var warned$1 = /* @__PURE__ */ new Set();
var PROCESS = typeof process === "object" && !!process ? process : {};
var emitWarning = (msg, type, code, fn) => {
typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
};
var AC = globalThis.AbortController;
var AS = globalThis.AbortSignal;
var _a;
if (typeof AC === "undefined") {
AS = class AbortSignal {
constructor() {
__publicField(this, "onabort");
__publicField(this, "_onabort", []);
__publicField(this, "reason");
__publicField(this, "aborted", false);
}
addEventListener(_, fn) {
this._onabort.push(fn);
}
};
AC = class AbortController {
constructor() {
__publicField(this, "signal", new AS());
warnACPolyfill();
}
abort(reason) {
var _a4, _b3;
if (this.signal.aborted)
return;
this.signal.reason = reason;
this.signal.aborted = true;
for (const fn of this.signal._onabort) {
fn(reason);
}
(_b3 = (_a4 = this.signal).onabort) == null ? void 0 : _b3.call(_a4, reason);
}
};
let printACPolyfillWarning = ((_a = PROCESS.env) == null ? void 0 : _a.LRU_CACHE_IGNORE_AC_WARNING) !== "1";
const warnACPolyfill = () => {
if (!printACPolyfillWarning)
return;
printACPolyfillWarning = false;
emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
};
}
var shouldWarn = (code) => !warned$1.has(code);
var isPosInt = (n2) => n2 && n2 === Math.floor(n2) && n2 > 0 && isFinite(n2);
var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
var ZeroArray = class extends Array {
constructor(size) {
super(size);
this.fill(0);
}
};
var _constructing;
var _Stack = class _Stack {
constructor(max, HeapCls) {
__publicField(this, "heap");
__publicField(this, "length");
if (!__privateGet(_Stack, _constructing)) {
throw new TypeError("instantiate Stack using Stack.create(n)");
}
this.heap = new HeapCls(max);
this.length = 0;
}
static create(max) {
const HeapCls = getUintArray(max);
if (!HeapCls)
return [];
__privateSet(_Stack, _constructing, true);
const s = new _Stack(max, HeapCls);
__privateSet(_Stack, _constructing, false);
return s;
}
push(n2) {
this.heap[this.length++] = n2;
}
pop() {
return this.heap[--this.length];
}
};
_constructing = new WeakMap();
// private constructor
__privateAdd(_Stack, _constructing, false);
var Stack = _Stack;
var _a2, _b, _max, _maxSize, _dispose, _disposeAfter, _fetchMethod, _memoMethod, _size, _calculatedSize, _keyMap, _keyList, _valList, _next, _prev, _head, _tail, _free, _disposed, _sizes, _starts, _ttls, _hasDispose, _hasFetchMethod, _hasDisposeAfter, _LRUCache_instances, initializeTTLTracking_fn, _updateItemAge, _statusTTL, _setItemTTL, _isStale, initializeSizeTracking_fn, _removeItemSize, _addItemSize, _requireSize, indexes_fn, rindexes_fn, isValidIndex_fn, evict_fn, backgroundFetch_fn, isBackgroundFetch_fn, connect_fn, moveToTail_fn, delete_fn, clear_fn;
var _LRUCache = class _LRUCache {
constructor(options2) {
__privateAdd(this, _LRUCache_instances);
// options that cannot be changed without disaster
__privateAdd(this, _max);
__privateAdd(this, _maxSize);
__privateAdd(this, _dispose);
__privateAdd(this, _disposeAfter);
__privateAdd(this, _fetchMethod);
__privateAdd(this, _memoMethod);
/**
* {@link LRUCache.OptionsBase.ttl}
*/
__publicField(this, "ttl");
/**
* {@link LRUCache.OptionsBase.ttlResolution}
*/
__publicField(this, "ttlResolution");
/**
* {@link LRUCache.OptionsBase.ttlAutopurge}
*/
__publicField(this, "ttlAutopurge");
/**
* {@link LRUCache.OptionsBase.updateAgeOnGet}
*/
__publicField(this, "updateAgeOnGet");
/**
* {@link LRUCache.OptionsBase.updateAgeOnHas}
*/
__publicField(this, "updateAgeOnHas");
/**
* {@link LRUCache.OptionsBase.allowStale}
*/
__publicField(this, "allowStale");
/**
* {@link LRUCache.OptionsBase.noDisposeOnSet}
*/
__publicField(this, "noDisposeOnSet");
/**
* {@link LRUCache.OptionsBase.noUpdateTTL}
*/
__publicField(this, "noUpdateTTL");
/**
* {@link LRUCache.OptionsBase.maxEntrySize}
*/
__publicField(this, "maxEntrySize");
/**
* {@link LRUCache.OptionsBase.sizeCalculation}
*/
__publicField(this, "sizeCalculation");
/**
* {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
*/
__publicField(this, "noDeleteOnFetchRejection");
/**
* {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
*/
__publicField(this, "noDeleteOnStaleGet");
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
*/
__publicField(this, "allowStaleOnFetchAbort");
/**
* {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
*/
__publicField(this, "allowStaleOnFetchRejection");
/**
* {@link LRUCache.OptionsBase.ignoreFetchAbort}
*/
__publicField(this, "ignoreFetchAbort");
// computed properties
__privateAdd(this, _size);
__privateAdd(this, _calculatedSize);
__privateAdd(this, _keyMap);
__privateAdd(this, _keyList);
__privateAdd(this, _valList);
__privateAdd(this, _next);
__privateAdd(this, _prev);
__privateAdd(this, _head);
__privateAdd(this, _tail);
__privateAdd(this, _free);
__privateAdd(this, _disposed);
__privateAdd(this, _sizes);
__privateAdd(this, _starts);
__privateAdd(this, _ttls);
__privateAdd(this, _hasDispose);
__privateAdd(this, _hasFetchMethod);
__privateAdd(this, _hasDisposeAfter);
// conditionally set private methods related to TTL
__privateAdd(this, _updateItemAge, () => {
});
__privateAdd(this, _statusTTL, () => {
});
__privateAdd(this, _setItemTTL, () => {
});
/* c8 ignore stop */
__privateAdd(this, _isStale, () => false);
__privateAdd(this, _removeItemSize, (_i2) => {
});
__privateAdd(this, _addItemSize, (_i2, _s2, _st) => {
});
__privateAdd(this, _requireSize, (_k2, _v, size, sizeCalculation) => {
if (size || sizeCalculation) {
throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
}
return 0;
});
/**
* A String value that is used in the creation of the default string
* description of an object. Called by the built-in method
* `Object.prototype.toString`.
*/
__publicField(this, _a2, "LRUCache");
const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options2;
if (max !== 0 && !isPosInt(max)) {
throw new TypeError("max option must be a nonnegative integer");
}
const UintArray = max ? getUintArray(max) : Array;
if (!UintArray) {
throw new Error("invalid max value: " + max);
}
__privateSet(this, _max, max);
__privateSet(this, _maxSize, maxSize);
this.maxEntrySize = maxEntrySize || __privateGet(this, _maxSize);
this.sizeCalculation = sizeCalculation;
if (this.sizeCalculation) {
if (!__privateGet(this, _maxSize) && !this.maxEntrySize) {
throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
}
if (typeof this.sizeCalculation !== "function") {
throw new TypeError("sizeCalculation set to non-function");
}
}
if (memoMethod !== void 0 && typeof memoMethod !== "function") {
throw new TypeError("memoMethod must be a function if defined");
}
__privateSet(this, _memoMethod, memoMethod);
if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
throw new TypeError("fetchMethod must be a function if specified");
}
__privateSet(this, _fetchMethod, fetchMethod);
__privateSet(this, _hasFetchMethod, !!fetchMethod);
__privateSet(this, _keyMap, /* @__PURE__ */ new Map());
__privateSet(this, _keyList, new Array(max).fill(void 0));
__privateSet(this, _valList, new Array(max).fill(void 0));
__privateSet(this, _next, new UintArray(max));
__privateSet(this, _prev, new UintArray(max));
__privateSet(this, _head, 0);
__privateSet(this, _tail, 0);
__privateSet(this, _free, Stack.create(max));
__privateSet(this, _size, 0);
__privateSet(this, _calculatedSize, 0);
if (typeof dispose === "function") {
__privateSet(this, _dispose, dispose);
}
if (typeof disposeAfter === "function") {
__privateSet(this, _disposeAfter, disposeAfter);
__privateSet(this, _disposed, []);
} else {
__privateSet(this, _disposeAfter, void 0);
__privateSet(this, _disposed, void 0);
}
__privateSet(this, _hasDispose, !!__privateGet(this, _dispose));
__privateSet(this, _hasDisposeAfter, !!__privateGet(this, _disposeAfter));
this.noDisposeOnSet = !!noDisposeOnSet;
this.noUpdateTTL = !!noUpdateTTL;
this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
this.ignoreFetchAbort = !!ignoreFetchAbort;
if (this.maxEntrySize !== 0) {
if (__privateGet(this, _maxSize) !== 0) {
if (!isPosInt(__privateGet(this, _maxSize))) {
throw new TypeError("maxSize must be a positive integer if specified");
}
}
if (!isPosInt(this.maxEntrySize)) {
throw new TypeError("maxEntrySize must be a positive integer if specified");
}
__privateMethod(this, _LRUCache_instances, initializeSizeTracking_fn).call(this);
}
this.allowStale = !!allowStale;
this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
this.updateAgeOnGet = !!updateAgeOnGet;
this.updateAgeOnHas = !!updateAgeOnHas;
this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
this.ttlAutopurge = !!ttlAutopurge;
this.ttl = ttl || 0;
if (this.ttl) {
if (!isPosInt(this.ttl)) {
throw new TypeError("ttl must be a positive integer if specified");
}
__privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);
}
if (__privateGet(this, _max) === 0 && this.ttl === 0 && __privateGet(this, _maxSize) === 0) {
throw new TypeError("At least one of max, maxSize, or ttl is required");
}
if (!this.ttlAutopurge && !__privateGet(this, _max) && !__privateGet(this, _maxSize)) {
const code = "LRU_CACHE_UNBOUNDED";
if (shouldWarn(code)) {
warned$1.add(code);
const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
}
}
}
/**
* Do not call this method unless you need to inspect the
* inner workings of the cache. If anything returned by this
* object is modified in any way, strange breakage may occur.
*
* These fields are private for a reason!
*
* @internal
*/
static unsafeExposeInternals(c) {
return {
// properties
starts: __privateGet(c, _starts),
ttls: __privateGet(c, _ttls),
sizes: __privateGet(c, _sizes),
keyMap: __privateGet(c, _keyMap),
keyList: __privateGet(c, _keyList),
valList: __privateGet(c, _valList),
next: __privateGet(c, _next),
prev: __privateGet(c, _prev),
get head() {
return __privateGet(c, _head);
},
get tail() {
return __privateGet(c, _tail);
},
free: __privateGet(c, _free),
// methods
isBackgroundFetch: (p) => {
var _a4;
return __privateMethod(_a4 = c, _LRUCache_instances, isBackgroundFetch_fn).call(_a4, p);
},
backgroundFetch: (k, index, options2, context) => {
var _a4;
return __privateMethod(_a4 = c, _LRUCache_instances, backgroundFetch_fn).call(_a4, k, index, options2, context);
},
moveToTail: (index) => {
var _a4;
return __privateMethod(_a4 = c, _LRUCache_instances, moveToTail_fn).call(_a4, index);
},
indexes: (options2) => {
var _a4;
return __privateMethod(_a4 = c, _LRUCache_instances, indexes_fn).call(_a4, options2);
},
rindexes: (options2) => {
var _a4;
return __privateMethod(_a4 = c, _LRUCache_instances, rindexes_fn).call(_a4, options2);
},
isStale: (index) => {
var _a4;
return __privateGet(_a4 = c, _isStale).call(_a4, index);
}
};
}
// Protected read-only members
/**
* {@link LRUCache.OptionsBase.max} (read-only)
*/
get max() {
return __privateGet(this, _max);
}
/**
* {@link LRUCache.OptionsBase.maxSize} (read-only)
*/
get maxSize() {
return __privateGet(this, _maxSize);
}
/**
* The total computed size of items in the cache (read-only)
*/
get calculatedSize() {
return __privateGet(this, _calculatedSize);
}
/**
* The number of items stored in the cache (read-only)
*/
get size() {
return __privateGet(this, _size);
}
/**
* {@link LRUCache.OptionsBase.fetchMethod} (read-only)
*/
get fetchMethod() {
return __privateGet(this, _fetchMethod);
}
get memoMethod() {
return __privateGet(this, _memoMethod);
}
/**
* {@link LRUCache.OptionsBase.dispose} (read-only)
*/
get dispose() {
return __privateGet(this, _dispose);
}
/**
* {@link LRUCache.OptionsBase.disposeAfter} (read-only)
*/
get disposeAfter() {
return __privateGet(this, _disposeAfter);
}
/**
* Return the number of ms left in the item's TTL. If item is not in cache,
* returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
*/
getRemainingTTL(key) {
return __privateGet(this, _keyMap).has(key) ? Infinity : 0;
}
/**
* Return a generator yielding `[key, value]` pairs,
* in order from most recently used to least recently used.
*/
*entries() {
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];
}
}
}
/**
* Inverse order version of {@link LRUCache.entries}
*
* Return a generator yielding `[key, value]` pairs,
* in order from least recently used to most recently used.
*/
*rentries() {
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];
}
}
}
/**
* Return a generator yielding the keys in the cache,
* in order from most recently used to least recently used.
*/
*keys() {
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
const k = __privateGet(this, _keyList)[i];
if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield k;
}
}
}
/**
* Inverse order version of {@link LRUCache.keys}
*
* Return a generator yielding the keys in the cache,
* in order from least recently used to most recently used.
*/
*rkeys() {
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
const k = __privateGet(this, _keyList)[i];
if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield k;
}
}
}
/**
* Return a generator yielding the values in the cache,
* in order from most recently used to least recently used.
*/
*values() {
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
const v = __privateGet(this, _valList)[i];
if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield __privateGet(this, _valList)[i];
}
}
}
/**
* Inverse order version of {@link LRUCache.values}
*
* Return a generator yielding the values in the cache,
* in order from least recently used to most recently used.
*/
*rvalues() {
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
const v = __privateGet(this, _valList)[i];
if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
yield __privateGet(this, _valList)[i];
}
}
}
/**
* Iterating over the cache itself yields the same results as
* {@link LRUCache.entries}
*/
[(_b = Symbol.iterator, _a2 = Symbol.toStringTag, _b)]() {
return this.entries();
}
/**
* Find a value for which the supplied fn method returns a truthy value,
* similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
*/
find(fn, getOptions2 = {}) {
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
const v = __privateGet(this, _valList)[i];
const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
if (value2 === void 0)
continue;
if (fn(value2, __privateGet(this, _keyList)[i], this)) {
return this.get(__privateGet(this, _keyList)[i], getOptions2);
}
}
}
/**
* Call the supplied function on each item in the cache, in order from most
* recently used to least recently used.
*
* `fn` is called as `fn(value, key, cache)`.
*
* If `thisp` is provided, function will be called in the `this`-context of
* the provided object, or the cache if no `thisp` object is provided.
*
* Does not update age or recenty of use, or iterate over stale values.
*/
forEach(fn, thisp = this) {
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
const v = __privateGet(this, _valList)[i];
const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
if (value2 === void 0)
continue;
fn.call(thisp, value2, __privateGet(this, _keyList)[i], this);
}
}
/**
* The same as {@link LRUCache.forEach} but items are iterated over in
* reverse order. (ie, less recently used items are iterated over first.)
*/
rforEach(fn, thisp = this) {
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
const v = __privateGet(this, _valList)[i];
const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
if (value2 === void 0)
continue;
fn.call(thisp, value2, __privateGet(this, _keyList)[i], this);
}
}
/**
* Delete any stale entries. Returns true if anything was removed,
* false otherwise.
*/
purgeStale() {
let deleted = false;
for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {
if (__privateGet(this, _isStale).call(this, i)) {
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[i], "expire");
deleted = true;
}
}
return deleted;
}
/**
* Get the extended info about a given entry, to get its value, size, and
* TTL info simultaneously. Returns `undefined` if the key is not present.
*
* Unlike {@link LRUCache#dump}, which is designed to be portable and survive
* serialization, the `start` value is always the current timestamp, and the
* `ttl` is a calculated remaining time to live (negative if expired).
*
* Always returns stale values, if their info is found in the cache, so be
* sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
* if relevant.
*/
info(key) {
const i = __privateGet(this, _keyMap).get(key);
if (i === void 0)
return void 0;
const v = __privateGet(this, _valList)[i];
const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
if (value2 === void 0)
return void 0;
const entry2 = { value: value2 };
if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
const ttl = __privateGet(this, _ttls)[i];
const start = __privateGet(this, _starts)[i];
if (ttl && start) {
const remain = ttl - (perf.now() - start);
entry2.ttl = remain;
entry2.start = Date.now();
}
}
if (__privateGet(this, _sizes)) {
entry2.size = __privateGet(this, _sizes)[i];
}
return entry2;
}
/**
* Return an array of [key, {@link LRUCache.Entry}] tuples which can be
* passed to {@link LRLUCache#load}.
*
* The `start` fields are calculated relative to a portable `Date.now()`
* timestamp, even if `performance.now()` is available.
*
* Stale entries are always included in the `dump`, even if
* {@link LRUCache.OptionsBase.allowStale} is false.
*
* Note: this returns an actual array, not a generator, so it can be more
* easily passed around.
*/
dump() {
const arr = [];
for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this, { allowStale: true })) {
const key = __privateGet(this, _keyList)[i];
const v = __privateGet(this, _valList)[i];
const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
if (value2 === void 0 || key === void 0)
continue;
const entry2 = { value: value2 };
if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
entry2.ttl = __privateGet(this, _ttls)[i];
const age = perf.now() - __privateGet(this, _starts)[i];
entry2.start = Math.floor(Date.now() - age);
}
if (__privateGet(this, _sizes)) {
entry2.size = __privateGet(this, _sizes)[i];
}
arr.unshift([key, entry2]);
}
return arr;
}
/**
* Reset the cache and load in the items in entries in the order listed.
*
* The shape of the resulting cache may be different if the same options are
* not used in both caches.
*
* The `start` fields are assumed to be calculated relative to a portable
* `Date.now()` timestamp, even if `performance.now()` is available.
*/
load(arr) {
this.clear();
for (const [key, entry2] of arr) {
if (entry2.start) {
const age = Date.now() - entry2.start;
entry2.start = perf.now() - age;
}
this.set(key, entry2.value, entry2);
}
}
/**
* Add a value to the cache.
*
* Note: if `undefined` is specified as a value, this is an alias for
* {@link LRUCache#delete}
*
* Fields on the {@link LRUCache.SetOptions} options param will override
* their corresponding values in the constructor options for the scope
* of this single `set()` operation.
*
* If `start` is provided, then that will set the effective start
* time for the TTL calculation. Note that this must be a previous
* value of `performance.now()` if supported, or a previous value of
* `Date.now()` if not.
*
* Options object may also include `size`, which will prevent
* calling the `sizeCalculation` function and just use the specified
* number if it is a positive integer, and `noDisposeOnSet` which
* will prevent calling a `dispose` function in the case of
* overwrites.
*
* If the `size` (or return value of `sizeCalculation`) for a given
* entry is greater than `maxEntrySize`, then the item will not be
* added to the cache.
*
* Will update the recency of the entry.
*
* If the value is `undefined`, then this is an alias for
* `cache.delete(key)`. `undefined` is never stored in the cache.
*/
set(k, v, setOptions = {}) {
var _a4, _b3, _c2, _d2, _e2;
if (v === void 0) {
this.delete(k);
return this;
}
const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status: status2 } = setOptions;
let { noUpdateTTL = this.noUpdateTTL } = setOptions;
const size = __privateGet(this, _requireSize).call(this, k, v, setOptions.size || 0, sizeCalculation);
if (this.maxEntrySize && size > this.maxEntrySize) {
if (status2) {
status2.set = "miss";
status2.maxEntrySizeExceeded = true;
}
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "set");
return this;
}
let index = __privateGet(this, _size) === 0 ? void 0 : __privateGet(this, _keyMap).get(k);
if (index === void 0) {
index = __privateGet(this, _size) === 0 ? __privateGet(this, _tail) : __privateGet(this, _free).length !== 0 ? __privateGet(this, _free).pop() : __privateGet(this, _size) === __privateGet(this, _max) ? __privateMethod(this, _LRUCache_instances, evict_fn).call(this, false) : __privateGet(this, _size);
__privateGet(this, _keyList)[index] = k;
__privateGet(this, _valList)[index] = v;
__privateGet(this, _keyMap).set(k, index);
__privateGet(this, _next)[__privateGet(this, _tail)] = index;
__privateGet(this, _prev)[index] = __privateGet(this, _tail);
__privateSet(this, _tail, index);
__privateWrapper(this, _size)._++;
__privateGet(this, _addItemSize).call(this, index, size, status2);
if (status2)
status2.set = "add";
noUpdateTTL = false;
} else {
__privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
const oldVal = __privateGet(this, _valList)[index];
if (v !== oldVal) {
if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal)) {
oldVal.__abortController.abort(new Error("replaced"));
const { __staleWhileFetching: s } = oldVal;
if (s !== void 0 && !noDisposeOnSet) {
if (__privateGet(this, _hasDispose)) {
(_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, s, k, "set");
}
if (__privateGet(this, _hasDisposeAfter)) {
(_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([s, k, "set"]);
}
}
} else if (!noDisposeOnSet) {
if (__privateGet(this, _hasDispose)) {
(_c2 = __privateGet(this, _dispose)) == null ? void 0 : _c2.call(this, oldVal, k, "set");
}
if (__privateGet(this, _hasDisposeAfter)) {
(_d2 = __privateGet(this, _disposed)) == null ? void 0 : _d2.push([oldVal, k, "set"]);
}
}
__privateGet(this, _removeItemSize).call(this, index);
__privateGet(this, _addItemSize).call(this, index, size, status2);
__privateGet(this, _valList)[index] = v;
if (status2) {
status2.set = "replace";
const oldValue = oldVal && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal) ? oldVal.__staleWhileFetching : oldVal;
if (oldValue !== void 0)
status2.oldValue = oldValue;
}
} else if (status2) {
status2.set = "update";
}
}
if (ttl !== 0 && !__privateGet(this, _ttls)) {
__privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);
}
if (__privateGet(this, _ttls)) {
if (!noUpdateTTL) {
__privateGet(this, _setItemTTL).call(this, index, ttl, start);
}
if (status2)
__privateGet(this, _statusTTL).call(this, status2, index);
}
if (!noDisposeOnSet && __privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
const dt = __privateGet(this, _disposed);
let task;
while (task = dt == null ? void 0 : dt.shift()) {
(_e2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _e2.call(this, ...task);
}
}
return this;
}
/**
* Evict the least recently used item, returning its value or
* `undefined` if cache is empty.
*/
pop() {
var _a4;
try {
while (__privateGet(this, _size)) {
const val = __privateGet(this, _valList)[__privateGet(this, _head)];
__privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, val)) {
if (val.__staleWhileFetching) {
return val.__staleWhileFetching;
}
} else if (val !== void 0) {
return val;
}
}
} finally {
if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
const dt = __privateGet(this, _disposed);
let task;
while (task = dt == null ? void 0 : dt.shift()) {
(_a4 = __privateGet(this, _disposeAfter)) == null ? void 0 : _a4.call(this, ...task);
}
}
}
}
/**
* Check if a key is in the cache, without updating the recency of use.
* Will return false if the item is stale, even though it is technically
* in the cache.
*
* Check if a key is in the cache, without updating the recency of
* use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
* to `true` in either the options or the constructor.
*
* Will return `false` if the item is stale, even though it is technically in
* the cache. The difference can be determined (if it matters) by using a
* `status` argument, and inspecting the `has` field.
*
* Will not update item age unless
* {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
*/
has(k, hasOptions = {}) {
const { updateAgeOnHas = this.updateAgeOnHas, status: status2 } = hasOptions;
const index = __privateGet(this, _keyMap).get(k);
if (index !== void 0) {
const v = __privateGet(this, _valList)[index];
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) && v.__staleWhileFetching === void 0) {
return false;
}
if (!__privateGet(this, _isStale).call(this, index)) {
if (updateAgeOnHas) {
__privateGet(this, _updateItemAge).call(this, index);
}
if (status2) {
status2.has = "hit";
__privateGet(this, _statusTTL).call(this, status2, index);
}
return true;
} else if (status2) {
status2.has = "stale";
__privateGet(this, _statusTTL).call(this, status2, index);
}
} else if (status2) {
status2.has = "miss";
}
return false;
}
/**
* Like {@link LRUCache#get} but doesn't update recency or delete stale
* items.
*
* Returns `undefined` if the item is stale, unless
* {@link LRUCache.OptionsBase.allowStale} is set.
*/
peek(k, peekOptions = {}) {
const { allowStale = this.allowStale } = peekOptions;
const index = __privateGet(this, _keyMap).get(k);
if (index === void 0 || !allowStale && __privateGet(this, _isStale).call(this, index)) {
return;
}
const v = __privateGet(this, _valList)[index];
return __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
}
async fetch(k, fetchOptions = {}) {
const {
// get options
allowStale = this.allowStale,
updateAgeOnGet = this.updateAgeOnGet,
noDeleteOnStaleGet = this.noDeleteOnStaleGet,
// set options
ttl = this.ttl,
noDisposeOnSet = this.noDisposeOnSet,
size = 0,
sizeCalculation = this.sizeCalculation,
noUpdateTTL = this.noUpdateTTL,
// fetch exclusive options
noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
ignoreFetchAbort = this.ignoreFetchAbort,
allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
context,
forceRefresh = false,
status: status2,
signal
} = fetchOptions;
if (!__privateGet(this, _hasFetchMethod)) {
if (status2)
status2.fetch = "get";
return this.get(k, {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
status: status2
});
}
const options2 = {
allowStale,
updateAgeOnGet,
noDeleteOnStaleGet,
ttl,
noDisposeOnSet,
size,
sizeCalculation,
noUpdateTTL,
noDeleteOnFetchRejection,
allowStaleOnFetchRejection,
allowStaleOnFetchAbort,
ignoreFetchAbort,
status: status2,
signal
};
let index = __privateGet(this, _keyMap).get(k);
if (index === void 0) {
if (status2)
status2.fetch = "miss";
const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options2, context);
return p.__returned = p;
} else {
const v = __privateGet(this, _valList)[index];
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
const stale = allowStale && v.__staleWhileFetching !== void 0;
if (status2) {
status2.fetch = "inflight";
if (stale)
status2.returnedStale = true;
}
return stale ? v.__staleWhileFetching : v.__returned = v;
}
const isStale = __privateGet(this, _isStale).call(this, index);
if (!forceRefresh && !isStale) {
if (status2)
status2.fetch = "hit";
__privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
if (updateAgeOnGet) {
__privateGet(this, _updateItemAge).call(this, index);
}
if (status2)
__privateGet(this, _statusTTL).call(this, status2, index);
return v;
}
const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options2, context);
const hasStale = p.__staleWhileFetching !== void 0;
const staleVal = hasStale && allowStale;
if (status2) {
status2.fetch = isStale ? "stale" : "refresh";
if (staleVal && isStale)
status2.returnedStale = true;
}
return staleVal ? p.__staleWhileFetching : p.__returned = p;
}
}
async forceFetch(k, fetchOptions = {}) {
const v = await this.fetch(k, fetchOptions);
if (v === void 0)
throw new Error("fetch() returned undefined");
return v;
}
memo(k, memoOptions = {}) {
const memoMethod = __privateGet(this, _memoMethod);
if (!memoMethod) {
throw new Error("no memoMethod provided to constructor");
}
const { context, forceRefresh, ...options2 } = memoOptions;
const v = this.get(k, options2);
if (!forceRefresh && v !== void 0)
return v;
const vv = memoMethod(k, v, {
options: options2,
context
});
this.set(k, vv, options2);
return vv;
}
/**
* Return a value from the cache. Will update the recency of the cache
* entry found.
*
* If the key is not found, get() will return `undefined`.
*/
get(k, getOptions2 = {}) {
const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status: status2 } = getOptions2;
const index = __privateGet(this, _keyMap).get(k);
if (index !== void 0) {
const value2 = __privateGet(this, _valList)[index];
const fetching = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, value2);
if (status2)
__privateGet(this, _statusTTL).call(this, status2, index);
if (__privateGet(this, _isStale).call(this, index)) {
if (status2)
status2.get = "stale";
if (!fetching) {
if (!noDeleteOnStaleGet) {
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "expire");
}
if (status2 && allowStale)
status2.returnedStale = true;
return allowStale ? value2 : void 0;
} else {
if (status2 && allowStale && value2.__staleWhileFetching !== void 0) {
status2.returnedStale = true;
}
return allowStale ? value2.__staleWhileFetching : void 0;
}
} else {
if (status2)
status2.get = "hit";
if (fetching) {
return value2.__staleWhileFetching;
}
__privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
if (updateAgeOnGet) {
__privateGet(this, _updateItemAge).call(this, index);
}
return value2;
}
} else if (status2) {
status2.get = "miss";
}
}
/**
* Deletes a key out of the cache.
*
* Returns true if the key was deleted, false otherwise.
*/
delete(k) {
return __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "delete");
}
/**
* Clear the cache entirely, throwing away all values.
*/
clear() {
return __privateMethod(this, _LRUCache_instances, clear_fn).call(this, "delete");
}
};
_max = new WeakMap();
_maxSize = new WeakMap();
_dispose = new WeakMap();
_disposeAfter = new WeakMap();
_fetchMethod = new WeakMap();
_memoMethod = new WeakMap();
_size = new WeakMap();
_calculatedSize = new WeakMap();
_keyMap = new WeakMap();
_keyList = new WeakMap();
_valList = new WeakMap();
_next = new WeakMap();
_prev = new WeakMap();
_head = new WeakMap();
_tail = new WeakMap();
_free = new WeakMap();
_disposed = new WeakMap();
_sizes = new WeakMap();
_starts = new WeakMap();
_ttls = new WeakMap();
_hasDispose = new WeakMap();
_hasFetchMethod = new WeakMap();
_hasDisposeAfter = new WeakMap();
_LRUCache_instances = new WeakSet();
initializeTTLTracking_fn = function() {
const ttls = new ZeroArray(__privateGet(this, _max));
const starts = new ZeroArray(__privateGet(this, _max));
__privateSet(this, _ttls, ttls);
__privateSet(this, _starts, starts);
__privateSet(this, _setItemTTL, (index, ttl, start = perf.now()) => {
starts[index] = ttl !== 0 ? start : 0;
ttls[index] = ttl;
if (ttl !== 0 && this.ttlAutopurge) {
const t2 = setTimeout(() => {
if (__privateGet(this, _isStale).call(this, index)) {
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[index], "expire");
}
}, ttl + 1);
if (t2.unref) {
t2.unref();
}
}
});
__privateSet(this, _updateItemAge, (index) => {
starts[index] = ttls[index] !== 0 ? perf.now() : 0;
});
__privateSet(this, _statusTTL, (status2, index) => {
if (ttls[index]) {
const ttl = ttls[index];
const start = starts[index];
if (!ttl || !start)
return;
status2.ttl = ttl;
status2.start = start;
status2.now = cachedNow || getNow();
const age = status2.now - start;
status2.remainingTTL = ttl - age;
}
});
let cachedNow = 0;
const getNow = () => {
const n2 = perf.now();
if (this.ttlResolution > 0) {
cachedNow = n2;
const t2 = setTimeout(() => cachedNow = 0, this.ttlResolution);
if (t2.unref) {
t2.unref();
}
}
return n2;
};
this.getRemainingTTL = (key) => {
const index = __privateGet(this, _keyMap).get(key);
if (index === void 0) {
return 0;
}
const ttl = ttls[index];
const start = starts[index];
if (!ttl || !start) {
return Infinity;
}
const age = (cachedNow || getNow()) - start;
return ttl - age;
};
__privateSet(this, _isStale, (index) => {
const s = starts[index];
const t2 = ttls[index];
return !!t2 && !!s && (cachedNow || getNow()) - s > t2;
});
};
_updateItemAge = new WeakMap();
_statusTTL = new WeakMap();
_setItemTTL = new WeakMap();
_isStale = new WeakMap();
initializeSizeTracking_fn = function() {
const sizes = new ZeroArray(__privateGet(this, _max));
__privateSet(this, _calculatedSize, 0);
__privateSet(this, _sizes, sizes);
__privateSet(this, _removeItemSize, (index) => {
__privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) - sizes[index]);
sizes[index] = 0;
});
__privateSet(this, _requireSize, (k, v, size, sizeCalculation) => {
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
return 0;
}
if (!isPosInt(size)) {
if (sizeCalculation) {
if (typeof sizeCalculation !== "function") {
throw new TypeError("sizeCalculation must be a function");
}
size = sizeCalculation(v, k);
if (!isPosInt(size)) {
throw new TypeError("sizeCalculation return invalid (expect positive integer)");
}
} else {
throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
}
}
return size;
});
__privateSet(this, _addItemSize, (index, size, status2) => {
sizes[index] = size;
if (__privateGet(this, _maxSize)) {
const maxSize = __privateGet(this, _maxSize) - sizes[index];
while (__privateGet(this, _calculatedSize) > maxSize) {
__privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);
}
}
__privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) + sizes[index]);
if (status2) {
status2.entrySize = size;
status2.totalCalculatedSize = __privateGet(this, _calculatedSize);
}
});
};
_removeItemSize = new WeakMap();
_addItemSize = new WeakMap();
_requireSize = new WeakMap();
indexes_fn = function* ({ allowStale = this.allowStale } = {}) {
if (__privateGet(this, _size)) {
for (let i = __privateGet(this, _tail); true; ) {
if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {
break;
}
if (allowStale || !__privateGet(this, _isStale).call(this, i)) {
yield i;
}
if (i === __privateGet(this, _head)) {
break;
} else {
i = __privateGet(this, _prev)[i];
}
}
}
};
rindexes_fn = function* ({ allowStale = this.allowStale } = {}) {
if (__privateGet(this, _size)) {
for (let i = __privateGet(this, _head); true; ) {
if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {
break;
}
if (allowStale || !__privateGet(this, _isStale).call(this, i)) {
yield i;
}
if (i === __privateGet(this, _tail)) {
break;
} else {
i = __privateGet(this, _next)[i];
}
}
}
};
isValidIndex_fn = function(index) {
return index !== void 0 && __privateGet(this, _keyMap).get(__privateGet(this, _keyList)[index]) === index;
};
evict_fn = function(free) {
var _a4, _b3;
const head = __privateGet(this, _head);
const k = __privateGet(this, _keyList)[head];
const v = __privateGet(this, _valList)[head];
if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
v.__abortController.abort(new Error("evicted"));
} else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {
if (__privateGet(this, _hasDispose)) {
(_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, "evict");
}
if (__privateGet(this, _hasDisposeAfter)) {
(_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, "evict"]);
}
}
__privateGet(this, _removeItemSize).call(this, head);
if (free) {
__privateGet(this, _keyList)[head] = void 0;
__privateGet(this, _valList)[head] = void 0;
__privateGet(this, _free).push(head);
}
if (__privateGet(this, _size) === 1) {
__privateSet(this, _head, __privateSet(this, _tail, 0));
__privateGet(this, _free).length = 0;
} else {
__privateSet(this, _head, __privateGet(this, _next)[head]);
}
__privateGet(this, _keyMap).delete(k);
__privateWrapper(this, _size)._--;
return head;
};
backgroundFetch_fn = function(k, index, options2, context) {
const v = index === void 0 ? void 0 : __privateGet(this, _valList)[index];
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
return v;
}
const ac = new AC();
const { signal } = options2;
signal == null ? void 0 : signal.addEventListener("abort", () => ac.abort(signal.reason), {
signal: ac.signal
});
const fetchOpts = {
signal: ac.signal,
options: options2,
context
};
const cb = (v2, updateCache = false) => {
const { aborted } = ac.signal;
const ignoreAbort = options2.ignoreFetchAbort && v2 !== void 0;
if (options2.status) {
if (aborted && !updateCache) {
options2.status.fetchAborted = true;
options2.status.fetchError = ac.signal.reason;
if (ignoreAbort)
options2.status.fetchAbortIgnored = true;
} else {
options2.status.fetchResolved = true;
}
}
if (aborted && !ignoreAbort && !updateCache) {
return fetchFail(ac.signal.reason);
}
const bf2 = p;
if (__privateGet(this, _valList)[index] === p) {
if (v2 === void 0) {
if (bf2.__staleWhileFetching) {
__privateGet(this, _valList)[index] = bf2.__staleWhileFetching;
} else {
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");
}
} else {
if (options2.status)
options2.status.fetchUpdated = true;
this.set(k, v2, fetchOpts.options);
}
}
return v2;
};
const eb = (er) => {
if (options2.status) {
options2.status.fetchRejected = true;
options2.status.fetchError = er;
}
return fetchFail(er);
};
const fetchFail = (er) => {
const { aborted } = ac.signal;
const allowStaleAborted = aborted && options2.allowStaleOnFetchAbort;
const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
const noDelete = allowStale || options2.noDeleteOnFetchRejection;
const bf2 = p;
if (__privateGet(this, _valList)[index] === p) {
const del = !noDelete || bf2.__staleWhileFetching === void 0;
if (del) {
__privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");
} else if (!allowStaleAborted) {
__privateGet(this, _valList)[index] = bf2.__staleWhileFetching;
}
}
if (allowStale) {
if (options2.status && bf2.__staleWhileFetching !== void 0) {
options2.status.returnedStale = true;
}
return bf2.__staleWhileFetching;
} else if (bf2.__returned === bf2) {
throw er;
}
};
const pcall = (res, rej) => {
var _a4;
const fmp = (_a4 = __privateGet(this, _fetchMethod)) == null ? void 0 : _a4.call(this, k, v, fetchOpts);
if (fmp && fmp instanceof Promise) {
fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
}
ac.signal.addEventListener("abort", () => {
if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
res(void 0);
if (options2.allowStaleOnFetchAbort) {
res = (v2) => cb(v2, true);
}
}
});
};
if (options2.status)
options2.status.fetchDispatched = true;
const p = new Promise(pcall).then(cb, eb);
const bf = Object.assign(p, {
__abortController: ac,
__staleWhileFetching: v,
__returned: void 0
});
if (index === void 0) {
this.set(k, bf, { ...fetchOpts.options, status: void 0 });
index = __privateGet(this, _keyMap).get(k);
} else {
__privateGet(this, _valList)[index] = bf;
}
return bf;
};
isBackgroundFetch_fn = function(p) {
if (!__privateGet(this, _hasFetchMethod))
return false;
const b = p;
return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
};
connect_fn = function(p, n2) {
__privateGet(this, _prev)[n2] = p;
__privateGet(this, _next)[p] = n2;
};
moveToTail_fn = function(index) {
if (index !== __privateGet(this, _tail)) {
if (index === __privateGet(this, _head)) {
__privateSet(this, _head, __privateGet(this, _next)[index]);
} else {
__privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _prev)[index], __privateGet(this, _next)[index]);
}
__privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _tail), index);
__privateSet(this, _tail, index);
}
};
delete_fn = function(k, reason) {
var _a4, _b3, _c2, _d2;
let deleted = false;
if (__privateGet(this, _size) !== 0) {
const index = __privateGet(this, _keyMap).get(k);
if (index !== void 0) {
deleted = true;
if (__privateGet(this, _size) === 1) {
__privateMethod(this, _LRUCache_instances, clear_fn).call(this, reason);
} else {
__privateGet(this, _removeItemSize).call(this, index);
const v = __privateGet(this, _valList)[index];
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
v.__abortController.abort(new Error("deleted"));
} else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {
if (__privateGet(this, _hasDispose)) {
(_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, reason);
}
if (__privateGet(this, _hasDisposeAfter)) {
(_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, reason]);
}
}
__privateGet(this, _keyMap).delete(k);
__privateGet(this, _keyList)[index] = void 0;
__privateGet(this, _valList)[index] = void 0;
if (index === __privateGet(this, _tail)) {
__privateSet(this, _tail, __privateGet(this, _prev)[index]);
} else if (index === __privateGet(this, _head)) {
__privateSet(this, _head, __privateGet(this, _next)[index]);
} else {
const pi = __privateGet(this, _prev)[index];
__privateGet(this, _next)[pi] = __privateGet(this, _next)[index];
const ni = __privateGet(this, _next)[index];
__privateGet(this, _prev)[ni] = __privateGet(this, _prev)[index];
}
__privateWrapper(this, _size)._--;
__privateGet(this, _free).push(index);
}
}
}
if (__privateGet(this, _hasDisposeAfter) && ((_c2 = __privateGet(this, _disposed)) == null ? void 0 : _c2.length)) {
const dt = __privateGet(this, _disposed);
let task;
while (task = dt == null ? void 0 : dt.shift()) {
(_d2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _d2.call(this, ...task);
}
}
return deleted;
};
clear_fn = function(reason) {
var _a4, _b3, _c2;
for (const index of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {
const v = __privateGet(this, _valList)[index];
if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
v.__abortController.abort(new Error("deleted"));
} else {
const k = __privateGet(this, _keyList)[index];
if (__privateGet(this, _hasDispose)) {
(_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, reason);
}
if (__privateGet(this, _hasDisposeAfter)) {
(_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, reason]);
}
}
}
__privateGet(this, _keyMap).clear();
__privateGet(this, _valList).fill(void 0);
__privateGet(this, _keyList).fill(void 0);
if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
__privateGet(this, _ttls).fill(0);
__privateGet(this, _starts).fill(0);
}
if (__privateGet(this, _sizes)) {
__privateGet(this, _sizes).fill(0);
}
__privateSet(this, _head, 0);
__privateSet(this, _tail, 0);
__privateGet(this, _free).length = 0;
__privateSet(this, _calculatedSize, 0);
__privateSet(this, _size, 0);
if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
const dt = __privateGet(this, _disposed);
let task;
while (task = dt == null ? void 0 : dt.shift()) {
(_c2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _c2.call(this, ...task);
}
}
};
var LRUCache = _LRUCache;
var proc = typeof process === "object" && process ? process : {
stdout: null,
stderr: null
};
var isStream = (s) => !!s && typeof s === "object" && (s instanceof Minipass || s instanceof import_node_stream.default || isReadable(s) || isWritable(s));
var isReadable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
s.pipe !== import_node_stream.default.Writable.prototype.pipe;
var isWritable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.write === "function" && typeof s.end === "function";
var EOF = Symbol("EOF");
var MAYBE_EMIT_END = Symbol("maybeEmitEnd");
var EMITTED_END = Symbol("emittedEnd");
var EMITTING_END = Symbol("emittingEnd");
var EMITTED_ERROR = Symbol("emittedError");
var CLOSED$1 = Symbol("closed");
var READ = Symbol("read");
var FLUSH = Symbol("flush");
var FLUSHCHUNK = Symbol("flushChunk");
var ENCODING$1 = Symbol("encoding");
var DECODER = Symbol("decoder");
var FLOWING = Symbol("flowing");
var PAUSED = Symbol("paused");
var RESUME = Symbol("resume");
var BUFFER = Symbol("buffer");
var PIPES = Symbol("pipes");
var BUFFERLENGTH = Symbol("bufferLength");
var BUFFERPUSH = Symbol("bufferPush");
var BUFFERSHIFT = Symbol("bufferShift");
var OBJECTMODE = Symbol("objectMode");
var DESTROYED = Symbol("destroyed");
var ERROR = Symbol("error");
var EMITDATA = Symbol("emitData");
var EMITEND = Symbol("emitEnd");
var EMITEND2 = Symbol("emitEnd2");
var ASYNC = Symbol("async");
var ABORT = Symbol("abort");
var ABORTED = Symbol("aborted");
var SIGNAL = Symbol("signal");
var DATALISTENERS = Symbol("dataListeners");
var DISCARDED = Symbol("discarded");
var defer$3 = (fn) => Promise.resolve().then(fn);
var nodefer = (fn) => fn();
var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
var isArrayBufferLike = (b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
var Pipe = class {
constructor(src2, dest, opts) {
__publicField(this, "src");
__publicField(this, "dest");
__publicField(this, "opts");
__publicField(this, "ondrain");
this.src = src2;
this.dest = dest;
this.opts = opts;
this.ondrain = () => src2[RESUME]();
this.dest.on("drain", this.ondrain);
}
unpipe() {
this.dest.removeListener("drain", this.ondrain);
}
// only here for the prototype
/* c8 ignore start */
proxyErrors(_er) {
}
/* c8 ignore stop */
end() {
this.unpipe();
if (this.opts.end)
this.dest.end();
}
};
var PipeProxyErrors = class extends Pipe {
unpipe() {
this.src.removeListener("error", this.proxyErrors);
super.unpipe();
}
constructor(src2, dest, opts) {
super(src2, dest, opts);
this.proxyErrors = (er) => dest.emit("error", er);
src2.on("error", this.proxyErrors);
}
};
var isObjectModeOptions = (o2) => !!o2.objectMode;
var isEncodingOptions = (o2) => !o2.objectMode && !!o2.encoding && o2.encoding !== "buffer";
var _a3, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
var Minipass = class extends import_node_events.EventEmitter {
/**
* If `RType` is Buffer, then options do not need to be provided.
* Otherwise, an options object must be provided to specify either
* {@link Minipass.SharedOptions.objectMode} or
* {@link Minipass.SharedOptions.encoding}, as appropriate.
*/
constructor(...args) {
const options2 = args[0] || {};
super();
__publicField(this, _s, false);
__publicField(this, _r, false);
__publicField(this, _q, []);
__publicField(this, _p, []);
__publicField(this, _o);
__publicField(this, _n);
__publicField(this, _m);
__publicField(this, _l);
__publicField(this, _k, false);
__publicField(this, _j, false);
__publicField(this, _i, false);
__publicField(this, _h, false);
__publicField(this, _g, null);
__publicField(this, _f, 0);
__publicField(this, _e, false);
__publicField(this, _d);
__publicField(this, _c, false);
__publicField(this, _b2, 0);
__publicField(this, _a3, false);
/**
* true if the stream can be written
*/
__publicField(this, "writable", true);
/**
* true if the stream can be read
*/
__publicField(this, "readable", true);
if (options2.objectMode && typeof options2.encoding === "string") {
throw new TypeError("Encoding and objectMode may not be used together");
}
if (isObjectModeOptions(options2)) {
this[OBJECTMODE] = true;
this[ENCODING$1] = null;
} else if (isEncodingOptions(options2)) {
this[ENCODING$1] = options2.encoding;
this[OBJECTMODE] = false;
} else {
this[OBJECTMODE] = false;
this[ENCODING$1] = null;
}
this[ASYNC] = !!options2.async;
this[DECODER] = this[ENCODING$1] ? new import_node_string_decoder.StringDecoder(this[ENCODING$1]) : null;
if (options2 && options2.debugExposeBuffer === true) {
Object.defineProperty(this, "buffer", { get: () => this[BUFFER] });
}
if (options2 && options2.debugExposePipes === true) {
Object.defineProperty(this, "pipes", { get: () => this[PIPES] });
}
const { signal } = options2;
if (signal) {
this[SIGNAL] = signal;
if (signal.aborted) {
this[ABORT]();
} else {
signal.addEventListener("abort", () => this[ABORT]());
}
}
}
/**
* The amount of data stored in the buffer waiting to be read.
*
* For Buffer strings, this will be the total byte length.
* For string encoding streams, this will be the string character length,
* according to JavaScript's `string.length` logic.
* For objectMode streams, this is a count of the items waiting to be
* emitted.
*/
get bufferLength() {
return this[BUFFERLENGTH];
}
/**
* The `BufferEncoding` currently in use, or `null`
*/
get encoding() {
return this[ENCODING$1];
}
/**
* @deprecated - This is a read only property
*/
set encoding(_enc) {
throw new Error("Encoding must be set at instantiation time");
}
/**
* @deprecated - Encoding may only be set at instantiation time
*/
setEncoding(_enc) {
throw new Error("Encoding must be set at instantiation time");
}
/**
* True if this is an objectMode stream
*/
get objectMode() {
return this[OBJECTMODE];
}
/**
* @deprecated - This is a read-only property
*/
set objectMode(_om) {
throw new Error("objectMode must be set at instantiation time");
}
/**
* true if this is an async stream
*/
get ["async"]() {
return this[ASYNC];
}
/**
* Set to true to make this stream async.
*
* Once set, it cannot be unset, as this would potentially cause incorrect
* behavior. Ie, a sync stream can be made async, but an async stream
* cannot be safely made sync.
*/
set ["async"](a) {
this[ASYNC] = this[ASYNC] || !!a;
}
// drop everything and get out of the flow completely
[(_s = FLOWING, _r = PAUSED, _q = PIPES, _p = BUFFER, _o = OBJECTMODE, _n = ENCODING$1, _m = ASYNC, _l = DECODER, _k = EOF, _j = EMITTED_END, _i = EMITTING_END, _h = CLOSED$1, _g = EMITTED_ERROR, _f = BUFFERLENGTH, _e = DESTROYED, _d = SIGNAL, _c = ABORTED, _b2 = DATALISTENERS, _a3 = DISCARDED, ABORT)]() {
var _a4, _b3;
this[ABORTED] = true;
this.emit("abort", (_a4 = this[SIGNAL]) == null ? void 0 : _a4.reason);
this.destroy((_b3 = this[SIGNAL]) == null ? void 0 : _b3.reason);
}
/**
* True if the stream has been aborted.
*/
get aborted() {
return this[ABORTED];
}
/**
* No-op setter. Stream aborted status is set via the AbortSignal provided
* in the constructor options.
*/
set aborted(_) {
}
write(chunk, encoding, cb) {
var _a4;
if (this[ABORTED])
return false;
if (this[EOF])
throw new Error("write after end");
if (this[DESTROYED]) {
this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
return true;
}
if (typeof encoding === "function") {
cb = encoding;
encoding = "utf8";
}
if (!encoding)
encoding = "utf8";
const fn = this[ASYNC] ? defer$3 : nodefer;
if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
if (isArrayBufferView(chunk)) {
chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
} else if (isArrayBufferLike(chunk)) {
chunk = Buffer.from(chunk);
} else if (typeof chunk !== "string") {
throw new Error("Non-contiguous data written to non-objectMode stream");
}
}
if (this[OBJECTMODE]) {
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
if (this[FLOWING])
this.emit("data", chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit("readable");
if (cb)
fn(cb);
return this[FLOWING];
}
if (!chunk.length) {
if (this[BUFFERLENGTH] !== 0)
this.emit("readable");
if (cb)
fn(cb);
return this[FLOWING];
}
if (typeof chunk === "string" && // unless it is a string already ready for us to use
!(encoding === this[ENCODING$1] && !((_a4 = this[DECODER]) == null ? void 0 : _a4.lastNeed))) {
chunk = Buffer.from(chunk, encoding);
}
if (Buffer.isBuffer(chunk) && this[ENCODING$1]) {
chunk = this[DECODER].write(chunk);
}
if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
this[FLUSH](true);
if (this[FLOWING])
this.emit("data", chunk);
else
this[BUFFERPUSH](chunk);
if (this[BUFFERLENGTH] !== 0)
this.emit("readable");
if (cb)
fn(cb);
return this[FLOWING];
}
/**
* Low-level explicit read method.
*
* In objectMode, the argument is ignored, and one item is returned if
* available.
*
* `n` is the number of bytes (or in the case of encoding streams,
* characters) to consume. If `n` is not provided, then the entire buffer
* is returned, or `null` is returned if no data is available.
*
* If `n` is greater that the amount of data in the internal buffer,
* then `null` is returned.
*/
read(n2) {
if (this[DESTROYED])
return null;
this[DISCARDED] = false;
if (this[BUFFERLENGTH] === 0 || n2 === 0 || n2 && n2 > this[BUFFERLENGTH]) {
this[MAYBE_EMIT_END]();
return null;
}
if (this[OBJECTMODE])
n2 = null;
if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
this[BUFFER] = [
this[ENCODING$1] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
];
}
const ret = this[READ](n2 || null, this[BUFFER][0]);
this[MAYBE_EMIT_END]();
return ret;
}
[READ](n2, chunk) {
if (this[OBJECTMODE])
this[BUFFERSHIFT]();
else {
const c = chunk;
if (n2 === c.length || n2 === null)
this[BUFFERSHIFT]();
else if (typeof c === "string") {
this[BUFFER][0] = c.slice(n2);
chunk = c.slice(0, n2);
this[BUFFERLENGTH] -= n2;
} else {
this[BUFFER][0] = c.subarray(n2);
chunk = c.subarray(0, n2);
this[BUFFERLENGTH] -= n2;
}
}
this.emit("data", chunk);
if (!this[BUFFER].length && !this[EOF])
this.emit("drain");
return chunk;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = void 0;
}
if (typeof encoding === "function") {
cb = encoding;
encoding = "utf8";
}
if (chunk !== void 0)
this.write(chunk, encoding);
if (cb)
this.once("end", cb);
this[EOF] = true;
this.writable = false;
if (this[FLOWING] || !this[PAUSED])
this[MAYBE_EMIT_END]();
return this;
}
// don't let the internal resume be overwritten
[RESUME]() {
if (this[DESTROYED])
return;
if (!this[DATALISTENERS] && !this[PIPES].length) {
this[DISCARDED] = true;
}
this[PAUSED] = false;
this[FLOWING] = true;
this.emit("resume");
if (this[BUFFER].length)
this[FLUSH]();
else if (this[EOF])
this[MAYBE_EMIT_END]();
else
this.emit("drain");
}
/**
* Resume the stream if it is currently in a paused state
*
* If called when there are no pipe destinations or `data` event listeners,
* this will place the stream in a "discarded" state, where all data will
* be thrown away. The discarded state is removed if a pipe destination or
* data handler is added, if pause() is called, or if any synchronous or
* asynchronous iteration is started.
*/
resume() {
return this[RESUME]();
}
/**
* Pause the stream
*/
pause() {
this[FLOWING] = false;
this[PAUSED] = true;
this[DISCARDED] = false;
}
/**
* true if the stream has been forcibly destroyed
*/
get destroyed() {
return this[DESTROYED];
}
/**
* true if the stream is currently in a flowing state, meaning that
* any writes will be immediately emitted.
*/
get flowing() {
return this[FLOWING];
}
/**
* true if the stream is currently in a paused state
*/
get paused() {
return this[PAUSED];
}
[BUFFERPUSH](chunk) {
if (this[OBJECTMODE])
this[BUFFERLENGTH] += 1;
else
this[BUFFERLENGTH] += chunk.length;
this[BUFFER].push(chunk);
}
[BUFFERSHIFT]() {
if (this[OBJECTMODE])
this[BUFFERLENGTH] -= 1;
else
this[BUFFERLENGTH] -= this[BUFFER][0].length;
return this[BUFFER].shift();
}
[FLUSH](noDrain = false) {
do {
} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
if (!noDrain && !this[BUFFER].length && !this[EOF])
this.emit("drain");
}
[FLUSHCHUNK](chunk) {
this.emit("data", chunk);
return this[FLOWING];
}
/**
* Pipe all data emitted by this stream into the destination provided.
*
* Triggers the flow of data.
*/
pipe(dest, opts) {
if (this[DESTROYED])
return dest;
this[DISCARDED] = false;
const ended = this[EMITTED_END];
opts = opts || {};
if (dest === proc.stdout || dest === proc.stderr)
opts.end = false;
else
opts.end = opts.end !== false;
opts.proxyErrors = !!opts.proxyErrors;
if (ended) {
if (opts.end)
dest.end();
} else {
this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
if (this[ASYNC])
defer$3(() => this[RESUME]());
else
this[RESUME]();
}
return dest;
}
/**
* Fully unhook a piped destination stream.
*
* If the destination stream was the only consumer of this stream (ie,
* there are no other piped destinations or `'data'` event listeners)
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
unpipe(dest) {
const p = this[PIPES].find((p2) => p2.dest === dest);
if (p) {
if (this[PIPES].length === 1) {
if (this[FLOWING] && this[DATALISTENERS] === 0) {
this[FLOWING] = false;
}
this[PIPES] = [];
} else
this[PIPES].splice(this[PIPES].indexOf(p), 1);
p.unpipe();
}
}
/**
* Alias for {@link Minipass#on}
*/
addListener(ev, handler) {
return this.on(ev, handler);
}
/**
* Mostly identical to `EventEmitter.on`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* - Adding a 'data' event handler will trigger the flow of data
*
* - Adding a 'readable' event handler when there is data waiting to be read
* will cause 'readable' to be emitted immediately.
*
* - Adding an 'endish' event handler ('end', 'finish', etc.) which has
* already passed will cause the event to be emitted immediately and all
* handlers removed.
*
* - Adding an 'error' event handler after an error has been emitted will
* cause the event to be re-emitted immediately with the error previously
* raised.
*/
on(ev, handler) {
const ret = super.on(ev, handler);
if (ev === "data") {
this[DISCARDED] = false;
this[DATALISTENERS]++;
if (!this[PIPES].length && !this[FLOWING]) {
this[RESUME]();
}
} else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
super.emit("readable");
} else if (isEndish(ev) && this[EMITTED_END]) {
super.emit(ev);
this.removeAllListeners(ev);
} else if (ev === "error" && this[EMITTED_ERROR]) {
const h = handler;
if (this[ASYNC])
defer$3(() => h.call(this, this[EMITTED_ERROR]));
else
h.call(this, this[EMITTED_ERROR]);
}
return ret;
}
/**
* Alias for {@link Minipass#off}
*/
removeListener(ev, handler) {
return this.off(ev, handler);
}
/**
* Mostly identical to `EventEmitter.off`
*
* If a 'data' event handler is removed, and it was the last consumer
* (ie, there are no pipe destinations or other 'data' event listeners),
* then the flow of data will stop until there is another consumer or
* {@link Minipass#resume} is explicitly called.
*/
off(ev, handler) {
const ret = super.off(ev, handler);
if (ev === "data") {
this[DATALISTENERS] = this.listeners("data").length;
if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* Mostly identical to `EventEmitter.removeAllListeners`
*
* If all 'data' event handlers are removed, and they were the last consumer
* (ie, there are no pipe destinations), then the flow of data will stop
* until there is another consumer or {@link Minipass#resume} is explicitly
* called.
*/
removeAllListeners(ev) {
const ret = super.removeAllListeners(ev);
if (ev === "data" || ev === void 0) {
this[DATALISTENERS] = 0;
if (!this[DISCARDED] && !this[PIPES].length) {
this[FLOWING] = false;
}
}
return ret;
}
/**
* true if the 'end' event has been emitted
*/
get emittedEnd() {
return this[EMITTED_END];
}
[MAYBE_EMIT_END]() {
if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
this[EMITTING_END] = true;
this.emit("end");
this.emit("prefinish");
this.emit("finish");
if (this[CLOSED$1])
this.emit("close");
this[EMITTING_END] = false;
}
}
/**
* Mostly identical to `EventEmitter.emit`, with the following
* behavior differences to prevent data loss and unnecessary hangs:
*
* If the stream has been destroyed, and the event is something other
* than 'close' or 'error', then `false` is returned and no handlers
* are called.
*
* If the event is 'end', and has already been emitted, then the event
* is ignored. If the stream is in a paused or non-flowing state, then
* the event will be deferred until data flow resumes. If the stream is
* async, then handlers will be called on the next tick rather than
* immediately.
*
* If the event is 'close', and 'end' has not yet been emitted, then
* the event will be deferred until after 'end' is emitted.
*
* If the event is 'error', and an AbortSignal was provided for the stream,
* and there are no listeners, then the event is ignored, matching the
* behavior of node core streams in the presense of an AbortSignal.
*
* If the event is 'finish' or 'prefinish', then all listeners will be
* removed after emitting the event, to prevent double-firing.
*/
emit(ev, ...args) {
const data = args[0];
if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
return false;
} else if (ev === "data") {
return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer$3(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
} else if (ev === "end") {
return this[EMITEND]();
} else if (ev === "close") {
this[CLOSED$1] = true;
if (!this[EMITTED_END] && !this[DESTROYED])
return false;
const ret2 = super.emit("close");
this.removeAllListeners("close");
return ret2;
} else if (ev === "error") {
this[EMITTED_ERROR] = data;
super.emit(ERROR, data);
const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
this[MAYBE_EMIT_END]();
return ret2;
} else if (ev === "resume") {
const ret2 = super.emit("resume");
this[MAYBE_EMIT_END]();
return ret2;
} else if (ev === "finish" || ev === "prefinish") {
const ret2 = super.emit(ev);
this.removeAllListeners(ev);
return ret2;
}
const ret = super.emit(ev, ...args);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITDATA](data) {
for (const p of this[PIPES]) {
if (p.dest.write(data) === false)
this.pause();
}
const ret = this[DISCARDED] ? false : super.emit("data", data);
this[MAYBE_EMIT_END]();
return ret;
}
[EMITEND]() {
if (this[EMITTED_END])
return false;
this[EMITTED_END] = true;
this.readable = false;
return this[ASYNC] ? (defer$3(() => this[EMITEND2]()), true) : this[EMITEND2]();
}
[EMITEND2]() {
if (this[DECODER]) {
const data = this[DECODER].end();
if (data) {
for (const p of this[PIPES]) {
p.dest.write(data);
}
if (!this[DISCARDED])
super.emit("data", data);
}
}
for (const p of this[PIPES]) {
p.end();
}
const ret = super.emit("end");
this.removeAllListeners("end");
return ret;
}
/**
* Return a Promise that resolves to an array of all emitted data once
* the stream ends.
*/
async collect() {
const buf = Object.assign([], {
dataLength: 0
});
if (!this[OBJECTMODE])
buf.dataLength = 0;
const p = this.promise();
this.on("data", (c) => {
buf.push(c);
if (!this[OBJECTMODE])
buf.dataLength += c.length;
});
await p;
return buf;
}
/**
* Return a Promise that resolves to the concatenation of all emitted data
* once the stream ends.
*
* Not allowed on objectMode streams.
*/
async concat() {
if (this[OBJECTMODE]) {
throw new Error("cannot concat in objectMode");
}
const buf = await this.collect();
return this[ENCODING$1] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
}
/**
* Return a void Promise that resolves once the stream ends.
*/
async promise() {
return new Promise((resolve3, reject) => {
this.on(DESTROYED, () => reject(new Error("stream destroyed")));
this.on("error", (er) => reject(er));
this.on("end", () => resolve3());
});
}
/**
* Asynchronous `for await of` iteration.
*
* This will continue emitting all chunks until the stream terminates.
*/
[Symbol.asyncIterator]() {
this[DISCARDED] = false;
let stopped = false;
const stop = async () => {
this.pause();
stopped = true;
return { value: void 0, done: true };
};
const next = () => {
if (stopped)
return stop();
const res = this.read();
if (res !== null)
return Promise.resolve({ done: false, value: res });
if (this[EOF])
return stop();
let resolve3;
let reject;
const onerr = (er) => {
this.off("data", ondata);
this.off("end", onend);
this.off(DESTROYED, ondestroy);
stop();
reject(er);
};
const ondata = (value2) => {
this.off("error", onerr);
this.off("end", onend);
this.off(DESTROYED, ondestroy);
this.pause();
resolve3({ value: value2, done: !!this[EOF] });
};
const onend = () => {
this.off("error", onerr);
this.off("data", ondata);
this.off(DESTROYED, ondestroy);
stop();
resolve3({ done: true, value: void 0 });
};
const ondestroy = () => onerr(new Error("stream destroyed"));
return new Promise((res2, rej) => {
reject = rej;
resolve3 = res2;
this.once(DESTROYED, ondestroy);
this.once("error", onerr);
this.once("end", onend);
this.once("data", ondata);
});
};
return {
next,
throw: stop,
return: stop,
[Symbol.asyncIterator]() {
return this;
}
};
}
/**
* Synchronous `for of` iteration.
*
* The iteration will terminate when the internal buffer runs out, even
* if the stream has not yet terminated.
*/
[Symbol.iterator]() {
this[DISCARDED] = false;
let stopped = false;
const stop = () => {
this.pause();
this.off(ERROR, stop);
this.off(DESTROYED, stop);
this.off("end", stop);
stopped = true;
return { done: true, value: void 0 };
};
const next = () => {
if (stopped)
return stop();
const value2 = this.read();
return value2 === null ? stop() : { done: false, value: value2 };
};
this.once("end", stop);
this.once(ERROR, stop);
this.once(DESTROYED, stop);
return {
next,
throw: stop,
return: stop,
[Symbol.iterator]() {
return this;
}
};
}
/**
* Destroy a stream, preventing it from being used for any further purpose.
*
* If the stream has a `close()` method, then it will be called on
* destruction.
*
* After destruction, any attempt to write data, read data, or emit most
* events will be ignored.
*
* If an error argument is provided, then it will be emitted in an
* 'error' event.
*/
destroy(er) {
if (this[DESTROYED]) {
if (er)
this.emit("error", er);
else
this.emit(DESTROYED);
return this;
}
this[DESTROYED] = true;
this[DISCARDED] = true;
this[BUFFER].length = 0;
this[BUFFERLENGTH] = 0;
const wc = this;
if (typeof wc.close === "function" && !this[CLOSED$1])
wc.close();
if (er)
this.emit("error", er);
else
this.emit(DESTROYED);
return this;
}
/**
* Alias for {@link isStream}
*
* Former export location, maintained for backwards compatibility.
*
* @deprecated
*/
static get isStream() {
return isStream;
}
};
var realpathSync = import_fs.realpathSync.native;
var defaultFS = {
lstatSync: import_fs.lstatSync,
readdir: import_fs.readdir,
readdirSync: import_fs.readdirSync,
readlinkSync: import_fs.readlinkSync,
realpathSync,
promises: {
lstat: import_promises.lstat,
readdir: import_promises.readdir,
readlink: import_promises.readlink,
realpath: import_promises.realpath
}
};
var fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === fs$j ? defaultFS : {
...defaultFS,
...fsOption,
promises: {
...defaultFS.promises,
...fsOption.promises || {}
}
};
var uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
var uncToDrive = (rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
var eitherSep = /[\\\/]/;
var UNKNOWN = 0;
var IFIFO = 1;
var IFCHR = 2;
var IFDIR = 4;
var IFBLK = 6;
var IFREG = 8;
var IFLNK = 10;
var IFSOCK = 12;
var IFMT = 15;
var IFMT_UNKNOWN = ~IFMT;
var READDIR_CALLED = 16;
var LSTAT_CALLED = 32;
var ENOTDIR = 64;
var ENOENT = 128;
var ENOREADLINK = 256;
var ENOREALPATH = 512;
var ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
var TYPEMASK = 1023;
var entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
var normalizeCache = /* @__PURE__ */ new Map();
var normalize = (s) => {
const c = normalizeCache.get(s);
if (c)
return c;
const n2 = s.normalize("NFKD");
normalizeCache.set(s, n2);
return n2;
};
var normalizeNocaseCache = /* @__PURE__ */ new Map();
var normalizeNocase = (s) => {
const c = normalizeNocaseCache.get(s);
if (c)
return c;
const n2 = normalize(s.toLowerCase());
normalizeNocaseCache.set(s, n2);
return n2;
};
var ResolveCache = class extends LRUCache {
constructor() {
super({ max: 256 });
}
};
var ChildrenCache = class extends LRUCache {
constructor(maxSize = 16 * 1024) {
super({
maxSize,
// parent + children
sizeCalculation: (a) => a.length + 1
});
}
};
var setAsCwd = Symbol("PathScurry setAsCwd");
var _fs, _dev, _mode, _nlink, _uid, _gid, _rdev, _blksize, _ino, _size2, _blocks, _atimeMs, _mtimeMs, _ctimeMs, _birthtimeMs, _atime, _mtime, _ctime, _birthtime, _matchName, _depth, _fullpath, _fullpathPosix, _relative, _relativePosix, _type, _children, _linkTarget, _realpath, _PathBase_instances, resolveParts_fn, readdirSuccess_fn, markENOENT_fn, markChildrenENOENT_fn, markENOREALPATH_fn, markENOTDIR_fn, readdirFail_fn, lstatFail_fn, readlinkFail_fn, readdirAddChild_fn, readdirAddNewChild_fn, readdirMaybePromoteChild_fn, readdirPromoteChild_fn, applyStat_fn, _onReaddirCB, _readdirCBInFlight, callOnReaddirCB_fn, _asyncReaddirInFlight;
var PathBase = class {
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
__privateAdd(this, _PathBase_instances);
/**
* the basename of this path
*
* **Important**: *always* test the path name against any test string
* usingthe {@link isNamed} method, and not by directly comparing this
* string. Otherwise, unicode path strings that the system sees as identical
* will not be properly treated as the same path, leading to incorrect
* behavior and possible security issues.
*/
__publicField(this, "name");
/**
* the Path entry corresponding to the path root.
*
* @internal
*/
__publicField(this, "root");
/**
* All roots found within the current PathScurry family
*
* @internal
*/
__publicField(this, "roots");
/**
* a reference to the parent path, or undefined in the case of root entries
*
* @internal
*/
__publicField(this, "parent");
/**
* boolean indicating whether paths are compared case-insensitively
* @internal
*/
__publicField(this, "nocase");
/**
* boolean indicating that this path is the current working directory
* of the PathScurry collection that contains it.
*/
__publicField(this, "isCWD", false);
// potential default fs override
__privateAdd(this, _fs);
// Stats fields
__privateAdd(this, _dev);
__privateAdd(this, _mode);
__privateAdd(this, _nlink);
__privateAdd(this, _uid);
__privateAdd(this, _gid);
__privateAdd(this, _rdev);
__privateAdd(this, _blksize);
__privateAdd(this, _ino);
__privateAdd(this, _size2);
__privateAdd(this, _blocks);
__privateAdd(this, _atimeMs);
__privateAdd(this, _mtimeMs);
__privateAdd(this, _ctimeMs);
__privateAdd(this, _birthtimeMs);
__privateAdd(this, _atime);
__privateAdd(this, _mtime);
__privateAdd(this, _ctime);
__privateAdd(this, _birthtime);
__privateAdd(this, _matchName);
__privateAdd(this, _depth);
__privateAdd(this, _fullpath);
__privateAdd(this, _fullpathPosix);
__privateAdd(this, _relative);
__privateAdd(this, _relativePosix);
__privateAdd(this, _type);
__privateAdd(this, _children);
__privateAdd(this, _linkTarget);
__privateAdd(this, _realpath);
__privateAdd(this, _onReaddirCB, []);
__privateAdd(this, _readdirCBInFlight, false);
__privateAdd(this, _asyncReaddirInFlight);
this.name = name2;
__privateSet(this, _matchName, nocase ? normalizeNocase(name2) : normalize(name2));
__privateSet(this, _type, type & TYPEMASK);
this.nocase = nocase;
this.roots = roots;
this.root = root || this;
__privateSet(this, _children, children);
__privateSet(this, _fullpath, opts.fullpath);
__privateSet(this, _relative, opts.relative);
__privateSet(this, _relativePosix, opts.relativePosix);
this.parent = opts.parent;
if (this.parent) {
__privateSet(this, _fs, __privateGet(this.parent, _fs));
} else {
__privateSet(this, _fs, fsFromOption(opts.fs));
}
}
get dev() {
return __privateGet(this, _dev);
}
get mode() {
return __privateGet(this, _mode);
}
get nlink() {
return __privateGet(this, _nlink);
}
get uid() {
return __privateGet(this, _uid);
}
get gid() {
return __privateGet(this, _gid);
}
get rdev() {
return __privateGet(this, _rdev);
}
get blksize() {
return __privateGet(this, _blksize);
}
get ino() {
return __privateGet(this, _ino);
}
get size() {
return __privateGet(this, _size2);
}
get blocks() {
return __privateGet(this, _blocks);
}
get atimeMs() {
return __privateGet(this, _atimeMs);
}
get mtimeMs() {
return __privateGet(this, _mtimeMs);
}
get ctimeMs() {
return __privateGet(this, _ctimeMs);
}
get birthtimeMs() {
return __privateGet(this, _birthtimeMs);
}
get atime() {
return __privateGet(this, _atime);
}
get mtime() {
return __privateGet(this, _mtime);
}
get ctime() {
return __privateGet(this, _ctime);
}
get birthtime() {
return __privateGet(this, _birthtime);
}
/**
* This property is for compatibility with the Dirent class as of
* Node v20, where Dirent['parentPath'] refers to the path of the
* directory that was passed to readdir. For root entries, it's the path
* to the entry itself.
*/
get parentPath() {
return (this.parent || this).fullpath();
}
/**
* Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
* this property refers to the *parent* path, not the path object itself.
*/
get path() {
return this.parentPath;
}
/**
* Returns the depth of the Path object from its root.
*
* For example, a path at `/foo/bar` would have a depth of 2.
*/
depth() {
if (__privateGet(this, _depth) !== void 0)
return __privateGet(this, _depth);
if (!this.parent)
return __privateSet(this, _depth, 0);
return __privateSet(this, _depth, this.parent.depth() + 1);
}
/**
* @internal
*/
childrenCache() {
return __privateGet(this, _children);
}
/**
* Get the Path object referenced by the string path, resolved from this Path
*/
resolve(path3) {
var _a4;
if (!path3) {
return this;
}
const rootPath = this.getRootString(path3);
const dir = path3.substring(rootPath.length);
const dirParts = dir.split(this.splitSep);
const result = rootPath ? __privateMethod(_a4 = this.getRoot(rootPath), _PathBase_instances, resolveParts_fn).call(_a4, dirParts) : __privateMethod(this, _PathBase_instances, resolveParts_fn).call(this, dirParts);
return result;
}
/**
* Returns the cached children Path objects, if still available. If they
* have fallen out of the cache, then returns an empty array, and resets the
* READDIR_CALLED bit, so that future calls to readdir() will require an fs
* lookup.
*
* @internal
*/
children() {
const cached = __privateGet(this, _children).get(this);
if (cached) {
return cached;
}
const children = Object.assign([], { provisional: 0 });
__privateGet(this, _children).set(this, children);
__privateSet(this, _type, __privateGet(this, _type) & ~READDIR_CALLED);
return children;
}
/**
* Resolves a path portion and returns or creates the child Path.
*
* Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
* `'..'`.
*
* This should not be called directly. If `pathPart` contains any path
* separators, it will lead to unsafe undefined behavior.
*
* Use `Path.resolve()` instead.
*
* @internal
*/
child(pathPart, opts) {
if (pathPart === "" || pathPart === ".") {
return this;
}
if (pathPart === "..") {
return this.parent || this;
}
const children = this.children();
const name2 = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
for (const p of children) {
if (__privateGet(p, _matchName) === name2) {
return p;
}
}
const s = this.parent ? this.sep : "";
const fullpath = __privateGet(this, _fullpath) ? __privateGet(this, _fullpath) + s + pathPart : void 0;
const pchild = this.newChild(pathPart, UNKNOWN, {
...opts,
parent: this,
fullpath
});
if (!this.canReaddir()) {
__privateSet(pchild, _type, __privateGet(pchild, _type) | ENOENT);
}
children.push(pchild);
return pchild;
}
/**
* The relative path from the cwd. If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpath()
*/
relative() {
if (this.isCWD)
return "";
if (__privateGet(this, _relative) !== void 0) {
return __privateGet(this, _relative);
}
const name2 = this.name;
const p = this.parent;
if (!p) {
return __privateSet(this, _relative, this.name);
}
const pv = p.relative();
return pv + (!pv || !p.parent ? "" : this.sep) + name2;
}
/**
* The relative path from the cwd, using / as the path separator.
* If it does not share an ancestor with
* the cwd, then this ends up being equivalent to the fullpathPosix()
* On posix systems, this is identical to relative().
*/
relativePosix() {
if (this.sep === "/")
return this.relative();
if (this.isCWD)
return "";
if (__privateGet(this, _relativePosix) !== void 0)
return __privateGet(this, _relativePosix);
const name2 = this.name;
const p = this.parent;
if (!p) {
return __privateSet(this, _relativePosix, this.fullpathPosix());
}
const pv = p.relativePosix();
return pv + (!pv || !p.parent ? "" : "/") + name2;
}
/**
* The fully resolved path string for this Path entry
*/
fullpath() {
if (__privateGet(this, _fullpath) !== void 0) {
return __privateGet(this, _fullpath);
}
const name2 = this.name;
const p = this.parent;
if (!p) {
return __privateSet(this, _fullpath, this.name);
}
const pv = p.fullpath();
const fp = pv + (!p.parent ? "" : this.sep) + name2;
return __privateSet(this, _fullpath, fp);
}
/**
* On platforms other than windows, this is identical to fullpath.
*
* On windows, this is overridden to return the forward-slash form of the
* full UNC path.
*/
fullpathPosix() {
if (__privateGet(this, _fullpathPosix) !== void 0)
return __privateGet(this, _fullpathPosix);
if (this.sep === "/")
return __privateSet(this, _fullpathPosix, this.fullpath());
if (!this.parent) {
const p2 = this.fullpath().replace(/\\/g, "/");
if (/^[a-z]:\//i.test(p2)) {
return __privateSet(this, _fullpathPosix, `//?/${p2}`);
} else {
return __privateSet(this, _fullpathPosix, p2);
}
}
const p = this.parent;
const pfpp = p.fullpathPosix();
const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
return __privateSet(this, _fullpathPosix, fpp);
}
/**
* Is the Path of an unknown type?
*
* Note that we might know *something* about it if there has been a previous
* filesystem operation, for example that it does not exist, or is not a
* link, or whether it has child entries.
*/
isUnknown() {
return (__privateGet(this, _type) & IFMT) === UNKNOWN;
}
isType(type) {
return this[`is${type}`]();
}
getType() {
return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
/* c8 ignore start */
this.isSocket() ? "Socket" : "Unknown"
);
}
/**
* Is the Path a regular file?
*/
isFile() {
return (__privateGet(this, _type) & IFMT) === IFREG;
}
/**
* Is the Path a directory?
*/
isDirectory() {
return (__privateGet(this, _type) & IFMT) === IFDIR;
}
/**
* Is the path a character device?
*/
isCharacterDevice() {
return (__privateGet(this, _type) & IFMT) === IFCHR;
}
/**
* Is the path a block device?
*/
isBlockDevice() {
return (__privateGet(this, _type) & IFMT) === IFBLK;
}
/**
* Is the path a FIFO pipe?
*/
isFIFO() {
return (__privateGet(this, _type) & IFMT) === IFIFO;
}
/**
* Is the path a socket?
*/
isSocket() {
return (__privateGet(this, _type) & IFMT) === IFSOCK;
}
/**
* Is the path a symbolic link?
*/
isSymbolicLink() {
return (__privateGet(this, _type) & IFLNK) === IFLNK;
}
/**
* Return the entry if it has been subject of a successful lstat, or
* undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* simply
* mean that we haven't called lstat on it.
*/
lstatCached() {
return __privateGet(this, _type) & LSTAT_CALLED ? this : void 0;
}
/**
* Return the cached link target if the entry has been the subject of a
* successful readlink, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readlink() has been called at some point.
*/
readlinkCached() {
return __privateGet(this, _linkTarget);
}
/**
* Returns the cached realpath target if the entry has been the subject
* of a successful realpath, or undefined otherwise.
*
* Does not read the filesystem, so an undefined result *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* realpath() has been called at some point.
*/
realpathCached() {
return __privateGet(this, _realpath);
}
/**
* Returns the cached child Path entries array if the entry has been the
* subject of a successful readdir(), or [] otherwise.
*
* Does not read the filesystem, so an empty array *could* just mean we
* don't have any cached data. Only use it if you are very sure that a
* readdir() has been called recently enough to still be valid.
*/
readdirCached() {
const children = this.children();
return children.slice(0, children.provisional);
}
/**
* Return true if it's worth trying to readlink. Ie, we don't (yet) have
* any indication that readlink will definitely fail.
*
* Returns false if the path is known to not be a symlink, if a previous
* readlink failed, or if the entry does not exist.
*/
canReadlink() {
if (__privateGet(this, _linkTarget))
return true;
if (!this.parent)
return false;
const ifmt = __privateGet(this, _type) & IFMT;
return !(ifmt !== UNKNOWN && ifmt !== IFLNK || __privateGet(this, _type) & ENOREADLINK || __privateGet(this, _type) & ENOENT);
}
/**
* Return true if readdir has previously been successfully called on this
* path, indicating that cachedReaddir() is likely valid.
*/
calledReaddir() {
return !!(__privateGet(this, _type) & READDIR_CALLED);
}
/**
* Returns true if the path is known to not exist. That is, a previous lstat
* or readdir failed to verify its existence when that would have been
* expected, or a parent entry was marked either enoent or enotdir.
*/
isENOENT() {
return !!(__privateGet(this, _type) & ENOENT);
}
/**
* Return true if the path is a match for the given path name. This handles
* case sensitivity and unicode normalization.
*
* Note: even on case-sensitive systems, it is **not** safe to test the
* equality of the `.name` property to determine whether a given pathname
* matches, due to unicode normalization mismatches.
*
* Always use this method instead of testing the `path.name` property
* directly.
*/
isNamed(n2) {
return !this.nocase ? __privateGet(this, _matchName) === normalize(n2) : __privateGet(this, _matchName) === normalizeNocase(n2);
}
/**
* Return the Path object corresponding to the target of a symbolic link.
*
* If the Path is not a symbolic link, or if the readlink call fails for any
* reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
*/
async readlink() {
var _a4;
const target = __privateGet(this, _linkTarget);
if (target) {
return target;
}
if (!this.canReadlink()) {
return void 0;
}
if (!this.parent) {
return void 0;
}
try {
const read2 = await __privateGet(this, _fs).promises.readlink(this.fullpath());
const linkTarget = (_a4 = await this.parent.realpath()) == null ? void 0 : _a4.resolve(read2);
if (linkTarget) {
return __privateSet(this, _linkTarget, linkTarget);
}
} catch (er) {
__privateMethod(this, _PathBase_instances, readlinkFail_fn).call(this, er.code);
return void 0;
}
}
/**
* Synchronous {@link PathBase.readlink}
*/
readlinkSync() {
var _a4;
const target = __privateGet(this, _linkTarget);
if (target) {
return target;
}
if (!this.canReadlink()) {
return void 0;
}
if (!this.parent) {
return void 0;
}
try {
const read2 = __privateGet(this, _fs).readlinkSync(this.fullpath());
const linkTarget = (_a4 = this.parent.realpathSync()) == null ? void 0 : _a4.resolve(read2);
if (linkTarget) {
return __privateSet(this, _linkTarget, linkTarget);
}
} catch (er) {
__privateMethod(this, _PathBase_instances, readlinkFail_fn).call(this, er.code);
return void 0;
}
}
/**
* Call lstat() on this Path, and update all known information that can be
* determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat() {
if ((__privateGet(this, _type) & ENOENT) === 0) {
try {
__privateMethod(this, _PathBase_instances, applyStat_fn).call(this, await __privateGet(this, _fs).promises.lstat(this.fullpath()));
return this;
} catch (er) {
__privateMethod(this, _PathBase_instances, lstatFail_fn).call(this, er.code);
}
}
}
/**
* synchronous {@link PathBase.lstat}
*/
lstatSync() {
if ((__privateGet(this, _type) & ENOENT) === 0) {
try {
__privateMethod(this, _PathBase_instances, applyStat_fn).call(this, __privateGet(this, _fs).lstatSync(this.fullpath()));
return this;
} catch (er) {
__privateMethod(this, _PathBase_instances, lstatFail_fn).call(this, er.code);
}
}
}
/**
* Standard node-style callback interface to get list of directory entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*
* @param cb The callback called with (er, entries). Note that the `er`
* param is somewhat extraneous, as all readdir() errors are handled and
* simply result in an empty set of entries being returned.
* @param allowZalgo Boolean indicating that immediately known results should
* *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
* zalgo at your peril, the dark pony lord is devious and unforgiving.
*/
readdirCB(cb, allowZalgo = false) {
if (!this.canReaddir()) {
if (allowZalgo)
cb(null, []);
else
queueMicrotask(() => cb(null, []));
return;
}
const children = this.children();
if (this.calledReaddir()) {
const c = children.slice(0, children.provisional);
if (allowZalgo)
cb(null, c);
else
queueMicrotask(() => cb(null, c));
return;
}
__privateGet(this, _onReaddirCB).push(cb);
if (__privateGet(this, _readdirCBInFlight)) {
return;
}
__privateSet(this, _readdirCBInFlight, true);
const fullpath = this.fullpath();
__privateGet(this, _fs).readdir(fullpath, { withFileTypes: true }, (er, entries) => {
if (er) {
__privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
children.provisional = 0;
} else {
for (const e2 of entries) {
__privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
}
__privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
}
__privateMethod(this, _PathBase_instances, callOnReaddirCB_fn).call(this, children.slice(0, children.provisional));
return;
});
}
/**
* Return an array of known child entries.
*
* If the Path cannot or does not contain any children, then an empty array
* is returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async readdir() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
const fullpath = this.fullpath();
if (__privateGet(this, _asyncReaddirInFlight)) {
await __privateGet(this, _asyncReaddirInFlight);
} else {
let resolve3 = () => {
};
__privateSet(this, _asyncReaddirInFlight, new Promise((res) => resolve3 = res));
try {
for (const e2 of await __privateGet(this, _fs).promises.readdir(fullpath, {
withFileTypes: true
})) {
__privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
}
__privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
} catch (er) {
__privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
children.provisional = 0;
}
__privateSet(this, _asyncReaddirInFlight, void 0);
resolve3();
}
return children.slice(0, children.provisional);
}
/**
* synchronous {@link PathBase.readdir}
*/
readdirSync() {
if (!this.canReaddir()) {
return [];
}
const children = this.children();
if (this.calledReaddir()) {
return children.slice(0, children.provisional);
}
const fullpath = this.fullpath();
try {
for (const e2 of __privateGet(this, _fs).readdirSync(fullpath, {
withFileTypes: true
})) {
__privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
}
__privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
} catch (er) {
__privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
children.provisional = 0;
}
return children.slice(0, children.provisional);
}
canReaddir() {
if (__privateGet(this, _type) & ENOCHILD)
return false;
const ifmt = IFMT & __privateGet(this, _type);
if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
return false;
}
return true;
}
shouldWalk(dirs, walkFilter) {
return (__privateGet(this, _type) & IFDIR) === IFDIR && !(__privateGet(this, _type) & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
}
/**
* Return the Path object corresponding to path as resolved
* by realpath(3).
*
* If the realpath call fails for any reason, `undefined` is returned.
*
* Result is cached, and thus may be outdated if the filesystem is mutated.
* On success, returns a Path object.
*/
async realpath() {
if (__privateGet(this, _realpath))
return __privateGet(this, _realpath);
if ((ENOREALPATH | ENOREADLINK | ENOENT) & __privateGet(this, _type))
return void 0;
try {
const rp = await __privateGet(this, _fs).promises.realpath(this.fullpath());
return __privateSet(this, _realpath, this.resolve(rp));
} catch (_) {
__privateMethod(this, _PathBase_instances, markENOREALPATH_fn).call(this);
}
}
/**
* Synchronous {@link realpath}
*/
realpathSync() {
if (__privateGet(this, _realpath))
return __privateGet(this, _realpath);
if ((ENOREALPATH | ENOREADLINK | ENOENT) & __privateGet(this, _type))
return void 0;
try {
const rp = __privateGet(this, _fs).realpathSync(this.fullpath());
return __privateSet(this, _realpath, this.resolve(rp));
} catch (_) {
__privateMethod(this, _PathBase_instances, markENOREALPATH_fn).call(this);
}
}
/**
* Internal method to mark this Path object as the scurry cwd,
* called by {@link PathScurry#chdir}
*
* @internal
*/
[setAsCwd](oldCwd) {
if (oldCwd === this)
return;
oldCwd.isCWD = false;
this.isCWD = true;
const changed = /* @__PURE__ */ new Set([]);
let rp = [];
let p = this;
while (p && p.parent) {
changed.add(p);
__privateSet(p, _relative, rp.join(this.sep));
__privateSet(p, _relativePosix, rp.join("/"));
p = p.parent;
rp.push("..");
}
p = oldCwd;
while (p && p.parent && !changed.has(p)) {
__privateSet(p, _relative, void 0);
__privateSet(p, _relativePosix, void 0);
p = p.parent;
}
}
};
_fs = new WeakMap();
_dev = new WeakMap();
_mode = new WeakMap();
_nlink = new WeakMap();
_uid = new WeakMap();
_gid = new WeakMap();
_rdev = new WeakMap();
_blksize = new WeakMap();
_ino = new WeakMap();
_size2 = new WeakMap();
_blocks = new WeakMap();
_atimeMs = new WeakMap();
_mtimeMs = new WeakMap();
_ctimeMs = new WeakMap();
_birthtimeMs = new WeakMap();
_atime = new WeakMap();
_mtime = new WeakMap();
_ctime = new WeakMap();
_birthtime = new WeakMap();
_matchName = new WeakMap();
_depth = new WeakMap();
_fullpath = new WeakMap();
_fullpathPosix = new WeakMap();
_relative = new WeakMap();
_relativePosix = new WeakMap();
_type = new WeakMap();
_children = new WeakMap();
_linkTarget = new WeakMap();
_realpath = new WeakMap();
_PathBase_instances = new WeakSet();
resolveParts_fn = function(dirParts) {
let p = this;
for (const part of dirParts) {
p = p.child(part);
}
return p;
};
readdirSuccess_fn = function(children) {
var _a4;
__privateSet(this, _type, __privateGet(this, _type) | READDIR_CALLED);
for (let p = children.provisional; p < children.length; p++) {
const c = children[p];
if (c)
__privateMethod(_a4 = c, _PathBase_instances, markENOENT_fn).call(_a4);
}
};
markENOENT_fn = function() {
if (__privateGet(this, _type) & ENOENT)
return;
__privateSet(this, _type, (__privateGet(this, _type) | ENOENT) & IFMT_UNKNOWN);
__privateMethod(this, _PathBase_instances, markChildrenENOENT_fn).call(this);
};
markChildrenENOENT_fn = function() {
var _a4;
const children = this.children();
children.provisional = 0;
for (const p of children) {
__privateMethod(_a4 = p, _PathBase_instances, markENOENT_fn).call(_a4);
}
};
markENOREALPATH_fn = function() {
__privateSet(this, _type, __privateGet(this, _type) | ENOREALPATH);
__privateMethod(this, _PathBase_instances, markENOTDIR_fn).call(this);
};
// save the information when we know the entry is not a dir
markENOTDIR_fn = function() {
if (__privateGet(this, _type) & ENOTDIR)
return;
let t2 = __privateGet(this, _type);
if ((t2 & IFMT) === IFDIR)
t2 &= IFMT_UNKNOWN;
__privateSet(this, _type, t2 | ENOTDIR);
__privateMethod(this, _PathBase_instances, markChildrenENOENT_fn).call(this);
};
readdirFail_fn = function(code = "") {
if (code === "ENOTDIR" || code === "EPERM") {
__privateMethod(this, _PathBase_instances, markENOTDIR_fn).call(this);
} else if (code === "ENOENT") {
__privateMethod(this, _PathBase_instances, markENOENT_fn).call(this);
} else {
this.children().provisional = 0;
}
};
lstatFail_fn = function(code = "") {
var _a4;
if (code === "ENOTDIR") {
const p = this.parent;
__privateMethod(_a4 = p, _PathBase_instances, markENOTDIR_fn).call(_a4);
} else if (code === "ENOENT") {
__privateMethod(this, _PathBase_instances, markENOENT_fn).call(this);
}
};
readlinkFail_fn = function(code = "") {
var _a4;
let ter = __privateGet(this, _type);
ter |= ENOREADLINK;
if (code === "ENOENT")
ter |= ENOENT;
if (code === "EINVAL" || code === "UNKNOWN") {
ter &= IFMT_UNKNOWN;
}
__privateSet(this, _type, ter);
if (code === "ENOTDIR" && this.parent) {
__privateMethod(_a4 = this.parent, _PathBase_instances, markENOTDIR_fn).call(_a4);
}
};
readdirAddChild_fn = function(e2, c) {
return __privateMethod(this, _PathBase_instances, readdirMaybePromoteChild_fn).call(this, e2, c) || __privateMethod(this, _PathBase_instances, readdirAddNewChild_fn).call(this, e2, c);
};
readdirAddNewChild_fn = function(e2, c) {
const type = entToType(e2);
const child = this.newChild(e2.name, type, { parent: this });
const ifmt = __privateGet(child, _type) & IFMT;
if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
__privateSet(child, _type, __privateGet(child, _type) | ENOTDIR);
}
c.unshift(child);
c.provisional++;
return child;
};
readdirMaybePromoteChild_fn = function(e2, c) {
for (let p = c.provisional; p < c.length; p++) {
const pchild = c[p];
const name2 = this.nocase ? normalizeNocase(e2.name) : normalize(e2.name);
if (name2 !== __privateGet(pchild, _matchName)) {
continue;
}
return __privateMethod(this, _PathBase_instances, readdirPromoteChild_fn).call(this, e2, pchild, p, c);
}
};
readdirPromoteChild_fn = function(e2, p, index, c) {
const v = p.name;
__privateSet(p, _type, __privateGet(p, _type) & IFMT_UNKNOWN | entToType(e2));
if (v !== e2.name)
p.name = e2.name;
if (index !== c.provisional) {
if (index === c.length - 1)
c.pop();
else
c.splice(index, 1);
c.unshift(p);
}
c.provisional++;
return p;
};
applyStat_fn = function(st) {
const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode: mode2, mtime, mtimeMs, nlink, rdev, size, uid } = st;
__privateSet(this, _atime, atime);
__privateSet(this, _atimeMs, atimeMs);
__privateSet(this, _birthtime, birthtime);
__privateSet(this, _birthtimeMs, birthtimeMs);
__privateSet(this, _blksize, blksize);
__privateSet(this, _blocks, blocks);
__privateSet(this, _ctime, ctime);
__privateSet(this, _ctimeMs, ctimeMs);
__privateSet(this, _dev, dev);
__privateSet(this, _gid, gid);
__privateSet(this, _ino, ino);
__privateSet(this, _mode, mode2);
__privateSet(this, _mtime, mtime);
__privateSet(this, _mtimeMs, mtimeMs);
__privateSet(this, _nlink, nlink);
__privateSet(this, _rdev, rdev);
__privateSet(this, _size2, size);
__privateSet(this, _uid, uid);
const ifmt = entToType(st);
__privateSet(this, _type, __privateGet(this, _type) & IFMT_UNKNOWN | ifmt | LSTAT_CALLED);
if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
__privateSet(this, _type, __privateGet(this, _type) | ENOTDIR);
}
};
_onReaddirCB = new WeakMap();
_readdirCBInFlight = new WeakMap();
callOnReaddirCB_fn = function(children) {
__privateSet(this, _readdirCBInFlight, false);
const cbs = __privateGet(this, _onReaddirCB).slice();
__privateGet(this, _onReaddirCB).length = 0;
cbs.forEach((cb) => cb(null, children));
};
_asyncReaddirInFlight = new WeakMap();
var PathWin32 = class _PathWin32 extends PathBase {
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name2, type, root, roots, nocase, children, opts);
/**
* Separator for generating path strings.
*/
__publicField(this, "sep", "\\");
/**
* Separator for parsing path strings.
*/
__publicField(this, "splitSep", eitherSep);
}
/**
* @internal
*/
newChild(name2, type = UNKNOWN, opts = {}) {
return new _PathWin32(name2, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
/**
* @internal
*/
getRootString(path3) {
return import_node_path3.win32.parse(path3).root;
}
/**
* @internal
*/
getRoot(rootPath) {
rootPath = uncToDrive(rootPath.toUpperCase());
if (rootPath === this.root.name) {
return this.root;
}
for (const [compare2, root] of Object.entries(this.roots)) {
if (this.sameRoot(rootPath, compare2)) {
return this.roots[rootPath] = root;
}
}
return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
}
/**
* @internal
*/
sameRoot(rootPath, compare2 = this.root.name) {
rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
return rootPath === compare2;
}
};
var PathPosix = class _PathPosix extends PathBase {
/**
* Do not create new Path objects directly. They should always be accessed
* via the PathScurry class or other methods on the Path class.
*
* @internal
*/
constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
super(name2, type, root, roots, nocase, children, opts);
/**
* separator for parsing path strings
*/
__publicField(this, "splitSep", "/");
/**
* separator for generating path strings
*/
__publicField(this, "sep", "/");
}
/**
* @internal
*/
getRootString(path3) {
return path3.startsWith("/") ? "/" : "";
}
/**
* @internal
*/
getRoot(_rootPath) {
return this.root;
}
/**
* @internal
*/
newChild(name2, type = UNKNOWN, opts = {}) {
return new _PathPosix(name2, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
}
};
var _resolveCache, _resolvePosixCache, _children2, _fs2;
var PathScurryBase = class {
/**
* This class should not be instantiated directly.
*
* Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
*
* @internal
*/
constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
/**
* The root Path entry for the current working directory of this Scurry
*/
__publicField(this, "root");
/**
* The string path for the root of this Scurry's current working directory
*/
__publicField(this, "rootPath");
/**
* A collection of all roots encountered, referenced by rootPath
*/
__publicField(this, "roots");
/**
* The Path entry corresponding to this PathScurry's current working directory.
*/
__publicField(this, "cwd");
__privateAdd(this, _resolveCache);
__privateAdd(this, _resolvePosixCache);
__privateAdd(this, _children2);
/**
* Perform path comparisons case-insensitively.
*
* Defaults true on Darwin and Windows systems, false elsewhere.
*/
__publicField(this, "nocase");
__privateAdd(this, _fs2);
__privateSet(this, _fs2, fsFromOption(fs2));
if (cwd instanceof URL || cwd.startsWith("file://")) {
cwd = (0, import_node_url2.fileURLToPath)(cwd);
}
const cwdPath = pathImpl.resolve(cwd);
this.roots = /* @__PURE__ */ Object.create(null);
this.rootPath = this.parseRootPath(cwdPath);
__privateSet(this, _resolveCache, new ResolveCache());
__privateSet(this, _resolvePosixCache, new ResolveCache());
__privateSet(this, _children2, new ChildrenCache(childrenCacheSize));
const split = cwdPath.substring(this.rootPath.length).split(sep2);
if (split.length === 1 && !split[0]) {
split.pop();
}
if (nocase === void 0) {
throw new TypeError("must provide nocase setting to PathScurryBase ctor");
}
this.nocase = nocase;
this.root = this.newRoot(__privateGet(this, _fs2));
this.roots[this.rootPath] = this.root;
let prev = this.root;
let len = split.length - 1;
const joinSep = pathImpl.sep;
let abs = this.rootPath;
let sawFirst = false;
for (const part of split) {
const l = len--;
prev = prev.child(part, {
relative: new Array(l).fill("..").join(joinSep),
relativePosix: new Array(l).fill("..").join("/"),
fullpath: abs += (sawFirst ? "" : joinSep) + part
});
sawFirst = true;
}
this.cwd = prev;
}
/**
* Get the depth of a provided path, string, or the cwd
*/
depth(path3 = this.cwd) {
if (typeof path3 === "string") {
path3 = this.cwd.resolve(path3);
}
return path3.depth();
}
/**
* Return the cache of child entries. Exposed so subclasses can create
* child Path objects in a platform-specific way.
*
* @internal
*/
childrenCache() {
return __privateGet(this, _children2);
}
/**
* Resolve one or more path strings to a resolved string
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolve(...paths) {
let r2 = "";
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === ".")
continue;
r2 = r2 ? `${p}/${r2}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = __privateGet(this, _resolveCache).get(r2);
if (cached !== void 0) {
return cached;
}
const result = this.cwd.resolve(r2).fullpath();
__privateGet(this, _resolveCache).set(r2, result);
return result;
}
/**
* Resolve one or more path strings to a resolved string, returning
* the posix path. Identical to .resolve() on posix systems, but on
* windows will return a forward-slash separated UNC path.
*
* Same interface as require('path').resolve.
*
* Much faster than path.resolve() when called multiple times for the same
* path, because the resolved Path objects are cached. Much slower
* otherwise.
*/
resolvePosix(...paths) {
let r2 = "";
for (let i = paths.length - 1; i >= 0; i--) {
const p = paths[i];
if (!p || p === ".")
continue;
r2 = r2 ? `${p}/${r2}` : p;
if (this.isAbsolute(p)) {
break;
}
}
const cached = __privateGet(this, _resolvePosixCache).get(r2);
if (cached !== void 0) {
return cached;
}
const result = this.cwd.resolve(r2).fullpathPosix();
__privateGet(this, _resolvePosixCache).set(r2, result);
return result;
}
/**
* find the relative path from the cwd to the supplied path string or entry
*/
relative(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return entry2.relative();
}
/**
* find the relative path from the cwd to the supplied path string or
* entry, using / as the path delimiter, even on Windows.
*/
relativePosix(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return entry2.relativePosix();
}
/**
* Return the basename for the provided string or Path object
*/
basename(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return entry2.name;
}
/**
* Return the dirname for the provided string or Path object
*/
dirname(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return (entry2.parent || entry2).fullpath();
}
async readdir(entry2 = this.cwd, opts = {
withFileTypes: true
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes } = opts;
if (!entry2.canReaddir()) {
return [];
} else {
const p = await entry2.readdir();
return withFileTypes ? p : p.map((e2) => e2.name);
}
}
readdirSync(entry2 = this.cwd, opts = {
withFileTypes: true
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true } = opts;
if (!entry2.canReaddir()) {
return [];
} else if (withFileTypes) {
return entry2.readdirSync();
} else {
return entry2.readdirSync().map((e2) => e2.name);
}
}
/**
* Call lstat() on the string or Path object, and update all known
* information that can be determined.
*
* Note that unlike `fs.lstat()`, the returned value does not contain some
* information, such as `mode`, `dev`, `nlink`, and `ino`. If that
* information is required, you will need to call `fs.lstat` yourself.
*
* If the Path refers to a nonexistent file, or if the lstat call fails for
* any reason, `undefined` is returned. Otherwise the updated Path object is
* returned.
*
* Results are cached, and thus may be out of date if the filesystem is
* mutated.
*/
async lstat(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return entry2.lstat();
}
/**
* synchronous {@link PathScurryBase.lstat}
*/
lstatSync(entry2 = this.cwd) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
}
return entry2.lstatSync();
}
async readlink(entry2 = this.cwd, { withFileTypes } = {
withFileTypes: false
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
withFileTypes = entry2.withFileTypes;
entry2 = this.cwd;
}
const e2 = await entry2.readlink();
return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
}
readlinkSync(entry2 = this.cwd, { withFileTypes } = {
withFileTypes: false
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
withFileTypes = entry2.withFileTypes;
entry2 = this.cwd;
}
const e2 = entry2.readlinkSync();
return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
}
async realpath(entry2 = this.cwd, { withFileTypes } = {
withFileTypes: false
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
withFileTypes = entry2.withFileTypes;
entry2 = this.cwd;
}
const e2 = await entry2.realpath();
return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
}
realpathSync(entry2 = this.cwd, { withFileTypes } = {
withFileTypes: false
}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
withFileTypes = entry2.withFileTypes;
entry2 = this.cwd;
}
const e2 = entry2.realpathSync();
return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
}
async walk(entry2 = this.cwd, opts = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
const results = [];
if (!filter2 || filter2(entry2)) {
results.push(withFileTypes ? entry2 : entry2.fullpath());
}
const dirs = /* @__PURE__ */ new Set();
const walk2 = (dir, cb) => {
dirs.add(dir);
dir.readdirCB((er, entries) => {
if (er) {
return cb(er);
}
let len = entries.length;
if (!len)
return cb();
const next = () => {
if (--len === 0) {
cb();
}
};
for (const e2 of entries) {
if (!filter2 || filter2(e2)) {
results.push(withFileTypes ? e2 : e2.fullpath());
}
if (follow && e2.isSymbolicLink()) {
e2.realpath().then((r2) => (r2 == null ? void 0 : r2.isUnknown()) ? r2.lstat() : r2).then((r2) => (r2 == null ? void 0 : r2.shouldWalk(dirs, walkFilter)) ? walk2(r2, next) : next());
} else {
if (e2.shouldWalk(dirs, walkFilter)) {
walk2(e2, next);
} else {
next();
}
}
}
}, true);
};
const start = entry2;
return new Promise((res, rej) => {
walk2(start, (er) => {
if (er)
return rej(er);
res(results);
});
});
}
walkSync(entry2 = this.cwd, opts = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
const results = [];
if (!filter2 || filter2(entry2)) {
results.push(withFileTypes ? entry2 : entry2.fullpath());
}
const dirs = /* @__PURE__ */ new Set([entry2]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e2 of entries) {
if (!filter2 || filter2(e2)) {
results.push(withFileTypes ? e2 : e2.fullpath());
}
let r2 = e2;
if (e2.isSymbolicLink()) {
if (!(follow && (r2 = e2.realpathSync())))
continue;
if (r2.isUnknown())
r2.lstatSync();
}
if (r2.shouldWalk(dirs, walkFilter)) {
dirs.add(r2);
}
}
}
return results;
}
/**
* Support for `for await`
*
* Alias for {@link PathScurryBase.iterate}
*
* Note: As of Node 19, this is very slow, compared to other methods of
* walking. Consider using {@link PathScurryBase.stream} if memory overhead
* and backpressure are concerns, or {@link PathScurryBase.walk} if not.
*/
[Symbol.asyncIterator]() {
return this.iterate();
}
iterate(entry2 = this.cwd, options2 = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
options2 = entry2;
entry2 = this.cwd;
}
return this.stream(entry2, options2)[Symbol.asyncIterator]();
}
/**
* Iterating over a PathScurry performs a synchronous walk.
*
* Alias for {@link PathScurryBase.iterateSync}
*/
[Symbol.iterator]() {
return this.iterateSync();
}
*iterateSync(entry2 = this.cwd, opts = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
if (!filter2 || filter2(entry2)) {
yield withFileTypes ? entry2 : entry2.fullpath();
}
const dirs = /* @__PURE__ */ new Set([entry2]);
for (const dir of dirs) {
const entries = dir.readdirSync();
for (const e2 of entries) {
if (!filter2 || filter2(e2)) {
yield withFileTypes ? e2 : e2.fullpath();
}
let r2 = e2;
if (e2.isSymbolicLink()) {
if (!(follow && (r2 = e2.realpathSync())))
continue;
if (r2.isUnknown())
r2.lstatSync();
}
if (r2.shouldWalk(dirs, walkFilter)) {
dirs.add(r2);
}
}
}
}
stream(entry2 = this.cwd, opts = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
const results = new Minipass({ objectMode: true });
if (!filter2 || filter2(entry2)) {
results.write(withFileTypes ? entry2 : entry2.fullpath());
}
const dirs = /* @__PURE__ */ new Set();
const queue2 = [entry2];
let processing = 0;
const process2 = () => {
let paused = false;
while (!paused) {
const dir = queue2.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const onReaddir = (er, entries, didRealpaths = false) => {
if (er)
return results.emit("error", er);
if (follow && !didRealpaths) {
const promises2 = [];
for (const e2 of entries) {
if (e2.isSymbolicLink()) {
promises2.push(e2.realpath().then((r2) => (r2 == null ? void 0 : r2.isUnknown()) ? r2.lstat() : r2));
}
}
if (promises2.length) {
Promise.all(promises2).then(() => onReaddir(null, entries, true));
return;
}
}
for (const e2 of entries) {
if (e2 && (!filter2 || filter2(e2))) {
if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e2 of entries) {
const r2 = e2.realpathCached() || e2;
if (r2.shouldWalk(dirs, walkFilter)) {
queue2.push(r2);
}
}
if (paused && !results.flowing) {
results.once("drain", process2);
} else if (!sync2) {
process2();
}
};
let sync2 = true;
dir.readdirCB(onReaddir, true);
sync2 = false;
}
};
process2();
return results;
}
streamSync(entry2 = this.cwd, opts = {}) {
if (typeof entry2 === "string") {
entry2 = this.cwd.resolve(entry2);
} else if (!(entry2 instanceof PathBase)) {
opts = entry2;
entry2 = this.cwd;
}
const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
const results = new Minipass({ objectMode: true });
const dirs = /* @__PURE__ */ new Set();
if (!filter2 || filter2(entry2)) {
results.write(withFileTypes ? entry2 : entry2.fullpath());
}
const queue2 = [entry2];
let processing = 0;
const process2 = () => {
let paused = false;
while (!paused) {
const dir = queue2.shift();
if (!dir) {
if (processing === 0)
results.end();
return;
}
processing++;
dirs.add(dir);
const entries = dir.readdirSync();
for (const e2 of entries) {
if (!filter2 || filter2(e2)) {
if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
paused = true;
}
}
}
processing--;
for (const e2 of entries) {
let r2 = e2;
if (e2.isSymbolicLink()) {
if (!(follow && (r2 = e2.realpathSync())))
continue;
if (r2.isUnknown())
r2.lstatSync();
}
if (r2.shouldWalk(dirs, walkFilter)) {
queue2.push(r2);
}
}
}
if (paused && !results.flowing)
results.once("drain", process2);
};
process2();
return results;
}
chdir(path3 = this.cwd) {
const oldCwd = this.cwd;
this.cwd = typeof path3 === "string" ? this.cwd.resolve(path3) : path3;
this.cwd[setAsCwd](oldCwd);
}
};
_resolveCache = new WeakMap();
_resolvePosixCache = new WeakMap();
_children2 = new WeakMap();
_fs2 = new WeakMap();
var PathScurryWin32 = class extends PathScurryBase {
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, import_node_path3.win32, "\\", { ...opts, nocase });
/**
* separator for generating path strings
*/
__publicField(this, "sep", "\\");
this.nocase = nocase;
for (let p = this.cwd; p; p = p.parent) {
p.nocase = this.nocase;
}
}
/**
* @internal
*/
parseRootPath(dir) {
return import_node_path3.win32.parse(dir).root.toUpperCase();
}
/**
* @internal
*/
newRoot(fs2) {
return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
}
};
var PathScurryPosix = class extends PathScurryBase {
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = false } = opts;
super(cwd, import_node_path3.posix, "/", { ...opts, nocase });
/**
* separator for generating path strings
*/
__publicField(this, "sep", "/");
this.nocase = nocase;
}
/**
* @internal
*/
parseRootPath(_dir) {
return "/";
}
/**
* @internal
*/
newRoot(fs2) {
return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
}
/**
* Return true if the provided path string is an absolute path
*/
isAbsolute(p) {
return p.startsWith("/");
}
};
var PathScurryDarwin = class extends PathScurryPosix {
constructor(cwd = process.cwd(), opts = {}) {
const { nocase = true } = opts;
super(cwd, { ...opts, nocase });
}
};
process.platform === "win32" ? PathWin32 : PathPosix;
var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
var isPatternList = (pl) => pl.length >= 1;
var isGlobList = (gl) => gl.length >= 1;
var _patternList, _globList, _index, _platform, _rest, _globString, _isDrive, _isUNC, _isAbsolute, _followGlobstar;
var _Pattern = class _Pattern {
constructor(patternList, globList, index, platform2) {
__privateAdd(this, _patternList);
__privateAdd(this, _globList);
__privateAdd(this, _index);
__publicField(this, "length");
__privateAdd(this, _platform);
__privateAdd(this, _rest);
__privateAdd(this, _globString);
__privateAdd(this, _isDrive);
__privateAdd(this, _isUNC);
__privateAdd(this, _isAbsolute);
__privateAdd(this, _followGlobstar, true);
if (!isPatternList(patternList)) {
throw new TypeError("empty pattern list");
}
if (!isGlobList(globList)) {
throw new TypeError("empty glob list");
}
if (globList.length !== patternList.length) {
throw new TypeError("mismatched pattern list and glob list lengths");
}
this.length = patternList.length;
if (index < 0 || index >= this.length) {
throw new TypeError("index out of range");
}
__privateSet(this, _patternList, patternList);
__privateSet(this, _globList, globList);
__privateSet(this, _index, index);
__privateSet(this, _platform, platform2);
if (__privateGet(this, _index) === 0) {
if (this.isUNC()) {
const [p0, p1, p2, p3, ...prest] = __privateGet(this, _patternList);
const [g0, g1, g2, g3, ...grest] = __privateGet(this, _globList);
if (prest[0] === "") {
prest.shift();
grest.shift();
}
const p = [p0, p1, p2, p3, ""].join("/");
const g = [g0, g1, g2, g3, ""].join("/");
__privateSet(this, _patternList, [p, ...prest]);
__privateSet(this, _globList, [g, ...grest]);
this.length = __privateGet(this, _patternList).length;
} else if (this.isDrive() || this.isAbsolute()) {
const [p1, ...prest] = __privateGet(this, _patternList);
const [g1, ...grest] = __privateGet(this, _globList);
if (prest[0] === "") {
prest.shift();
grest.shift();
}
const p = p1 + "/";
const g = g1 + "/";
__privateSet(this, _patternList, [p, ...prest]);
__privateSet(this, _globList, [g, ...grest]);
this.length = __privateGet(this, _patternList).length;
}
}
}
/**
* The first entry in the parsed list of patterns
*/
pattern() {
return __privateGet(this, _patternList)[__privateGet(this, _index)];
}
/**
* true of if pattern() returns a string
*/
isString() {
return typeof __privateGet(this, _patternList)[__privateGet(this, _index)] === "string";
}
/**
* true of if pattern() returns GLOBSTAR
*/
isGlobstar() {
return __privateGet(this, _patternList)[__privateGet(this, _index)] === GLOBSTAR$2;
}
/**
* true if pattern() returns a regexp
*/
isRegExp() {
return __privateGet(this, _patternList)[__privateGet(this, _index)] instanceof RegExp;
}
/**
* The /-joined set of glob parts that make up this pattern
*/
globString() {
return __privateSet(this, _globString, __privateGet(this, _globString) || (__privateGet(this, _index) === 0 ? this.isAbsolute() ? __privateGet(this, _globList)[0] + __privateGet(this, _globList).slice(1).join("/") : __privateGet(this, _globList).join("/") : __privateGet(this, _globList).slice(__privateGet(this, _index)).join("/")));
}
/**
* true if there are more pattern parts after this one
*/
hasMore() {
return this.length > __privateGet(this, _index) + 1;
}
/**
* The rest of the pattern after this part, or null if this is the end
*/
rest() {
if (__privateGet(this, _rest) !== void 0)
return __privateGet(this, _rest);
if (!this.hasMore())
return __privateSet(this, _rest, null);
__privateSet(this, _rest, new _Pattern(__privateGet(this, _patternList), __privateGet(this, _globList), __privateGet(this, _index) + 1, __privateGet(this, _platform)));
__privateSet(__privateGet(this, _rest), _isAbsolute, __privateGet(this, _isAbsolute));
__privateSet(__privateGet(this, _rest), _isUNC, __privateGet(this, _isUNC));
__privateSet(__privateGet(this, _rest), _isDrive, __privateGet(this, _isDrive));
return __privateGet(this, _rest);
}
/**
* true if the pattern represents a //unc/path/ on windows
*/
isUNC() {
const pl = __privateGet(this, _patternList);
return __privateGet(this, _isUNC) !== void 0 ? __privateGet(this, _isUNC) : __privateSet(this, _isUNC, __privateGet(this, _platform) === "win32" && __privateGet(this, _index) === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3]);
}
// pattern like C:/...
// split = ['C:', ...]
// XXX: would be nice to handle patterns like `c:*` to test the cwd
// in c: for *, but I don't know of a way to even figure out what that
// cwd is without actually chdir'ing into it?
/**
* True if the pattern starts with a drive letter on Windows
*/
isDrive() {
const pl = __privateGet(this, _patternList);
return __privateGet(this, _isDrive) !== void 0 ? __privateGet(this, _isDrive) : __privateSet(this, _isDrive, __privateGet(this, _platform) === "win32" && __privateGet(this, _index) === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]));
}
// pattern = '/' or '/...' or '/x/...'
// split = ['', ''] or ['', ...] or ['', 'x', ...]
// Drive and UNC both considered absolute on windows
/**
* True if the pattern is rooted on an absolute path
*/
isAbsolute() {
const pl = __privateGet(this, _patternList);
return __privateGet(this, _isAbsolute) !== void 0 ? __privateGet(this, _isAbsolute) : __privateSet(this, _isAbsolute, pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC());
}
/**
* consume the root of the pattern, and return it
*/
root() {
const p = __privateGet(this, _patternList)[0];
return typeof p === "string" && this.isAbsolute() && __privateGet(this, _index) === 0 ? p : "";
}
/**
* Check to see if the current globstar pattern is allowed to follow
* a symbolic link.
*/
checkFollowGlobstar() {
return !(__privateGet(this, _index) === 0 || !this.isGlobstar() || !__privateGet(this, _followGlobstar));
}
/**
* Mark that the current globstar pattern is following a symbolic link
*/
markFollowGlobstar() {
if (__privateGet(this, _index) === 0 || !this.isGlobstar() || !__privateGet(this, _followGlobstar))
return false;
__privateSet(this, _followGlobstar, false);
return true;
}
};
_patternList = new WeakMap();
_globList = new WeakMap();
_index = new WeakMap();
_platform = new WeakMap();
_rest = new WeakMap();
_globString = new WeakMap();
_isDrive = new WeakMap();
_isUNC = new WeakMap();
_isAbsolute = new WeakMap();
_followGlobstar = new WeakMap();
var Pattern = _Pattern;
var defaultPlatform$1 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Ignore = class {
constructor(ignored, { nobrace, nocase, noext, noglobstar, platform: platform2 = defaultPlatform$1 }) {
__publicField(this, "relative");
__publicField(this, "relativeChildren");
__publicField(this, "absolute");
__publicField(this, "absoluteChildren");
__publicField(this, "platform");
__publicField(this, "mmopts");
this.relative = [];
this.absolute = [];
this.relativeChildren = [];
this.absoluteChildren = [];
this.platform = platform2;
this.mmopts = {
dot: true,
nobrace,
nocase,
noext,
noglobstar,
optimizationLevel: 2,
platform: platform2,
nocomment: true,
nonegate: true
};
for (const ign of ignored)
this.add(ign);
}
add(ign) {
const mm = new Minimatch(ign, this.mmopts);
for (let i = 0; i < mm.set.length; i++) {
const parsed = mm.set[i];
const globParts = mm.globParts[i];
if (!parsed || !globParts) {
throw new Error("invalid pattern object");
}
while (parsed[0] === "." && globParts[0] === ".") {
parsed.shift();
globParts.shift();
}
const p = new Pattern(parsed, globParts, 0, this.platform);
const m = new Minimatch(p.globString(), this.mmopts);
const children = globParts[globParts.length - 1] === "**";
const absolute = p.isAbsolute();
if (absolute)
this.absolute.push(m);
else
this.relative.push(m);
if (children) {
if (absolute)
this.absoluteChildren.push(m);
else
this.relativeChildren.push(m);
}
}
}
ignored(p) {
const fullpath = p.fullpath();
const fullpaths = `${fullpath}/`;
const relative2 = p.relative() || ".";
const relatives = `${relative2}/`;
for (const m of this.relative) {
if (m.match(relative2) || m.match(relatives))
return true;
}
for (const m of this.absolute) {
if (m.match(fullpath) || m.match(fullpaths))
return true;
}
return false;
}
childrenIgnored(p) {
const fullpath = p.fullpath() + "/";
const relative2 = (p.relative() || ".") + "/";
for (const m of this.relativeChildren) {
if (m.match(relative2))
return true;
}
for (const m of this.absoluteChildren) {
if (m.match(fullpath))
return true;
}
return false;
}
};
var HasWalkedCache = class _HasWalkedCache {
constructor(store = /* @__PURE__ */ new Map()) {
__publicField(this, "store");
this.store = store;
}
copy() {
return new _HasWalkedCache(new Map(this.store));
}
hasWalked(target, pattern2) {
var _a4;
return (_a4 = this.store.get(target.fullpath())) == null ? void 0 : _a4.has(pattern2.globString());
}
storeWalked(target, pattern2) {
const fullpath = target.fullpath();
const cached = this.store.get(fullpath);
if (cached)
cached.add(pattern2.globString());
else
this.store.set(fullpath, /* @__PURE__ */ new Set([pattern2.globString()]));
}
};
var MatchRecord = class {
constructor() {
__publicField(this, "store", /* @__PURE__ */ new Map());
}
add(target, absolute, ifDir) {
const n2 = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
const current = this.store.get(target);
this.store.set(target, current === void 0 ? n2 : n2 & current);
}
// match, absolute, ifdir
entries() {
return [...this.store.entries()].map(([path3, n2]) => [
path3,
!!(n2 & 2),
!!(n2 & 1)
]);
}
};
var SubWalks = class {
constructor() {
__publicField(this, "store", /* @__PURE__ */ new Map());
}
add(target, pattern2) {
if (!target.canReaddir()) {
return;
}
const subs = this.store.get(target);
if (subs) {
if (!subs.find((p) => p.globString() === pattern2.globString())) {
subs.push(pattern2);
}
} else
this.store.set(target, [pattern2]);
}
get(target) {
const subs = this.store.get(target);
if (!subs) {
throw new Error("attempting to walk unknown path");
}
return subs;
}
entries() {
return this.keys().map((k) => [k, this.store.get(k)]);
}
keys() {
return [...this.store.keys()].filter((t2) => t2.canReaddir());
}
};
var Processor = class _Processor {
constructor(opts, hasWalkedCache) {
__publicField(this, "hasWalkedCache");
__publicField(this, "matches", new MatchRecord());
__publicField(this, "subwalks", new SubWalks());
__publicField(this, "patterns");
__publicField(this, "follow");
__publicField(this, "dot");
__publicField(this, "opts");
this.opts = opts;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
}
processPatterns(target, patterns) {
this.patterns = patterns;
const processingSet = patterns.map((p) => [target, p]);
for (let [t2, pattern2] of processingSet) {
this.hasWalkedCache.storeWalked(t2, pattern2);
const root = pattern2.root();
const absolute = pattern2.isAbsolute() && this.opts.absolute !== false;
if (root) {
t2 = t2.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
const rest2 = pattern2.rest();
if (!rest2) {
this.matches.add(t2, true, false);
continue;
} else {
pattern2 = rest2;
}
}
if (t2.isENOENT())
continue;
let p;
let rest;
let changed = false;
while (typeof (p = pattern2.pattern()) === "string" && (rest = pattern2.rest())) {
const c = t2.resolve(p);
t2 = c;
pattern2 = rest;
changed = true;
}
p = pattern2.pattern();
rest = pattern2.rest();
if (changed) {
if (this.hasWalkedCache.hasWalked(t2, pattern2))
continue;
this.hasWalkedCache.storeWalked(t2, pattern2);
}
if (typeof p === "string") {
const ifDir = p === ".." || p === "" || p === ".";
this.matches.add(t2.resolve(p), absolute, ifDir);
continue;
} else if (p === GLOBSTAR$2) {
if (!t2.isSymbolicLink() || this.follow || pattern2.checkFollowGlobstar()) {
this.subwalks.add(t2, pattern2);
}
const rp = rest == null ? void 0 : rest.pattern();
const rrest = rest == null ? void 0 : rest.rest();
if (!rest || (rp === "" || rp === ".") && !rrest) {
this.matches.add(t2, absolute, rp === "" || rp === ".");
} else {
if (rp === "..") {
const tp = t2.parent || t2;
if (!rrest)
this.matches.add(tp, absolute, true);
else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
this.subwalks.add(tp, rrest);
}
}
}
} else if (p instanceof RegExp) {
this.subwalks.add(t2, pattern2);
}
}
return this;
}
subwalkTargets() {
return this.subwalks.keys();
}
child() {
return new _Processor(this.opts, this.hasWalkedCache);
}
// return a new Processor containing the subwalks for each
// child entry, and a set of matches, and
// a hasWalkedCache that's a copy of this one
// then we're going to call
filterEntries(parent, entries) {
const patterns = this.subwalks.get(parent);
const results = this.child();
for (const e2 of entries) {
for (const pattern2 of patterns) {
const absolute = pattern2.isAbsolute();
const p = pattern2.pattern();
const rest = pattern2.rest();
if (p === GLOBSTAR$2) {
results.testGlobstar(e2, pattern2, rest, absolute);
} else if (p instanceof RegExp) {
results.testRegExp(e2, p, rest, absolute);
} else {
results.testString(e2, p, rest, absolute);
}
}
}
return results;
}
testGlobstar(e2, pattern2, rest, absolute) {
if (this.dot || !e2.name.startsWith(".")) {
if (!pattern2.hasMore()) {
this.matches.add(e2, absolute, false);
}
if (e2.canReaddir()) {
if (this.follow || !e2.isSymbolicLink()) {
this.subwalks.add(e2, pattern2);
} else if (e2.isSymbolicLink()) {
if (rest && pattern2.checkFollowGlobstar()) {
this.subwalks.add(e2, rest);
} else if (pattern2.markFollowGlobstar()) {
this.subwalks.add(e2, pattern2);
}
}
}
}
if (rest) {
const rp = rest.pattern();
if (typeof rp === "string" && // dots and empty were handled already
rp !== ".." && rp !== "" && rp !== ".") {
this.testString(e2, rp, rest.rest(), absolute);
} else if (rp === "..") {
const ep = e2.parent || e2;
this.subwalks.add(ep, rest);
} else if (rp instanceof RegExp) {
this.testRegExp(e2, rp, rest.rest(), absolute);
}
}
}
testRegExp(e2, p, rest, absolute) {
if (!p.test(e2.name))
return;
if (!rest) {
this.matches.add(e2, absolute, false);
} else {
this.subwalks.add(e2, rest);
}
}
testString(e2, p, rest, absolute) {
if (!e2.isNamed(p))
return;
if (!rest) {
this.matches.add(e2, absolute, false);
} else {
this.subwalks.add(e2, rest);
}
}
};
var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
var _onResume, _ignore, _sep, _GlobUtil_instances, ignored_fn, childrenIgnored_fn;
var GlobUtil = class {
constructor(patterns, path3, opts) {
__privateAdd(this, _GlobUtil_instances);
__publicField(this, "path");
__publicField(this, "patterns");
__publicField(this, "opts");
__publicField(this, "seen", /* @__PURE__ */ new Set());
__publicField(this, "paused", false);
__publicField(this, "aborted", false);
__privateAdd(this, _onResume, []);
__privateAdd(this, _ignore);
__privateAdd(this, _sep);
__publicField(this, "signal");
__publicField(this, "maxDepth");
__publicField(this, "includeChildMatches");
this.patterns = patterns;
this.path = path3;
this.opts = opts;
__privateSet(this, _sep, !opts.posix && opts.platform === "win32" ? "\\" : "/");
this.includeChildMatches = opts.includeChildMatches !== false;
if (opts.ignore || !this.includeChildMatches) {
__privateSet(this, _ignore, makeIgnore(opts.ignore ?? [], opts));
if (!this.includeChildMatches && typeof __privateGet(this, _ignore).add !== "function") {
const m = "cannot ignore child matches, ignore lacks add() method.";
throw new Error(m);
}
}
this.maxDepth = opts.maxDepth || Infinity;
if (opts.signal) {
this.signal = opts.signal;
this.signal.addEventListener("abort", () => {
__privateGet(this, _onResume).length = 0;
});
}
}
// backpressure mechanism
pause() {
this.paused = true;
}
resume() {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
return;
this.paused = false;
let fn = void 0;
while (!this.paused && (fn = __privateGet(this, _onResume).shift())) {
fn();
}
}
onResume(fn) {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
return;
if (!this.paused) {
fn();
} else {
__privateGet(this, _onResume).push(fn);
}
}
// do the requisite realpath/stat checking, and return the path
// to add or undefined to filter it out.
async matchCheck(e2, ifDir) {
if (ifDir && this.opts.nodir)
return void 0;
let rpc;
if (this.opts.realpath) {
rpc = e2.realpathCached() || await e2.realpath();
if (!rpc)
return void 0;
e2 = rpc;
}
const needStat = e2.isUnknown() || this.opts.stat;
const s = needStat ? await e2.lstat() : e2;
if (this.opts.follow && this.opts.nodir && (s == null ? void 0 : s.isSymbolicLink())) {
const target = await s.realpath();
if (target && (target.isUnknown() || this.opts.stat)) {
await target.lstat();
}
}
return this.matchCheckTest(s, ifDir);
}
matchCheckTest(e2, ifDir) {
var _a4;
return e2 && (this.maxDepth === Infinity || e2.depth() <= this.maxDepth) && (!ifDir || e2.canReaddir()) && (!this.opts.nodir || !e2.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e2.isSymbolicLink() || !((_a4 = e2.realpathCached()) == null ? void 0 : _a4.isDirectory())) && !__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, e2) ? e2 : void 0;
}
matchCheckSync(e2, ifDir) {
if (ifDir && this.opts.nodir)
return void 0;
let rpc;
if (this.opts.realpath) {
rpc = e2.realpathCached() || e2.realpathSync();
if (!rpc)
return void 0;
e2 = rpc;
}
const needStat = e2.isUnknown() || this.opts.stat;
const s = needStat ? e2.lstatSync() : e2;
if (this.opts.follow && this.opts.nodir && (s == null ? void 0 : s.isSymbolicLink())) {
const target = s.realpathSync();
if (target && ((target == null ? void 0 : target.isUnknown()) || this.opts.stat)) {
target.lstatSync();
}
}
return this.matchCheckTest(s, ifDir);
}
matchFinish(e2, absolute) {
var _a4;
if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, e2))
return;
if (!this.includeChildMatches && ((_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.add)) {
const ign = `${e2.relativePosix()}/**`;
__privateGet(this, _ignore).add(ign);
}
const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
this.seen.add(e2);
const mark = this.opts.mark && e2.isDirectory() ? __privateGet(this, _sep) : "";
if (this.opts.withFileTypes) {
this.matchEmit(e2);
} else if (abs) {
const abs2 = this.opts.posix ? e2.fullpathPosix() : e2.fullpath();
this.matchEmit(abs2 + mark);
} else {
const rel = this.opts.posix ? e2.relativePosix() : e2.relative();
const pre = this.opts.dotRelative && !rel.startsWith(".." + __privateGet(this, _sep)) ? "." + __privateGet(this, _sep) : "";
this.matchEmit(!rel ? "." + mark : pre + rel + mark);
}
}
async match(e2, absolute, ifDir) {
const p = await this.matchCheck(e2, ifDir);
if (p)
this.matchFinish(p, absolute);
}
matchSync(e2, absolute, ifDir) {
const p = this.matchCheckSync(e2, ifDir);
if (p)
this.matchFinish(p, absolute);
}
walkCB(target, patterns, cb) {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
cb();
this.walkCB2(target, patterns, new Processor(this.opts), cb);
}
walkCB2(target, patterns, processor, cb) {
var _a4;
if (__privateMethod(this, _GlobUtil_instances, childrenIgnored_fn).call(this, target))
return cb();
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
let tasks2 = 1;
const next = () => {
if (--tasks2 === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
continue;
tasks2++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const t2 of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
continue;
}
tasks2++;
const childrenCached = t2.readdirCached();
if (t2.calledReaddir())
this.walkCB3(t2, childrenCached, processor, next);
else {
t2.readdirCB((_, entries) => this.walkCB3(t2, entries, processor, next), true);
}
}
next();
}
walkCB3(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks2 = 1;
const next = () => {
if (--tasks2 === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
continue;
tasks2++;
this.match(m, absolute, ifDir).then(() => next());
}
for (const [target2, patterns] of processor.subwalks.entries()) {
tasks2++;
this.walkCB2(target2, patterns, processor.child(), next);
}
next();
}
walkCBSync(target, patterns, cb) {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
cb();
this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
}
walkCB2Sync(target, patterns, processor, cb) {
var _a4;
if (__privateMethod(this, _GlobUtil_instances, childrenIgnored_fn).call(this, target))
return cb();
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
cb();
if (this.paused) {
this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
return;
}
processor.processPatterns(target, patterns);
let tasks2 = 1;
const next = () => {
if (--tasks2 === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const t2 of processor.subwalkTargets()) {
if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
continue;
}
tasks2++;
const children = t2.readdirSync();
this.walkCB3Sync(t2, children, processor, next);
}
next();
}
walkCB3Sync(target, entries, processor, cb) {
processor = processor.filterEntries(target, entries);
let tasks2 = 1;
const next = () => {
if (--tasks2 === 0)
cb();
};
for (const [m, absolute, ifDir] of processor.matches.entries()) {
if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
continue;
this.matchSync(m, absolute, ifDir);
}
for (const [target2, patterns] of processor.subwalks.entries()) {
tasks2++;
this.walkCB2Sync(target2, patterns, processor.child(), next);
}
next();
}
};
_onResume = new WeakMap();
_ignore = new WeakMap();
_sep = new WeakMap();
_GlobUtil_instances = new WeakSet();
ignored_fn = function(path3) {
var _a4, _b3;
return this.seen.has(path3) || !!((_b3 = (_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.ignored) == null ? void 0 : _b3.call(_a4, path3));
};
childrenIgnored_fn = function(path3) {
var _a4, _b3;
return !!((_b3 = (_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.childrenIgnored) == null ? void 0 : _b3.call(_a4, path3));
};
var GlobWalker = class extends GlobUtil {
constructor(patterns, path3, opts) {
super(patterns, path3, opts);
__publicField(this, "matches", /* @__PURE__ */ new Set());
}
matchEmit(e2) {
this.matches.add(e2);
}
async walk() {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
await this.path.lstat();
}
await new Promise((res, rej) => {
this.walkCB(this.path, this.patterns, () => {
var _a5;
if ((_a5 = this.signal) == null ? void 0 : _a5.aborted) {
rej(this.signal.reason);
} else {
res(this.matches);
}
});
});
return this.matches;
}
walkSync() {
var _a4;
if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
throw this.signal.reason;
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => {
var _a5;
if ((_a5 = this.signal) == null ? void 0 : _a5.aborted)
throw this.signal.reason;
});
return this.matches;
}
};
var GlobStream = class extends GlobUtil {
constructor(patterns, path3, opts) {
super(patterns, path3, opts);
__publicField(this, "results");
this.results = new Minipass({
signal: this.signal,
objectMode: true
});
this.results.on("drain", () => this.resume());
this.results.on("resume", () => this.resume());
}
matchEmit(e2) {
this.results.write(e2);
if (!this.results.flowing)
this.pause();
}
stream() {
const target = this.path;
if (target.isUnknown()) {
target.lstat().then(() => {
this.walkCB(target, this.patterns, () => this.results.end());
});
} else {
this.walkCB(target, this.patterns, () => this.results.end());
}
return this.results;
}
streamSync() {
if (this.path.isUnknown()) {
this.path.lstatSync();
}
this.walkCBSync(this.path, this.patterns, () => this.results.end());
return this.results;
}
};
var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Glob = class {
/**
* All options are stored as properties on the `Glob` object.
*
* See {@link GlobOptions} for full options descriptions.
*
* Note that a previous `Glob` object can be passed as the
* `GlobOptions` to another `Glob` instantiation to re-use settings
* and caches with a new pattern.
*
* Traversal functions can be called multiple times to run the walk
* again.
*/
constructor(pattern2, opts) {
__publicField(this, "absolute");
__publicField(this, "cwd");
__publicField(this, "root");
__publicField(this, "dot");
__publicField(this, "dotRelative");
__publicField(this, "follow");
__publicField(this, "ignore");
__publicField(this, "magicalBraces");
__publicField(this, "mark");
__publicField(this, "matchBase");
__publicField(this, "maxDepth");
__publicField(this, "nobrace");
__publicField(this, "nocase");
__publicField(this, "nodir");
__publicField(this, "noext");
__publicField(this, "noglobstar");
__publicField(this, "pattern");
__publicField(this, "platform");
__publicField(this, "realpath");
__publicField(this, "scurry");
__publicField(this, "stat");
__publicField(this, "signal");
__publicField(this, "windowsPathsNoEscape");
__publicField(this, "withFileTypes");
__publicField(this, "includeChildMatches");
/**
* The options provided to the constructor.
*/
__publicField(this, "opts");
/**
* An array of parsed immutable {@link Pattern} objects.
*/
__publicField(this, "patterns");
if (!opts)
throw new TypeError("glob options required");
this.withFileTypes = !!opts.withFileTypes;
this.signal = opts.signal;
this.follow = !!opts.follow;
this.dot = !!opts.dot;
this.dotRelative = !!opts.dotRelative;
this.nodir = !!opts.nodir;
this.mark = !!opts.mark;
if (!opts.cwd) {
this.cwd = "";
} else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
opts.cwd = (0, import_node_url2.fileURLToPath)(opts.cwd);
}
this.cwd = opts.cwd || "";
this.root = opts.root;
this.magicalBraces = !!opts.magicalBraces;
this.nobrace = !!opts.nobrace;
this.noext = !!opts.noext;
this.realpath = !!opts.realpath;
this.absolute = opts.absolute;
this.includeChildMatches = opts.includeChildMatches !== false;
this.noglobstar = !!opts.noglobstar;
this.matchBase = !!opts.matchBase;
this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
this.stat = !!opts.stat;
this.ignore = opts.ignore;
if (this.withFileTypes && this.absolute !== void 0) {
throw new Error("cannot set absolute and withFileTypes:true");
}
if (typeof pattern2 === "string") {
pattern2 = [pattern2];
}
this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
if (this.windowsPathsNoEscape) {
pattern2 = pattern2.map((p) => p.replace(/\\/g, "/"));
}
if (this.matchBase) {
if (opts.noglobstar) {
throw new TypeError("base matching requires globstar");
}
pattern2 = pattern2.map((p) => p.includes("/") ? p : `./**/${p}`);
}
this.pattern = pattern2;
this.platform = opts.platform || defaultPlatform;
this.opts = { ...opts, platform: this.platform };
if (opts.scurry) {
this.scurry = opts.scurry;
if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
throw new Error("nocase option contradicts provided scurry option");
}
} else {
const Scurry = opts.platform === "win32" ? PathScurryWin32 : opts.platform === "darwin" ? PathScurryDarwin : opts.platform ? PathScurryPosix : PathScurry;
this.scurry = new Scurry(this.cwd, {
nocase: opts.nocase,
fs: opts.fs
});
}
this.nocase = this.scurry.nocase;
const nocaseMagicOnly = this.platform === "darwin" || this.platform === "win32";
const mmo = {
// default nocase based on platform
...opts,
dot: this.dot,
matchBase: this.matchBase,
nobrace: this.nobrace,
nocase: this.nocase,
nocaseMagicOnly,
nocomment: true,
noext: this.noext,
nonegate: true,
optimizationLevel: 2,
platform: this.platform,
windowsPathsNoEscape: this.windowsPathsNoEscape,
debug: !!this.opts.debug
};
const mms = this.pattern.map((p) => new Minimatch(p, mmo));
const [matchSet, globParts] = mms.reduce((set2, m) => {
set2[0].push(...m.set);
set2[1].push(...m.globParts);
return set2;
}, [[], []]);
this.patterns = matchSet.map((set2, i) => {
const g = globParts[i];
if (!g)
throw new Error("invalid pattern object");
return new Pattern(set2, g, 0, this.platform);
});
}
async walk() {
return [
...await new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).walk()
];
}
walkSync() {
return [
...new GlobWalker(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).walkSync()
];
}
stream() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).stream();
}
streamSync() {
return new GlobStream(this.patterns, this.scurry.cwd, {
...this.opts,
maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
platform: this.platform,
nocase: this.nocase,
includeChildMatches: this.includeChildMatches
}).streamSync();
}
/**
* Default sync iteration function. Returns a Generator that
* iterates over the results.
*/
iterateSync() {
return this.streamSync()[Symbol.iterator]();
}
[Symbol.iterator]() {
return this.iterateSync();
}
/**
* Default async iteration function. Returns an AsyncGenerator that
* iterates over the results.
*/
iterate() {
return this.stream()[Symbol.asyncIterator]();
}
[Symbol.asyncIterator]() {
return this.iterate();
}
};
var hasMagic = (pattern2, options2 = {}) => {
if (!Array.isArray(pattern2)) {
pattern2 = [pattern2];
}
for (const p of pattern2) {
if (new Minimatch(p, options2).hasMagic())
return true;
}
return false;
};
function globStreamSync(pattern2, options2 = {}) {
return new Glob(pattern2, options2).streamSync();
}
function globStream(pattern2, options2 = {}) {
return new Glob(pattern2, options2).stream();
}
function globSync(pattern2, options2 = {}) {
return new Glob(pattern2, options2).walkSync();
}
async function glob_(pattern2, options2 = {}) {
return new Glob(pattern2, options2).walk();
}
function globIterateSync(pattern2, options2 = {}) {
return new Glob(pattern2, options2).iterateSync();
}
function globIterate(pattern2, options2 = {}) {
return new Glob(pattern2, options2).iterate();
}
var streamSync = globStreamSync;
var stream$5 = Object.assign(globStream, { sync: globStreamSync });
var iterateSync = globIterateSync;
var iterate = Object.assign(globIterate, {
sync: globIterateSync
});
var sync$9 = Object.assign(globSync, {
stream: globStreamSync,
iterate: globIterateSync
});
var glob$1 = Object.assign(glob_, {
glob: glob_,
globSync,
sync: sync$9,
globStream,
stream: stream$5,
globStreamSync,
streamSync,
globIterate,
iterate,
globIterateSync,
iterateSync,
Glob,
hasMagic,
escape: escape$2,
unescape: unescape$1
});
glob$1.glob = glob$1;
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars$1.length; i++) {
const c = chars$1.charCodeAt(i);
intToChar[i] = c;
charToInt[c] = i;
}
var td = typeof TextDecoder !== "undefined" ? new TextDecoder() : typeof Buffer !== "undefined" ? {
decode(buf) {
const out2 = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out2.toString();
}
} : {
decode(buf) {
let out2 = "";
for (let i = 0; i < buf.length; i++) {
out2 += String.fromCharCode(buf[i]);
}
return out2;
}
};
function decode(mappings) {
const state = new Int32Array(5);
const decoded = [];
let index = 0;
do {
const semi = indexOf(mappings, index);
const line = [];
let sorted = true;
let lastCol = 0;
state[0] = 0;
for (let i = index; i < semi; i++) {
let seg;
i = decodeInteger(mappings, i, state, 0);
const col = state[0];
if (col < lastCol)
sorted = false;
lastCol = col;
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 1);
i = decodeInteger(mappings, i, state, 2);
i = decodeInteger(mappings, i, state, 3);
if (hasMoreVlq(mappings, i, semi)) {
i = decodeInteger(mappings, i, state, 4);
seg = [col, state[1], state[2], state[3], state[4]];
} else {
seg = [col, state[1], state[2], state[3]];
}
} else {
seg = [col];
}
line.push(seg);
}
if (!sorted)
sort(line);
decoded.push(line);
index = semi + 1;
} while (index <= mappings.length);
return decoded;
}
function indexOf(mappings, index) {
const idx = mappings.indexOf(";", index);
return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
let value2 = 0;
let shift = 0;
let integer = 0;
do {
const c = mappings.charCodeAt(pos++);
integer = charToInt[c];
value2 |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value2 & 1;
value2 >>>= 1;
if (shouldNegate) {
value2 = -2147483648 | -value2;
}
state[j] += value2;
return pos;
}
function hasMoreVlq(mappings, i, length) {
if (i >= length)
return false;
return mappings.charCodeAt(i) !== comma;
}
function sort(line) {
line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
return a[0] - b[0];
}
function encode$1(decoded) {
const state = new Int32Array(5);
const bufLength = 1024 * 16;
const subLength = bufLength - 36;
const buf = new Uint8Array(bufLength);
const sub = buf.subarray(0, subLength);
let pos = 0;
let out2 = "";
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) {
if (pos === bufLength) {
out2 += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
if (line.length === 0)
continue;
state[0] = 0;
for (let j = 0; j < line.length; j++) {
const segment = line[j];
if (pos > subLength) {
out2 += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
if (j > 0)
buf[pos++] = comma;
pos = encodeInteger(buf, pos, state, segment, 0);
if (segment.length === 1)
continue;
pos = encodeInteger(buf, pos, state, segment, 1);
pos = encodeInteger(buf, pos, state, segment, 2);
pos = encodeInteger(buf, pos, state, segment, 3);
if (segment.length === 4)
continue;
pos = encodeInteger(buf, pos, state, segment, 4);
}
}
return out2 + td.decode(buf.subarray(0, pos));
}
function encodeInteger(buf, pos, state, segment, j) {
const next = segment[j];
let num = next - state[j];
state[j] = next;
num = num < 0 ? -num << 1 | 1 : num << 1;
do {
let clamped = num & 31;
num >>>= 5;
if (num > 0)
clamped |= 32;
buf[pos++] = intToChar[clamped];
} while (num > 0);
return pos;
}
var BitSet = class _BitSet {
constructor(arg) {
this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
}
add(n2) {
this.bits[n2 >> 5] |= 1 << (n2 & 31);
}
has(n2) {
return !!(this.bits[n2 >> 5] & 1 << (n2 & 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.");
};
}
}
var btoa$1 = getBtoa();
var SourceMap$1 = class SourceMap {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode$1(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") {
this.x_google_ignoreList = properties.x_google_ignoreList;
}
}
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 min2 = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min2 + 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 = fromParts.length;
while (i--) fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
var toString$1 = Object.prototype.toString;
function isObject$2(thing) {
return toString$1.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j = lineOffsets.length;
while (i < j) {
const m = i + j >> 1;
if (index < lineOffsets[m]) {
j = m;
} else {
i = m + 1;
}
}
const line = i - 1;
const column = index - lineOffsets[line];
return { line, column };
};
}
var 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 segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
if (nameIndex >= 0) {
segment2.push(nameIndex);
}
this.rawSegments.push(segment2);
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 first2 = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (this.hires || first2 || 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);
}
}
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first2 = true;
} else {
loc.column += 1;
this.generatedCodeColumn += 1;
first2 = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str) return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
var n$1 = "\n";
var warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class _MagicString {
constructor(string2, options2 = {}) {
const chunk = new Chunk(0, string2.length, string2);
Object.defineProperties(this, {
original: { writable: true, value: string2 },
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: options2.filename },
indentExclusionRanges: { writable: true, value: options2.indentExclusionRanges },
sourcemapLocations: { writable: true, value: new BitSet() },
storedNames: { writable: true, value: {} },
indentStr: { writable: true, value: void 0 },
ignoreList: { writable: true, value: options2.ignoreList }
});
this.byStart[0] = chunk;
this.byEnd[string2.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) {
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) {
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 });
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(options2) {
options2 = options2 || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options2.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: options2.file ? options2.file.split(/[/\\]/).pop() : void 0,
sources: [
options2.source ? getRelativePath(options2.file || "", options2.source) : options2.file || ""
],
sourcesContent: options2.includeContent ? [this.original] : void 0,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
};
}
generateMap(options2) {
return new SourceMap$1(this.generateDecodedMap(options2));
}
_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, options2) {
const pattern2 = /^[^\r\n]/gm;
if (isObject$2(indentStr)) {
options2 = indentStr;
indentStr = void 0;
}
if (indentStr === void 0) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "") return this;
options2 = options2 || {};
const isExcluded = {};
if (options2.exclude) {
const exclusions = typeof options2.exclude[0] === "number" ? [options2.exclude] : options2.exclude;
exclusions.forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
isExcluded[i] = true;
}
});
}
let shouldIndentNextCharacter = options2.indentStart !== false;
const replacer = (match2) => {
if (shouldIndentNextCharacter) return `${indentStr}${match2}`;
shouldIndentNextCharacter = true;
return match2;
};
this.intro = this.intro.replace(pattern2, 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(pattern2, 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(pattern2, 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) {
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first2 = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first2.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 = first2;
if (newRight) newRight.previous = last;
if (!first2.previous) this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first2.previous;
this.lastChunk.next = null;
}
first2.previous = newLeft;
last.next = newRight || null;
if (!newLeft) this.firstChunk = first2;
if (!newRight) this.lastChunk = last;
return this;
}
overwrite(start, end, content, options2) {
options2 = options2 || {};
return this.update(start, end, content, { ...options2, overwrite: !options2.contentOnly });
}
update(start, end, content, options2) {
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
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 (options2 === 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;
}
options2 = { storeName: true };
}
const storeName = options2 !== void 0 ? options2.storeName : false;
const overwrite = options2 !== void 0 ? options2.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first2 = this.byStart[start];
const last = this.byEnd[end];
if (first2) {
let chunk = first2;
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);
}
first2.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) {
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) {
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) {
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) {
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$1);
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$1);
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n$1);
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n$1);
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n$1);
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length) {
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;
}
// TODO deprecate this? not really very useful
snip(start, end) {
const clone2 = this.clone();
clone2.remove(0, start);
clone2.remove(end, clone2.original.length);
return clone2;
}
_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 = 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 = 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(match2, str) {
if (typeof replacement === "string") {
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
if (i === "$") return "$";
if (i === "&") return match2[0];
const num = +i;
if (num < match2.length) return match2[+i];
return `$${i}`;
});
} else {
return replacement(...match2, match2.index, str, match2.groups);
}
}
function matchAll2(re, str) {
let match2;
const matches2 = [];
while (match2 = re.exec(str)) {
matches2.push(match2);
}
return matches2;
}
if (searchValue.global) {
const matches2 = matchAll2(searchValue, this.original);
matches2.forEach((match2) => {
if (match2.index != null) {
const replacement2 = getReplacement(match2, this.original);
if (replacement2 !== match2[0]) {
this.overwrite(
match2.index,
match2.index + match2[0].length,
replacement2
);
}
}
});
} else {
const match2 = this.original.match(searchValue);
if (match2 && match2.index != null) {
const replacement2 = getReplacement(match2, this.original);
if (replacement2 !== match2[0]) {
this.overwrite(
match2.index,
match2.index + match2[0].length,
replacement2
);
}
}
}
return this;
}
_replaceString(string2, replacement) {
const { original } = this;
const index = original.indexOf(string2);
if (index !== -1) {
this.overwrite(index, index + string2.length, replacement);
}
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") {
return this._replaceString(searchValue, replacement);
}
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string2, replacement) {
const { original } = this;
const stringLength = string2.length;
for (let index = original.indexOf(string2); index !== -1; index = original.indexOf(string2, index + stringLength)) {
const previous = original.slice(index, index + stringLength);
if (previous !== 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);
}
};
function isReference(node2, parent) {
if (node2.type === "MemberExpression") {
return !node2.computed && isReference(node2.object, node2);
}
if (node2.type === "Identifier") {
if (!parent)
return true;
switch (parent.type) {
case "MemberExpression":
return parent.computed || node2 === parent.object;
case "MethodDefinition":
return parent.computed;
case "FieldDefinition":
return parent.computed || node2 === parent.value;
case "Property":
return parent.computed || node2 === parent.value;
case "ExportSpecifier":
case "ImportSpecifier":
return node2 === parent.local;
case "LabeledStatement":
case "BreakStatement":
case "ContinueStatement":
return false;
default:
return true;
}
}
return false;
}
var version$2 = "26.0.1";
var peerDependencies = {
rollup: "^2.68.0||^3.0.0||^4.0.0"
};
function tryParse(parse4, code, id) {
try {
return parse4(code, { allowReturnOutsideFunction: true });
} catch (err2) {
err2.message += ` in ${id}`;
throw err2;
}
}
var firstpassGlobal = /\b(?:require|module|exports|global)\b/;
var firstpassNoGlobal = /\b(?:require|module|exports)\b/;
function hasCjsKeywords(code, ignoreGlobal) {
const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
return firstpass.test(code);
}
function analyzeTopLevelStatements(parse4, code, id) {
const ast = tryParse(parse4, code, id);
let isEsModule = false;
let hasDefaultExport = false;
let hasNamedExports = false;
for (const node2 of ast.body) {
switch (node2.type) {
case "ExportDefaultDeclaration":
isEsModule = true;
hasDefaultExport = true;
break;
case "ExportNamedDeclaration":
isEsModule = true;
if (node2.declaration) {
hasNamedExports = true;
} else {
for (const specifier of node2.specifiers) {
if (specifier.exported.name === "default") {
hasDefaultExport = true;
} else {
hasNamedExports = true;
}
}
}
break;
case "ExportAllDeclaration":
isEsModule = true;
if (node2.exported && node2.exported.name === "default") {
hasDefaultExport = true;
} else {
hasNamedExports = true;
}
break;
case "ImportDeclaration":
isEsModule = true;
break;
}
}
return { isEsModule, hasDefaultExport, hasNamedExports, ast };
}
function deconflict(scopes, globals, identifier) {
let i = 1;
let deconflicted = makeLegalIdentifier(identifier);
const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
while (hasConflicts()) {
deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
i += 1;
}
for (const scope of scopes) {
scope.declarations[deconflicted] = true;
}
return deconflicted;
}
function getName(id) {
const name2 = makeLegalIdentifier((0, import_path.basename)(id, (0, import_path.extname)(id)));
if (name2 !== "index") {
return name2;
}
return makeLegalIdentifier((0, import_path.basename)((0, import_path.dirname)(id)));
}
function normalizePathSlashes(path3) {
return path3.replace(/\\/g, "/");
}
var getVirtualPathForDynamicRequirePath = (path3, commonDir) => `/${normalizePathSlashes((0, import_path.relative)(commonDir, path3))}`;
function capitalize(name2) {
return name2[0].toUpperCase() + name2.slice(1);
}
function getStrictRequiresFilter({ strictRequires }) {
switch (strictRequires) {
case true:
return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
case void 0:
case "auto":
case "debug":
case null:
return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
case false:
return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
default:
if (typeof strictRequires === "string" || Array.isArray(strictRequires)) {
return {
strictRequiresFilter: createFilter$1(strictRequires),
detectCyclesAndConditional: false
};
}
throw new Error('Unexpected value for "strictRequires" option.');
}
}
function getPackageEntryPoint(dirPath) {
let entryPoint = "index.js";
try {
if ((0, import_fs.existsSync)((0, import_path.join)(dirPath, "package.json"))) {
entryPoint = JSON.parse((0, import_fs.readFileSync)((0, import_path.join)(dirPath, "package.json"), { encoding: "utf8" })).main || entryPoint;
}
} catch (ignored) {
}
return entryPoint;
}
function isDirectory$1(path3) {
try {
if ((0, import_fs.statSync)(path3).isDirectory()) return true;
} catch (ignored) {
}
return false;
}
function getDynamicRequireModules(patterns, dynamicRequireRoot) {
const dynamicRequireModules = /* @__PURE__ */ new Map();
const dirNames = /* @__PURE__ */ new Set();
for (const pattern2 of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
const isNegated = pattern2.startsWith("!");
const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath);
for (const path3 of glob$1.sync(isNegated ? pattern2.substr(1) : pattern2).sort((a, b) => a.localeCompare(b, "en"))) {
const resolvedPath = (0, import_path.resolve)(path3);
const requirePath = normalizePathSlashes(resolvedPath);
if (isDirectory$1(resolvedPath)) {
dirNames.add(resolvedPath);
const modulePath = (0, import_path.resolve)((0, import_path.join)(resolvedPath, getPackageEntryPoint(path3)));
modifyMap(requirePath, modulePath);
modifyMap(normalizePathSlashes(modulePath), modulePath);
} else {
dirNames.add((0, import_path.dirname)(resolvedPath));
modifyMap(requirePath, resolvedPath);
}
}
}
return {
commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
dynamicRequireModules
};
}
var FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
var COMMONJS_REQUIRE_EXPORT = "commonjsRequire";
var CREATE_COMMONJS_REQUIRE_EXPORT = "createCommonjsRequire";
function getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires) {
if (!isDynamicRequireModulesEnabled) {
return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
${FAILED_REQUIRE_ERROR}
}`;
}
const dynamicModuleImports = [...dynamicRequireModules.values()].map(
(id, index) => `import ${id.endsWith(".json") ? `json${index}` : `{ __require as require${index} }`} from ${JSON.stringify(id)};`
).join("\n");
const dynamicModuleProps = [...dynamicRequireModules.keys()].map(
(id, index) => ` ${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${id.endsWith(".json") ? `function () { return json${index}; }` : `require${index}`}`
).join(",\n");
return `${dynamicModuleImports}
var dynamicModules;
function getDynamicModules() {
return dynamicModules || (dynamicModules = {
${dynamicModuleProps}
});
}
export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
function handleRequire(path) {
var resolvedPath = commonjsResolve(path, originalModuleDir);
if (resolvedPath !== null) {
return getDynamicModules()[resolvedPath]();
}
${ignoreDynamicRequires ? "return require(path);" : FAILED_REQUIRE_ERROR}
}
handleRequire.resolve = function (path) {
var resolvedPath = commonjsResolve(path, originalModuleDir);
if (resolvedPath !== null) {
return resolvedPath;
}
return require.resolve(path);
}
return handleRequire;
}
function commonjsResolve (path, originalModuleDir) {
var shouldTryNodeModules = isPossibleNodeModulesPath(path);
path = normalize(path);
var relPath;
if (path[0] === '/') {
originalModuleDir = '';
}
var modules = getDynamicModules();
var checkedExtensions = ['', '.js', '.json'];
while (true) {
if (!shouldTryNodeModules) {
relPath = normalize(originalModuleDir + '/' + path);
} else {
relPath = normalize(originalModuleDir + '/node_modules/' + path);
}
if (relPath.endsWith('/..')) {
break; // Travelled too far up, avoid infinite loop
}
for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
var resolvedPath = relPath + checkedExtensions[extensionIndex];
if (modules[resolvedPath]) {
return resolvedPath;
}
}
if (!shouldTryNodeModules) break;
var nextDir = normalize(originalModuleDir + '/..');
if (nextDir === originalModuleDir) break;
originalModuleDir = nextDir;
}
return null;
}
function isPossibleNodeModulesPath (modulePath) {
var c0 = modulePath[0];
if (c0 === '/' || c0 === '\\\\') return false;
var c1 = modulePath[1], c2 = modulePath[2];
if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
(c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
return true;
}
function normalize (path) {
path = path.replace(/\\\\/g, '/');
var parts = path.split('/');
var slashed = parts[0] === '';
for (var i = 1; i < parts.length; i++) {
if (parts[i] === '.' || parts[i] === '') {
parts.splice(i--, 1);
}
}
for (var i = 1; i < parts.length; i++) {
if (parts[i] !== '..') continue;
if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
parts.splice(--i, 2);
i--;
}
}
path = parts.join('/');
if (slashed && path[0] !== '/') path = '/' + path;
else if (path.length === 0) path = '.';
return path;
}`;
}
var isWrappedId = (id, suffix) => id.endsWith(suffix);
var wrapId = (id, suffix) => `\0${id}${suffix}`;
var unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
var PROXY_SUFFIX = "?commonjs-proxy";
var WRAPPED_SUFFIX = "?commonjs-wrapped";
var EXTERNAL_SUFFIX = "?commonjs-external";
var EXPORTS_SUFFIX = "?commonjs-exports";
var MODULE_SUFFIX = "?commonjs-module";
var ENTRY_SUFFIX = "?commonjs-entry";
var ES_IMPORT_SUFFIX = "?commonjs-es-import";
var DYNAMIC_MODULES_ID = "\0commonjs-dynamic-modules";
var HELPERS_ID = "\0commonjsHelpers.js";
var IS_WRAPPED_COMMONJS = "withRequireFunction";
var HELPERS = `
export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
export function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
export function getDefaultExportFromNamespaceIfPresent (n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
}
export function getDefaultExportFromNamespaceIfNotNamed (n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
}
export function getAugmentedNamespace(n) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == "function") {
var a = function a () {
if (this instanceof a) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, '__esModule', {value: true});
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(a, k, d.get ? d : {
enumerable: true,
get: function () {
return n[k];
}
});
});
return a;
}
`;
function getHelpersModule() {
return HELPERS;
}
function getUnknownRequireProxy(id, requireReturnsDefault) {
if (requireReturnsDefault === true || id.endsWith(".json")) {
return `export { default } from ${JSON.stringify(id)};`;
}
const name2 = getName(id);
const exported = requireReturnsDefault === "auto" ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name2});` : requireReturnsDefault === "preferred" ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name2});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name2});` : `export default ${name2};`;
return `import * as ${name2} from ${JSON.stringify(id)}; ${exported}`;
}
async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
const name2 = getName(id);
const {
meta: { commonjs: commonjsMeta }
} = await loadModule({ id });
if (!commonjsMeta) {
return getUnknownRequireProxy(id, requireReturnsDefault);
}
if (commonjsMeta.isCommonJS) {
return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
}
if (!requireReturnsDefault) {
return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name2} from ${JSON.stringify(
id
)}; export default /*@__PURE__*/getAugmentedNamespace(${name2});`;
}
if (requireReturnsDefault !== true && (requireReturnsDefault === "namespace" || !commonjsMeta.hasDefaultExport || requireReturnsDefault === "auto" && commonjsMeta.hasNamedExports)) {
return `import * as ${name2} from ${JSON.stringify(id)}; export default ${name2};`;
}
return `export { default } from ${JSON.stringify(id)};`;
}
function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
const {
meta: { commonjs: commonjsMeta },
hasDefaultExport
} = getModuleInfo(id);
if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
const stringifiedId = JSON.stringify(id);
let code = `export * from ${stringifiedId};`;
if (hasDefaultExport) {
code += `export { default } from ${stringifiedId};`;
}
return shebang + code;
}
const result = getEsImportProxy(id, defaultIsModuleExports);
return {
...result,
code: shebang + result.code
};
}
function getEsImportProxy(id, defaultIsModuleExports) {
const name2 = getName(id);
const exportsName = `${name2}Exports`;
const requireModule = `require${capitalize(name2)}`;
let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";
import { __require as ${requireModule} } from ${JSON.stringify(id)};
var ${exportsName} = ${requireModule}();
export { ${exportsName} as __moduleExports };`;
if (defaultIsModuleExports === true) {
code += `
export { ${exportsName} as default };`;
} else {
code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
}
return {
code,
syntheticNamedExports: "__moduleExports"
};
}
function getCandidatesForExtension(resolved, extension2) {
return [resolved + extension2, `${resolved}${import_path.sep}index${extension2}`];
}
function getCandidates(resolved, extensions2) {
return extensions2.reduce(
(paths, extension2) => paths.concat(getCandidatesForExtension(resolved, extension2)),
[resolved]
);
}
function resolveExtensions(importee, importer, extensions2) {
if (importee[0] !== "." || !importer) return void 0;
const resolved = (0, import_path.resolve)((0, import_path.dirname)(importer), importee);
const candidates = getCandidates(resolved, extensions2);
for (let i = 0; i < candidates.length; i += 1) {
try {
const stats = (0, import_fs.statSync)(candidates[i]);
if (stats.isFile()) return { id: candidates[i] };
} catch (err2) {
}
}
return void 0;
}
function getResolveId(extensions2, isPossibleCjsId) {
const currentlyResolving = /* @__PURE__ */ new Map();
return {
/**
* This is a Maps of importers to Sets of require sources being resolved at
* the moment by resolveRequireSourcesAndUpdateMeta
*/
currentlyResolving,
async resolveId(importee, importer, resolveOptions) {
const customOptions = resolveOptions.custom;
if (customOptions && customOptions["node-resolve"] && customOptions["node-resolve"].isRequire) {
return null;
}
const currentlyResolvingForParent = currentlyResolving.get(importer);
if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
this.warn({
code: "THIS_RESOLVE_WITHOUT_OPTIONS",
message: 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
url: "https://rollupjs.org/guide/en/#resolveid"
});
return null;
}
if (isWrappedId(importee, WRAPPED_SUFFIX)) {
return unwrapId(importee, WRAPPED_SUFFIX);
}
if (importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) {
return importee;
}
if (importer) {
if (importer === DYNAMIC_MODULES_ID || // Proxies are only importing resolved ids, no need to resolve again
isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX)) {
return importee;
}
if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
if (!await this.resolve(
importee,
importer,
Object.assign({ skipSelf: true }, resolveOptions)
)) {
return null;
}
return { id: importee, external: true };
}
}
if (importee.startsWith("\0")) {
return null;
}
const resolved = await this.resolve(
importee,
importer,
Object.assign({ skipSelf: true }, resolveOptions)
) || resolveExtensions(importee, importer, extensions2);
if (!resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id)) {
return resolved;
}
const moduleInfo = await this.load(resolved);
const {
meta: { commonjs: commonjsMeta }
} = moduleInfo;
if (commonjsMeta) {
const { isCommonJS } = commonjsMeta;
if (isCommonJS) {
if (resolveOptions.isEntry) {
moduleInfo.moduleSideEffects = true;
return resolved.id + ENTRY_SUFFIX;
}
if (isCommonJS === IS_WRAPPED_COMMONJS) {
return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
}
}
}
return resolved;
}
};
}
function getRequireResolver(extensions2, detectCyclesAndConditional, currentlyResolving) {
const knownCjsModuleTypes = /* @__PURE__ */ Object.create(null);
const requiredIds = /* @__PURE__ */ Object.create(null);
const unconditionallyRequiredIds = /* @__PURE__ */ Object.create(null);
const dependencies = /* @__PURE__ */ Object.create(null);
const getDependencies = (id) => dependencies[id] || (dependencies[id] = /* @__PURE__ */ new Set());
const isCyclic = (id) => {
const dependenciesToCheck = new Set(getDependencies(id));
for (const dependency of dependenciesToCheck) {
if (dependency === id) {
return true;
}
for (const childDependency of getDependencies(dependency)) {
dependenciesToCheck.add(childDependency);
}
}
return false;
};
const fullyAnalyzedModules = /* @__PURE__ */ Object.create(null);
const getTypeForFullyAnalyzedModule = (id) => {
const knownType = knownCjsModuleTypes[id];
if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
return knownType;
}
if (isCyclic(id)) {
return knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
}
return knownType;
};
const setInitialParentType = (id, initialCommonJSType) => {
if (fullyAnalyzedModules[id]) {
return;
}
knownCjsModuleTypes[id] = initialCommonJSType;
if (detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id]) {
knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
}
};
const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
const childId = resolved.id;
requiredIds[childId] = true;
if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
unconditionallyRequiredIds[childId] = true;
}
getDependencies(parentId).add(childId);
if (!isCyclic(childId)) {
await loadModule(resolved);
}
};
const getTypeForImportedModule = async (resolved, loadModule) => {
if (resolved.id in knownCjsModuleTypes) {
return knownCjsModuleTypes[resolved.id];
}
const {
meta: { commonjs: commonjs2 }
} = await loadModule(resolved);
return commonjs2 && commonjs2.isCommonJS || false;
};
return {
getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter(
(id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
),
isRequiredId: (id) => requiredIds[id],
async shouldTransformCachedModule({
id: parentId,
resolvedSources,
meta: { commonjs: parentMeta }
}) {
if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
const parentRequires = parentMeta && parentMeta.requires;
if (parentRequires) {
setInitialParentType(parentId, parentMeta.initialCommonJSType);
await Promise.all(
parentRequires.map(
({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load)
)
);
if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
return true;
}
for (const {
resolved: { id }
} of parentRequires) {
if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
return true;
}
}
fullyAnalyzedModules[parentId] = true;
for (const {
resolved: { id }
} of parentRequires) {
fullyAnalyzedModules[id] = true;
}
}
const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
return (await Promise.all(
Object.keys(resolvedSources).map((source) => resolvedSources[source]).filter(({ id, external }) => !(external || parentRequireSet.has(id))).map(async (resolved) => {
if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
return await getTypeForImportedModule(
(await this.load({ id: resolved.id })).meta.commonjs.resolved,
this.load
) !== IS_WRAPPED_COMMONJS;
}
return await getTypeForImportedModule(resolved, this.load) === IS_WRAPPED_COMMONJS;
})
)).some((shouldTransform) => shouldTransform);
},
/* eslint-disable no-param-reassign */
resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
parentMeta.initialCommonJSType = isParentCommonJS;
parentMeta.requires = [];
parentMeta.isRequiredCommonJS = /* @__PURE__ */ Object.create(null);
setInitialParentType(parentId, isParentCommonJS);
const currentlyResolvingForParent = currentlyResolving.get(parentId) || /* @__PURE__ */ new Set();
currentlyResolving.set(parentId, currentlyResolvingForParent);
const requireTargets = await Promise.all(
sources.map(async ({ source, isConditional }) => {
if (source.startsWith("\0")) {
return { id: source, allowProxy: false };
}
currentlyResolvingForParent.add(source);
const resolved = await rollupContext.resolve(source, parentId, {
skipSelf: false,
custom: { "node-resolve": { isRequire: true } }
}) || resolveExtensions(source, parentId, extensions2);
currentlyResolvingForParent.delete(source);
if (!resolved) {
return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
}
const childId = resolved.id;
if (resolved.external) {
return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
}
parentMeta.requires.push({ resolved, isConditional });
await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
return { id: childId, allowProxy: true };
})
);
parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
fullyAnalyzedModules[parentId] = true;
return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
const isCommonJS = parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId);
fullyAnalyzedModules[dependencyId] = true;
return {
source: sources[index].source,
id: allowProxy ? isCommonJS === IS_WRAPPED_COMMONJS ? wrapId(dependencyId, WRAPPED_SUFFIX) : wrapId(dependencyId, PROXY_SUFFIX) : dependencyId,
isCommonJS
};
});
},
isCurrentlyResolving(source, parentId) {
const currentlyResolvingForParent = currentlyResolving.get(parentId);
return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
}
};
}
function validateVersion(actualVersion, peerDependencyVersion, name2) {
const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
let minMajor = Infinity;
let minMinor = Infinity;
let minPatch = Infinity;
let foundVersion;
while (foundVersion = versionRegexp.exec(peerDependencyVersion)) {
const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number);
if (foundMajor < minMajor) {
minMajor = foundMajor;
minMinor = foundMinor;
minPatch = foundPatch;
}
}
if (!actualVersion) {
throw new Error(
`Insufficient ${name2} version: "@rollup/plugin-commonjs" requires at least ${name2}@${minMajor}.${minMinor}.${minPatch}.`
);
}
const [major, minor, patch] = actualVersion.split(".").map(Number);
if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) {
throw new Error(
`Insufficient ${name2} version: "@rollup/plugin-commonjs" requires at least ${name2}@${minMajor}.${minMinor}.${minPatch} but found ${name2}@${actualVersion}.`
);
}
}
var operators = {
"==": (x) => equals(x.left, x.right, false),
"!=": (x) => not(operators["=="](x)),
"===": (x) => equals(x.left, x.right, true),
"!==": (x) => not(operators["==="](x)),
"!": (x) => isFalsy(x.argument),
"&&": (x) => isTruthy(x.left) && isTruthy(x.right),
"||": (x) => isTruthy(x.left) || isTruthy(x.right)
};
function not(value2) {
return value2 === null ? value2 : !value2;
}
function equals(a, b, strict) {
if (a.type !== b.type) return null;
if (a.type === "Literal") return strict ? a.value === b.value : a.value == b.value;
return null;
}
function isTruthy(node2) {
if (!node2) return false;
if (node2.type === "Literal") return !!node2.value;
if (node2.type === "ParenthesizedExpression") return isTruthy(node2.expression);
if (node2.operator in operators) return operators[node2.operator](node2);
return null;
}
function isFalsy(node2) {
return not(isTruthy(node2));
}
function getKeypath(node2) {
const parts = [];
while (node2.type === "MemberExpression") {
if (node2.computed) return null;
parts.unshift(node2.property.name);
node2 = node2.object;
}
if (node2.type !== "Identifier") return null;
const { name: name2 } = node2;
parts.unshift(name2);
return { name: name2, keypath: parts.join(".") };
}
var KEY_COMPILED_ESM = "__esModule";
function getDefineCompiledEsmType(node2) {
const definedPropertyWithExports = getDefinePropertyCallName(node2, "exports");
const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node2, "module.exports");
if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
return isTruthy(definedProperty.value) ? definedPropertyWithExports ? "exports" : "module" : false;
}
return false;
}
function getDefinePropertyCallName(node2, targetName) {
const {
callee: { object, property }
} = node2;
if (!object || object.type !== "Identifier" || object.name !== "Object") return;
if (!property || property.type !== "Identifier" || property.name !== "defineProperty") return;
if (node2.arguments.length !== 3) return;
const targetNames = targetName.split(".");
const [target, key, value2] = node2.arguments;
if (targetNames.length === 1) {
if (target.type !== "Identifier" || target.name !== targetNames[0]) {
return;
}
}
if (targetNames.length === 2) {
if (target.type !== "MemberExpression" || target.object.name !== targetNames[0] || target.property.name !== targetNames[1]) {
return;
}
}
if (value2.type !== "ObjectExpression" || !value2.properties) return;
const valueProperty = value2.properties.find((p) => p.key && p.key.name === "value");
if (!valueProperty || !valueProperty.value) return;
return { key: key.value, value: valueProperty.value };
}
function isShorthandProperty(parent) {
return parent && parent.type === "Property" && parent.shorthand;
}
function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
const args = [];
const passedArgs = [];
if (uses.module) {
args.push("module");
passedArgs.push(moduleName);
}
if (uses.exports) {
args.push("exports");
passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
}
magicString.trim().indent(" ", { exclude: indentExclusionRanges }).prepend(`(function (${args.join(", ")}) {
`).append(`
} (${passedArgs.join(", ")}));`);
}
function rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName) {
const exports2 = [];
const exportDeclarations = [];
if (usesRequireWrapper) {
getExportsWhenUsingRequireWrapper(
magicString,
wrapped,
exportMode,
exports2,
moduleExportsAssignments,
exportsAssignmentsByName,
moduleName,
exportsName,
requireName,
defineCompiledEsmExpressions
);
} else if (exportMode === "replace") {
getExportsForReplacedModuleExports(
magicString,
exports2,
exportDeclarations,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsName,
defaultIsModuleExports,
HELPERS_NAME
);
} else {
if (exportMode === "module") {
exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
exports2.push(`${exportedExportsName} as __moduleExports`);
} else {
exports2.push(`${exportsName} as __moduleExports`);
}
if (wrapped) {
exportDeclarations.push(
getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
);
} else {
getExports(
magicString,
exports2,
exportDeclarations,
moduleExportsAssignments,
exportsAssignmentsByName,
deconflictedExportNames,
topLevelAssignments,
moduleName,
exportsName,
exportedExportsName,
defineCompiledEsmExpressions,
HELPERS_NAME,
defaultIsModuleExports,
exportMode
);
}
}
if (exports2.length) {
exportDeclarations.push(`export { ${exports2.join(", ")} }`);
}
return `
${exportDeclarations.join(";\n")};`;
}
function getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports2, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions) {
exports2.push(`${requireName} as __require`);
if (wrapped) return;
if (exportMode === "replace") {
rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
} else {
rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
for (const [exportName, { nodes }] of exportsAssignmentsByName) {
for (const { node: node2, type } of nodes) {
magicString.overwrite(
node2.start,
node2.left.end,
`${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`
);
}
}
replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
defineCompiledEsmExpressions,
magicString,
exportMode,
moduleName,
exportsName
);
}
}
function getExportsForReplacedModuleExports(magicString, exports2, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME) {
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, exportsName);
}
magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, "var ");
exports2.push(`${exportsName} as __moduleExports`);
exportDeclarations.push(
getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
);
}
function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
return `export default ${defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`}`;
}
function getExports(magicString, exports2, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode) {
let deconflictedDefaultExportName;
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
}
for (const [exportName, { nodes }] of exportsAssignmentsByName) {
const deconflicted = deconflictedExportNames[exportName];
let needsDeclaration = true;
for (const { node: node2, type } of nodes) {
let replacement = `${deconflicted} = ${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`;
if (needsDeclaration && topLevelAssignments.has(node2)) {
replacement = `var ${replacement}`;
needsDeclaration = false;
}
magicString.overwrite(node2.start, node2.left.end, replacement);
}
if (needsDeclaration) {
magicString.prepend(`var ${deconflicted};
`);
}
if (exportName === "default") {
deconflictedDefaultExportName = deconflicted;
} else {
exports2.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
}
}
const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
defineCompiledEsmExpressions,
magicString,
exportMode,
moduleName,
exportsName
);
if (defaultIsModuleExports === false || defaultIsModuleExports === "auto" && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) {
exports2.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
} else if (defaultIsModuleExports === true || !isRestorableCompiledEsm && moduleExportsAssignments.length === 0) {
exports2.push(`${exportedExportsName} as default`);
} else {
exportDeclarations.push(
getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
);
}
}
function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
for (const { left } of moduleExportsAssignments) {
magicString.overwrite(left.start, left.end, exportsName);
}
}
function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName) {
let isRestorableCompiledEsm = false;
for (const { node: node2, type } of defineCompiledEsmExpressions) {
isRestorableCompiledEsm = true;
const moduleExportsExpression = node2.type === "CallExpression" ? node2.arguments[0] : node2.left.object;
magicString.overwrite(
moduleExportsExpression.start,
moduleExportsExpression.end,
exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName
);
}
return isRestorableCompiledEsm;
}
function isRequireExpression(node2, scope) {
if (!node2) return false;
if (node2.type !== "CallExpression") return false;
if (node2.arguments.length === 0) return false;
return isRequire(node2.callee, scope);
}
function isRequire(node2, scope) {
return node2.type === "Identifier" && node2.name === "require" && !scope.contains("require") || node2.type === "MemberExpression" && isModuleRequire(node2, scope);
}
function isModuleRequire({ object, property }, scope) {
return object.type === "Identifier" && object.name === "module" && property.type === "Identifier" && property.name === "require" && !scope.contains("module");
}
function hasDynamicArguments(node2) {
return node2.arguments.length > 1 || node2.arguments[0].type !== "Literal" && (node2.arguments[0].type !== "TemplateLiteral" || node2.arguments[0].expressions.length > 0);
}
var reservedMethod = { resolve: true, cache: true, main: true };
function isNodeRequirePropertyAccess(parent) {
return parent && parent.property && reservedMethod[parent.property.name];
}
function getRequireStringArg(node2) {
return node2.arguments[0].type === "Literal" ? node2.arguments[0].value : node2.arguments[0].quasis[0].value.cooked;
}
function getRequireHandlers() {
const requireExpressions = [];
function addRequireExpression(sourceId, node2, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved) {
requireExpressions.push({
sourceId,
node: node2,
scope,
usesReturnValue,
isInsideTryBlock,
isInsideConditional,
toBeRemoved
});
}
async function rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta) {
const imports = [];
imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
if (dynamicRequireName) {
imports.push(
`import { ${isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
);
}
if (exportMode === "module") {
imports.push(
`import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`,
`var ${exportsName} = ${moduleName}.exports`
);
} else if (exportMode === "exports") {
imports.push(
`import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
);
}
const requiresBySource = collectSources(requireExpressions);
const requireTargets = await resolveRequireSourcesAndUpdateMeta(
id,
needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
commonjsMeta,
Object.keys(requiresBySource).map((source) => {
return {
source,
isConditional: requiresBySource[source].every((require3) => require3.isInsideConditional)
};
})
);
processRequireExpressions(
imports,
requireTargets,
requiresBySource,
getIgnoreTryCatchRequireStatementMode,
magicString
);
return imports.length ? `${imports.join(";\n")};
` : "";
}
return {
addRequireExpression,
rewriteRequireExpressionsAndGetImportBlock
};
}
function collectSources(requireExpressions) {
const requiresBySource = /* @__PURE__ */ Object.create(null);
for (const requireExpression of requireExpressions) {
const { sourceId } = requireExpression;
if (!requiresBySource[sourceId]) {
requiresBySource[sourceId] = [];
}
const requires = requiresBySource[sourceId];
requires.push(requireExpression);
}
return requiresBySource;
}
function processRequireExpressions(imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString) {
const generateRequireName = getGenerateRequireName();
for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
const requires = requiresBySource[source];
const name2 = generateRequireName(requires);
let usesRequired = false;
let needsImport = false;
for (const { node: node2, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : { canConvertRequire: true, shouldRemoveRequire: false };
if (shouldRemoveRequire) {
if (usesReturnValue) {
magicString.overwrite(node2.start, node2.end, "undefined");
} else {
magicString.remove(toBeRemoved.start, toBeRemoved.end);
}
} else if (canConvertRequire) {
needsImport = true;
if (isCommonJS === IS_WRAPPED_COMMONJS) {
magicString.overwrite(node2.start, node2.end, `${name2}()`);
} else if (usesReturnValue) {
usesRequired = true;
magicString.overwrite(node2.start, node2.end, name2);
} else {
magicString.remove(toBeRemoved.start, toBeRemoved.end);
}
}
}
if (needsImport) {
if (isCommonJS === IS_WRAPPED_COMMONJS) {
imports.push(`import { __require as ${name2} } from ${JSON.stringify(resolvedId)}`);
} else {
imports.push(`import ${usesRequired ? `${name2} from ` : ""}${JSON.stringify(resolvedId)}`);
}
}
}
}
function getGenerateRequireName() {
let uid = 0;
return (requires) => {
let name2;
const hasNameConflict = ({ scope }) => scope.contains(name2);
do {
name2 = `require$$${uid}`;
uid += 1;
} while (requires.some(hasNameConflict));
return name2;
};
}
var exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
var functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
async function transformCommonjs(parse4, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta) {
const ast = astCache || tryParse(parse4, code, id);
const magicString = new MagicString(code);
const uses = {
module: false,
exports: false,
global: false,
require: false
};
const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath((0, import_path.dirname)(id), commonDir);
let scope = attachScopes(ast, "scope");
let lexicalDepth = 0;
let programDepth = 0;
let classBodyDepth = 0;
let currentTryBlockEnd = null;
let shouldWrap = false;
const globals = /* @__PURE__ */ new Set();
let currentConditionalNodeEnd = null;
const conditionalNodes = /* @__PURE__ */ new Set();
const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
const reassignedNames = /* @__PURE__ */ new Set();
const topLevelDeclarations = [];
const skippedNodes = /* @__PURE__ */ new Set();
const moduleAccessScopes = /* @__PURE__ */ new Set([scope]);
const exportsAccessScopes = /* @__PURE__ */ new Set([scope]);
const moduleExportsAssignments = [];
let firstTopLevelModuleExportsAssignment = null;
const exportsAssignmentsByName = /* @__PURE__ */ new Map();
const topLevelAssignments = /* @__PURE__ */ new Set();
const topLevelDefineCompiledEsmExpressions = [];
const replacedGlobal = [];
const replacedDynamicRequires = [];
const importedVariables = /* @__PURE__ */ new Set();
const indentExclusionRanges = [];
walk$3(ast, {
enter(node2, parent) {
if (skippedNodes.has(node2)) {
this.skip();
return;
}
if (currentTryBlockEnd !== null && node2.start > currentTryBlockEnd) {
currentTryBlockEnd = null;
}
if (currentConditionalNodeEnd !== null && node2.start > currentConditionalNodeEnd) {
currentConditionalNodeEnd = null;
}
if (currentConditionalNodeEnd === null && conditionalNodes.has(node2)) {
currentConditionalNodeEnd = node2.end;
}
programDepth += 1;
if (node2.scope) ({ scope } = node2);
if (functionType.test(node2.type)) lexicalDepth += 1;
if (sourceMap) {
magicString.addSourcemapLocation(node2.start);
magicString.addSourcemapLocation(node2.end);
}
switch (node2.type) {
case "AssignmentExpression":
if (node2.left.type === "MemberExpression") {
const flattened = getKeypath(node2.left);
if (!flattened || scope.contains(flattened.name)) return;
const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
if (!exportsPatternMatch || flattened.keypath === "exports") return;
const [, exportName] = exportsPatternMatch;
uses[flattened.name] = true;
if (flattened.keypath === "module.exports") {
moduleExportsAssignments.push(node2);
if (programDepth > 3) {
moduleAccessScopes.add(scope);
} else if (!firstTopLevelModuleExportsAssignment) {
firstTopLevelModuleExportsAssignment = node2;
}
} else if (exportName === KEY_COMPILED_ESM) {
if (programDepth > 3) {
shouldWrap = true;
} else {
topLevelDefineCompiledEsmExpressions.push({ node: node2, type: flattened.name });
}
} else {
const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
nodes: [],
scopes: /* @__PURE__ */ new Set()
};
exportsAssignments.nodes.push({ node: node2, type: flattened.name });
exportsAssignments.scopes.add(scope);
exportsAccessScopes.add(scope);
exportsAssignmentsByName.set(exportName, exportsAssignments);
if (programDepth <= 3) {
topLevelAssignments.add(node2);
}
}
skippedNodes.add(node2.left);
} else {
for (const name2 of extractAssignedNames(node2.left)) {
reassignedNames.add(name2);
}
}
return;
case "CallExpression": {
const defineCompiledEsmType = getDefineCompiledEsmType(node2);
if (defineCompiledEsmType) {
if (programDepth === 3 && parent.type === "ExpressionStatement") {
skippedNodes.add(node2.arguments[0]);
topLevelDefineCompiledEsmExpressions.push({ node: node2, type: defineCompiledEsmType });
} else {
shouldWrap = true;
}
return;
}
if (isDynamicRequireModulesEnabled && node2.callee.object && isRequire(node2.callee.object, scope) && node2.callee.property.name === "resolve") {
checkDynamicRequire(node2.start);
uses.require = true;
const requireNode2 = node2.callee.object;
replacedDynamicRequires.push(requireNode2);
skippedNodes.add(node2.callee);
return;
}
if (!isRequireExpression(node2, scope)) {
const keypath = getKeypath(node2.callee);
if (keypath && importedVariables.has(keypath.name)) {
currentConditionalNodeEnd = Infinity;
}
return;
}
skippedNodes.add(node2.callee);
uses.require = true;
if (hasDynamicArguments(node2)) {
if (isDynamicRequireModulesEnabled) {
checkDynamicRequire(node2.start);
}
if (!ignoreDynamicRequires) {
replacedDynamicRequires.push(node2.callee);
}
return;
}
const requireStringArg = getRequireStringArg(node2);
if (!ignoreRequire(requireStringArg)) {
const usesReturnValue = parent.type !== "ExpressionStatement";
const toBeRemoved = parent.type === "ExpressionStatement" && (!currentConditionalNodeEnd || // We should completely remove requires directly in a try-catch
// so that Rollup can remove up the try-catch
currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd) ? parent : node2;
addRequireExpression(
requireStringArg,
node2,
scope,
usesReturnValue,
currentTryBlockEnd !== null,
currentConditionalNodeEnd !== null,
toBeRemoved
);
if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") {
for (const name2 of extractAssignedNames(parent.id)) {
importedVariables.add(name2);
}
}
}
return;
}
case "ClassBody":
classBodyDepth += 1;
return;
case "ConditionalExpression":
case "IfStatement":
if (isFalsy(node2.test)) {
skippedNodes.add(node2.consequent);
} else if (isTruthy(node2.test)) {
if (node2.alternate) {
skippedNodes.add(node2.alternate);
}
} else {
conditionalNodes.add(node2.consequent);
if (node2.alternate) {
conditionalNodes.add(node2.alternate);
}
}
return;
case "ArrowFunctionExpression":
case "FunctionDeclaration":
case "FunctionExpression":
if (currentConditionalNodeEnd === null && !(parent.type === "CallExpression" && parent.callee === node2)) {
currentConditionalNodeEnd = node2.end;
}
return;
case "Identifier": {
const { name: name2 } = node2;
if (!isReference(node2, parent) || scope.contains(name2) || parent.type === "PropertyDefinition" && parent.key === node2)
return;
switch (name2) {
case "require":
uses.require = true;
if (isNodeRequirePropertyAccess(parent)) {
return;
}
if (!ignoreDynamicRequires) {
if (isShorthandProperty(parent)) {
skippedNodes.add(parent.value);
magicString.prependRight(node2.start, "require: ");
}
replacedDynamicRequires.push(node2);
}
return;
case "module":
case "exports":
shouldWrap = true;
uses[name2] = true;
return;
case "global":
uses.global = true;
if (!ignoreGlobal) {
replacedGlobal.push(node2);
}
return;
case "define":
magicString.overwrite(node2.start, node2.end, "undefined", {
storeName: true
});
return;
default:
globals.add(name2);
return;
}
}
case "LogicalExpression":
if (node2.operator === "&&") {
if (isFalsy(node2.left)) {
skippedNodes.add(node2.right);
} else if (!isTruthy(node2.left)) {
conditionalNodes.add(node2.right);
}
} else if (node2.operator === "||") {
if (isTruthy(node2.left)) {
skippedNodes.add(node2.right);
} else if (!isFalsy(node2.left)) {
conditionalNodes.add(node2.right);
}
}
return;
case "MemberExpression":
if (!isDynamicRequireModulesEnabled && isModuleRequire(node2, scope)) {
uses.require = true;
replacedDynamicRequires.push(node2);
skippedNodes.add(node2.object);
skippedNodes.add(node2.property);
}
return;
case "ReturnStatement":
if (lexicalDepth === 0) {
shouldWrap = true;
}
return;
case "ThisExpression":
if (lexicalDepth === 0 && !classBodyDepth) {
uses.global = true;
if (!ignoreGlobal) {
replacedGlobal.push(node2);
}
}
return;
case "TryStatement":
if (currentTryBlockEnd === null) {
currentTryBlockEnd = node2.block.end;
}
if (currentConditionalNodeEnd === null) {
currentConditionalNodeEnd = node2.end;
}
return;
case "UnaryExpression":
if (node2.operator === "typeof") {
const flattened = getKeypath(node2.argument);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
if (!isEsModule && (flattened.keypath === "module.exports" || flattened.keypath === "module" || flattened.keypath === "exports")) {
magicString.overwrite(node2.start, node2.end, `'object'`, {
storeName: false
});
}
}
return;
case "VariableDeclaration":
if (!scope.parent) {
topLevelDeclarations.push(node2);
}
return;
case "TemplateElement":
if (node2.value.raw.includes("\n")) {
indentExclusionRanges.push([node2.start, node2.end]);
}
}
},
leave(node2) {
programDepth -= 1;
if (node2.scope) scope = scope.parent;
if (functionType.test(node2.type)) lexicalDepth -= 1;
if (node2.type === "ClassBody") classBodyDepth -= 1;
}
});
const nameBase = getName(id);
const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
const helpersName = deconflict([scope], globals, "commonjsHelpers");
const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict(
[scope],
globals,
isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
);
const deconflictedExportNames = /* @__PURE__ */ Object.create(null);
for (const [exportName, { scopes }] of exportsAssignmentsByName) {
deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
}
for (const node2 of replacedGlobal) {
magicString.overwrite(node2.start, node2.end, `${helpersName}.commonjsGlobal`, {
storeName: true
});
}
for (const node2 of replacedDynamicRequires) {
magicString.overwrite(
node2.start,
node2.end,
isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName,
{
contentOnly: true,
storeName: true
}
);
}
shouldWrap = !isEsModule && (shouldWrap || uses.exports && moduleExportsAssignments.length > 0);
if (!(shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0) && (ignoreGlobal || !uses.global)) {
return { meta: { commonjs: { isCommonJS: false } } };
}
let leadingComment = "";
if (code.startsWith("/*")) {
const commentEnd = code.indexOf("*/", 2) + 2;
leadingComment = `${code.slice(0, commentEnd)}
`;
magicString.remove(0, commentEnd).trim();
}
let shebang = "";
if (code.startsWith("#!")) {
const shebangEndPosition = code.indexOf("\n") + 1;
shebang = code.slice(0, shebangEndPosition);
magicString.remove(0, shebangEndPosition).trim();
}
const exportMode = isEsModule ? "none" : shouldWrap ? uses.module ? "module" : "exports" : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? "replace" : "module" : moduleExportsAssignments.length === 0 ? "exports" : "module";
const exportedExportsName = exportMode === "module" ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
magicString,
topLevelDeclarations,
reassignedNames,
helpersName,
dynamicRequireName,
moduleName,
exportsName,
id,
exportMode,
resolveRequireSourcesAndUpdateMeta,
needsRequireWrapper,
isEsModule,
isDynamicRequireModulesEnabled,
getIgnoreTryCatchRequireStatementMode,
commonjsMeta
);
const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
const exportBlock = isEsModule ? "" : rewriteExportsAndGetExportsBlock(
magicString,
moduleName,
exportsName,
exportedExportsName,
shouldWrap,
moduleExportsAssignments,
firstTopLevelModuleExportsAssignment,
exportsAssignmentsByName,
topLevelAssignments,
topLevelDefineCompiledEsmExpressions,
deconflictedExportNames,
code,
helpersName,
exportMode,
defaultIsModuleExports,
usesRequireWrapper,
requireName
);
if (shouldWrap) {
wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
}
if (usesRequireWrapper) {
magicString.trim().indent(" ", {
exclude: indentExclusionRanges
});
const exported = exportMode === "module" ? `${moduleName}.exports` : exportsName;
magicString.prepend(
`var ${isRequiredName};
function ${requireName} () {
if (${isRequiredName}) return ${exported};
${isRequiredName} = 1;
`
).append(`
return ${exported};
}`);
if (exportMode === "replace") {
magicString.prepend(`var ${exportsName};
`);
}
}
magicString.trim().prepend(shebang + leadingComment + importBlock).append(exportBlock);
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap() : null,
syntheticNamedExports: isEsModule || usesRequireWrapper ? false : "__moduleExports",
meta: { commonjs: { ...commonjsMeta, shebang } }
};
}
var PLUGIN_NAME = "commonjs";
function commonjs(options2 = {}) {
const {
ignoreGlobal,
ignoreDynamicRequires,
requireReturnsDefault: requireReturnsDefaultOption,
defaultIsModuleExports: defaultIsModuleExportsOption,
esmExternals
} = options2;
const extensions2 = options2.extensions || [".js"];
const filter2 = createFilter$1(options2.include, options2.exclude);
const isPossibleCjsId = (id) => {
const extName = (0, import_path.extname)(id);
return extName === ".cjs" || extensions2.includes(extName) && filter2(id);
};
const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options2);
const getRequireReturnsDefault = typeof requireReturnsDefaultOption === "function" ? requireReturnsDefaultOption : () => requireReturnsDefaultOption;
let esmExternalIds;
const isEsmExternal = typeof esmExternals === "function" ? esmExternals : Array.isArray(esmExternals) ? (esmExternalIds = new Set(esmExternals), (id) => esmExternalIds.has(id)) : () => esmExternals;
const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === "function" ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === "boolean" ? defaultIsModuleExportsOption : "auto";
const dynamicRequireRoot = typeof options2.dynamicRequireRoot === "string" ? (0, import_path.resolve)(options2.dynamicRequireRoot) : process.cwd();
const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
options2.dynamicRequireTargets,
dynamicRequireRoot
);
const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
const ignoreRequire = typeof options2.ignore === "function" ? options2.ignore : Array.isArray(options2.ignore) ? (id) => options2.ignore.includes(id) : () => false;
const getIgnoreTryCatchRequireStatementMode = (id) => {
const mode2 = typeof options2.ignoreTryCatch === "function" ? options2.ignoreTryCatch(id) : Array.isArray(options2.ignoreTryCatch) ? options2.ignoreTryCatch.includes(id) : typeof options2.ignoreTryCatch !== "undefined" ? options2.ignoreTryCatch : true;
return {
canConvertRequire: mode2 !== "remove" && mode2 !== true,
shouldRemoveRequire: mode2 === "remove"
};
};
const { currentlyResolving, resolveId } = getResolveId(extensions2, isPossibleCjsId);
const sourceMap = options2.sourceMap !== false;
let requireResolver;
function transformAndCheckExports(code, id) {
const normalizedId = normalizePathSlashes(id);
const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
this.parse,
code,
id
);
const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
if (hasDefaultExport) {
commonjsMeta.hasDefaultExport = true;
}
if (hasNamedExports) {
commonjsMeta.hasNamedExports = true;
}
if (!dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || isEsModule && !options2.transformMixedEsModules)) {
commonjsMeta.isCommonJS = false;
return { meta: { commonjs: commonjsMeta } };
}
const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
const checkDynamicRequire = (position) => {
const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) {
this.error(
{
code: "DYNAMIC_REQUIRE_OUTSIDE_ROOT",
normalizedId,
normalizedDynamicRequireRoot,
message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${(0, import_path.dirname)(
normalizedId
)}" or one of its parent directories.`
},
position
);
}
};
return transformCommonjs(
this.parse,
code,
id,
isEsModule,
ignoreGlobal || isEsModule,
ignoreRequire,
ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
getIgnoreTryCatchRequireStatementMode,
sourceMap,
isDynamicRequireModulesEnabled,
dynamicRequireModules,
commonDir,
ast,
getDefaultIsModuleExports(id),
needsRequireWrapper,
requireResolver.resolveRequireSourcesAndUpdateMeta(this),
requireResolver.isRequiredId(id),
checkDynamicRequire,
commonjsMeta
);
}
return {
name: PLUGIN_NAME,
version: version$2,
options(rawOptions) {
const plugins2 = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : [];
plugins2.unshift({
name: "commonjs--resolver",
resolveId
});
return { ...rawOptions, plugins: plugins2 };
},
buildStart({ plugins: plugins2 }) {
validateVersion(this.meta.rollupVersion, peerDependencies.rollup, "rollup");
const nodeResolve = plugins2.find(({ name: name2 }) => name2 === "node-resolve");
if (nodeResolve) {
validateVersion(nodeResolve.version, "^13.0.6", "@rollup/plugin-node-resolve");
}
if (options2.namedExports != null) {
this.warn(
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
);
}
requireResolver = getRequireResolver(
extensions2,
detectCyclesAndConditional,
currentlyResolving
);
},
buildEnd() {
if (options2.strictRequires === "debug") {
const wrappedIds = requireResolver.getWrappedIds();
if (wrappedIds.length) {
this.warn({
code: "WRAPPED_IDS",
ids: wrappedIds,
message: `The commonjs plugin automatically wrapped the following files:
[
${wrappedIds.map((id) => ` ${JSON.stringify((0, import_path.relative)(process.cwd(), id))}`).join(",\n")}
]`
});
} else {
this.warn({
code: "WRAPPED_IDS",
ids: wrappedIds,
message: "The commonjs plugin did not wrap any files."
});
}
}
},
load(id) {
if (id === HELPERS_ID) {
return getHelpersModule();
}
if (isWrappedId(id, MODULE_SUFFIX)) {
const name2 = getName(unwrapId(id, MODULE_SUFFIX));
return {
code: `var ${name2} = {exports: {}}; export {${name2} as __module}`,
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXPORTS_SUFFIX)) {
const name2 = getName(unwrapId(id, EXPORTS_SUFFIX));
return {
code: `var ${name2} = {}; export {${name2} as __exports}`,
meta: { commonjs: { isCommonJS: false } }
};
}
if (isWrappedId(id, EXTERNAL_SUFFIX)) {
const actualId = unwrapId(id, EXTERNAL_SUFFIX);
return getUnknownRequireProxy(
actualId,
isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
);
}
if (id.endsWith(ENTRY_SUFFIX)) {
const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
const {
meta: { commonjs: commonjsMeta }
} = this.getModuleInfo(acutalId);
const shebang = (commonjsMeta == null ? void 0 : commonjsMeta.shebang) ?? "";
return getEntryProxy(
acutalId,
getDefaultIsModuleExports(acutalId),
this.getModuleInfo,
shebang
);
}
if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
}
if (id === DYNAMIC_MODULES_ID) {
return getDynamicModuleRegistry(
isDynamicRequireModulesEnabled,
dynamicRequireModules,
commonDir,
ignoreDynamicRequires
);
}
if (isWrappedId(id, PROXY_SUFFIX)) {
const actualId = unwrapId(id, PROXY_SUFFIX);
return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
}
return null;
},
shouldTransformCachedModule(...args) {
return requireResolver.shouldTransformCachedModule.call(this, ...args);
},
transform(code, id) {
if (!isPossibleCjsId(id)) return null;
try {
return transformAndCheckExports.call(this, code, id);
} catch (err2) {
return this.error(err2, err2.pos);
}
}
};
}
var schemeRegex = /^[\w+.-]+:\/\//;
var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
return input.startsWith("//");
}
function isAbsolutePath(input) {
return input.startsWith("/");
}
function isFileUrl(input) {
return input.startsWith("file:");
}
function isRelative(input) {
return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
const match2 = urlRegex.exec(input);
return makeUrl(match2[1], match2[2] || "", match2[3], match2[4] || "", match2[5] || "/", match2[6] || "", match2[7] || "");
}
function parseFileUrl(input) {
const match2 = fileRegex.exec(input);
const path3 = match2[2];
return makeUrl("file:", "", match2[1] || "", "", isAbsolutePath(path3) ? path3 : "/" + path3, match2[3] || "", match2[4] || "");
}
function makeUrl(scheme, user, host, port, path3, query, hash2) {
return {
scheme,
user,
host,
port,
path: path3,
query,
hash: hash2,
type: 7
};
}
function parseUrl$3(input) {
if (isSchemeRelativeUrl(input)) {
const url3 = parseAbsoluteUrl("http:" + input);
url3.scheme = "";
url3.type = 6;
return url3;
}
if (isAbsolutePath(input)) {
const url3 = parseAbsoluteUrl("http://foo.com" + input);
url3.scheme = "";
url3.host = "";
url3.type = 5;
return url3;
}
if (isFileUrl(input))
return parseFileUrl(input);
if (isAbsoluteUrl(input))
return parseAbsoluteUrl(input);
const url2 = parseAbsoluteUrl("http://foo.com/" + input);
url2.scheme = "";
url2.host = "";
url2.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
return url2;
}
function stripPathFilename(path3) {
if (path3.endsWith("/.."))
return path3;
const index = path3.lastIndexOf("/");
return path3.slice(0, index + 1);
}
function mergePaths(url2, base) {
normalizePath$4(base, base.type);
if (url2.path === "/") {
url2.path = base.path;
} else {
url2.path = stripPathFilename(base.path) + url2.path;
}
}
function normalizePath$4(url2, type) {
const rel = type <= 4;
const pieces = url2.path.split("/");
let pointer = 1;
let positive = 0;
let addTrailingSlash = false;
for (let i = 1; i < pieces.length; i++) {
const piece = pieces[i];
if (!piece) {
addTrailingSlash = true;
continue;
}
addTrailingSlash = false;
if (piece === ".")
continue;
if (piece === "..") {
if (positive) {
addTrailingSlash = true;
positive--;
pointer--;
} else if (rel) {
pieces[pointer++] = piece;
}
continue;
}
pieces[pointer++] = piece;
positive++;
}
let path3 = "";
for (let i = 1; i < pointer; i++) {
path3 += "/" + pieces[i];
}
if (!path3 || addTrailingSlash && !path3.endsWith("/..")) {
path3 += "/";
}
url2.path = path3;
}
function resolve$2(input, base) {
if (!input && !base)
return "";
const url2 = parseUrl$3(input);
let inputType = url2.type;
if (base && inputType !== 7) {
const baseUrl = parseUrl$3(base);
const baseType = baseUrl.type;
switch (inputType) {
case 1:
url2.hash = baseUrl.hash;
case 2:
url2.query = baseUrl.query;
case 3:
case 4:
mergePaths(url2, baseUrl);
case 5:
url2.user = baseUrl.user;
url2.host = baseUrl.host;
url2.port = baseUrl.port;
case 6:
url2.scheme = baseUrl.scheme;
}
if (baseType > inputType)
inputType = baseType;
}
normalizePath$4(url2, inputType);
const queryHash = url2.query + url2.hash;
switch (inputType) {
case 2:
case 3:
return queryHash;
case 4: {
const path3 = url2.path.slice(1);
if (!path3)
return queryHash || ".";
if (isRelative(base || input) && !isRelative(path3)) {
return "./" + path3 + queryHash;
}
return path3 + queryHash;
}
case 5:
return url2.path + queryHash;
default:
return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash;
}
}
function resolve$1(input, base) {
if (base && !base.endsWith("/"))
base += "/";
return resolve$2(input, base);
}
function stripFilename(path3) {
if (!path3)
return "";
const index = path3.lastIndexOf("/");
return path3.slice(0, index + 1);
}
var COLUMN$1 = 0;
var SOURCES_INDEX$1 = 1;
var SOURCE_LINE$1 = 2;
var SOURCE_COLUMN$1 = 3;
var NAMES_INDEX$1 = 4;
function maybeSort(mappings, owned) {
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
if (unsortedIndex === mappings.length)
return mappings;
if (!owned)
mappings = mappings.slice();
for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
mappings[i] = sortSegments(mappings[i], owned);
}
return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
for (let i = start; i < mappings.length; i++) {
if (!isSorted(mappings[i]))
return i;
}
return mappings.length;
}
function isSorted(line) {
for (let j = 1; j < line.length; j++) {
if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
return false;
}
}
return true;
}
function sortSegments(line, owned) {
if (!owned)
line = line.slice();
return line.sort(sortComparator);
}
function sortComparator(a, b) {
return a[COLUMN$1] - b[COLUMN$1];
}
var found = false;
function binarySearch(haystack, needle, low, high) {
while (low <= high) {
const mid = low + (high - low >> 1);
const cmp = haystack[mid][COLUMN$1] - needle;
if (cmp === 0) {
found = true;
return mid;
}
if (cmp < 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
found = false;
return low - 1;
}
function upperBound(haystack, needle, index) {
for (let i = index + 1; i < haystack.length; index = i++) {
if (haystack[i][COLUMN$1] !== needle)
break;
}
return index;
}
function lowerBound(haystack, needle, index) {
for (let i = index - 1; i >= 0; index = i--) {
if (haystack[i][COLUMN$1] !== needle)
break;
}
return index;
}
function memoizedState() {
return {
lastKey: -1,
lastNeedle: -1,
lastIndex: -1
};
}
function memoizedBinarySearch(haystack, needle, state, key) {
const { lastKey, lastNeedle, lastIndex } = state;
let low = 0;
let high = haystack.length - 1;
if (key === lastKey) {
if (needle === lastNeedle) {
found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
return lastIndex;
}
if (needle >= lastNeedle) {
low = lastIndex === -1 ? 0 : lastIndex;
} else {
high = lastIndex;
}
}
state.lastKey = key;
state.lastNeedle = needle;
return state.lastIndex = binarySearch(haystack, needle, low, high);
}
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
var TraceMap = class {
constructor(map2, mapUrl) {
const isString2 = typeof map2 === "string";
if (!isString2 && map2._decodedMemo)
return map2;
const parsed = isString2 ? JSON.parse(map2) : map2;
const { version: version3, file, names, sourceRoot, sources, sourcesContent } = parsed;
this.version = version3;
this.file = file;
this.names = names || [];
this.sourceRoot = sourceRoot;
this.sources = sources;
this.sourcesContent = sourcesContent;
this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
const from = resolve$1(sourceRoot || "", stripFilename(mapUrl));
this.resolvedSources = sources.map((s) => resolve$1(s || "", from));
const { mappings } = parsed;
if (typeof mappings === "string") {
this._encoded = mappings;
this._decoded = void 0;
} else {
this._encoded = void 0;
this._decoded = maybeSort(mappings, isString2);
}
this._decodedMemo = memoizedState();
this._bySources = void 0;
this._bySourceMemos = void 0;
}
};
function cast$2(map2) {
return map2;
}
function encodedMappings(map2) {
var _a4;
var _b3;
return (_a4 = (_b3 = cast$2(map2))._encoded) !== null && _a4 !== void 0 ? _a4 : _b3._encoded = encode$1(cast$2(map2)._decoded);
}
function decodedMappings(map2) {
var _a4;
return (_a4 = cast$2(map2))._decoded || (_a4._decoded = decode(cast$2(map2)._encoded));
}
function traceSegment(map2, line, column) {
const decoded = decodedMappings(map2);
if (line >= decoded.length)
return null;
const segments = decoded[line];
const index = traceSegmentInternal(segments, cast$2(map2)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
return index === -1 ? null : segments[index];
}
function originalPositionFor$1(map2, needle) {
let { line, column, bias } = needle;
line--;
if (line < 0)
throw new Error(LINE_GTR_ZERO);
if (column < 0)
throw new Error(COL_GTR_EQ_ZERO);
const decoded = decodedMappings(map2);
if (line >= decoded.length)
return OMapping(null, null, null, null);
const segments = decoded[line];
const index = traceSegmentInternal(segments, cast$2(map2)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
if (index === -1)
return OMapping(null, null, null, null);
const segment = segments[index];
if (segment.length === 1)
return OMapping(null, null, null, null);
const { names, resolvedSources } = map2;
return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
}
function decodedMap(map2) {
return clone(map2, decodedMappings(map2));
}
function encodedMap(map2) {
return clone(map2, encodedMappings(map2));
}
function clone(map2, mappings) {
return {
version: map2.version,
file: map2.file,
names: map2.names,
sourceRoot: map2.sourceRoot,
sources: map2.sources,
sourcesContent: map2.sourcesContent,
mappings,
ignoreList: map2.ignoreList || map2.x_google_ignoreList
};
}
function OMapping(source, line, column, name2) {
return { source, line, column, name: name2 };
}
function traceSegmentInternal(segments, memo, line, column, bias) {
let index = memoizedBinarySearch(segments, column, memo, line);
if (found) {
index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
} else if (bias === LEAST_UPPER_BOUND)
index++;
if (index === -1 || index === segments.length)
return -1;
return index;
}
var SetArray = class {
constructor() {
this._indexes = { __proto__: null };
this.array = [];
}
};
function cast$1(set2) {
return set2;
}
function get(setarr, key) {
return cast$1(setarr)._indexes[key];
}
function put(setarr, key) {
const index = get(setarr, key);
if (index !== void 0)
return index;
const { array: array2, _indexes: indexes } = cast$1(setarr);
const length = array2.push(key);
return indexes[key] = length - 1;
}
function remove(setarr, key) {
const index = get(setarr, key);
if (index === void 0)
return;
const { array: array2, _indexes: indexes } = cast$1(setarr);
for (let i = index + 1; i < array2.length; i++) {
const k = array2[i];
array2[i - 1] = k;
indexes[k]--;
}
indexes[key] = void 0;
array2.pop();
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var NO_NAME = -1;
var GenMapping = class {
constructor({ file, sourceRoot } = {}) {
this._names = new SetArray();
this._sources = new SetArray();
this._sourcesContent = [];
this._mappings = [];
this.file = file;
this.sourceRoot = sourceRoot;
this._ignoreList = new SetArray();
}
};
function cast(map2) {
return map2;
}
var maybeAddSegment = (map2, genLine, genColumn, source, sourceLine, sourceColumn, name2, content) => {
return addSegmentInternal(true, map2, genLine, genColumn, source, sourceLine, sourceColumn, name2);
};
function setSourceContent(map2, source, content) {
const { _sources: sources, _sourcesContent: sourcesContent } = cast(map2);
const index = put(sources, source);
sourcesContent[index] = content;
}
function setIgnore(map2, source, ignore = true) {
const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map2);
const index = put(sources, source);
if (index === sourcesContent.length)
sourcesContent[index] = null;
if (ignore)
put(ignoreList, index);
else
remove(ignoreList, index);
}
function toDecodedMap(map2) {
const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast(map2);
removeEmptyFinalLines(mappings);
return {
version: 3,
file: map2.file || void 0,
names: names.array,
sourceRoot: map2.sourceRoot || void 0,
sources: sources.array,
sourcesContent,
mappings,
ignoreList: ignoreList.array
};
}
function toEncodedMap(map2) {
const decoded = toDecodedMap(map2);
return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) });
}
function addSegmentInternal(skipable, map2, genLine, genColumn, source, sourceLine, sourceColumn, name2, content) {
const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast(map2);
const line = getLine(mappings, genLine);
const index = getColumnIndex(line, genColumn);
if (!source) {
if (skipSourceless(line, index))
return;
return insert(line, index, [genColumn]);
}
const sourcesIndex = put(sources, source);
const namesIndex = name2 ? put(names, name2) : NO_NAME;
if (sourcesIndex === sourcesContent.length)
sourcesContent[sourcesIndex] = null;
if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
return;
}
return insert(line, index, name2 ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
}
function getLine(mappings, index) {
for (let i = mappings.length; i <= index; i++) {
mappings[i] = [];
}
return mappings[index];
}
function getColumnIndex(line, genColumn) {
let index = line.length;
for (let i = index - 1; i >= 0; index = i--) {
const current = line[i];
if (genColumn >= current[COLUMN])
break;
}
return index;
}
function insert(array2, index, value2) {
for (let i = array2.length; i > index; i--) {
array2[i] = array2[i - 1];
}
array2[index] = value2;
}
function removeEmptyFinalLines(mappings) {
const { length } = mappings;
let len = length;
for (let i = len - 1; i >= 0; len = i, i--) {
if (mappings[i].length > 0)
break;
}
if (len < length)
mappings.length = len;
}
function skipSourceless(line, index) {
if (index === 0)
return true;
const prev = line[index - 1];
return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
if (index === 0)
return false;
const prev = line[index - 1];
if (prev.length === 1)
return false;
return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
}
var SOURCELESS_MAPPING = SegmentObject("", -1, -1, "", null, false);
var EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name2, content, ignore) {
return { source, line, column, name: name2, content, ignore };
}
function Source(map2, sources, source, content, ignore) {
return {
map: map2,
sources,
source,
content,
ignore
};
}
function MapSource(map2, sources) {
return Source(map2, sources, "", null, false);
}
function OriginalSource(source, content, ignore) {
return Source(null, EMPTY_SOURCES, source, content, ignore);
}
function traceMappings(tree) {
const gen = new GenMapping({ file: tree.map.file });
const { sources: rootSources, map: map2 } = tree;
const rootNames = map2.names;
const rootMappings = decodedMappings(map2);
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
const genCol = segment[0];
let traced = SOURCELESS_MAPPING;
if (segment.length !== 1) {
const source2 = rootSources[segment[1]];
traced = originalPositionFor(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
if (traced == null)
continue;
}
const { column, line, name: name2, content, source, ignore } = traced;
maybeAddSegment(gen, i, genCol, source, line, column, name2);
if (source && content != null)
setSourceContent(gen, source, content);
if (ignore)
setIgnore(gen, source, true);
}
}
return gen;
}
function originalPositionFor(source, line, column, name2) {
if (!source.map) {
return SegmentObject(source.source, line, column, name2, source.content, source.ignore);
}
const segment = traceSegment(source.map, line, column);
if (segment == null)
return null;
if (segment.length === 1)
return SOURCELESS_MAPPING;
return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name2);
}
function asArray(value2) {
if (Array.isArray(value2))
return value2;
return [value2];
}
function buildSourceMapTree(input, loader) {
const maps = asArray(input).map((m) => new TraceMap(m, ""));
const map2 = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length > 1) {
throw new Error(`Transformation map ${i} must have exactly one source file.
Did you specify these with the most recent transformation maps first?`);
}
}
let tree = build$2(map2, loader, "", 0);
for (let i = maps.length - 1; i >= 0; i--) {
tree = MapSource(maps[i], [tree]);
}
return tree;
}
function build$2(map2, loader, importer, importerDepth) {
const { resolvedSources, sourcesContent, ignoreList } = map2;
const depth2 = importerDepth + 1;
const children = resolvedSources.map((sourceFile, i) => {
const ctx = {
importer,
depth: depth2,
source: sourceFile || "",
content: void 0,
ignore: void 0
};
const sourceMap = loader(ctx.source, ctx);
const { source, content, ignore } = ctx;
if (sourceMap)
return build$2(new TraceMap(sourceMap, source), loader, source, depth2);
const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
return OriginalSource(source, sourceContent, ignored);
});
return MapSource(map2, children);
}
var SourceMap2 = class {
constructor(map2, options2) {
const out2 = options2.decodedMappings ? toDecodedMap(map2) : toEncodedMap(map2);
this.version = out2.version;
this.file = out2.file;
this.mappings = out2.mappings;
this.names = out2.names;
this.ignoreList = out2.ignoreList;
this.sourceRoot = out2.sourceRoot;
this.sources = out2.sources;
if (!options2.excludeContent) {
this.sourcesContent = out2.sourcesContent;
}
}
toString() {
return JSON.stringify(this);
}
};
function remapping(input, loader, options2) {
const opts = { excludeContent: !!options2, decodedMappings: false };
const tree = buildSourceMapTree(input, loader);
return new SourceMap2(traceMappings(tree), opts);
}
var src$3 = { exports: {} };
var browser$3 = { exports: {} };
var ms$1;
var hasRequiredMs$1;
function requireMs$1() {
if (hasRequiredMs$1) return ms$1;
hasRequiredMs$1 = 1;
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
ms$1 = function(val, options2) {
options2 = options2 || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse4(val);
} else if (type === "number" && isFinite(val)) {
return options2.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse4(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match2) {
return;
}
var n2 = parseFloat(match2[1]);
var type = (match2[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n2 * y;
case "weeks":
case "week":
case "w":
return n2 * w;
case "days":
case "day":
case "d":
return n2 * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n2 * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n2 * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n2 * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n2;
default:
return void 0;
}
}
function fmtShort(ms2) {
var msAbs = Math.abs(ms2);
if (msAbs >= d) {
return Math.round(ms2 / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms2 / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms2 / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms2 / s) + "s";
}
return ms2 + "ms";
}
function fmtLong(ms2) {
var msAbs = Math.abs(ms2);
if (msAbs >= d) {
return plural(ms2, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms2, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms2, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms2, msAbs, s, "second");
}
return ms2 + " ms";
}
function plural(ms2, msAbs, n2, name2) {
var isPlural = msAbs >= n2 * 1.5;
return Math.round(ms2 / n2) + " " + name2 + (isPlural ? "s" : "");
}
return ms$1;
}
var common$b;
var hasRequiredCommon;
function requireCommon() {
if (hasRequiredCommon) return common$b;
hasRequiredCommon = 1;
function setup(env2) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = requireMs$1();
createDebug.destroy = destroy2;
Object.keys(env2).forEach((key) => {
createDebug[key] = env2[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash2 = 0;
for (let i = 0; i < namespace.length; i++) {
hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
hash2 |= 0;
}
return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug2(...args) {
if (!debug2.enabled) {
return;
}
const self2 = debug2;
const curr = Number(/* @__PURE__ */ new Date());
const ms2 = curr - (prevTime || curr);
self2.diff = ms2;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format2) => {
if (match2 === "%%") {
return "%";
}
index++;
const formatter2 = createDebug.formatters[format2];
if (typeof formatter2 === "function") {
const val = args[index];
match2 = formatter2.call(self2, val);
args.splice(index, 1);
index--;
}
return match2;
});
createDebug.formatArgs.call(self2, args);
const logFn = self2.log || createDebug.log;
logFn.apply(self2, args);
}
debug2.namespace = namespace;
debug2.useColors = createDebug.useColors();
debug2.color = createDebug.selectColor(namespace);
debug2.extend = extend;
debug2.destroy = createDebug.destroy;
Object.defineProperty(debug2, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug2);
}
return debug2;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
continue;
}
namespaces = split[i].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
} else {
createDebug.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name2) {
if (name2[name2.length - 1] === "*") {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name2)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name2)) {
return true;
}
}
return false;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy2() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
common$b = setup;
return common$b;
}
var hasRequiredBrowser$1;
function requireBrowser$1() {
if (hasRequiredBrowser$1) return browser$3.exports;
hasRequiredBrowser$1 = 1;
(function(module, exports2) {
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load2;
exports2.useColors = useColors;
exports2.storage = localstorage();
exports2.destroy = /* @__PURE__ */ (() => {
let warned2 = false;
return () => {
if (!warned2) {
warned2 = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports2.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match2) => {
if (match2 === "%%") {
return;
}
index++;
if (match2 === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports2.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports2.storage.setItem("debug", namespaces);
} else {
exports2.storage.removeItem("debug");
}
} catch (error2) {
}
}
function load2() {
let r2;
try {
r2 = exports2.storage.getItem("debug");
} catch (error2) {
}
if (!r2 && typeof process !== "undefined" && "env" in process) {
r2 = process.env.DEBUG;
}
return r2;
}
function localstorage() {
try {
return localStorage;
} catch (error2) {
}
}
module.exports = requireCommon()(exports2);
const { formatters } = module.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error2) {
return "[UnexpectedJSONParseError]: " + error2.message;
}
};
})(browser$3, browser$3.exports);
return browser$3.exports;
}
var node$1 = { exports: {} };
var hasRequiredNode$1;
function requireNode$1() {
if (hasRequiredNode$1) return node$1.exports;
hasRequiredNode$1 = 1;
(function(module, exports2) {
const tty = import_tty.default;
const util2 = import_util.default;
exports2.init = init2;
exports2.log = log;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load2;
exports2.useColors = useColors;
exports2.destroy = util2.deprecate(
() => {
},
"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
);
exports2.colors = [6, 2, 3, 4, 5, 1];
try {
const supportsColor = require2("supports-color");
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports2.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error2) {
}
exports2.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === "null") {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
function useColors() {
return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
function formatArgs(args) {
const { namespace: name2, useColors: useColors2 } = this;
if (useColors2) {
const c = this.color;
const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
const prefix = ` ${colorCode};1m${name2} \x1B[0m`;
args[0] = prefix + args[0].split("\n").join("\n" + prefix);
args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name2 + " " + args[0];
}
}
function getDate() {
if (exports2.inspectOpts.hideDate) {
return "";
}
return (/* @__PURE__ */ new Date()).toISOString() + " ";
}
function log(...args) {
return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
}
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
delete process.env.DEBUG;
}
}
function load2() {
return process.env.DEBUG;
}
function init2(debug2) {
debug2.inspectOpts = {};
const keys = Object.keys(exports2.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
}
}
module.exports = requireCommon()(exports2);
const { formatters } = module.exports;
formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
};
formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts);
};
})(node$1, node$1.exports);
return node$1.exports;
}
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
src$3.exports = requireBrowser$1();
} else {
src$3.exports = requireNode$1();
}
var srcExports$1 = src$3.exports;
var debug$i = getDefaultExportFromCjs(srcExports$1);
var pnp;
if (process.versions.pnp) {
try {
pnp = (0, import_node_module.createRequire)(import.meta.url)("pnpapi");
} catch {
}
}
function invalidatePackageData(packageCache, pkgPath) {
const pkgDir = normalizePath$3(import_node_path3.default.dirname(pkgPath));
packageCache.forEach((pkg, cacheKey) => {
if (pkg.dir === pkgDir) {
packageCache.delete(cacheKey);
}
});
}
function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
if (pnp) {
const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
if (packageCache == null ? void 0 : packageCache.has(cacheKey)) return packageCache.get(cacheKey);
try {
const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
considerBuiltins: false
});
if (!pkg) return null;
const pkgData = loadPackageData(import_node_path3.default.join(pkg, "package.json"));
packageCache == null ? void 0 : packageCache.set(cacheKey, pkgData);
return pkgData;
} catch {
return null;
}
}
const originalBasedir = basedir;
while (basedir) {
if (packageCache) {
const cached = getRpdCache(
packageCache,
pkgName,
basedir,
originalBasedir,
preserveSymlinks
);
if (cached) return cached;
}
const pkg = import_node_path3.default.join(basedir, "node_modules", pkgName, "package.json");
try {
if (import_node_fs2.default.existsSync(pkg)) {
const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
const pkgData = loadPackageData(pkgPath);
if (packageCache) {
setRpdCache(
packageCache,
pkgData,
pkgName,
basedir,
originalBasedir,
preserveSymlinks
);
}
return pkgData;
}
} catch {
}
const nextBasedir = import_node_path3.default.dirname(basedir);
if (nextBasedir === basedir) break;
basedir = nextBasedir;
}
return null;
}
function findNearestPackageData(basedir, packageCache) {
var _a4;
const originalBasedir = basedir;
while (basedir) {
if (packageCache) {
const cached = getFnpdCache(packageCache, basedir, originalBasedir);
if (cached) return cached;
}
const pkgPath = import_node_path3.default.join(basedir, "package.json");
if ((_a4 = tryStatSync(pkgPath)) == null ? void 0 : _a4.isFile()) {
try {
const pkgData = loadPackageData(pkgPath);
if (packageCache) {
setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
}
return pkgData;
} catch {
}
}
const nextBasedir = import_node_path3.default.dirname(basedir);
if (nextBasedir === basedir) break;
basedir = nextBasedir;
}
return null;
}
function findNearestMainPackageData(basedir, packageCache) {
const nearestPackage = findNearestPackageData(basedir, packageCache);
return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
import_node_path3.default.dirname(nearestPackage.dir),
packageCache
));
}
function loadPackageData(pkgPath) {
const data = JSON.parse(import_node_fs2.default.readFileSync(pkgPath, "utf-8"));
const pkgDir = normalizePath$3(import_node_path3.default.dirname(pkgPath));
const { sideEffects } = data;
let hasSideEffects;
if (typeof sideEffects === "boolean") {
hasSideEffects = () => sideEffects;
} else if (Array.isArray(sideEffects)) {
if (sideEffects.length <= 0) {
hasSideEffects = () => false;
} else {
const finalPackageSideEffects = sideEffects.map((sideEffect) => {
if (sideEffect.includes("/")) {
return sideEffect;
}
return `**/${sideEffect}`;
});
hasSideEffects = createFilter2(finalPackageSideEffects, null, {
resolve: pkgDir
});
}
} else {
hasSideEffects = () => null;
}
const pkg = {
dir: pkgDir,
data,
hasSideEffects,
webResolvedImports: {},
nodeResolvedImports: {},
setResolvedCache(key, entry2, targetWeb) {
if (targetWeb) {
pkg.webResolvedImports[key] = entry2;
} else {
pkg.nodeResolvedImports[key] = entry2;
}
},
getResolvedCache(key, targetWeb) {
if (targetWeb) {
return pkg.webResolvedImports[key];
} else {
return pkg.nodeResolvedImports[key];
}
}
};
return pkg;
}
function watchPackageDataPlugin(packageCache) {
const watchQueue = /* @__PURE__ */ new Set();
const watchedDirs = /* @__PURE__ */ new Set();
const watchFileStub = (id) => {
watchQueue.add(id);
};
let watchFile = watchFileStub;
const setPackageData = packageCache.set.bind(packageCache);
packageCache.set = (id, pkg) => {
if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) {
watchedDirs.add(pkg.dir);
watchFile(import_node_path3.default.join(pkg.dir, "package.json"));
}
return setPackageData(id, pkg);
};
return {
name: "vite:watch-package-data",
buildStart() {
watchFile = this.addWatchFile.bind(this);
watchQueue.forEach(watchFile);
watchQueue.clear();
},
buildEnd() {
watchFile = watchFileStub;
},
watchChange(id) {
if (id.endsWith("/package.json")) {
invalidatePackageData(packageCache, import_node_path3.default.normalize(id));
}
},
handleHotUpdate({ file }) {
if (file.endsWith("/package.json")) {
invalidatePackageData(packageCache, import_node_path3.default.normalize(file));
}
}
};
}
function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
const pkgData = packageCache.get(cacheKey);
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
});
return pkgData;
}
}
function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
});
}
function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
}
function getFnpdCache(packageCache, basedir, originalBasedir) {
const cacheKey = getFnpdCacheKey(basedir);
const pkgData = packageCache.get(cacheKey);
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getFnpdCacheKey(dir), pkgData);
});
return pkgData;
}
}
function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
packageCache.set(getFnpdCacheKey(basedir), pkgData);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
packageCache.set(getFnpdCacheKey(dir), pkgData);
});
}
function getFnpdCacheKey(basedir) {
return `fnpd_${basedir}`;
}
function traverseBetweenDirs(longerDir, shorterDir, cb) {
while (longerDir !== shorterDir) {
cb(longerDir);
longerDir = import_node_path3.default.dirname(longerDir);
}
}
var createFilter2 = createFilter$1;
var replaceSlashOrColonRE = /[/:]/g;
var replaceDotRE = /\./g;
var replaceNestedIdRE = /(\s*>\s*)/g;
var replaceHashRE = /#/g;
var flattenId = (id) => {
const flatId = limitFlattenIdLength(
id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____")
);
return flatId;
};
var FLATTEN_ID_HASH_LENGTH = 8;
var FLATTEN_ID_MAX_FILE_LENGTH = 170;
var limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
if (id.length <= limit) {
return id;
}
return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id);
};
var normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
var NODE_BUILTIN_NAMESPACE = "node:";
var NPM_BUILTIN_NAMESPACE = "npm:";
var BUN_BUILTIN_NAMESPACE = "bun:";
var nodeBuiltins = import_node_module.builtinModules.filter((id) => !id.includes(":"));
function isBuiltin(id) {
if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) return true;
if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) return true;
return isNodeBuiltin(id);
}
function isNodeBuiltin(id) {
if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
return nodeBuiltins.includes(id);
}
function isInNodeModules$1(id) {
return id.includes("node_modules");
}
function moduleListContains(moduleList, id) {
return moduleList == null ? void 0 : moduleList.some(
(m) => m === id || id.startsWith(withTrailingSlash(m))
);
}
function isOptimizable(id, optimizeDeps2) {
const { extensions: extensions2 } = optimizeDeps2;
return OPTIMIZABLE_ENTRY_RE.test(id) || ((extensions2 == null ? void 0 : extensions2.some((ext2) => id.endsWith(ext2))) ?? false);
}
var bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
var _require$1 = (0, import_node_module.createRequire)(import.meta.url);
function resolveDependencyVersion(dep, pkgRelativePath = "../../package.json") {
const pkgPath = import_node_path3.default.resolve(_require$1.resolve(dep), pkgRelativePath);
return JSON.parse(import_node_fs2.default.readFileSync(pkgPath, "utf-8")).version;
}
var rollupVersion = resolveDependencyVersion("rollup");
var filter = process.env.VITE_DEBUG_FILTER;
var DEBUG = process.env.DEBUG;
function createDebugger(namespace, options2 = {}) {
const log = debug$i(namespace);
const { onlyWhenFocused } = options2;
let enabled = log.enabled;
if (enabled && onlyWhenFocused) {
const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace;
enabled = !!(DEBUG == null ? void 0 : DEBUG.includes(ns));
}
if (enabled) {
return (...args) => {
if (!filter || args.some((a) => {
var _a4;
return (_a4 = a == null ? void 0 : a.includes) == null ? void 0 : _a4.call(a, filter);
})) {
log(...args);
}
};
}
}
function testCaseInsensitiveFS() {
if (!CLIENT_ENTRY.endsWith("client.mjs")) {
throw new Error(
`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
);
}
if (!import_node_fs2.default.existsSync(CLIENT_ENTRY)) {
throw new Error(
"cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY
);
}
return import_node_fs2.default.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
}
var urlCanParse = (
// eslint-disable-next-line n/no-unsupported-features/node-builtins
import_node_url2.URL.canParse ?? // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
((path22, base) => {
try {
new import_node_url2.URL(path22, base);
return true;
} catch {
return false;
}
})
);
var isCaseInsensitiveFS = testCaseInsensitiveFS();
var VOLUME_RE = /^[A-Z]:/i;
function normalizePath$3(id) {
return import_node_path3.default.posix.normalize(isWindows$3 ? slash$1(id) : id);
}
function fsPathFromId(id) {
const fsPath = normalizePath$3(
id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
);
return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
}
function fsPathFromUrl(url2) {
return fsPathFromId(cleanUrl(url2));
}
function isParentDirectory(dir, file) {
dir = withTrailingSlash(dir);
return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
}
function isSameFileUri(file1, file2) {
return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
}
var externalRE = /^(https?:)?\/\//;
var isExternalUrl = (url2) => externalRE.test(url2);
var dataUrlRE = /^\s*data:/i;
var isDataUrl = (url2) => dataUrlRE.test(url2);
var virtualModuleRE = /^virtual-module:.*/;
var virtualModulePrefix = "virtual-module:";
var knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
var isJSRequest = (url2) => {
url2 = cleanUrl(url2);
if (knownJsSrcRE.test(url2)) {
return true;
}
if (!import_node_path3.default.extname(url2) && url2[url2.length - 1] !== "/") {
return true;
}
return false;
};
var knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
var isTsRequest = (url2) => knownTsRE.test(url2);
var importQueryRE = /(\?|&)import=?(?:&|$)/;
var directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
var internalPrefixes = [
FS_PREFIX,
VALID_ID_PREFIX,
CLIENT_PUBLIC_PATH,
ENV_PUBLIC_PATH
];
var InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join("|")})`);
var trailingSeparatorRE = /[?&]$/;
var isImportRequest = (url2) => importQueryRE.test(url2);
var isInternalRequest = (url2) => InternalPrefixRE.test(url2);
function removeImportQuery(url2) {
return url2.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
}
function removeDirectQuery(url2) {
return url2.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
}
var urlRE = /(\?|&)url(?:&|$)/;
var rawRE = /(\?|&)raw(?:&|$)/;
function removeUrlQuery(url2) {
return url2.replace(urlRE, "$1").replace(trailingSeparatorRE, "");
}
var replacePercentageRE = /%/g;
function injectQuery(url2, queryToInject) {
const resolvedUrl = new import_node_url2.URL(
url2.replace(replacePercentageRE, "%25"),
"relative:///"
);
const { search, hash: hash2 } = resolvedUrl;
let pathname = cleanUrl(url2);
pathname = isWindows$3 ? slash$1(pathname) : pathname;
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash2 ?? ""}`;
}
var timestampRE = /\bt=\d{13}&?\b/;
function removeTimestampQuery(url2) {
return url2.replace(timestampRE, "").replace(trailingSeparatorRE, "");
}
async function asyncReplace(input, re, replacer) {
let match2;
let remaining = input;
let rewritten = "";
while (match2 = re.exec(remaining)) {
rewritten += remaining.slice(0, match2.index);
rewritten += await replacer(match2);
remaining = remaining.slice(match2.index + match2[0].length);
}
rewritten += remaining;
return rewritten;
}
function timeFrom(start, subtract = 0) {
const time = import_node_perf_hooks.performance.now() - start - subtract;
const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
if (time < 10) {
return colors$1.green(timeString);
} else if (time < 50) {
return colors$1.yellow(timeString);
} else {
return colors$1.red(timeString);
}
}
function prettifyUrl(url2, root) {
url2 = removeTimestampQuery(url2);
const isAbsoluteFile = url2.startsWith(root);
if (isAbsoluteFile || url2.startsWith(FS_PREFIX)) {
const file = import_node_path3.default.posix.relative(
root,
isAbsoluteFile ? url2 : fsPathFromId(url2)
);
return colors$1.dim(file);
} else {
return colors$1.dim(url2);
}
}
function isObject$1(value2) {
return Object.prototype.toString.call(value2) === "[object Object]";
}
function isDefined(value2) {
return value2 != null;
}
function tryStatSync(file) {
try {
return import_node_fs2.default.statSync(file, { throwIfNoEntry: false });
} catch {
}
}
function lookupFile(dir, fileNames) {
var _a4;
while (dir) {
for (const fileName of fileNames) {
const fullPath = import_node_path3.default.join(dir, fileName);
if ((_a4 = tryStatSync(fullPath)) == null ? void 0 : _a4.isFile()) return fullPath;
}
const parentDir2 = import_node_path3.default.dirname(dir);
if (parentDir2 === dir) return;
dir = parentDir2;
}
}
function isFilePathESM(filePath, packageCache) {
if (/\.m[jt]s$/.test(filePath)) {
return true;
} else if (/\.c[jt]s$/.test(filePath)) {
return false;
} else {
try {
const pkg = findNearestPackageData(import_node_path3.default.dirname(filePath), packageCache);
return (pkg == null ? void 0 : pkg.data.type) === "module";
} catch {
return false;
}
}
}
var splitRE = /\r?\n/g;
var range = 2;
function pad$1(source, n2 = 2) {
const lines = source.split(splitRE);
return lines.map((l) => ` `.repeat(n2) + l).join(`
`);
}
function posToNumber(source, pos) {
if (typeof pos === "number") return pos;
const lines = source.split(splitRE);
const { line, column } = pos;
let start = 0;
for (let i = 0; i < line - 1 && i < lines.length; i++) {
start += lines[i].length + 1;
}
return start + column;
}
function numberToPos(source, offset2) {
if (typeof offset2 !== "number") return offset2;
if (offset2 > source.length) {
throw new Error(
`offset is longer than source length! offset ${offset2} > length ${source.length}`
);
}
const lines = source.split(splitRE);
let counted = 0;
let line = 0;
let column = 0;
for (; line < lines.length; line++) {
const lineLength = lines[line].length + 1;
if (counted + lineLength >= offset2) {
column = offset2 - counted + 1;
break;
}
counted += lineLength;
}
return { line: line + 1, column };
}
function generateCodeFrame(source, start = 0, end) {
start = Math.max(posToNumber(source, start), 0);
end = Math.min(
end !== void 0 ? posToNumber(source, end) : start,
source.length
);
const lines = source.split(splitRE);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length;
if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) continue;
const line = j + 1;
res.push(
`${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`
);
const lineLength = lines[j].length;
if (j === i) {
const pad2 = Math.max(start - (count - lineLength), 0);
const length = Math.max(
1,
end > count ? lineLength - pad2 : end - start
);
res.push(` | ` + " ".repeat(pad2) + "^".repeat(length));
} else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + "^".repeat(length));
}
count += lineLength + 1;
}
}
break;
}
count++;
}
return res.join("\n");
}
function isFileReadable(filename) {
if (!tryStatSync(filename)) {
return false;
}
try {
import_node_fs2.default.accessSync(filename, import_node_fs2.default.constants.R_OK);
return true;
} catch {
return false;
}
}
var splitFirstDirRE = /(.+?)[\\/](.+)/;
function emptyDir(dir, skip) {
const skipInDir = [];
let nested = null;
if (skip == null ? void 0 : skip.length) {
for (const file of skip) {
if (import_node_path3.default.dirname(file) !== ".") {
const matched = file.match(splitFirstDirRE);
if (matched) {
nested ?? (nested = /* @__PURE__ */ new Map());
const [, nestedDir, skipPath] = matched;
let nestedSkip = nested.get(nestedDir);
if (!nestedSkip) {
nestedSkip = [];
nested.set(nestedDir, nestedSkip);
}
if (!nestedSkip.includes(skipPath)) {
nestedSkip.push(skipPath);
}
}
} else {
skipInDir.push(file);
}
}
}
for (const file of import_node_fs2.default.readdirSync(dir)) {
if (skipInDir.includes(file)) {
continue;
}
if (nested == null ? void 0 : nested.has(file)) {
emptyDir(import_node_path3.default.resolve(dir, file), nested.get(file));
} else {
import_node_fs2.default.rmSync(import_node_path3.default.resolve(dir, file), { recursive: true, force: true });
}
}
}
function copyDir(srcDir, destDir) {
import_node_fs2.default.mkdirSync(destDir, { recursive: true });
for (const file of import_node_fs2.default.readdirSync(srcDir)) {
const srcFile = import_node_path3.default.resolve(srcDir, file);
if (srcFile === destDir) {
continue;
}
const destFile = import_node_path3.default.resolve(destDir, file);
const stat2 = import_node_fs2.default.statSync(srcFile);
if (stat2.isDirectory()) {
copyDir(srcFile, destFile);
} else {
import_node_fs2.default.copyFileSync(srcFile, destFile);
}
}
}
var ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
async function recursiveReaddir(dir) {
if (!import_node_fs2.default.existsSync(dir)) {
return [];
}
let dirents;
try {
dirents = await import_promises.default.readdir(dir, { withFileTypes: true });
} catch (e2) {
if (e2.code === "EACCES") {
return [];
}
throw e2;
}
if (dirents.some((dirent) => dirent.isSymbolicLink())) {
const err2 = new Error(
"Symbolic links are not supported in recursiveReaddir"
);
err2.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
throw err2;
}
const files = await Promise.all(
dirents.map((dirent) => {
const res = import_node_path3.default.resolve(dir, dirent.name);
return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res);
})
);
return files.flat(1);
}
var safeRealpathSync = isWindows$3 ? windowsSafeRealPathSync : import_node_fs2.default.realpathSync.native;
var windowsNetworkMap = /* @__PURE__ */ new Map();
function windowsMappedRealpathSync(path22) {
const realPath = import_node_fs2.default.realpathSync.native(path22);
if (realPath.startsWith("\\\\")) {
for (const [network, volume] of windowsNetworkMap) {
if (realPath.startsWith(network)) return realPath.replace(network, volume);
}
}
return realPath;
}
var parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/;
var firstSafeRealPathSyncRun = false;
function windowsSafeRealPathSync(path22) {
if (!firstSafeRealPathSyncRun) {
optimizeSafeRealPathSync();
firstSafeRealPathSyncRun = true;
}
return import_node_fs2.default.realpathSync(path22);
}
function optimizeSafeRealPathSync() {
const nodeVersion = process.versions.node.split(".").map(Number);
if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
safeRealpathSync = import_node_fs2.default.realpathSync;
return;
}
try {
import_node_fs2.default.realpathSync.native(import_node_path3.default.resolve("./"));
} catch (error2) {
if (error2.message.includes("EISDIR: illegal operation on a directory")) {
safeRealpathSync = import_node_fs2.default.realpathSync;
return;
}
}
(0, import_node_child_process.exec)("net use", (error2, stdout) => {
if (error2) return;
const lines = stdout.split("\n");
for (const line of lines) {
const m = line.match(parseNetUseRE);
if (m) windowsNetworkMap.set(m[3], m[2]);
}
if (windowsNetworkMap.size === 0) {
safeRealpathSync = import_node_fs2.default.realpathSync.native;
} else {
safeRealpathSync = windowsMappedRealpathSync;
}
});
}
function ensureWatchedFile(watcher, file, root) {
if (file && // only need to watch if out of root
!file.startsWith(withTrailingSlash(root)) && // some rollup plugins use null bytes for private resolved Ids
!file.includes("\0") && import_node_fs2.default.existsSync(file)) {
watcher.add(import_node_path3.default.resolve(file));
}
}
var escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
var imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
function joinSrcset(ret) {
return ret.map(({ url: url2, descriptor }) => url2 + (descriptor ? ` ${descriptor}` : "")).join(", ");
}
function splitSrcSetDescriptor(srcs) {
return splitSrcSet(srcs).map((s) => {
var _a4;
const src2 = s.replace(escapedSpaceCharacters, " ").trim();
const url2 = ((_a4 = imageSetUrlRE.exec(src2)) == null ? void 0 : _a4[0]) ?? "";
return {
url: url2,
descriptor: src2.slice(url2.length).trim()
};
}).filter(({ url: url2 }) => !!url2);
}
function processSrcSet(srcs, replacer) {
return Promise.all(
splitSrcSetDescriptor(srcs).map(async ({ url: url2, descriptor }) => ({
url: await replacer({ url: url2, descriptor }),
descriptor
}))
).then(joinSrcset);
}
function processSrcSetSync(srcs, replacer) {
return joinSrcset(
splitSrcSetDescriptor(srcs).map(({ url: url2, descriptor }) => ({
url: replacer({ url: url2, descriptor }),
descriptor
}))
);
}
var cleanSrcSetRE = new RegExp(`(?:url|image|gradient|cross-fade)\\([^)]*\\)|"([^"]|(?<=\\\\)")*"|'([^']|(?<=\\\\)')*'|data:\\w+\\/[\\w.+\\-]+;base64,[\\w+/=]+|\\?\\S+,`, "g");
function splitSrcSet(srcs) {
const parts = [];
const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer);
let startIndex = 0;
let splitIndex;
do {
splitIndex = cleanedSrcs.indexOf(",", startIndex);
parts.push(
srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : void 0)
);
startIndex = splitIndex + 1;
} while (splitIndex !== -1);
return parts;
}
var windowsDriveRE = /^[A-Z]:/;
var replaceWindowsDriveRE = /^([A-Z]):\//;
var linuxAbsolutePathRE = /^\/[^/]/;
function escapeToLinuxLikePath(path22) {
if (windowsDriveRE.test(path22)) {
return path22.replace(replaceWindowsDriveRE, "/windows/$1/");
}
if (linuxAbsolutePathRE.test(path22)) {
return `/linux${path22}`;
}
return path22;
}
var revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
function unescapeToLinuxLikePath(path22) {
if (path22.startsWith("/linux/")) {
return path22.slice("/linux".length);
}
if (path22.startsWith("/windows/")) {
return path22.replace(revertWindowsDriveRE, "$1:/");
}
return path22;
}
var nullSourceMap = {
names: [],
sources: [],
mappings: "",
version: 3
};
function combineSourcemaps(filename, sourcemapList) {
if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) {
return { ...nullSourceMap };
}
sourcemapList = sourcemapList.map((sourcemap) => {
const newSourcemaps = { ...sourcemap };
newSourcemaps.sources = sourcemap.sources.map(
(source) => source ? escapeToLinuxLikePath(source) : null
);
if (sourcemap.sourceRoot) {
newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
}
return newSourcemaps;
});
let map2;
let mapIndex = 1;
const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
if (useArrayInterface) {
map2 = remapping(sourcemapList, () => null);
} else {
map2 = remapping(sourcemapList[0], function loader(sourcefile) {
const mapForSources = sourcemapList.slice(mapIndex).find((s) => s.sources.includes(sourcefile));
if (mapForSources) {
mapIndex++;
return mapForSources;
}
return null;
});
}
if (!map2.file) {
delete map2.file;
}
map2.sources = map2.sources.map(
(source) => source ? unescapeToLinuxLikePath(source) : source
);
map2.file = filename;
return map2;
}
function unique(arr) {
return Array.from(new Set(arr));
}
async function getLocalhostAddressIfDiffersFromDNS() {
const [nodeResult, dnsResult] = await Promise.all([
import_node_dns.promises.lookup("localhost"),
import_node_dns.promises.lookup("localhost", { verbatim: true })
]);
const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;
return isSame ? void 0 : nodeResult.address;
}
function diffDnsOrderChange(oldUrls, newUrls) {
return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
}
async function resolveHostname(optionsHost) {
let host;
if (optionsHost === void 0 || optionsHost === false) {
host = "localhost";
} else if (optionsHost === true) {
host = void 0;
} else {
host = optionsHost;
}
let name2 = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
if (host === "localhost") {
const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
if (localhostAddr) {
name2 = localhostAddr;
}
}
return { host, name: name2 };
}
async function resolveServerUrls(server2, options2, config2) {
const address = server2.address();
const isAddressInfo = (x) => x == null ? void 0 : x.address;
if (!isAddressInfo(address)) {
return { local: [], network: [] };
}
const local = [];
const network = [];
const hostname = await resolveHostname(options2.host);
const protocol = options2.https ? "https" : "http";
const port = address.port;
const base = config2.rawBase === "./" || config2.rawBase === "" ? "/" : config2.rawBase;
if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
let hostnameName = hostname.name;
if (hostnameName.includes(":")) {
hostnameName = `[${hostnameName}]`;
}
const address2 = `${protocol}://${hostnameName}:${port}${base}`;
if (loopbackHosts.has(hostname.host)) {
local.push(address2);
} else {
network.push(address2);
}
} else {
Object.values(import_node_os.default.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter(
(detail) => detail && detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number
detail.family === 4)
).forEach((detail) => {
let host = detail.address.replace("127.0.0.1", hostname.name);
if (host.includes(":")) {
host = `[${host}]`;
}
const url2 = `${protocol}://${host}:${port}${base}`;
if (detail.address.includes("127.0.0.1")) {
local.push(url2);
} else {
network.push(url2);
}
});
}
return { local, network };
}
function arraify(target) {
return Array.isArray(target) ? target : [target];
}
var multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
var singlelineCommentsRE = /\/\/.*/g;
var requestQuerySplitRE = /\?(?!.*[/|}])/;
var requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
var blankReplacer = (match2) => " ".repeat(match2.length);
function getHash(text, length = 8) {
const h = (0, import_node_crypto.createHash)("sha256").update(text).digest("hex").substring(0, length);
if (length <= 64) return h;
return h.padEnd(length, "_");
}
var _dirname = import_node_path3.default.dirname((0, import_node_url2.fileURLToPath)(import.meta.url));
var requireResolveFromRootWithFallback = (root, id) => {
const found2 = resolvePackageData(id, root) || resolvePackageData(id, _dirname);
if (!found2) {
const error2 = new Error(`${JSON.stringify(id)} not found.`);
error2.code = "MODULE_NOT_FOUND";
throw error2;
}
return _require$1.resolve(id, { paths: [root, _dirname] });
};
function emptyCssComments(raw) {
return raw.replace(multilineCommentsRE, blankReplacer);
}
function backwardCompatibleWorkerPlugins(plugins2) {
if (Array.isArray(plugins2)) {
return plugins2;
}
if (typeof plugins2 === "function") {
return plugins2();
}
return [];
}
function mergeConfigRecursively(defaults2, overrides, rootPath) {
const merged = { ...defaults2 };
for (const key in overrides) {
const value2 = overrides[key];
if (value2 == null) {
continue;
}
const existing = merged[key];
if (existing == null) {
merged[key] = value2;
continue;
}
if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
merged[key] = mergeAlias(existing, value2);
continue;
} else if (key === "assetsInclude" && rootPath === "") {
merged[key] = [].concat(existing, value2);
continue;
} else if (key === "noExternal" && rootPath === "ssr" && (existing === true || value2 === true)) {
merged[key] = true;
continue;
} else if (key === "plugins" && rootPath === "worker") {
merged[key] = () => [
...backwardCompatibleWorkerPlugins(existing),
...backwardCompatibleWorkerPlugins(value2)
];
continue;
}
if (Array.isArray(existing) || Array.isArray(value2)) {
merged[key] = [...arraify(existing), ...arraify(value2)];
continue;
}
if (isObject$1(existing) && isObject$1(value2)) {
merged[key] = mergeConfigRecursively(
existing,
value2,
rootPath ? `${rootPath}.${key}` : key
);
continue;
}
merged[key] = value2;
}
return merged;
}
function mergeConfig(defaults2, overrides, isRoot = true) {
if (typeof defaults2 === "function" || typeof overrides === "function") {
throw new Error(`Cannot merge config in form of callback`);
}
return mergeConfigRecursively(defaults2, overrides, isRoot ? "" : ".");
}
function mergeAlias(a, b) {
if (!a) return b;
if (!b) return a;
if (isObject$1(a) && isObject$1(b)) {
return { ...a, ...b };
}
return [...normalizeAlias(b), ...normalizeAlias(a)];
}
function normalizeAlias(o2 = []) {
return Array.isArray(o2) ? o2.map(normalizeSingleAlias) : Object.keys(o2).map(
(find2) => normalizeSingleAlias({
find: find2,
replacement: o2[find2]
})
);
}
function normalizeSingleAlias({
find: find2,
replacement,
customResolver
}) {
if (typeof find2 === "string" && find2[find2.length - 1] === "/" && replacement[replacement.length - 1] === "/") {
find2 = find2.slice(0, find2.length - 1);
replacement = replacement.slice(0, replacement.length - 1);
}
const alias2 = {
find: find2,
replacement
};
if (customResolver) {
alias2.customResolver = customResolver;
}
return alias2;
}
function transformStableResult(s, id, config2) {
return {
code: s.toString(),
map: config2.command === "build" && config2.build.sourcemap ? s.generateMap({ hires: "boundary", source: id }) : null
};
}
async function asyncFlatten(arr) {
do {
arr = (await Promise.all(arr)).flat(Infinity);
} while (arr.some((v) => v == null ? void 0 : v.then));
return arr;
}
function stripBomTag(content) {
if (content.charCodeAt(0) === 65279) {
return content.slice(1);
}
return content;
}
var windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
var isNonDriveRelativeAbsolutePath = (p) => {
if (!isWindows$3) return p[0] === "/";
return windowsDrivePathPrefixRE.test(p);
};
function shouldServeFile(filePath, root) {
if (!isCaseInsensitiveFS) return true;
return hasCorrectCase(filePath, root);
}
function hasCorrectCase(file, assets) {
if (file === assets) return true;
const parent = import_node_path3.default.dirname(file);
if (import_node_fs2.default.readdirSync(parent).includes(import_node_path3.default.basename(file))) {
return hasCorrectCase(parent, assets);
}
return false;
}
function joinUrlSegments(a, b) {
if (!a || !b) {
return a || b || "";
}
if (a[a.length - 1] === "/") {
a = a.substring(0, a.length - 1);
}
if (b[0] !== "/") {
b = "/" + b;
}
return a + b;
}
function removeLeadingSlash(str) {
return str[0] === "/" ? str.slice(1) : str;
}
function stripBase(path22, base) {
if (path22 === base) {
return "/";
}
const devBase = withTrailingSlash(base);
return path22.startsWith(devBase) ? path22.slice(devBase.length - 1) : path22;
}
function arrayEqual(a, b) {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
function evalValue(rawValue) {
const fn = new Function(`
var console, exports, global, module, process, require
return (
${rawValue}
)
`);
return fn();
}
function getNpmPackageName(importPath) {
const parts = importPath.split("/");
if (parts[0][0] === "@") {
if (!parts[1]) return null;
return `${parts[0]}/${parts[1]}`;
} else {
return parts[0];
}
}
var escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
return str.replace(escapeRegexRE, "\\$&");
}
function getPackageManagerCommand(type = "install") {
var _a4;
const packageManager = ((_a4 = process.env.npm_config_user_agent) == null ? void 0 : _a4.split(" ")[0].split("/")[0]) || "npm";
switch (type) {
case "install":
return packageManager === "npm" ? "npm install" : `${packageManager} add`;
case "uninstall":
return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
case "update":
return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
default:
throw new TypeError(`Unknown command type: ${type}`);
}
}
function isDevServer(server2) {
return "pluginContainer" in server2;
}
function promiseWithResolvers() {
let resolve3;
let reject;
const promise2 = new Promise((_resolve, _reject) => {
resolve3 = _resolve;
reject = _reject;
});
return { promise: promise2, resolve: resolve3, reject };
}
function createSerialPromiseQueue() {
let previousTask;
return {
async run(f2) {
const thisTask = f2();
const depTasks = Promise.all([previousTask, thisTask]);
previousTask = depTasks;
const [, result] = await depTasks;
if (previousTask === depTasks) {
previousTask = void 0;
}
return result;
}
};
}
function sortObjectKeys(obj) {
const sorted = {};
for (const key of Object.keys(obj).sort()) {
sorted[key] = obj[key];
}
return sorted;
}
function displayTime(time) {
if (time < 1e3) {
return `${time}ms`;
}
time = time / 1e3;
if (time < 60) {
return `${time.toFixed(2)}s`;
}
const mins = parseInt((time / 60).toString());
const seconds = time % 60;
return `${mins}m${seconds < 1 ? "" : ` ${seconds.toFixed(0)}s`}`;
}
function encodeURIPath(uri) {
if (uri.startsWith("data:")) return uri;
const filePath = cleanUrl(uri);
const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
return encodeURI(filePath) + postfix;
}
function partialEncodeURIPath(uri) {
if (uri.startsWith("data:")) return uri;
const filePath = cleanUrl(uri);
const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
return filePath.replaceAll("%", "%25") + postfix;
}
var setupSIGTERMListener = (callback) => {
process.once("SIGTERM", callback);
if (process.env.CI !== "true") {
process.stdin.on("end", callback);
}
};
var teardownSIGTERMListener = (callback) => {
process.off("SIGTERM", callback);
if (process.env.CI !== "true") {
process.stdin.off("end", callback);
}
};
var LogLevels = {
silent: 0,
error: 1,
warn: 2,
info: 3
};
var lastType;
var lastMsg;
var sameCount = 0;
function clearScreen() {
const repeatCount = process.stdout.rows - 2;
const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
console.log(blank);
import_node_readline.default.cursorTo(process.stdout, 0, 0);
import_node_readline.default.clearScreenDown(process.stdout);
}
var timeFormatter;
function getTimeFormatter() {
timeFormatter ?? (timeFormatter = new Intl.DateTimeFormat(void 0, {
hour: "numeric",
minute: "numeric",
second: "numeric"
}));
return timeFormatter;
}
function createLogger(level = "info", options2 = {}) {
if (options2.customLogger) {
return options2.customLogger;
}
const loggedErrors = /* @__PURE__ */ new WeakSet();
const { prefix = "[vite]", allowClearScreen = true } = options2;
const thresh = LogLevels[level];
const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
const clear = canClearScreen ? clearScreen : () => {
};
function format2(type, msg, options22 = {}) {
if (options22.timestamp) {
let tag = "";
if (type === "info") {
tag = colors$1.cyan(colors$1.bold(prefix));
} else if (type === "warn") {
tag = colors$1.yellow(colors$1.bold(prefix));
} else {
tag = colors$1.red(colors$1.bold(prefix));
}
return `${colors$1.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${msg}`;
} else {
return msg;
}
}
function output(type, msg, options22 = {}) {
if (thresh >= LogLevels[type]) {
const method = type === "info" ? "log" : type;
if (options22.error) {
loggedErrors.add(options22.error);
}
if (canClearScreen) {
if (type === lastType && msg === lastMsg) {
sameCount++;
clear();
console[method](
format2(type, msg, options22),
colors$1.yellow(`(x${sameCount + 1})`)
);
} else {
sameCount = 0;
lastMsg = msg;
lastType = type;
if (options22.clear) {
clear();
}
console[method](format2(type, msg, options22));
}
} else {
console[method](format2(type, msg, options22));
}
}
}
const warnedMessages = /* @__PURE__ */ new Set();
const logger = {
hasWarned: false,
info(msg, opts) {
output("info", msg, opts);
},
warn(msg, opts) {
logger.hasWarned = true;
output("warn", msg, opts);
},
warnOnce(msg, opts) {
if (warnedMessages.has(msg)) return;
logger.hasWarned = true;
output("warn", msg, opts);
warnedMessages.add(msg);
},
error(msg, opts) {
logger.hasWarned = true;
output("error", msg, opts);
},
clearScreen(type) {
if (thresh >= LogLevels[type]) {
clear();
}
},
hasErrorLogged(error2) {
return loggedErrors.has(error2);
}
};
return logger;
}
function printServerUrls(urls, optionsHost, info) {
const colorUrl = (url2) => colors$1.cyan(url2.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`));
for (const url2 of urls.local) {
info(` ${colors$1.green("➜")} ${colors$1.bold("Local")}: ${colorUrl(url2)}`);
}
for (const url2 of urls.network) {
info(` ${colors$1.green("➜")} ${colors$1.bold("Network")}: ${colorUrl(url2)}`);
}
if (urls.network.length === 0 && optionsHost === void 0) {
info(
colors$1.dim(` ${colors$1.green("➜")} ${colors$1.bold("Network")}: use `) + colors$1.bold("--host") + colors$1.dim(" to expose")
);
}
}
var groups = [
{ name: "Assets", color: colors$1.green },
{ name: "CSS", color: colors$1.magenta },
{ name: "JS", color: colors$1.cyan }
];
var COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
function buildReporterPlugin(config2) {
const compress = (0, import_node_util.promisify)(import_node_zlib.gzip);
const chunkLimit = config2.build.chunkSizeWarningLimit;
const numberFormatter = new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
minimumFractionDigits: 2
});
const displaySize = (bytes) => {
return `${numberFormatter.format(bytes / 1e3)} kB`;
};
const tty = process.stdout.isTTY && !process.env.CI;
const shouldLogInfo = LogLevels[config2.logLevel || "info"] >= LogLevels.info;
let hasTransformed = false;
let hasRenderedChunk = false;
let hasCompressChunk = false;
let transformedCount = 0;
let chunkCount = 0;
let compressedCount = 0;
async function getCompressedSize(code) {
if (config2.build.ssr || !config2.build.reportCompressedSize) {
return null;
}
if (shouldLogInfo && !hasCompressChunk) {
if (!tty) {
config2.logger.info("computing gzip size...");
} else {
writeLine("computing gzip size (0)...");
}
hasCompressChunk = true;
}
const compressed = await compress(
typeof code === "string" ? code : Buffer.from(code)
);
compressedCount++;
if (shouldLogInfo && tty) {
writeLine(`computing gzip size (${compressedCount})...`);
}
return compressed.length;
}
const logTransform = throttle((id) => {
writeLine(
`transforming (${transformedCount}) ${colors$1.dim(
import_node_path3.default.relative(config2.root, id)
)}`
);
});
return {
name: "vite:reporter",
transform(_, id) {
transformedCount++;
if (shouldLogInfo) {
if (!tty) {
if (!hasTransformed) {
config2.logger.info(`transforming...`);
}
} else {
if (id.includes(`?`)) return;
logTransform(id);
}
hasTransformed = true;
}
return null;
},
buildStart() {
transformedCount = 0;
},
buildEnd() {
if (shouldLogInfo) {
if (tty) {
clearLine$1();
}
config2.logger.info(
`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`
);
}
},
renderStart() {
chunkCount = 0;
compressedCount = 0;
},
renderChunk(code, chunk, options2) {
if (!options2.inlineDynamicImports) {
for (const id of chunk.moduleIds) {
const module = this.getModuleInfo(id);
if (!module) continue;
if (module.importers.length && module.dynamicImporters.length) {
const detectedIneffectiveDynamicImport = module.dynamicImporters.some(
(id2) => !isInNodeModules$1(id2) && chunk.moduleIds.includes(id2)
);
if (detectedIneffectiveDynamicImport) {
this.warn(
`
(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(
", "
)} but also statically imported by ${module.importers.join(
", "
)}, dynamic import will not move module into another chunk.
`
);
}
}
}
}
chunkCount++;
if (shouldLogInfo) {
if (!tty) {
if (!hasRenderedChunk) {
config2.logger.info("rendering chunks...");
}
} else {
writeLine(`rendering chunks (${chunkCount})...`);
}
hasRenderedChunk = true;
}
return null;
},
generateBundle() {
if (shouldLogInfo && tty) clearLine$1();
},
async writeBundle({ dir: outDir }, output) {
let hasLargeChunks = false;
if (shouldLogInfo) {
const entries = (await Promise.all(
Object.values(output).map(
async (chunk) => {
if (chunk.type === "chunk") {
return {
name: chunk.fileName,
group: "JS",
size: chunk.code.length,
compressedSize: await getCompressedSize(chunk.code),
mapSize: chunk.map ? chunk.map.toString().length : null
};
} else {
if (chunk.fileName.endsWith(".map")) return null;
const isCSS = chunk.fileName.endsWith(".css");
const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
return {
name: chunk.fileName,
group: isCSS ? "CSS" : "Assets",
size: chunk.source.length,
mapSize: null,
// Rollup doesn't support CSS maps?
compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null
};
}
}
)
)).filter(isDefined);
if (tty) clearLine$1();
let longest = 0;
let biggestSize = 0;
let biggestMap = 0;
let biggestCompressSize = 0;
for (const entry2 of entries) {
if (entry2.name.length > longest) longest = entry2.name.length;
if (entry2.size > biggestSize) biggestSize = entry2.size;
if (entry2.mapSize && entry2.mapSize > biggestMap) {
biggestMap = entry2.mapSize;
}
if (entry2.compressedSize && entry2.compressedSize > biggestCompressSize) {
biggestCompressSize = entry2.compressedSize;
}
}
const sizePad = displaySize(biggestSize).length;
const mapPad = displaySize(biggestMap).length;
const compressPad = displaySize(biggestCompressSize).length;
const relativeOutDir = normalizePath$3(
import_node_path3.default.relative(
config2.root,
import_node_path3.default.resolve(config2.root, outDir ?? config2.build.outDir)
)
);
const assetsDir = import_node_path3.default.join(config2.build.assetsDir, "/");
for (const group of groups) {
const filtered = entries.filter((e2) => e2.group === group.name);
if (!filtered.length) continue;
for (const entry2 of filtered.sort((a, z) => a.size - z.size)) {
const isLarge = group.name === "JS" && entry2.size / 1e3 > chunkLimit;
if (isLarge) hasLargeChunks = true;
const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
let log = colors$1.dim(withTrailingSlash(relativeOutDir));
log += !config2.build.lib && entry2.name.startsWith(withTrailingSlash(assetsDir)) ? colors$1.dim(assetsDir) + group.color(
entry2.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length)
) : group.color(entry2.name.padEnd(longest + 2));
log += colors$1.bold(
sizeColor(displaySize(entry2.size).padStart(sizePad))
);
if (entry2.compressedSize) {
log += colors$1.dim(
` │ gzip: ${displaySize(entry2.compressedSize).padStart(
compressPad
)}`
);
}
if (entry2.mapSize) {
log += colors$1.dim(
` │ map: ${displaySize(entry2.mapSize).padStart(mapPad)}`
);
}
config2.logger.info(log);
}
}
} else {
hasLargeChunks = Object.values(output).some((chunk) => {
return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit;
});
}
if (hasLargeChunks && config2.build.minify && !config2.build.lib && !config2.build.ssr) {
config2.logger.warn(
colors$1.yellow(
`
(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`
)
);
}
}
};
}
function writeLine(output) {
clearLine$1();
if (output.length < process.stdout.columns) {
process.stdout.write(output);
} else {
process.stdout.write(output.substring(0, process.stdout.columns - 1));
}
}
function clearLine$1() {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
}
function throttle(fn) {
let timerHandle = null;
return (...args) => {
if (timerHandle) return;
fn(...args);
timerHandle = setTimeout(() => {
timerHandle = null;
}, 100);
};
}
var POSIX_SEP_RE = new RegExp("\\" + import_node_path3.default.posix.sep, "g");
var NATIVE_SEP_RE = new RegExp("\\" + import_node_path3.default.sep, "g");
var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
var GLOB_ALL_PATTERN = `**/*`;
var TS_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
var JS_EXTENSIONS = [".js", ".jsx", ".mjs", ".cjs"];
var TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS);
var TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext2) => ext2.substring(1)).join("|")})`;
var TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext2) => ext2.substring(1)).join(
"|"
)})`;
var IS_POSIX = import_node_path3.default.posix.sep === import_node_path3.default.sep;
function makePromise() {
let resolve3, reject;
const promise2 = new Promise((res, rej) => {
resolve3 = res;
reject = rej;
});
return { promise: promise2, resolve: resolve3, reject };
}
async function resolveTSConfigJson(filename, cache) {
if (import_node_path3.default.extname(filename) !== ".json") {
return;
}
const tsconfig = import_node_path3.default.resolve(filename);
if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) {
return tsconfig;
}
return import_node_fs2.promises.stat(tsconfig).then((stat2) => {
if (stat2.isFile() || stat2.isFIFO()) {
return tsconfig;
} else {
throw new Error(`${filename} exists but is not a regular file.`);
}
});
}
var isInNodeModules = IS_POSIX ? (dir) => dir.includes("/node_modules/") : (dir) => dir.match(/[/\\]node_modules[/\\]/);
var posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, import_node_path3.default.sep);
var native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, import_node_path3.default.posix.sep);
var resolve2posix = IS_POSIX ? (dir, filename) => dir ? import_node_path3.default.resolve(dir, filename) : import_node_path3.default.resolve(filename) : (dir, filename) => native2posix(
dir ? import_node_path3.default.resolve(posix2native(dir), posix2native(filename)) : import_node_path3.default.resolve(posix2native(filename))
);
function resolveReferencedTSConfigFiles(result, options2) {
const dir = import_node_path3.default.dirname(result.tsconfigFile);
return result.tsconfig.references.map((ref) => {
const refPath = ref.path.endsWith(".json") ? ref.path : import_node_path3.default.join(ref.path, (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json");
return resolve2posix(dir, refPath);
});
}
function resolveSolutionTSConfig(filename, result) {
var _a4;
const allowJs = (_a4 = result.tsconfig.compilerOptions) == null ? void 0 : _a4.allowJs;
const extensions2 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
if (result.referenced && extensions2.some((ext2) => filename.endsWith(ext2)) && !isIncluded(filename, result)) {
const solutionTSConfig = result.referenced.find(
(referenced) => isIncluded(filename, referenced)
);
if (solutionTSConfig) {
return solutionTSConfig;
}
}
return result;
}
function isIncluded(filename, result) {
var _a4;
const dir = native2posix(import_node_path3.default.dirname(result.tsconfigFile));
const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
const absoluteFilename = resolve2posix(null, filename);
if (files.includes(filename)) {
return true;
}
const allowJs = (_a4 = result.tsconfig.compilerOptions) == null ? void 0 : _a4.allowJs;
const isIncluded2 = isGlobMatch(
absoluteFilename,
dir,
result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]),
allowJs
);
if (isIncluded2) {
const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
return !isExcluded;
}
return false;
}
function isGlobMatch(filename, dir, patterns, allowJs) {
const extensions2 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
return patterns.some((pattern2) => {
let lastWildcardIndex = pattern2.length;
let hasWildcard = false;
for (let i = pattern2.length - 1; i > -1; i--) {
if (pattern2[i] === "*" || pattern2[i] === "?") {
lastWildcardIndex = i;
hasWildcard = true;
break;
}
}
if (lastWildcardIndex < pattern2.length - 1 && !filename.endsWith(pattern2.slice(lastWildcardIndex + 1))) {
return false;
}
if (pattern2.endsWith("*") && !extensions2.some((ext2) => filename.endsWith(ext2))) {
return false;
}
if (pattern2 === GLOB_ALL_PATTERN) {
return filename.startsWith(`${dir}/`);
}
const resolvedPattern = resolve2posix(dir, pattern2);
let firstWildcardIndex = -1;
for (let i = 0; i < resolvedPattern.length; i++) {
if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
firstWildcardIndex = i;
hasWildcard = true;
break;
}
}
if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
return false;
}
if (!hasWildcard) {
return filename === resolvedPattern;
}
if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
}
const regex2 = pattern2regex(resolvedPattern, allowJs);
PATTERN_REGEX_CACHE.set(resolvedPattern, regex2);
return regex2.test(filename);
});
}
function pattern2regex(resolvedPattern, allowJs) {
let regexStr = "^";
for (let i = 0; i < resolvedPattern.length; i++) {
const char = resolvedPattern[i];
if (char === "?") {
regexStr += "[^\\/]";
continue;
}
if (char === "*") {
if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
i += 2;
regexStr += "(?:[^\\/]*\\/)*";
continue;
}
regexStr += "[^\\/]*";
continue;
}
if ("/.+^${}()|[]\\".includes(char)) {
regexStr += `\\`;
}
regexStr += char;
}
if (resolvedPattern.endsWith("*")) {
regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
}
regexStr += "$";
return new RegExp(regexStr);
}
function replaceTokens(tsconfig, configDir) {
return JSON.parse(
JSON.stringify(tsconfig).replaceAll(/"(?:\.\.\/)*\${configDir}/g, `"${native2posix(configDir)}`)
);
}
async function find(filename, options2) {
let dir = import_node_path3.default.dirname(import_node_path3.default.resolve(filename));
if ((options2 == null ? void 0 : options2.ignoreNodeModules) && isInNodeModules(dir)) {
return null;
}
const cache = options2 == null ? void 0 : options2.cache;
const configName = (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json";
if (cache == null ? void 0 : cache.hasConfigPath(dir, configName)) {
return cache.getConfigPath(dir, configName);
}
const {
/** @type {Promise<string|null>} */
promise: promise2,
resolve: resolve3,
reject
} = makePromise();
if ((options2 == null ? void 0 : options2.root) && !import_node_path3.default.isAbsolute(options2.root)) {
options2.root = import_node_path3.default.resolve(options2.root);
}
findUp(dir, { promise: promise2, resolve: resolve3, reject }, options2);
return promise2;
}
function findUp(dir, { resolve: resolve3, reject, promise: promise2 }, options2) {
const { cache, root, configName } = options2 ?? {};
if (cache) {
if (cache.hasConfigPath(dir, configName)) {
let cached;
try {
cached = cache.getConfigPath(dir, configName);
} catch (e2) {
reject(e2);
return;
}
if (cached == null ? void 0 : cached.then) {
cached.then(resolve3).catch(reject);
} else {
resolve3(cached);
}
} else {
cache.setConfigPath(dir, promise2, configName);
}
}
const tsconfig = import_node_path3.default.join(dir, (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json");
import_node_fs2.default.stat(tsconfig, (err2, stats) => {
if (stats && (stats.isFile() || stats.isFIFO())) {
resolve3(tsconfig);
} else if ((err2 == null ? void 0 : err2.code) !== "ENOENT") {
reject(err2);
} else {
let parent;
if (root === dir || (parent = import_node_path3.default.dirname(dir)) === dir) {
resolve3(null);
} else {
findUp(parent, { promise: promise2, resolve: resolve3, reject }, options2);
}
}
});
}
function toJson(tsconfigJson) {
const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
if (stripped.trim() === "") {
return "{}";
} else {
return stripped;
}
}
function stripDanglingComma(pseudoJson) {
let insideString = false;
let offset2 = 0;
let result = "";
let danglingCommaPos = null;
for (let i = 0; i < pseudoJson.length; i++) {
const currentCharacter = pseudoJson[i];
if (currentCharacter === '"') {
const escaped2 = isEscaped(pseudoJson, i);
if (!escaped2) {
insideString = !insideString;
}
}
if (insideString) {
danglingCommaPos = null;
continue;
}
if (currentCharacter === ",") {
danglingCommaPos = i;
continue;
}
if (danglingCommaPos) {
if (currentCharacter === "}" || currentCharacter === "]") {
result += pseudoJson.slice(offset2, danglingCommaPos) + " ";
offset2 = danglingCommaPos + 1;
danglingCommaPos = null;
} else if (!currentCharacter.match(/\s/)) {
danglingCommaPos = null;
}
}
}
return result + pseudoJson.substring(offset2);
}
function isEscaped(jsonString, quotePosition) {
let index = quotePosition - 1;
let backslashCount = 0;
while (jsonString[index] === "\\") {
index -= 1;
backslashCount += 1;
}
return Boolean(backslashCount % 2);
}
function strip(string2, start, end) {
return string2.slice(start, end).replace(/\S/g, " ");
}
var singleComment = Symbol("singleComment");
var multiComment = Symbol("multiComment");
function stripJsonComments(jsonString) {
let isInsideString = false;
let isInsideComment = false;
let offset2 = 0;
let result = "";
for (let index = 0; index < jsonString.length; index++) {
const currentCharacter = jsonString[index];
const nextCharacter = jsonString[index + 1];
if (!isInsideComment && currentCharacter === '"') {
const escaped2 = isEscaped(jsonString, index);
if (!escaped2) {
isInsideString = !isInsideString;
}
}
if (isInsideString) {
continue;
}
if (!isInsideComment && currentCharacter + nextCharacter === "//") {
result += jsonString.slice(offset2, index);
offset2 = index;
isInsideComment = singleComment;
index++;
} else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
index++;
isInsideComment = false;
result += strip(jsonString, offset2, index);
offset2 = index;
} else if (isInsideComment === singleComment && currentCharacter === "\n") {
isInsideComment = false;
result += strip(jsonString, offset2, index);
offset2 = index;
} else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
result += jsonString.slice(offset2, index);
offset2 = index;
isInsideComment = multiComment;
index++;
} else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
index++;
isInsideComment = false;
result += strip(jsonString, offset2, index + 1);
offset2 = index + 1;
}
}
return result + (isInsideComment ? strip(jsonString.slice(offset2)) : jsonString.slice(offset2));
}
function stripBom(string2) {
if (string2.charCodeAt(0) === 65279) {
return string2.slice(1);
}
return string2;
}
var not_found_result = {
tsconfigFile: null,
tsconfig: {}
};
async function parse$e(filename, options2) {
const cache = options2 == null ? void 0 : options2.cache;
if (cache == null ? void 0 : cache.hasParseResult(filename)) {
return getParsedDeep(filename, cache, options2);
}
const {
resolve: resolve3,
reject,
/** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/
promise: promise2
} = makePromise();
cache == null ? void 0 : cache.setParseResult(filename, promise2, true);
try {
let tsconfigFile = await resolveTSConfigJson(filename, cache) || await find(filename, options2);
if (!tsconfigFile) {
resolve3(not_found_result);
return promise2;
}
let result;
if (filename !== tsconfigFile && (cache == null ? void 0 : cache.hasParseResult(tsconfigFile))) {
result = await getParsedDeep(tsconfigFile, cache, options2);
} else {
result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile);
await Promise.all([parseExtends(result, cache), parseReferences(result, options2)]);
}
result.tsconfig = replaceTokens(result.tsconfig, import_node_path3.default.dirname(tsconfigFile));
resolve3(resolveSolutionTSConfig(filename, result));
} catch (e2) {
reject(e2);
}
return promise2;
}
async function getParsedDeep(filename, cache, options2) {
const result = await cache.getParseResult(filename);
if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
const promise2 = Promise.all([
parseExtends(result, cache),
parseReferences(result, options2)
]).then(() => result);
cache.setParseResult(filename, promise2, true);
return promise2;
}
return result;
}
async function parseFile$1(tsconfigFile, cache, skipCache) {
if (!skipCache && (cache == null ? void 0 : cache.hasParseResult(tsconfigFile)) && !cache.getParseResult(tsconfigFile)._isRootFile_) {
return cache.getParseResult(tsconfigFile);
}
const promise2 = import_node_fs2.promises.readFile(tsconfigFile, "utf-8").then(toJson).then((json) => {
const parsed = JSON.parse(json);
applyDefaults(parsed, tsconfigFile);
return {
tsconfigFile,
tsconfig: normalizeTSConfig(parsed, import_node_path3.default.dirname(tsconfigFile))
};
}).catch((e2) => {
throw new TSConfckParseError(
`parsing ${tsconfigFile} failed: ${e2}`,
"PARSE_FILE",
tsconfigFile,
e2
);
});
if (!skipCache && (!(cache == null ? void 0 : cache.hasParseResult(tsconfigFile)) || !cache.getParseResult(tsconfigFile)._isRootFile_)) {
cache == null ? void 0 : cache.setParseResult(tsconfigFile, promise2);
}
return promise2;
}
function normalizeTSConfig(tsconfig, dir) {
var _a4;
const baseUrl = (_a4 = tsconfig.compilerOptions) == null ? void 0 : _a4.baseUrl;
if (baseUrl && !baseUrl.startsWith("${") && !import_node_path3.default.isAbsolute(baseUrl)) {
tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
}
return tsconfig;
}
async function parseReferences(result, options2) {
if (!result.tsconfig.references) {
return;
}
const referencedFiles = resolveReferencedTSConfigFiles(result, options2);
const referenced = await Promise.all(
referencedFiles.map((file) => parseFile$1(file, options2 == null ? void 0 : options2.cache))
);
await Promise.all(referenced.map((ref) => parseExtends(ref, options2 == null ? void 0 : options2.cache)));
referenced.forEach((ref) => {
ref.solution = result;
});
result.referenced = referenced;
}
async function parseExtends(result, cache) {
if (!result.tsconfig.extends) {
return;
}
const extended = [
{ tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
];
let pos = 0;
const extendsPath = [];
let currentBranchDepth = 0;
while (pos < extended.length) {
const extending = extended[pos];
extendsPath.push(extending.tsconfigFile);
if (extending.tsconfig.extends) {
currentBranchDepth += 1;
let resolvedExtends;
if (!Array.isArray(extending.tsconfig.extends)) {
resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
} else {
resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
}
const circularExtends = resolvedExtends.find(
(tsconfigFile) => extendsPath.includes(tsconfigFile)
);
if (circularExtends) {
const circle = extendsPath.concat([circularExtends]).join(" -> ");
throw new TSConfckParseError(
`Circular dependency in "extends": ${circle}`,
"EXTENDS_CIRCULAR",
result.tsconfigFile
);
}
extended.splice(
pos + 1,
0,
...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))
);
} else {
extendsPath.splice(-currentBranchDepth);
currentBranchDepth = 0;
}
pos = pos + 1;
}
result.extended = extended;
for (const ext2 of result.extended.slice(1)) {
extendTSConfig(result, ext2);
}
}
function resolveExtends(extended, from) {
if (extended === "..") {
extended = "../tsconfig.json";
}
const req2 = (0, import_module.createRequire)(from);
let error2;
try {
return req2.resolve(extended);
} catch (e2) {
error2 = e2;
}
if (extended[0] !== "." && !import_node_path3.default.isAbsolute(extended)) {
try {
return req2.resolve(`${extended}/tsconfig.json`);
} catch (e2) {
error2 = e2;
}
}
throw new TSConfckParseError(
`failed to resolve "extends":"${extended}" in ${from}`,
"EXTENDS_RESOLVE",
from,
error2
);
}
var EXTENDABLE_KEYS = [
"compilerOptions",
"files",
"include",
"exclude",
"watchOptions",
"compileOnSave",
"typeAcquisition",
"buildOptions"
];
function extendTSConfig(extending, extended) {
const extendingConfig = extending.tsconfig;
const extendedConfig = extended.tsconfig;
const relativePath = native2posix(
import_node_path3.default.relative(import_node_path3.default.dirname(extending.tsconfigFile), import_node_path3.default.dirname(extended.tsconfigFile))
);
for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
if (key === "compilerOptions") {
if (!extendingConfig.compilerOptions) {
extendingConfig.compilerOptions = {};
}
for (const option of Object.keys(extendedConfig.compilerOptions)) {
if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
continue;
}
extendingConfig.compilerOptions[option] = rebaseRelative(
option,
extendedConfig.compilerOptions[option],
relativePath
);
}
} else if (extendingConfig[key] === void 0) {
if (key === "watchOptions") {
extendingConfig.watchOptions = {};
for (const option of Object.keys(extendedConfig.watchOptions)) {
extendingConfig.watchOptions[option] = rebaseRelative(
option,
extendedConfig.watchOptions[option],
relativePath
);
}
} else {
extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
}
}
}
}
var REBASE_KEYS = [
// root
"files",
"include",
"exclude",
// compilerOptions
"baseUrl",
"rootDir",
"rootDirs",
"typeRoots",
"outDir",
"outFile",
"declarationDir",
// watchOptions
"excludeDirectories",
"excludeFiles"
];
function rebaseRelative(key, value2, prependPath) {
if (!REBASE_KEYS.includes(key)) {
return value2;
}
if (Array.isArray(value2)) {
return value2.map((x) => rebasePath(x, prependPath));
} else {
return rebasePath(value2, prependPath);
}
}
function rebasePath(value2, prependPath) {
if (import_node_path3.default.isAbsolute(value2)) {
return value2;
} else {
return import_node_path3.default.posix.normalize(import_node_path3.default.posix.join(prependPath, value2));
}
}
var TSConfckParseError = class _TSConfckParseError extends Error {
/**
*
* @param {string} message - error message
* @param {string} code - error code
* @param {string} tsconfigFile - path to tsconfig file
* @param {Error?} cause - cause of this error
*/
constructor(message, code, tsconfigFile, cause) {
super(message);
/**
* error code
* @type {string}
*/
__publicField(this, "code");
/**
* error cause
* @type { Error | undefined}
*/
__publicField(this, "cause");
/**
* absolute path of tsconfig file where the error happened
* @type {string}
*/
__publicField(this, "tsconfigFile");
Object.setPrototypeOf(this, _TSConfckParseError.prototype);
this.name = _TSConfckParseError.name;
this.code = code;
this.cause = cause;
this.tsconfigFile = tsconfigFile;
}
};
function applyDefaults(tsconfig, tsconfigFile) {
if (isJSConfig(tsconfigFile)) {
tsconfig.compilerOptions = {
...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
...tsconfig.compilerOptions
};
}
}
var DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
allowJs: true,
maxNodeModuleJsDepth: 2,
allowSyntheticDefaultImports: true,
skipLibCheck: true,
noEmit: true
};
function isJSConfig(configFileName) {
return import_node_path3.default.basename(configFileName) === "jsconfig.json";
}
var _configPaths, _parsed;
var TSConfckCache = class {
constructor() {
/**
* map directories to their closest tsconfig.json
* @internal
* @private
* @type{Map<string,(Promise<string|null>|string|null)>}
*/
__privateAdd(this, _configPaths, /* @__PURE__ */ new Map());
/**
* map files to their parsed tsconfig result
* @internal
* @private
* @type {Map<string,(Promise<T>|T)> }
*/
__privateAdd(this, _parsed, /* @__PURE__ */ new Map());
}
/**
* clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
*/
clear() {
__privateGet(this, _configPaths).clear();
__privateGet(this, _parsed).clear();
}
/**
* has cached closest config for files in dir
* @param {string} dir
* @param {string} [configName=tsconfig.json]
* @returns {boolean}
*/
hasConfigPath(dir, configName = "tsconfig.json") {
return __privateGet(this, _configPaths).has(`${dir}/${configName}`);
}
/**
* get cached closest tsconfig for files in dir
* @param {string} dir
* @param {string} [configName=tsconfig.json]
* @returns {Promise<string|null>|string|null}
* @throws {unknown} if cached value is an error
*/
getConfigPath(dir, configName = "tsconfig.json") {
const key = `${dir}/${configName}`;
const value2 = __privateGet(this, _configPaths).get(key);
if (value2 == null || value2.length || value2.then) {
return value2;
} else {
throw value2;
}
}
/**
* has parsed tsconfig for file
* @param {string} file
* @returns {boolean}
*/
hasParseResult(file) {
return __privateGet(this, _parsed).has(file);
}
/**
* get parsed tsconfig for file
* @param {string} file
* @returns {Promise<T>|T}
* @throws {unknown} if cached value is an error
*/
getParseResult(file) {
const value2 = __privateGet(this, _parsed).get(file);
if (value2.then || value2.tsconfig) {
return value2;
} else {
throw value2;
}
}
/**
* @internal
* @private
* @param file
* @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile()
* @param {Promise<T>} result
*/
setParseResult(file, result, isRootFile = false) {
Object.defineProperty(result, "_isRootFile_", {
value: isRootFile,
writable: false,
enumerable: false,
configurable: false
});
__privateGet(this, _parsed).set(file, result);
result.then((parsed) => {
if (__privateGet(this, _parsed).get(file) === result) {
__privateGet(this, _parsed).set(file, parsed);
}
}).catch((e2) => {
if (__privateGet(this, _parsed).get(file) === result) {
__privateGet(this, _parsed).set(file, e2);
}
});
}
/**
* @internal
* @private
* @param {string} dir
* @param {Promise<string|null>} configPath
* @param {string} [configName=tsconfig.json]
*/
setConfigPath(dir, configPath, configName = "tsconfig.json") {
const key = `${dir}/${configName}`;
__privateGet(this, _configPaths).set(key, configPath);
configPath.then((path3) => {
if (__privateGet(this, _configPaths).get(key) === configPath) {
__privateGet(this, _configPaths).set(key, path3);
}
}).catch((e2) => {
if (__privateGet(this, _configPaths).get(key) === configPath) {
__privateGet(this, _configPaths).set(key, e2);
}
});
}
};
_configPaths = new WeakMap();
_parsed = new WeakMap();
var debug$h = createDebugger("vite:esbuild");
var IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/;
var validExtensionRE = /\.\w+$/;
var jsxExtensionsRE = /\.(?:j|t)sx\b/;
var defaultEsbuildSupported = {
"dynamic-import": true,
"import-meta": true
};
var server;
async function transformWithEsbuild(code, filename, options2, inMap) {
let loader = options2 == null ? void 0 : options2.loader;
if (!loader) {
const ext2 = import_node_path3.default.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
if (ext2 === "cjs" || ext2 === "mjs") {
loader = "js";
} else if (ext2 === "cts" || ext2 === "mts") {
loader = "ts";
} else {
loader = ext2;
}
}
let tsconfigRaw = options2 == null ? void 0 : options2.tsconfigRaw;
if (typeof tsconfigRaw !== "string") {
const meaningfulFields = [
"alwaysStrict",
"experimentalDecorators",
"importsNotUsedAsValues",
"jsx",
"jsxFactory",
"jsxFragmentFactory",
"jsxImportSource",
"preserveValueImports",
"target",
"useDefineForClassFields",
"verbatimModuleSyntax"
];
const compilerOptionsForFile = {};
if (loader === "ts" || loader === "tsx") {
const loadedTsconfig = await loadTsconfigJsonForFile(filename);
const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
for (const field of meaningfulFields) {
if (field in loadedCompilerOptions) {
compilerOptionsForFile[field] = loadedCompilerOptions[field];
}
}
}
const compilerOptions = {
...compilerOptionsForFile,
...tsconfigRaw == null ? void 0 : tsconfigRaw.compilerOptions
};
if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) {
compilerOptions.useDefineForClassFields = false;
}
if (options2) {
options2.jsx && (compilerOptions.jsx = void 0);
options2.jsxFactory && (compilerOptions.jsxFactory = void 0);
options2.jsxFragment && (compilerOptions.jsxFragmentFactory = void 0);
options2.jsxImportSource && (compilerOptions.jsxImportSource = void 0);
}
tsconfigRaw = {
...tsconfigRaw,
compilerOptions
};
}
const resolvedOptions = {
sourcemap: true,
// ensure source file name contains full query
sourcefile: filename,
...options2,
loader,
tsconfigRaw
};
delete resolvedOptions.include;
delete resolvedOptions.exclude;
delete resolvedOptions.jsxInject;
try {
const result = await (0, import_esbuild.transform)(code, resolvedOptions);
let map2;
if (inMap && resolvedOptions.sourcemap) {
const nextMap = JSON.parse(result.map);
nextMap.sourcesContent = [];
map2 = combineSourcemaps(filename, [
nextMap,
inMap
]);
} else {
map2 = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
}
return {
...result,
map: map2
};
} catch (e2) {
debug$h == null ? void 0 : debug$h(`esbuild error with options used: `, resolvedOptions);
if (e2.errors) {
e2.frame = "";
e2.errors.forEach((m) => {
if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") {
m.text += '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.';
}
e2.frame += `
` + prettifyMessage(m, code);
});
e2.loc = e2.errors[0].location;
}
throw e2;
}
}
function esbuildPlugin(config2) {
const options2 = config2.esbuild;
const { jsxInject, include, exclude, ...esbuildTransformOptions } = options2;
const filter2 = createFilter2(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
const transformOptions = {
target: "esnext",
charset: "utf8",
...esbuildTransformOptions,
minify: false,
minifyIdentifiers: false,
minifySyntax: false,
minifyWhitespace: false,
treeShaking: false,
// keepNames is not needed when minify is disabled.
// Also transforming multiple times with keepNames enabled breaks
// tree-shaking. (#9164)
keepNames: false,
supported: {
...defaultEsbuildSupported,
...esbuildTransformOptions.supported
}
};
return {
name: "vite:esbuild",
configureServer(_server) {
server = _server;
server.watcher.on("add", reloadOnTsconfigChange).on("change", reloadOnTsconfigChange).on("unlink", reloadOnTsconfigChange);
},
buildEnd() {
server = null;
},
async transform(code, id) {
if (filter2(id) || filter2(cleanUrl(id))) {
const result = await transformWithEsbuild(code, id, transformOptions);
if (result.warnings.length) {
result.warnings.forEach((m) => {
this.warn(prettifyMessage(m, code));
});
}
if (jsxInject && jsxExtensionsRE.test(id)) {
result.code = jsxInject + ";" + result.code;
}
return {
code: result.code,
map: result.map
};
}
}
};
}
var rollupToEsbuildFormatMap = {
es: "esm",
cjs: "cjs",
// passing `var Lib = (() => {})()` to esbuild with format = "iife"
// will turn it to `(() => { var Lib = (() => {})() })()`,
// so we remove the format config to tell esbuild not doing this
//
// although esbuild doesn't change format, there is still possibility
// that `{ treeShaking: true }` removes a top-level no-side-effect variable
// like: `var Lib = 1`, which becomes `` after esbuild transforming,
// but thankfully rollup does not do this optimization now
iife: void 0
};
var buildEsbuildPlugin = (config2) => {
return {
name: "vite:esbuild-transpile",
async renderChunk(code, chunk, opts) {
if (opts.__vite_skip_esbuild__) {
return null;
}
const options2 = resolveEsbuildTranspileOptions(config2, opts.format);
if (!options2) {
return null;
}
const res = await transformWithEsbuild(code, chunk.fileName, options2);
if (config2.build.lib) {
const esbuildCode = res.code;
const contentIndex = opts.format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : opts.format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
if (contentIndex > 0) {
const esbuildHelpers = esbuildCode.slice(0, contentIndex);
res.code = esbuildCode.slice(contentIndex).replace(`"use strict";`, `"use strict";` + esbuildHelpers);
}
}
return res;
}
};
};
function resolveEsbuildTranspileOptions(config2, format2) {
const target = config2.build.target;
const minify = config2.build.minify === "esbuild";
if ((!target || target === "esnext") && !minify) {
return null;
}
const isEsLibBuild = config2.build.lib && format2 === "es";
const esbuildOptions = config2.esbuild || {};
const options2 = {
charset: "utf8",
...esbuildOptions,
loader: "js",
target: target || void 0,
format: rollupToEsbuildFormatMap[format2],
supported: {
...defaultEsbuildSupported,
...esbuildOptions.supported
}
};
if (!minify) {
return {
...options2,
minify: false,
minifyIdentifiers: false,
minifySyntax: false,
minifyWhitespace: false,
treeShaking: false
};
}
if (options2.minifyIdentifiers != null || options2.minifySyntax != null || options2.minifyWhitespace != null) {
if (isEsLibBuild) {
return {
...options2,
minify: false,
minifyIdentifiers: options2.minifyIdentifiers ?? true,
minifySyntax: options2.minifySyntax ?? true,
minifyWhitespace: false,
treeShaking: true
};
} else {
return {
...options2,
minify: false,
minifyIdentifiers: options2.minifyIdentifiers ?? true,
minifySyntax: options2.minifySyntax ?? true,
minifyWhitespace: options2.minifyWhitespace ?? true,
treeShaking: true
};
}
}
if (isEsLibBuild) {
return {
...options2,
minify: false,
minifyIdentifiers: true,
minifySyntax: true,
minifyWhitespace: false,
treeShaking: true
};
} else {
return {
...options2,
minify: true,
treeShaking: true
};
}
}
function prettifyMessage(m, code) {
let res = colors$1.yellow(m.text);
if (m.location) {
res += `
` + generateCodeFrame(code, m.location);
}
return res + `
`;
}
var tsconfckCache;
async function loadTsconfigJsonForFile(filename) {
try {
if (!tsconfckCache) {
tsconfckCache = new TSConfckCache();
}
const result = await parse$e(filename, {
cache: tsconfckCache,
ignoreNodeModules: true
});
if (server && result.tsconfigFile) {
ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
}
return result.tsconfig;
} catch (e2) {
if (e2 instanceof TSConfckParseError) {
if (server && e2.tsconfigFile) {
ensureWatchedFile(server.watcher, e2.tsconfigFile, server.config.root);
}
}
throw e2;
}
}
async function reloadOnTsconfigChange(changedFile) {
if (!server) return;
if (import_node_path3.default.basename(changedFile) === "tsconfig.json" || changedFile.endsWith(".json") && (tsconfckCache == null ? void 0 : tsconfckCache.hasParseResult(changedFile))) {
server.config.logger.info(
`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`,
{ clear: server.config.clearScreen, timestamp: true }
);
server.moduleGraph.invalidateAll();
tsconfckCache == null ? void 0 : tsconfckCache.clear();
if (server) {
server.hot.send({
type: "full-reload",
path: "*"
});
}
}
}
var Worker = class {
constructor(fn, options2 = {}) {
/** @internal */
__publicField(this, "_code");
/** @internal */
__publicField(this, "_parentFunctions");
/** @internal */
__publicField(this, "_max");
/** @internal */
__publicField(this, "_pool");
/** @internal */
__publicField(this, "_idlePool");
/** @internal */
__publicField(this, "_queue");
var _a4, _b3;
this._code = genWorkerCode(fn, options2.parentFunctions ?? {});
this._parentFunctions = options2.parentFunctions ?? {};
const defaultMax = Math.max(
1,
// os.availableParallelism is available from Node.js 18.14.0
(((_b3 = (_a4 = import_node_os.default).availableParallelism) == null ? void 0 : _b3.call(_a4)) ?? import_node_os.default.cpus().length) - 1
);
this._max = options2.max || defaultMax;
this._pool = [];
this._idlePool = [];
this._queue = [];
}
async run(...args) {
const worker = await this._getAvailableWorker();
return new Promise((resolve3, reject) => {
worker.currentResolve = resolve3;
worker.currentReject = reject;
worker.postMessage({ type: "run", args });
});
}
stop() {
this._pool.forEach((w) => w.unref());
this._queue.forEach(
([, reject]) => reject(
new Error("Main worker pool stopped before a worker was available.")
)
);
this._pool = [];
this._idlePool = [];
this._queue = [];
}
/** @internal */
async _getAvailableWorker() {
if (this._idlePool.length) {
return this._idlePool.shift();
}
if (this._pool.length < this._max) {
const worker = new import_node_worker_threads.Worker(this._code, { eval: true });
worker.on("message", async (args) => {
if (args.type === "run") {
if ("result" in args) {
worker.currentResolve && worker.currentResolve(args.result);
worker.currentResolve = null;
} else {
if (args.error instanceof ReferenceError) {
args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
}
worker.currentReject && worker.currentReject(args.error);
worker.currentReject = null;
}
this._assignDoneWorker(worker);
} else if (args.type === "parentFunction") {
try {
const result = await this._parentFunctions[args.name](...args.args);
worker.postMessage({ type: "parentFunction", id: args.id, result });
} catch (e2) {
worker.postMessage({
type: "parentFunction",
id: args.id,
error: e2
});
}
}
});
worker.on("error", (err2) => {
worker.currentReject && worker.currentReject(err2);
worker.currentReject = null;
});
worker.on("exit", (code) => {
const i = this._pool.indexOf(worker);
if (i > -1)
this._pool.splice(i, 1);
if (code !== 0 && worker.currentReject) {
worker.currentReject(
new Error(`Worker stopped with non-0 exit code ${code}`)
);
worker.currentReject = null;
}
});
this._pool.push(worker);
return worker;
}
let resolve3;
let reject;
const onWorkerAvailablePromise = new Promise((r2, rj) => {
resolve3 = r2;
reject = rj;
});
this._queue.push([resolve3, reject]);
return onWorkerAvailablePromise;
}
/** @internal */
_assignDoneWorker(worker) {
if (this._queue.length) {
const [resolve3] = this._queue.shift();
resolve3(worker);
return;
}
this._idlePool.push(worker);
}
};
function genWorkerCode(fn, parentFunctions) {
const createParentFunctionCaller = (parentPort) => {
let id = 0;
const resolvers = /* @__PURE__ */ new Map();
const call2 = (key) => async (...args) => {
id++;
let resolve3, reject;
const promise2 = new Promise((res, rej) => {
resolve3 = res;
reject = rej;
});
resolvers.set(id, { resolve: resolve3, reject });
parentPort.postMessage({ type: "parentFunction", id, name: key, args });
return await promise2;
};
const receive = (id2, args) => {
if (resolvers.has(id2)) {
const { resolve: resolve3, reject } = resolvers.get(id2);
resolvers.delete(id2);
if ("result" in args) {
resolve3(args.result);
} else {
reject(args.error);
}
}
};
return { call: call2, receive };
};
return `
const { parentPort } = require('worker_threads')
const parentFunctionCaller = (${createParentFunctionCaller.toString()})(parentPort)
const doWork = (() => {
${Object.keys(parentFunctions).map(
(key) => `const ${key} = parentFunctionCaller.call(${JSON.stringify(key)});`
).join("\n")}
return (${fn.toString()})()
})()
parentPort.on('message', async (args) => {
if (args.type === 'run') {
try {
const res = await doWork(...args.args)
parentPort.postMessage({ type: 'run', result: res })
} catch (e) {
parentPort.postMessage({ type: 'run', error: e })
}
} else if (args.type === 'parentFunction') {
parentFunctionCaller.receive(args.id, args)
}
})
`;
}
var FakeWorker = class {
constructor(fn, options2 = {}) {
/** @internal */
__publicField(this, "_fn");
const argsAndCode = genFakeWorkerArgsAndCode(
fn,
options2.parentFunctions ?? {}
);
const require22 = (0, import_node_module.createRequire)(import.meta.url);
this._fn = new Function(...argsAndCode)(require22, options2.parentFunctions);
}
async run(...args) {
try {
return await this._fn(...args);
} catch (err2) {
if (err2 instanceof ReferenceError) {
err2.message += ". Maybe you forgot to pass the function to parentFunction?";
}
throw err2;
}
}
stop() {
}
};
function genFakeWorkerArgsAndCode(fn, parentFunctions) {
return [
"require",
"parentFunctions",
`
${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
return (${fn.toString()})()
`
];
}
var WorkerWithFallback = class {
constructor(fn, options2) {
/** @internal */
__publicField(this, "_disableReal");
/** @internal */
__publicField(this, "_realWorker");
/** @internal */
__publicField(this, "_fakeWorker");
/** @internal */
__publicField(this, "_shouldUseFake");
this._disableReal = options2.max !== void 0 && options2.max <= 0;
this._realWorker = new Worker(fn, options2);
this._fakeWorker = new FakeWorker(fn, options2);
this._shouldUseFake = options2.shouldUseFake;
}
async run(...args) {
const useFake = this._disableReal || this._shouldUseFake(...args);
return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
}
stop() {
this._realWorker.stop();
this._fakeWorker.stop();
}
};
var terserPath;
var loadTerserPath = (root) => {
if (terserPath) return terserPath;
try {
terserPath = requireResolveFromRootWithFallback(root, "terser");
} catch (e2) {
if (e2.code === "MODULE_NOT_FOUND") {
throw new Error(
"terser not found. Since Vite v3, terser has become an optional dependency. You need to install it."
);
} else {
const message = new Error(`terser failed to load:
${e2.message}`);
message.stack = e2.stack + "\n" + message.stack;
throw message;
}
}
return terserPath;
};
function terserPlugin(config2) {
const { maxWorkers, ...terserOptions } = config2.build.terserOptions;
const makeWorker = () => new Worker(
() => async (terserPath2, code, options2) => {
const terser = require2(terserPath2);
return terser.minify(code, options2);
},
{
max: maxWorkers
}
);
let worker;
return {
name: "vite:terser",
async renderChunk(code, _chunk, outputOptions) {
if (config2.build.minify !== "terser" && // @ts-expect-error injected by @vitejs/plugin-legacy
!outputOptions.__vite_force_terser__) {
return null;
}
if (config2.build.lib && outputOptions.format === "es") {
return null;
}
worker || (worker = makeWorker());
const terserPath2 = loadTerserPath(config2.root);
const res = await worker.run(terserPath2, code, {
safari10: true,
...terserOptions,
sourceMap: !!outputOptions.sourcemap,
module: outputOptions.format.startsWith("es"),
toplevel: outputOptions.format === "cjs"
});
return {
code: res.code,
map: res.map
};
},
closeBundle() {
worker == null ? void 0 : worker.stop();
}
};
}
var mimes = {
"3g2": "video/3gpp2",
"3gp": "video/3gpp",
"3gpp": "video/3gpp",
"3mf": "model/3mf",
"aac": "audio/aac",
"ac": "application/pkix-attr-cert",
"adp": "audio/adpcm",
"adts": "audio/aac",
"ai": "application/postscript",
"aml": "application/automationml-aml+xml",
"amlx": "application/automationml-amlx+zip",
"amr": "audio/amr",
"apng": "image/apng",
"appcache": "text/cache-manifest",
"appinstaller": "application/appinstaller",
"appx": "application/appx",
"appxbundle": "application/appxbundle",
"asc": "application/pgp-keys",
"atom": "application/atom+xml",
"atomcat": "application/atomcat+xml",
"atomdeleted": "application/atomdeleted+xml",
"atomsvc": "application/atomsvc+xml",
"au": "audio/basic",
"avci": "image/avci",
"avcs": "image/avcs",
"avif": "image/avif",
"aw": "application/applixware",
"bdoc": "application/bdoc",
"bin": "application/octet-stream",
"bmp": "image/bmp",
"bpk": "application/octet-stream",
"btf": "image/prs.btif",
"btif": "image/prs.btif",
"buffer": "application/octet-stream",
"ccxml": "application/ccxml+xml",
"cdfx": "application/cdfx+xml",
"cdmia": "application/cdmi-capability",
"cdmic": "application/cdmi-container",
"cdmid": "application/cdmi-domain",
"cdmio": "application/cdmi-object",
"cdmiq": "application/cdmi-queue",
"cer": "application/pkix-cert",
"cgm": "image/cgm",
"cjs": "application/node",
"class": "application/java-vm",
"coffee": "text/coffeescript",
"conf": "text/plain",
"cpl": "application/cpl+xml",
"cpt": "application/mac-compactpro",
"crl": "application/pkix-crl",
"css": "text/css",
"csv": "text/csv",
"cu": "application/cu-seeme",
"cwl": "application/cwl",
"cww": "application/prs.cww",
"davmount": "application/davmount+xml",
"dbk": "application/docbook+xml",
"deb": "application/octet-stream",
"def": "text/plain",
"deploy": "application/octet-stream",
"dib": "image/bmp",
"disposition-notification": "message/disposition-notification",
"dist": "application/octet-stream",
"distz": "application/octet-stream",
"dll": "application/octet-stream",
"dmg": "application/octet-stream",
"dms": "application/octet-stream",
"doc": "application/msword",
"dot": "application/msword",
"dpx": "image/dpx",
"drle": "image/dicom-rle",
"dsc": "text/prs.lines.tag",
"dssc": "application/dssc+der",
"dtd": "application/xml-dtd",
"dump": "application/octet-stream",
"dwd": "application/atsc-dwd+xml",
"ear": "application/java-archive",
"ecma": "application/ecmascript",
"elc": "application/octet-stream",
"emf": "image/emf",
"eml": "message/rfc822",
"emma": "application/emma+xml",
"emotionml": "application/emotionml+xml",
"eps": "application/postscript",
"epub": "application/epub+zip",
"exe": "application/octet-stream",
"exi": "application/exi",
"exp": "application/express",
"exr": "image/aces",
"ez": "application/andrew-inset",
"fdf": "application/fdf",
"fdt": "application/fdt+xml",
"fits": "image/fits",
"g3": "image/g3fax",
"gbr": "application/rpki-ghostbusters",
"geojson": "application/geo+json",
"gif": "image/gif",
"glb": "model/gltf-binary",
"gltf": "model/gltf+json",
"gml": "application/gml+xml",
"gpx": "application/gpx+xml",
"gram": "application/srgs",
"grxml": "application/srgs+xml",
"gxf": "application/gxf",
"gz": "application/gzip",
"h261": "video/h261",
"h263": "video/h263",
"h264": "video/h264",
"heic": "image/heic",
"heics": "image/heic-sequence",
"heif": "image/heif",
"heifs": "image/heif-sequence",
"hej2": "image/hej2k",
"held": "application/atsc-held+xml",
"hjson": "application/hjson",
"hlp": "application/winhlp",
"hqx": "application/mac-binhex40",
"hsj2": "image/hsj2",
"htm": "text/html",
"html": "text/html",
"ics": "text/calendar",
"ief": "image/ief",
"ifb": "text/calendar",
"iges": "model/iges",
"igs": "model/iges",
"img": "application/octet-stream",
"in": "text/plain",
"ini": "text/plain",
"ink": "application/inkml+xml",
"inkml": "application/inkml+xml",
"ipfix": "application/ipfix",
"iso": "application/octet-stream",
"its": "application/its+xml",
"jade": "text/jade",
"jar": "application/java-archive",
"jhc": "image/jphc",
"jls": "image/jls",
"jp2": "image/jp2",
"jpe": "image/jpeg",
"jpeg": "image/jpeg",
"jpf": "image/jpx",
"jpg": "image/jpeg",
"jpg2": "image/jp2",
"jpgm": "image/jpm",
"jpgv": "video/jpeg",
"jph": "image/jph",
"jpm": "image/jpm",
"jpx": "image/jpx",
"js": "text/javascript",
"json": "application/json",
"json5": "application/json5",
"jsonld": "application/ld+json",
"jsonml": "application/jsonml+json",
"jsx": "text/jsx",
"jt": "model/jt",
"jxr": "image/jxr",
"jxra": "image/jxra",
"jxrs": "image/jxrs",
"jxs": "image/jxs",
"jxsc": "image/jxsc",
"jxsi": "image/jxsi",
"jxss": "image/jxss",
"kar": "audio/midi",
"ktx": "image/ktx",
"ktx2": "image/ktx2",
"less": "text/less",
"lgr": "application/lgr+xml",
"list": "text/plain",
"litcoffee": "text/coffeescript",
"log": "text/plain",
"lostxml": "application/lost+xml",
"lrf": "application/octet-stream",
"m1v": "video/mpeg",
"m21": "application/mp21",
"m2a": "audio/mpeg",
"m2v": "video/mpeg",
"m3a": "audio/mpeg",
"m4a": "audio/mp4",
"m4p": "application/mp4",
"m4s": "video/iso.segment",
"ma": "application/mathematica",
"mads": "application/mads+xml",
"maei": "application/mmt-aei+xml",
"man": "text/troff",
"manifest": "text/cache-manifest",
"map": "application/json",
"mar": "application/octet-stream",
"markdown": "text/markdown",
"mathml": "application/mathml+xml",
"mb": "application/mathematica",
"mbox": "application/mbox",
"md": "text/markdown",
"mdx": "text/mdx",
"me": "text/troff",
"mesh": "model/mesh",
"meta4": "application/metalink4+xml",
"metalink": "application/metalink+xml",
"mets": "application/mets+xml",
"mft": "application/rpki-manifest",
"mid": "audio/midi",
"midi": "audio/midi",
"mime": "message/rfc822",
"mj2": "video/mj2",
"mjp2": "video/mj2",
"mjs": "text/javascript",
"mml": "text/mathml",
"mods": "application/mods+xml",
"mov": "video/quicktime",
"mp2": "audio/mpeg",
"mp21": "application/mp21",
"mp2a": "audio/mpeg",
"mp3": "audio/mpeg",
"mp4": "video/mp4",
"mp4a": "audio/mp4",
"mp4s": "application/mp4",
"mp4v": "video/mp4",
"mpd": "application/dash+xml",
"mpe": "video/mpeg",
"mpeg": "video/mpeg",
"mpf": "application/media-policy-dataset+xml",
"mpg": "video/mpeg",
"mpg4": "video/mp4",
"mpga": "audio/mpeg",
"mpp": "application/dash-patch+xml",
"mrc": "application/marc",
"mrcx": "application/marcxml+xml",
"ms": "text/troff",
"mscml": "application/mediaservercontrol+xml",
"msh": "model/mesh",
"msi": "application/octet-stream",
"msix": "application/msix",
"msixbundle": "application/msixbundle",
"msm": "application/octet-stream",
"msp": "application/octet-stream",
"mtl": "model/mtl",
"musd": "application/mmt-usd+xml",
"mxf": "application/mxf",
"mxmf": "audio/mobile-xmf",
"mxml": "application/xv+xml",
"n3": "text/n3",
"nb": "application/mathematica",
"nq": "application/n-quads",
"nt": "application/n-triples",
"obj": "model/obj",
"oda": "application/oda",
"oga": "audio/ogg",
"ogg": "audio/ogg",
"ogv": "video/ogg",
"ogx": "application/ogg",
"omdoc": "application/omdoc+xml",
"onepkg": "application/onenote",
"onetmp": "application/onenote",
"onetoc": "application/onenote",
"onetoc2": "application/onenote",
"opf": "application/oebps-package+xml",
"opus": "audio/ogg",
"otf": "font/otf",
"owl": "application/rdf+xml",
"oxps": "application/oxps",
"p10": "application/pkcs10",
"p7c": "application/pkcs7-mime",
"p7m": "application/pkcs7-mime",
"p7s": "application/pkcs7-signature",
"p8": "application/pkcs8",
"pdf": "application/pdf",
"pfr": "application/font-tdpfr",
"pgp": "application/pgp-encrypted",
"pkg": "application/octet-stream",
"pki": "application/pkixcmp",
"pkipath": "application/pkix-pkipath",
"pls": "application/pls+xml",
"png": "image/png",
"prc": "model/prc",
"prf": "application/pics-rules",
"provx": "application/provenance+xml",
"ps": "application/postscript",
"pskcxml": "application/pskc+xml",
"pti": "image/prs.pti",
"qt": "video/quicktime",
"raml": "application/raml+yaml",
"rapd": "application/route-apd+xml",
"rdf": "application/rdf+xml",
"relo": "application/p2p-overlay+xml",
"rif": "application/reginfo+xml",
"rl": "application/resource-lists+xml",
"rld": "application/resource-lists-diff+xml",
"rmi": "audio/midi",
"rnc": "application/relax-ng-compact-syntax",
"rng": "application/xml",
"roa": "application/rpki-roa",
"roff": "text/troff",
"rq": "application/sparql-query",
"rs": "application/rls-services+xml",
"rsat": "application/atsc-rsat+xml",
"rsd": "application/rsd+xml",
"rsheet": "application/urc-ressheet+xml",
"rss": "application/rss+xml",
"rtf": "text/rtf",
"rtx": "text/richtext",
"rusd": "application/route-usd+xml",
"s3m": "audio/s3m",
"sbml": "application/sbml+xml",
"scq": "application/scvp-cv-request",
"scs": "application/scvp-cv-response",
"sdp": "application/sdp",
"senmlx": "application/senml+xml",
"sensmlx": "application/sensml+xml",
"ser": "application/java-serialized-object",
"setpay": "application/set-payment-initiation",
"setreg": "application/set-registration-initiation",
"sgi": "image/sgi",
"sgm": "text/sgml",
"sgml": "text/sgml",
"shex": "text/shex",
"shf": "application/shf+xml",
"shtml": "text/html",
"sieve": "application/sieve",
"sig": "application/pgp-signature",
"sil": "audio/silk",
"silo": "model/mesh",
"siv": "application/sieve",
"slim": "text/slim",
"slm": "text/slim",
"sls": "application/route-s-tsid+xml",
"smi": "application/smil+xml",
"smil": "application/smil+xml",
"snd": "audio/basic",
"so": "application/octet-stream",
"spdx": "text/spdx",
"spp": "application/scvp-vp-response",
"spq": "application/scvp-vp-request",
"spx": "audio/ogg",
"sql": "application/sql",
"sru": "application/sru+xml",
"srx": "application/sparql-results+xml",
"ssdl": "application/ssdl+xml",
"ssml": "application/ssml+xml",
"stk": "application/hyperstudio",
"stl": "model/stl",
"stpx": "model/step+xml",
"stpxz": "model/step-xml+zip",
"stpz": "model/step+zip",
"styl": "text/stylus",
"stylus": "text/stylus",
"svg": "image/svg+xml",
"svgz": "image/svg+xml",
"swidtag": "application/swid+xml",
"t": "text/troff",
"t38": "image/t38",
"td": "application/urc-targetdesc+xml",
"tei": "application/tei+xml",
"teicorpus": "application/tei+xml",
"text": "text/plain",
"tfi": "application/thraud+xml",
"tfx": "image/tiff-fx",
"tif": "image/tiff",
"tiff": "image/tiff",
"toml": "application/toml",
"tr": "text/troff",
"trig": "application/trig",
"ts": "video/mp2t",
"tsd": "application/timestamped-data",
"tsv": "text/tab-separated-values",
"ttc": "font/collection",
"ttf": "font/ttf",
"ttl": "text/turtle",
"ttml": "application/ttml+xml",
"txt": "text/plain",
"u3d": "model/u3d",
"u8dsn": "message/global-delivery-status",
"u8hdr": "message/global-headers",
"u8mdn": "message/global-disposition-notification",
"u8msg": "message/global",
"ubj": "application/ubjson",
"uri": "text/uri-list",
"uris": "text/uri-list",
"urls": "text/uri-list",
"vcard": "text/vcard",
"vrml": "model/vrml",
"vtt": "text/vtt",
"vxml": "application/voicexml+xml",
"war": "application/java-archive",
"wasm": "application/wasm",
"wav": "audio/wav",
"weba": "audio/webm",
"webm": "video/webm",
"webmanifest": "application/manifest+json",
"webp": "image/webp",
"wgsl": "text/wgsl",
"wgt": "application/widget",
"wif": "application/watcherinfo+xml",
"wmf": "image/wmf",
"woff": "font/woff",
"woff2": "font/woff2",
"wrl": "model/vrml",
"wsdl": "application/wsdl+xml",
"wspolicy": "application/wspolicy+xml",
"x3d": "model/x3d+xml",
"x3db": "model/x3d+fastinfoset",
"x3dbz": "model/x3d+binary",
"x3dv": "model/x3d-vrml",
"x3dvz": "model/x3d+vrml",
"x3dz": "model/x3d+xml",
"xaml": "application/xaml+xml",
"xav": "application/xcap-att+xml",
"xca": "application/xcap-caps+xml",
"xcs": "application/calendar+xml",
"xdf": "application/xcap-diff+xml",
"xdssc": "application/dssc+xml",
"xel": "application/xcap-el+xml",
"xenc": "application/xenc+xml",
"xer": "application/patch-ops-error+xml",
"xfdf": "application/xfdf",
"xht": "application/xhtml+xml",
"xhtml": "application/xhtml+xml",
"xhvml": "application/xv+xml",
"xlf": "application/xliff+xml",
"xm": "audio/xm",
"xml": "text/xml",
"xns": "application/xcap-ns+xml",
"xop": "application/xop+xml",
"xpl": "application/xproc+xml",
"xsd": "application/xml",
"xsf": "application/prs.xsf+xml",
"xsl": "application/xml",
"xslt": "application/xml",
"xspf": "application/xspf+xml",
"xvm": "application/xv+xml",
"xvml": "application/xv+xml",
"yaml": "text/yaml",
"yang": "application/yang",
"yin": "application/yin+xml",
"yml": "text/yaml",
"zip": "application/zip"
};
function lookup(extn) {
let tmp = ("" + extn).trim().toLowerCase();
let idx = tmp.lastIndexOf(".");
return mimes[!~idx ? tmp : tmp.substring(++idx)];
}
var publicFilesMap = /* @__PURE__ */ new WeakMap();
async function initPublicFiles(config2) {
let fileNames;
try {
fileNames = await recursiveReaddir(config2.publicDir);
} catch (e2) {
if (e2.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) {
return;
}
throw e2;
}
const publicFiles = new Set(
fileNames.map((fileName) => fileName.slice(config2.publicDir.length))
);
publicFilesMap.set(config2, publicFiles);
return publicFiles;
}
function getPublicFiles(config2) {
return publicFilesMap.get(config2);
}
function checkPublicFile(url2, config2) {
const { publicDir } = config2;
if (!publicDir || url2[0] !== "/") {
return;
}
const fileName = cleanUrl(url2);
const publicFiles = getPublicFiles(config2);
if (publicFiles) {
return publicFiles.has(fileName) ? normalizePath$3(import_node_path3.default.join(publicDir, fileName)) : void 0;
}
const publicFile = normalizePath$3(import_node_path3.default.join(publicDir, fileName));
if (!publicFile.startsWith(withTrailingSlash(publicDir))) {
return;
}
return import_node_fs2.default.existsSync(publicFile) ? publicFile : void 0;
}
var assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
var jsSourceMapRE = /\.[cm]?js\.map$/;
var assetCache = /* @__PURE__ */ new WeakMap();
var generatedAssets = /* @__PURE__ */ new WeakMap();
function registerCustomMime() {
mimes["ico"] = "image/x-icon";
mimes["flac"] = "audio/flac";
mimes["eot"] = "application/vnd.ms-fontobject";
}
function renderAssetUrlInJS(ctx, config2, chunk, opts, code) {
const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
opts.format,
config2.isWorker
);
let match2;
let s;
assetUrlRE.lastIndex = 0;
while (match2 = assetUrlRE.exec(code)) {
s || (s = new MagicString(code));
const [full, referenceId, postfix = ""] = match2;
const file = ctx.getFileName(referenceId);
chunk.viteMetadata.importedAssets.add(cleanUrl(file));
const filename = file + postfix;
const replacement = toOutputFilePathInJS(
filename,
"asset",
chunk.fileName,
"js",
config2,
toRelativeRuntime
);
const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
s.update(match2.index, match2.index + full.length, replacementString);
}
const publicAssetUrlMap = publicAssetUrlCache.get(config2);
publicAssetUrlRE.lastIndex = 0;
while (match2 = publicAssetUrlRE.exec(code)) {
s || (s = new MagicString(code));
const [full, hash2] = match2;
const publicUrl = publicAssetUrlMap.get(hash2).slice(1);
const replacement = toOutputFilePathInJS(
publicUrl,
"public",
chunk.fileName,
"js",
config2,
toRelativeRuntime
);
const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
s.update(match2.index, match2.index + full.length, replacementString);
}
return s;
}
function assetPlugin(config2) {
registerCustomMime();
let moduleGraph;
return {
name: "vite:asset",
buildStart() {
assetCache.set(config2, /* @__PURE__ */ new Map());
generatedAssets.set(config2, /* @__PURE__ */ new Map());
},
configureServer(server2) {
moduleGraph = server2.moduleGraph;
},
resolveId(id) {
if (!config2.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
return;
}
const publicFile = checkPublicFile(id, config2);
if (publicFile) {
return id;
}
},
async load(id) {
var _a4;
if (id[0] === "\0") {
return;
}
if (rawRE.test(id)) {
const file = checkPublicFile(id, config2) || cleanUrl(id);
this.addWatchFile(file);
return `export default ${JSON.stringify(
await import_promises.default.readFile(file, "utf-8")
)}`;
}
if (!urlRE.test(id) && !config2.assetsInclude(cleanUrl(id))) {
return;
}
id = removeUrlQuery(id);
let url2 = await fileToUrl$1(id, config2, this);
if (moduleGraph) {
const mod = moduleGraph.getModuleById(id);
if (mod && mod.lastHMRTimestamp > 0) {
url2 = injectQuery(url2, `t=${mod.lastHMRTimestamp}`);
}
}
return {
code: `export default ${JSON.stringify(encodeURIPath(url2))}`,
// Force rollup to keep this module from being shared between other entry points if it's an entrypoint.
// If the resulting chunk is empty, it will be removed in generateBundle.
moduleSideEffects: config2.command === "build" && ((_a4 = this.getModuleInfo(id)) == null ? void 0 : _a4.isEntry) ? "no-treeshake" : false
};
},
renderChunk(code, chunk, opts) {
const s = renderAssetUrlInJS(this, config2, chunk, opts, code);
if (s) {
return {
code: s.toString(),
map: config2.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
};
} else {
return null;
}
},
generateBundle(_, bundle) {
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config2.assetsInclude(chunk.moduleIds[0])) {
delete bundle[file];
}
}
if (config2.command === "build" && config2.build.ssr && !config2.build.ssrEmitAssets) {
for (const file in bundle) {
if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) {
delete bundle[file];
}
}
}
}
};
}
async function fileToUrl$1(id, config2, ctx) {
if (config2.command === "serve") {
return fileToDevUrl(id, config2);
} else {
return fileToBuiltUrl(id, config2, ctx);
}
}
function fileToDevUrl(id, config2) {
var _a4;
let rtn;
if (checkPublicFile(id, config2)) {
rtn = id;
} else if (id.startsWith(withTrailingSlash(config2.root))) {
rtn = "/" + import_node_path3.default.posix.relative(config2.root, id);
} else {
rtn = import_node_path3.default.posix.join(FS_PREFIX, id);
}
const base = joinUrlSegments(((_a4 = config2.server) == null ? void 0 : _a4.origin) ?? "", config2.base);
return joinUrlSegments(base, removeLeadingSlash(rtn));
}
function getPublicAssetFilename(hash2, config2) {
var _a4;
return (_a4 = publicAssetUrlCache.get(config2)) == null ? void 0 : _a4.get(hash2);
}
var publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
var publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
function publicFileToBuiltUrl(url2, config2) {
if (config2.command !== "build") {
return joinUrlSegments(config2.base, url2);
}
const hash2 = getHash(url2);
let cache = publicAssetUrlCache.get(config2);
if (!cache) {
cache = /* @__PURE__ */ new Map();
publicAssetUrlCache.set(config2, cache);
}
if (!cache.get(hash2)) {
cache.set(hash2, url2);
}
return `__VITE_PUBLIC_ASSET__${hash2}__`;
}
var GIT_LFS_PREFIX = import_node_buffer.Buffer.from("version https://git-lfs.github.com");
function isGitLfsPlaceholder(content) {
if (content.length < GIT_LFS_PREFIX.length) return false;
return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
}
async function fileToBuiltUrl(id, config2, pluginContext, skipPublicCheck = false, forceInline) {
if (!skipPublicCheck && checkPublicFile(id, config2)) {
return publicFileToBuiltUrl(id, config2);
}
const cache = assetCache.get(config2);
const cached = cache.get(id);
if (cached) {
return cached;
}
const file = cleanUrl(id);
const content = await import_promises.default.readFile(file);
let url2;
if (shouldInline(config2, file, id, content, pluginContext, forceInline)) {
if (config2.build.lib && isGitLfsPlaceholder(content)) {
config2.logger.warn(
colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`)
);
}
if (file.endsWith(".svg")) {
url2 = svgToDataURL(content);
} else {
const mimeType = lookup(file) ?? "application/octet-stream";
url2 = `data:${mimeType};base64,${content.toString("base64")}`;
}
} else {
const { search, hash: hash2 } = (0, import_node_url2.parse)(id);
const postfix = (search || "") + (hash2 || "");
const referenceId = pluginContext.emitFile({
// Ignore directory structure for asset file names
name: import_node_path3.default.basename(file),
type: "asset",
source: content
});
const originalName = normalizePath$3(import_node_path3.default.relative(config2.root, file));
generatedAssets.get(config2).set(referenceId, { originalName });
url2 = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
}
cache.set(id, url2);
return url2;
}
async function urlToBuiltUrl(url2, importer, config2, pluginContext, forceInline) {
if (checkPublicFile(url2, config2)) {
return publicFileToBuiltUrl(url2, config2);
}
const file = url2[0] === "/" ? import_node_path3.default.join(config2.root, url2) : import_node_path3.default.join(import_node_path3.default.dirname(importer), url2);
return fileToBuiltUrl(
file,
config2,
pluginContext,
// skip public check since we just did it above
true,
forceInline
);
}
var shouldInline = (config2, file, id, content, pluginContext, forceInline) => {
var _a4;
if (config2.build.lib) return true;
if ((_a4 = pluginContext.getModuleInfo(id)) == null ? void 0 : _a4.isEntry) return false;
if (forceInline !== void 0) return forceInline;
let limit;
if (typeof config2.build.assetsInlineLimit === "function") {
const userShouldInline = config2.build.assetsInlineLimit(file, content);
if (userShouldInline != null) return userShouldInline;
limit = DEFAULT_ASSETS_INLINE_LIMIT;
} else {
limit = Number(config2.build.assetsInlineLimit);
}
if (file.endsWith(".html")) return false;
if (file.endsWith(".svg") && id.includes("#")) return false;
return content.length < limit && !isGitLfsPlaceholder(content);
};
var nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
function svgToDataURL(content) {
const stringContent = content.toString();
if (stringContent.includes("<text") || stringContent.includes("<foreignObject") || nestedQuotesRE.test(stringContent)) {
return `data:image/svg+xml;base64,${content.toString("base64")}`;
} else {
return "data:image/svg+xml," + stringContent.trim().replaceAll(/>\s+</g, "><").replaceAll('"', "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
}
}
var endsWithJSRE = /\.[cm]?js$/;
function manifestPlugin(config2) {
const manifest = {};
let outputCount;
return {
name: "vite:manifest",
buildStart() {
outputCount = 0;
},
generateBundle({ format: format2 }, bundle) {
var _a4, _b3;
function getChunkName(chunk) {
return getChunkOriginalFileName(chunk, config2.root, format2);
}
function getInternalImports(imports) {
const filteredImports = [];
for (const file of imports) {
if (bundle[file] === void 0) {
continue;
}
filteredImports.push(getChunkName(bundle[file]));
}
return filteredImports;
}
function createChunk(chunk) {
var _a5, _b4;
const manifestChunk = {
file: chunk.fileName,
name: chunk.name
};
if (chunk.facadeModuleId) {
manifestChunk.src = getChunkName(chunk);
}
if (chunk.isEntry) {
manifestChunk.isEntry = true;
}
if (chunk.isDynamicEntry) {
manifestChunk.isDynamicEntry = true;
}
if (chunk.imports.length) {
const internalImports = getInternalImports(chunk.imports);
if (internalImports.length > 0) {
manifestChunk.imports = internalImports;
}
}
if (chunk.dynamicImports.length) {
const internalImports = getInternalImports(chunk.dynamicImports);
if (internalImports.length > 0) {
manifestChunk.dynamicImports = internalImports;
}
}
if ((_a5 = chunk.viteMetadata) == null ? void 0 : _a5.importedCss.size) {
manifestChunk.css = [...chunk.viteMetadata.importedCss];
}
if ((_b4 = chunk.viteMetadata) == null ? void 0 : _b4.importedAssets.size) {
manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
}
return manifestChunk;
}
function createAsset(asset, src2, isEntry) {
const manifestChunk = {
file: asset.fileName,
src: src2
};
if (isEntry) manifestChunk.isEntry = true;
return manifestChunk;
}
const fileNameToAssetMeta = /* @__PURE__ */ new Map();
const assets = generatedAssets.get(config2);
assets.forEach((asset, referenceId) => {
try {
const fileName = this.getFileName(referenceId);
fileNameToAssetMeta.set(fileName, asset);
} catch (error2) {
assets.delete(referenceId);
}
});
const fileNameToAsset = /* @__PURE__ */ new Map();
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk") {
manifest[getChunkName(chunk)] = createChunk(chunk);
} else if (chunk.type === "asset" && typeof chunk.name === "string") {
const assetMeta = fileNameToAssetMeta.get(chunk.fileName);
const src2 = (assetMeta == null ? void 0 : assetMeta.originalName) ?? chunk.name;
const asset = createAsset(chunk, src2, assetMeta == null ? void 0 : assetMeta.isEntry);
const file2 = (_a4 = manifest[src2]) == null ? void 0 : _a4.file;
if (file2 && endsWithJSRE.test(file2)) continue;
manifest[src2] = asset;
fileNameToAsset.set(chunk.fileName, asset);
}
}
assets.forEach(({ originalName }, referenceId) => {
if (!manifest[originalName]) {
const fileName = this.getFileName(referenceId);
const asset = fileNameToAsset.get(fileName);
if (asset) {
manifest[originalName] = asset;
}
}
});
outputCount++;
const output = (_b3 = config2.build.rollupOptions) == null ? void 0 : _b3.output;
const outputLength = Array.isArray(output) ? output.length : 1;
if (outputCount >= outputLength) {
this.emitFile({
fileName: typeof config2.build.manifest === "string" ? config2.build.manifest : ".vite/manifest.json",
type: "asset",
source: JSON.stringify(sortObjectKeys(manifest), void 0, 2)
});
}
}
};
}
function getChunkOriginalFileName(chunk, root, format2) {
if (chunk.facadeModuleId) {
let name2 = normalizePath$3(import_node_path3.default.relative(root, chunk.facadeModuleId));
if (format2 === "system" && !chunk.name.includes("-legacy")) {
const ext2 = import_node_path3.default.extname(name2);
const endPos = ext2.length !== 0 ? -ext2.length : void 0;
name2 = name2.slice(0, endPos) + `-legacy` + ext2;
}
return name2.replace(/\0/g, "");
} else {
return `_` + import_node_path3.default.basename(chunk.fileName);
}
}
var dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
var base64RE = /base64/i;
var dataUriPrefix = `\0/@data-uri/`;
function dataURIPlugin() {
let resolved;
return {
name: "vite:data-uri",
buildStart() {
resolved = /* @__PURE__ */ new Map();
},
resolveId(id) {
if (!dataUriRE.test(id)) {
return;
}
const uri = new import_node_url2.URL(id);
if (uri.protocol !== "data:") {
return;
}
const match2 = uri.pathname.match(dataUriRE);
if (!match2) {
return;
}
const [, mime, format2, data] = match2;
if (mime !== "text/javascript") {
throw new Error(
`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`
);
}
const base64 = format2 && base64RE.test(format2.substring(1));
const content = base64 ? Buffer.from(data, "base64").toString("utf-8") : data;
resolved.set(id, content);
return dataUriPrefix + id;
},
load(id) {
if (id.startsWith(dataUriPrefix)) {
return resolved.get(id.slice(dataUriPrefix.length));
}
}
};
}
var ImportType;
!function(A2) {
A2[A2.Static = 1] = "Static", A2[A2.Dynamic = 2] = "Dynamic", A2[A2.ImportMeta = 3] = "ImportMeta", A2[A2.StaticSourcePhase = 4] = "StaticSourcePhase", A2[A2.DynamicSourcePhase = 5] = "DynamicSourcePhase";
}(ImportType || (ImportType = {}));
var A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
function parse$d(E2, g = "@") {
if (!C) return init.then(() => parse$d(E2));
const I = E2.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
w > 0 && C.memory.grow(Math.ceil(w / 65536));
const K = C.sa(I - 1);
if ((A ? B : Q)(E2, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(new Error(`Parse error ${g}:${E2.slice(0, C.e()).split("\n").length}:${C.e() - E2.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
const D = [], o2 = [];
for (; C.ri(); ) {
const A2 = C.is(), Q2 = C.ie(), B2 = C.it(), g2 = C.ai(), I2 = C.id(), w2 = C.ss(), K2 = C.se();
let o3;
C.ip() && (o3 = k(E2.slice(-1 === I2 ? A2 - 1 : A2, -1 === I2 ? Q2 + 1 : Q2))), D.push({ n: o3, t: B2, s: A2, e: Q2, ss: w2, se: K2, d: I2, a: g2 });
}
for (; C.re(); ) {
const A2 = C.es(), Q2 = C.ee(), B2 = C.els(), g2 = C.ele(), I2 = E2.slice(A2, Q2), w2 = I2[0], K2 = B2 < 0 ? void 0 : E2.slice(B2, g2), D2 = K2 ? K2[0] : "";
o2.push({ s: A2, e: Q2, ls: B2, le: g2, n: '"' === w2 || "'" === w2 ? k(I2) : I2, ln: '"' === D2 || "'" === D2 ? k(K2) : K2 });
}
function k(A2) {
try {
return (0, eval)(A2);
} catch (A3) {
}
}
return [D, o2, !!C.f(), !!C.ms()];
}
function Q(A2, Q2) {
const B2 = A2.length;
let C2 = 0;
for (; C2 < B2; ) {
const B3 = A2.charCodeAt(C2);
Q2[C2++] = (255 & B3) << 8 | B3 >>> 8;
}
}
function B(A2, Q2) {
const B2 = A2.length;
let C2 = 0;
for (; C2 < B2; ) Q2[C2] = A2.charCodeAt(C2++);
}
var C;
var init = WebAssembly.compile((E = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKm0EwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQvcCAEGf0EAIQBBAEEAKAKwCiIBQQxqIgI2ArAKQQEQKSEDQQAoArAKIQQCQAJAAkACQAJAAkACQAJAIANBLkcNAEEAIARBAmo2ArAKAkBBARApIgNB8wBGDQAgA0HtAEcNB0EAKAKwCiIDQQJqQZwIQQYQLw0HAkBBACgCnAoiBBAqDQAgBC8BAEEuRg0ICyABIAEgA0EIakEAKALUCRABDwtBACgCsAoiA0ECakGiCEEKEC8NBgJAQQAoApwKIgQQKg0AIAQvAQBBLkYNBwsgA0EMaiEDDAELIANB8wBHDQEgBCACTQ0BQQYhAEEAIQIgBEECakGiCEEKEC8NAiAEQQxqIQMCQCAELwEMIgVBd2oiBEEXSw0AQQEgBHRBn4CABHENAQsgBUGgAUcNAgtBACADNgKwCkEBIQBBARApIQMLAkACQAJAAkAgA0H7AEYNACADQShHDQFBACgCpApBAC8BmAoiA0EDdGoiBEEAKAKwCjYCBEEAIANBAWo7AZgKIARBBTYCAEEAKAKcCi8BAEEuRg0HQQBBACgCsAoiBEECajYCsApBARApIQMgAUEAKAKwCkEAIAQQAQJAAkAgAA0AQQAoAvAJIQQMAQtBACgC8AkiBEEFNgIcC0EAQQAvAZYKIgBBAWo7AZYKQQAoAqgKIABBAnRqIAQ2AgACQCADQSJGDQAgA0EnRg0AQQBBACgCsApBfmo2ArAKDwsgAxAaQQBBACgCsApBAmoiAzYCsAoCQAJAAkBBARApQVdqDgQBAgIAAgtBAEEAKAKwCkECajYCsApBARApGkEAKALwCSIEIAM2AgQgBEEBOgAYIARBACgCsAoiAzYCEEEAIANBfmo2ArAKDwtBACgC8AkiBCADNgIEIARBAToAGEEAQQAvAZgKQX9qOwGYCiAEQQAoArAKQQJqNgIMQQBBAC8BlgpBf2o7AZYKDwtBAEEAKAKwCkF+ajYCsAoPCyAADQJBACgCsAohA0EALwGYCg0BA0ACQAJAAkAgA0EAKAK0Ck8NAEEBECkiA0EiRg0BIANBJ0YNASADQf0ARw0CQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0JC0EAIANBCGo2ArAKAkBBARApIgNBIkYNACADQSdHDQkLIAEgA0EAECsPCyADEBoLQQBBACgCsApBAmoiAzYCsAoMAAsLIAANAUEGIQBBACECAkAgA0FZag4EBAMDBAALIANBIkYNAwwCC0EAIANBfmo2ArAKDwtBDCEAQQEhAgtBACgCsAoiAyABIABBAXRqRw0AQQAgA0F+ajYCsAoPC0EALwGYCg0CQQAoArAKIQNBACgCtAohAANAIAMgAE8NAQJAAkAgAy8BACIEQSdGDQAgBEEiRw0BCyABIAQgAhArDwtBACADQQJqIgM2ArAKDAALCxAlCw8LQQBBACgCsApBfmo2ArAKC0cBA39BACgCsApBAmohAEEAKAK0CiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2ArAKC5gBAQN/QQBBACgCsAoiAUECajYCsAogAUEGaiEBQQAoArQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2ArAKDAELIAFBfmohAQtBACABNgKwCg8LIAFBAmohAQwACwuIAQEEf0EAKAKwCiEBQQAoArQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKwChAlDwtBACABNgKwCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQaYJQQUQHQ0AIABBlghBAxAdDQAgAEGwCUECEB0hAQsgAQtGAQN/QQAhAwJAIAAgAkEBdCICayIEQQJqIgBBACgC3AkiBUkNACAAIAEgAhAvDQACQCAAIAVHDQBBAQ8LIAQQJiEDCyADC4MBAQJ/QQEhAQJAAkACQAJAAkACQCAALwEAIgJBRWoOBAUEBAEACwJAIAJBm39qDgQDBAQCAAsgAkEpRg0EIAJB+QBHDQMgAEF+akG8CUEGEB0PCyAAQX5qLwEAQT1GDwsgAEF+akG0CUEEEB0PCyAAQX5qQcgJQQMQHQ8LQQAhAQsgAQu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQcoIQQIQHQ8LIABBfGpBzghBAxAdDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAnDwsgAEF6akHjABAnDwsgAEF8akHUCEEEEB0PCyAAQXxqQdwIQQYQHQ8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB6AhBBhAdDwsgAEF4akH0CEECEB0PCyAAQX5qQfgIQQQQHQ8LQQEhASAAQX5qIgBB6QAQJw0EIABBgAlBBRAdDwsgAEF+akHkABAnDwsgAEF+akGKCUEHEB0PCyAAQX5qQZgJQQQQHQ8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAnDwsgAEF8akGgCUEDEB0hAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAocSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akH4CEEEEB0PCyAAQX5qLwEAQfUARw0AIABBfGpB3AhBBhAdIQELIAEL3gEBBH9BACgCsAohAEEAKAK0CiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2ArAKQQBBAC8BmAoiAkEBajsBmApBACgCpAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCsApBAEEALwGYCkF/aiIAOwGYCkEAKAKkCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2ArAKCxAlCwtwAQJ/AkACQANAQQBBACgCsAoiAEECaiIBNgKwCiAAQQAoArQKTw0BAkACQAJAIAEvAQAiAUGlf2oOAgECAAsCQCABQXZqDgQEAwMEAAsgAUEvRw0CDAQLEC4aDAELQQAgAEEEajYCsAoMAAsLECULCzUBAX9BAEEBOgD8CUEAKAKwCiEAQQBBACgCtApBAmo2ArAKQQAgAEEAKALcCWtBAXU2ApAKC0MBAn9BASEBAkAgAC8BACICQXdqQf//A3FBBUkNACACQYABckGgAUYNAEEAIQEgAhAoRQ0AIAJBLkcgABAqcg8LIAELPQECf0EAIQICQEEAKALcCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAECAhAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKwCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQGAwCCyAAEBkMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACECFFDQMMAQsgAkGgAUcNAgtBAEEAKAKwCiIDQQJqIgE2ArAKIANBACgCtApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELnAQBAX8CQCABQSJGDQAgAUEnRg0AECUPC0EAKAKwCiEDIAEQGiAAIANBAmpBACgCsApBACgC0AkQAQJAIAJFDQBBACgC8AlBBDYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQAMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhACABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIABBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiAiEAA0BBACAAQQJqNgKwCgJAAkACQEEBECkiAEEiRg0AIABBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQAMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSEADAELIAAQLCEACwJAIABBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAEEiRg0AIABBJ0YNAEEAIAE2ArAKDwsgABAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAEEsRg0AIABB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiEADAELC0EAKALwCSIBIAI2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(E, "base64") : Uint8Array.from(atob(E), (A2) => A2.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A2 }) => {
C = A2;
});
var E;
var convertSourceMap$1 = {};
(function(exports2) {
Object.defineProperty(exports2, "commentRegex", {
get: function getCommentRegex() {
return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
}
});
Object.defineProperty(exports2, "mapFileCommentRegex", {
get: function getMapFileCommentRegex() {
return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
}
});
var decodeBase64;
if (typeof Buffer !== "undefined") {
if (typeof Buffer.from === "function") {
decodeBase64 = decodeBase64WithBufferFrom;
} else {
decodeBase64 = decodeBase64WithNewBuffer;
}
} else {
decodeBase64 = decodeBase64WithAtob;
}
function decodeBase64WithBufferFrom(base64) {
return Buffer.from(base64, "base64").toString();
}
function decodeBase64WithNewBuffer(base64) {
if (typeof value === "number") {
throw new TypeError("The value to decode must not be of type number.");
}
return new Buffer(base64, "base64").toString();
}
function decodeBase64WithAtob(base64) {
return decodeURIComponent(escape(atob(base64)));
}
function stripComment(sm) {
return sm.split(",").pop();
}
function readFromFileMap(sm, read2) {
var r2 = exports2.mapFileCommentRegex.exec(sm);
var filename = r2[1] || r2[2];
try {
var sm = read2(filename);
if (sm != null && typeof sm.catch === "function") {
return sm.catch(throwError);
} else {
return sm;
}
} catch (e2) {
throwError(e2);
}
function throwError(e2) {
throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e2.stack);
}
}
function Converter(sm, opts) {
opts = opts || {};
if (opts.hasComment) {
sm = stripComment(sm);
}
if (opts.encoding === "base64") {
sm = decodeBase64(sm);
} else if (opts.encoding === "uri") {
sm = decodeURIComponent(sm);
}
if (opts.isJSON || opts.encoding) {
sm = JSON.parse(sm);
}
this.sourcemap = sm;
}
Converter.prototype.toJSON = function(space) {
return JSON.stringify(this.sourcemap, null, space);
};
if (typeof Buffer !== "undefined") {
if (typeof Buffer.from === "function") {
Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
} else {
Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
}
} else {
Converter.prototype.toBase64 = encodeBase64WithBtoa;
}
function encodeBase64WithBufferFrom() {
var json = this.toJSON();
return Buffer.from(json, "utf8").toString("base64");
}
function encodeBase64WithNewBuffer() {
var json = this.toJSON();
if (typeof json === "number") {
throw new TypeError("The json to encode must not be of type number.");
}
return new Buffer(json, "utf8").toString("base64");
}
function encodeBase64WithBtoa() {
var json = this.toJSON();
return btoa(unescape(encodeURIComponent(json)));
}
Converter.prototype.toURI = function() {
var json = this.toJSON();
return encodeURIComponent(json);
};
Converter.prototype.toComment = function(options2) {
var encoding, content, data;
if (options2 != null && options2.encoding === "uri") {
encoding = "";
content = this.toURI();
} else {
encoding = ";base64";
content = this.toBase64();
}
data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
return options2 != null && options2.multiline ? "/*# " + data + " */" : "//# " + data;
};
Converter.prototype.toObject = function() {
return JSON.parse(this.toJSON());
};
Converter.prototype.addProperty = function(key, value2) {
if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
return this.setProperty(key, value2);
};
Converter.prototype.setProperty = function(key, value2) {
this.sourcemap[key] = value2;
return this;
};
Converter.prototype.getProperty = function(key) {
return this.sourcemap[key];
};
exports2.fromObject = function(obj) {
return new Converter(obj);
};
exports2.fromJSON = function(json) {
return new Converter(json, { isJSON: true });
};
exports2.fromURI = function(uri) {
return new Converter(uri, { encoding: "uri" });
};
exports2.fromBase64 = function(base64) {
return new Converter(base64, { encoding: "base64" });
};
exports2.fromComment = function(comment) {
var m, encoding;
comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
m = exports2.commentRegex.exec(comment);
encoding = m && m[4] || "uri";
return new Converter(comment, { encoding, hasComment: true });
};
function makeConverter(sm) {
return new Converter(sm, { isJSON: true });
}
exports2.fromMapFileComment = function(comment, read2) {
if (typeof read2 === "string") {
throw new Error(
"String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
);
}
var sm = readFromFileMap(comment, read2);
if (sm != null && typeof sm.then === "function") {
return sm.then(makeConverter);
} else {
return makeConverter(sm);
}
};
exports2.fromSource = function(content) {
var m = content.match(exports2.commentRegex);
return m ? exports2.fromComment(m.pop()) : null;
};
exports2.fromMapFileSource = function(content, read2) {
if (typeof read2 === "string") {
throw new Error(
"String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
);
}
var m = content.match(exports2.mapFileCommentRegex);
return m ? exports2.fromMapFileComment(m.pop(), read2) : null;
};
exports2.removeComments = function(src2) {
return src2.replace(exports2.commentRegex, "");
};
exports2.removeMapFileComments = function(src2) {
return src2.replace(exports2.mapFileCommentRegex, "");
};
exports2.generateMapFileComment = function(file, options2) {
var data = "sourceMappingURL=" + file;
return options2 && options2.multiline ? "/*# " + data + " */" : "//# " + data;
};
})(convertSourceMap$1);
var convertSourceMap = getDefaultExportFromCjs(convertSourceMap$1);
var debug$g = createDebugger("vite:sourcemap", {
onlyWhenFocused: true
});
var virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
async function computeSourceRoute(map2, file) {
let sourceRoot;
try {
sourceRoot = await import_promises.default.realpath(
import_node_path3.default.resolve(import_node_path3.default.dirname(file), map2.sourceRoot || "")
);
} catch {
}
return sourceRoot;
}
async function injectSourcesContent(map2, file, logger) {
let sourceRootPromise;
const missingSources = [];
const sourcesContent = map2.sourcesContent || [];
const sourcesContentPromises = [];
for (let index = 0; index < map2.sources.length; index++) {
const sourcePath = map2.sources[index];
if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) {
sourcesContentPromises.push(
(async () => {
sourceRootPromise ?? (sourceRootPromise = computeSourceRoute(map2, file));
const sourceRoot = await sourceRootPromise;
let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
if (sourceRoot) {
resolvedSourcePath = import_node_path3.default.resolve(sourceRoot, resolvedSourcePath);
}
sourcesContent[index] = await import_promises.default.readFile(resolvedSourcePath, "utf-8").catch(() => {
missingSources.push(resolvedSourcePath);
return null;
});
})()
);
}
}
await Promise.all(sourcesContentPromises);
map2.sourcesContent = sourcesContent;
if (missingSources.length) {
logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
debug$g == null ? void 0 : debug$g(`Missing sources:
` + missingSources.join(`
`));
}
}
function genSourceMapUrl(map2) {
if (typeof map2 !== "string") {
map2 = JSON.stringify(map2);
}
return `data:application/json;base64,${Buffer.from(map2).toString("base64")}`;
}
function getCodeWithSourcemap(type, code, map2) {
if (debug$g) {
code += `
/*${JSON.stringify(map2, null, 2).replace(/\*\//g, "*\\/")}*/
`;
}
if (type === "js") {
code += `
//# sourceMappingURL=${genSourceMapUrl(map2)}`;
} else if (type === "css") {
code += `
/*# sourceMappingURL=${genSourceMapUrl(map2)} */`;
}
return code;
}
function applySourcemapIgnoreList(map2, sourcemapPath, sourcemapIgnoreList, logger) {
let { x_google_ignoreList } = map2;
if (x_google_ignoreList === void 0) {
x_google_ignoreList = [];
}
for (let sourcesIndex = 0; sourcesIndex < map2.sources.length; ++sourcesIndex) {
const sourcePath = map2.sources[sourcesIndex];
if (!sourcePath) continue;
const ignoreList = sourcemapIgnoreList(
import_node_path3.default.isAbsolute(sourcePath) ? sourcePath : import_node_path3.default.resolve(import_node_path3.default.dirname(sourcemapPath), sourcePath),
sourcemapPath
);
if (logger && typeof ignoreList !== "boolean") {
logger.warn("sourcemapIgnoreList function must return a boolean.");
}
if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
x_google_ignoreList.push(sourcesIndex);
}
}
if (x_google_ignoreList.length > 0) {
if (!map2.x_google_ignoreList) map2.x_google_ignoreList = x_google_ignoreList;
}
}
async function extractSourcemapFromFile(code, filePath) {
var _a4;
const map2 = (_a4 = convertSourceMap.fromSource(code) || await convertSourceMap.fromMapFileSource(
code,
createConvertSourceMapReadMap(filePath)
)) == null ? void 0 : _a4.toObject();
if (map2) {
return {
code: code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer),
map: map2
};
}
}
function createConvertSourceMapReadMap(originalFileName) {
return (filename) => {
return import_promises.default.readFile(
import_node_path3.default.resolve(import_node_path3.default.dirname(originalFileName), filename),
"utf-8"
);
};
}
var tasks = {};
var utils$g = {};
var array$1 = {};
Object.defineProperty(array$1, "__esModule", { value: true });
array$1.splitWhen = array$1.flatten = void 0;
function flatten$1(items) {
return items.reduce((collection, item) => [].concat(collection, item), []);
}
array$1.flatten = flatten$1;
function splitWhen(items, predicate) {
const result = [[]];
let groupIndex = 0;
for (const item of items) {
if (predicate(item)) {
groupIndex++;
result[groupIndex] = [];
} else {
result[groupIndex].push(item);
}
}
return result;
}
array$1.splitWhen = splitWhen;
var errno$1 = {};
Object.defineProperty(errno$1, "__esModule", { value: true });
errno$1.isEnoentCodeError = void 0;
function isEnoentCodeError(error2) {
return error2.code === "ENOENT";
}
errno$1.isEnoentCodeError = isEnoentCodeError;
var fs$i = {};
Object.defineProperty(fs$i, "__esModule", { value: true });
fs$i.createDirentFromStats = void 0;
var DirentFromStats$1 = class DirentFromStats {
constructor(name2, stats) {
this.name = name2;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
};
function createDirentFromStats$1(name2, stats) {
return new DirentFromStats$1(name2, stats);
}
fs$i.createDirentFromStats = createDirentFromStats$1;
var path$i = {};
Object.defineProperty(path$i, "__esModule", { value: true });
path$i.convertPosixPathToPattern = path$i.convertWindowsPathToPattern = path$i.convertPathToPattern = path$i.escapePosixPath = path$i.escapeWindowsPath = path$i.escape = path$i.removeLeadingDotSegment = path$i.makeAbsolute = path$i.unixify = void 0;
var os$4 = import_os.default;
var path$h = import_path.default;
var IS_WINDOWS_PLATFORM = os$4.platform() === "win32";
var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2;
var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
var WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g;
var DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
var WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g;
function unixify(filepath) {
return filepath.replace(/\\/g, "/");
}
path$i.unixify = unixify;
function makeAbsolute(cwd, filepath) {
return path$h.resolve(cwd, filepath);
}
path$i.makeAbsolute = makeAbsolute;
function removeLeadingDotSegment(entry2) {
if (entry2.charAt(0) === ".") {
const secondCharactery = entry2.charAt(1);
if (secondCharactery === "/" || secondCharactery === "\\") {
return entry2.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
}
}
return entry2;
}
path$i.removeLeadingDotSegment = removeLeadingDotSegment;
path$i.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
function escapeWindowsPath(pattern2) {
return pattern2.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2");
}
path$i.escapeWindowsPath = escapeWindowsPath;
function escapePosixPath(pattern2) {
return pattern2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2");
}
path$i.escapePosixPath = escapePosixPath;
path$i.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
function convertWindowsPathToPattern(filepath) {
return escapeWindowsPath(filepath).replace(DOS_DEVICE_PATH_RE, "//$1").replace(WINDOWS_BACKSLASHES_RE, "/");
}
path$i.convertWindowsPathToPattern = convertWindowsPathToPattern;
function convertPosixPathToPattern(filepath) {
return escapePosixPath(filepath);
}
path$i.convertPosixPathToPattern = convertPosixPathToPattern;
var pattern$1 = {};
var isExtglob$1 = function isExtglob(str) {
if (typeof str !== "string" || str === "") {
return false;
}
var match2;
while (match2 = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
if (match2[2]) return true;
str = str.slice(match2.index + match2[0].length);
}
return false;
};
var isExtglob2 = isExtglob$1;
var chars = { "{": "}", "(": ")", "[": "]" };
var strictCheck = function(str) {
if (str[0] === "!") {
return true;
}
var index = 0;
var pipeIndex = -2;
var closeSquareIndex = -2;
var closeCurlyIndex = -2;
var closeParenIndex = -2;
var backSlashIndex = -2;
while (index < str.length) {
if (str[index] === "*") {
return true;
}
if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) {
return true;
}
if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
if (closeSquareIndex < index) {
closeSquareIndex = str.indexOf("]", index);
}
if (closeSquareIndex > index) {
if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
return true;
}
backSlashIndex = str.indexOf("\\", index);
if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
return true;
}
}
}
if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
closeCurlyIndex = str.indexOf("}", index);
if (closeCurlyIndex > index) {
backSlashIndex = str.indexOf("\\", index);
if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
return true;
}
}
}
if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
closeParenIndex = str.indexOf(")", index);
if (closeParenIndex > index) {
backSlashIndex = str.indexOf("\\", index);
if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
return true;
}
}
}
if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
if (pipeIndex < index) {
pipeIndex = str.indexOf("|", index);
}
if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
closeParenIndex = str.indexOf(")", pipeIndex);
if (closeParenIndex > pipeIndex) {
backSlashIndex = str.indexOf("\\", pipeIndex);
if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
return true;
}
}
}
}
if (str[index] === "\\") {
var open2 = str[index + 1];
index += 2;
var close2 = chars[open2];
if (close2) {
var n2 = str.indexOf(close2, index);
if (n2 !== -1) {
index = n2 + 1;
}
}
if (str[index] === "!") {
return true;
}
} else {
index++;
}
}
return false;
};
var relaxedCheck = function(str) {
if (str[0] === "!") {
return true;
}
var index = 0;
while (index < str.length) {
if (/[*?{}()[\]]/.test(str[index])) {
return true;
}
if (str[index] === "\\") {
var open2 = str[index + 1];
index += 2;
var close2 = chars[open2];
if (close2) {
var n2 = str.indexOf(close2, index);
if (n2 !== -1) {
index = n2 + 1;
}
}
if (str[index] === "!") {
return true;
}
} else {
index++;
}
}
return false;
};
var isGlob$2 = function isGlob(str, options2) {
if (typeof str !== "string" || str === "") {
return false;
}
if (isExtglob2(str)) {
return true;
}
var check = strictCheck;
if (options2 && options2.strict === false) {
check = relaxedCheck;
}
return check(str);
};
var isGlob$1 = isGlob$2;
var pathPosixDirname = import_path.default.posix.dirname;
var isWin32 = import_os.default.platform() === "win32";
var slash = "/";
var backslash = /\\/g;
var enclosure = /[\{\[].*[\}\]]$/;
var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
var globParent$2 = function globParent(str, opts) {
var options2 = Object.assign({ flipBackslashes: true }, opts);
if (options2.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
str = str.replace(backslash, slash);
}
if (enclosure.test(str)) {
str += slash;
}
str += "a";
do {
str = pathPosixDirname(str);
} while (isGlob$1(str) || globby.test(str));
return str.replace(escaped, "$1");
};
var utils$f = {};
(function(exports2) {
exports2.isInteger = (num) => {
if (typeof num === "number") {
return Number.isInteger(num);
}
if (typeof num === "string" && num.trim() !== "") {
return Number.isInteger(Number(num));
}
return false;
};
exports2.find = (node2, type) => node2.nodes.find((node3) => node3.type === type);
exports2.exceedsLimit = (min2, max, step = 1, limit) => {
if (limit === false) return false;
if (!exports2.isInteger(min2) || !exports2.isInteger(max)) return false;
return (Number(max) - Number(min2)) / Number(step) >= limit;
};
exports2.escapeNode = (block, n2 = 0, type) => {
const node2 = block.nodes[n2];
if (!node2) return;
if (type && node2.type === type || node2.type === "open" || node2.type === "close") {
if (node2.escaped !== true) {
node2.value = "\\" + node2.value;
node2.escaped = true;
}
}
};
exports2.encloseBrace = (node2) => {
if (node2.type !== "brace") return false;
if (node2.commas >> 0 + node2.ranges >> 0 === 0) {
node2.invalid = true;
return true;
}
return false;
};
exports2.isInvalidBrace = (block) => {
if (block.type !== "brace") return false;
if (block.invalid === true || block.dollar) return true;
if (block.commas >> 0 + block.ranges >> 0 === 0) {
block.invalid = true;
return true;
}
if (block.open !== true || block.close !== true) {
block.invalid = true;
return true;
}
return false;
};
exports2.isOpenOrClose = (node2) => {
if (node2.type === "open" || node2.type === "close") {
return true;
}
return node2.open === true || node2.close === true;
};
exports2.reduce = (nodes) => nodes.reduce((acc, node2) => {
if (node2.type === "text") acc.push(node2.value);
if (node2.type === "range") node2.type = "text";
return acc;
}, []);
exports2.flatten = (...args) => {
const result = [];
const flat = (arr) => {
for (let i = 0; i < arr.length; i++) {
const ele = arr[i];
if (Array.isArray(ele)) {
flat(ele);
continue;
}
if (ele !== void 0) {
result.push(ele);
}
}
return result;
};
flat(args);
return result;
};
})(utils$f);
var utils$e = utils$f;
var stringify$7 = (ast, options2 = {}) => {
const stringify2 = (node2, parent = {}) => {
const invalidBlock = options2.escapeInvalid && utils$e.isInvalidBrace(parent);
const invalidNode = node2.invalid === true && options2.escapeInvalid === true;
let output = "";
if (node2.value) {
if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node2)) {
return "\\" + node2.value;
}
return node2.value;
}
if (node2.value) {
return node2.value;
}
if (node2.nodes) {
for (const child of node2.nodes) {
output += stringify2(child);
}
}
return output;
};
return stringify2(ast);
};
var isNumber$2 = function(num) {
if (typeof num === "number") {
return num - num === 0;
}
if (typeof num === "string" && num.trim() !== "") {
return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
}
return false;
};
var isNumber$1 = isNumber$2;
var toRegexRange$1 = (min2, max, options2) => {
if (isNumber$1(min2) === false) {
throw new TypeError("toRegexRange: expected the first argument to be a number");
}
if (max === void 0 || min2 === max) {
return String(min2);
}
if (isNumber$1(max) === false) {
throw new TypeError("toRegexRange: expected the second argument to be a number.");
}
let opts = { relaxZeros: true, ...options2 };
if (typeof opts.strictZeros === "boolean") {
opts.relaxZeros = opts.strictZeros === false;
}
let relax = String(opts.relaxZeros);
let shorthand = String(opts.shorthand);
let capture = String(opts.capture);
let wrap2 = String(opts.wrap);
let cacheKey = min2 + ":" + max + "=" + relax + shorthand + capture + wrap2;
if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
return toRegexRange$1.cache[cacheKey].result;
}
let a = Math.min(min2, max);
let b = Math.max(min2, max);
if (Math.abs(a - b) === 1) {
let result = min2 + "|" + max;
if (opts.capture) {
return `(${result})`;
}
if (opts.wrap === false) {
return result;
}
return `(?:${result})`;
}
let isPadded2 = hasPadding(min2) || hasPadding(max);
let state = { min: min2, max, a, b };
let positives = [];
let negatives = [];
if (isPadded2) {
state.isPadded = isPadded2;
state.maxLen = String(state.max).length;
}
if (a < 0) {
let newMin = b < 0 ? Math.abs(b) : 1;
negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
a = state.a = 0;
}
if (b >= 0) {
positives = splitToPatterns(a, b, state, opts);
}
state.negatives = negatives;
state.positives = positives;
state.result = collatePatterns(negatives, positives);
if (opts.capture === true) {
state.result = `(${state.result})`;
} else if (opts.wrap !== false && positives.length + negatives.length > 1) {
state.result = `(?:${state.result})`;
}
toRegexRange$1.cache[cacheKey] = state;
return state.result;
};
function collatePatterns(neg, pos, options2) {
let onlyNegative = filterPatterns(neg, pos, "-", false) || [];
let onlyPositive = filterPatterns(pos, neg, "", false) || [];
let intersected = filterPatterns(neg, pos, "-?", true) || [];
let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
return subpatterns.join("|");
}
function splitToRanges(min2, max) {
let nines = 1;
let zeros2 = 1;
let stop = countNines(min2, nines);
let stops = /* @__PURE__ */ new Set([max]);
while (min2 <= stop && stop <= max) {
stops.add(stop);
nines += 1;
stop = countNines(min2, nines);
}
stop = countZeros(max + 1, zeros2) - 1;
while (min2 < stop && stop <= max) {
stops.add(stop);
zeros2 += 1;
stop = countZeros(max + 1, zeros2) - 1;
}
stops = [...stops];
stops.sort(compare);
return stops;
}
function rangeToPattern(start, stop, options2) {
if (start === stop) {
return { pattern: start, count: [], digits: 0 };
}
let zipped = zip(start, stop);
let digits = zipped.length;
let pattern2 = "";
let count = 0;
for (let i = 0; i < digits; i++) {
let [startDigit, stopDigit] = zipped[i];
if (startDigit === stopDigit) {
pattern2 += startDigit;
} else if (startDigit !== "0" || stopDigit !== "9") {
pattern2 += toCharacterClass(startDigit, stopDigit);
} else {
count++;
}
}
if (count) {
pattern2 += options2.shorthand === true ? "\\d" : "[0-9]";
}
return { pattern: pattern2, count: [count], digits };
}
function splitToPatterns(min2, max, tok, options2) {
let ranges = splitToRanges(min2, max);
let tokens = [];
let start = min2;
let prev;
for (let i = 0; i < ranges.length; i++) {
let max2 = ranges[i];
let obj = rangeToPattern(String(start), String(max2), options2);
let zeros2 = "";
if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
if (prev.count.length > 1) {
prev.count.pop();
}
prev.count.push(obj.count[0]);
prev.string = prev.pattern + toQuantifier(prev.count);
start = max2 + 1;
continue;
}
if (tok.isPadded) {
zeros2 = padZeros(max2, tok, options2);
}
obj.string = zeros2 + obj.pattern + toQuantifier(obj.count);
tokens.push(obj);
start = max2 + 1;
prev = obj;
}
return tokens;
}
function filterPatterns(arr, comparison, prefix, intersection, options2) {
let result = [];
for (let ele of arr) {
let { string: string2 } = ele;
if (!intersection && !contains(comparison, "string", string2)) {
result.push(prefix + string2);
}
if (intersection && contains(comparison, "string", string2)) {
result.push(prefix + string2);
}
}
return result;
}
function zip(a, b) {
let arr = [];
for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
return arr;
}
function compare(a, b) {
return a > b ? 1 : b > a ? -1 : 0;
}
function contains(arr, key, val) {
return arr.some((ele) => ele[key] === val);
}
function countNines(min2, len) {
return Number(String(min2).slice(0, -len) + "9".repeat(len));
}
function countZeros(integer, zeros2) {
return integer - integer % Math.pow(10, zeros2);
}
function toQuantifier(digits) {
let [start = 0, stop = ""] = digits;
if (stop || start > 1) {
return `{${start + (stop ? "," + stop : "")}}`;
}
return "";
}
function toCharacterClass(a, b, options2) {
return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
}
function hasPadding(str) {
return /^-?(0+)\d/.test(str);
}
function padZeros(value2, tok, options2) {
if (!tok.isPadded) {
return value2;
}
let diff = Math.abs(tok.maxLen - String(value2).length);
let relax = options2.relaxZeros !== false;
switch (diff) {
case 0:
return "";
case 1:
return relax ? "0?" : "0";
case 2:
return relax ? "0{0,2}" : "00";
default: {
return relax ? `0{0,${diff}}` : `0{${diff}}`;
}
}
}
toRegexRange$1.cache = {};
toRegexRange$1.clearCache = () => toRegexRange$1.cache = {};
var toRegexRange_1 = toRegexRange$1;
var util$1 = import_util.default;
var toRegexRange = toRegexRange_1;
var isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
var transform = (toNumber) => {
return (value2) => toNumber === true ? Number(value2) : String(value2);
};
var isValidValue = (value2) => {
return typeof value2 === "number" || typeof value2 === "string" && value2 !== "";
};
var isNumber = (num) => Number.isInteger(+num);
var zeros = (input) => {
let value2 = `${input}`;
let index = -1;
if (value2[0] === "-") value2 = value2.slice(1);
if (value2 === "0") return false;
while (value2[++index] === "0") ;
return index > 0;
};
var stringify$6 = (start, end, options2) => {
if (typeof start === "string" || typeof end === "string") {
return true;
}
return options2.stringify === true;
};
var pad = (input, maxLength, toNumber) => {
if (maxLength > 0) {
let dash = input[0] === "-" ? "-" : "";
if (dash) input = input.slice(1);
input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0");
}
if (toNumber === false) {
return String(input);
}
return input;
};
var toMaxLen = (input, maxLength) => {
let negative = input[0] === "-" ? "-" : "";
if (negative) {
input = input.slice(1);
maxLength--;
}
while (input.length < maxLength) input = "0" + input;
return negative ? "-" + input : input;
};
var toSequence = (parts, options2, maxLen) => {
parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
let prefix = options2.capture ? "" : "?:";
let positives = "";
let negatives = "";
let result;
if (parts.positives.length) {
positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
}
if (parts.negatives.length) {
negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
}
if (positives && negatives) {
result = `${positives}|${negatives}`;
} else {
result = positives || negatives;
}
if (options2.wrap) {
return `(${prefix}${result})`;
}
return result;
};
var toRange = (a, b, isNumbers, options2) => {
if (isNumbers) {
return toRegexRange(a, b, { wrap: false, ...options2 });
}
let start = String.fromCharCode(a);
if (a === b) return start;
let stop = String.fromCharCode(b);
return `[${start}-${stop}]`;
};
var toRegex = (start, end, options2) => {
if (Array.isArray(start)) {
let wrap2 = options2.wrap === true;
let prefix = options2.capture ? "" : "?:";
return wrap2 ? `(${prefix}${start.join("|")})` : start.join("|");
}
return toRegexRange(start, end, options2);
};
var rangeError = (...args) => {
return new RangeError("Invalid range arguments: " + util$1.inspect(...args));
};
var invalidRange = (start, end, options2) => {
if (options2.strictRanges === true) throw rangeError([start, end]);
return [];
};
var invalidStep = (step, options2) => {
if (options2.strictRanges === true) {
throw new TypeError(`Expected step "${step}" to be a number`);
}
return [];
};
var fillNumbers = (start, end, step = 1, options2 = {}) => {
let a = Number(start);
let b = Number(end);
if (!Number.isInteger(a) || !Number.isInteger(b)) {
if (options2.strictRanges === true) throw rangeError([start, end]);
return [];
}
if (a === 0) a = 0;
if (b === 0) b = 0;
let descending = a > b;
let startString = String(start);
let endString = String(end);
let stepString = String(step);
step = Math.max(Math.abs(step), 1);
let padded = zeros(startString) || zeros(endString) || zeros(stepString);
let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
let toNumber = padded === false && stringify$6(start, end, options2) === false;
let format2 = options2.transform || transform(toNumber);
if (options2.toRegex && step === 1) {
return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options2);
}
let parts = { negatives: [], positives: [] };
let push2 = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
let range2 = [];
let index = 0;
while (descending ? a >= b : a <= b) {
if (options2.toRegex === true && step > 1) {
push2(a);
} else {
range2.push(pad(format2(a, index), maxLen, toNumber));
}
a = descending ? a - step : a + step;
index++;
}
if (options2.toRegex === true) {
return step > 1 ? toSequence(parts, options2, maxLen) : toRegex(range2, null, { wrap: false, ...options2 });
}
return range2;
};
var fillLetters = (start, end, step = 1, options2 = {}) => {
if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) {
return invalidRange(start, end, options2);
}
let format2 = options2.transform || ((val) => String.fromCharCode(val));
let a = `${start}`.charCodeAt(0);
let b = `${end}`.charCodeAt(0);
let descending = a > b;
let min2 = Math.min(a, b);
let max = Math.max(a, b);
if (options2.toRegex && step === 1) {
return toRange(min2, max, false, options2);
}
let range2 = [];
let index = 0;
while (descending ? a >= b : a <= b) {
range2.push(format2(a, index));
a = descending ? a - step : a + step;
index++;
}
if (options2.toRegex === true) {
return toRegex(range2, null, { wrap: false, options: options2 });
}
return range2;
};
var fill$2 = (start, end, step, options2 = {}) => {
if (end == null && isValidValue(start)) {
return [start];
}
if (!isValidValue(start) || !isValidValue(end)) {
return invalidRange(start, end, options2);
}
if (typeof step === "function") {
return fill$2(start, end, 1, { transform: step });
}
if (isObject(step)) {
return fill$2(start, end, 0, step);
}
let opts = { ...options2 };
if (opts.capture === true) opts.wrap = true;
step = step || opts.step || 1;
if (!isNumber(step)) {
if (step != null && !isObject(step)) return invalidStep(step, opts);
return fill$2(start, end, 1, step);
}
if (isNumber(start) && isNumber(end)) {
return fillNumbers(start, end, step, opts);
}
return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
};
var fillRange = fill$2;
var fill$1 = fillRange;
var utils$d = utils$f;
var compile$1 = (ast, options2 = {}) => {
const walk2 = (node2, parent = {}) => {
const invalidBlock = utils$d.isInvalidBrace(parent);
const invalidNode = node2.invalid === true && options2.escapeInvalid === true;
const invalid = invalidBlock === true || invalidNode === true;
const prefix = options2.escapeInvalid === true ? "\\" : "";
let output = "";
if (node2.isOpen === true) {
return prefix + node2.value;
}
if (node2.isClose === true) {
console.log("node.isClose", prefix, node2.value);
return prefix + node2.value;
}
if (node2.type === "open") {
return invalid ? prefix + node2.value : "(";
}
if (node2.type === "close") {
return invalid ? prefix + node2.value : ")";
}
if (node2.type === "comma") {
return node2.prev.type === "comma" ? "" : invalid ? node2.value : "|";
}
if (node2.value) {
return node2.value;
}
if (node2.nodes && node2.ranges > 0) {
const args = utils$d.reduce(node2.nodes);
const range2 = fill$1(...args, { ...options2, wrap: false, toRegex: true, strictZeros: true });
if (range2.length !== 0) {
return args.length > 1 && range2.length > 1 ? `(${range2})` : range2;
}
}
if (node2.nodes) {
for (const child of node2.nodes) {
output += walk2(child, node2);
}
}
return output;
};
return walk2(ast);
};
var compile_1 = compile$1;
var fill = fillRange;
var stringify$5 = stringify$7;
var utils$c = utils$f;
var append$1 = (queue2 = "", stash = "", enclose = false) => {
const result = [];
queue2 = [].concat(queue2);
stash = [].concat(stash);
if (!stash.length) return queue2;
if (!queue2.length) {
return enclose ? utils$c.flatten(stash).map((ele) => `{${ele}}`) : stash;
}
for (const item of queue2) {
if (Array.isArray(item)) {
for (const value2 of item) {
result.push(append$1(value2, stash, enclose));
}
} else {
for (let ele of stash) {
if (enclose === true && typeof ele === "string") ele = `{${ele}}`;
result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : item + ele);
}
}
}
return utils$c.flatten(result);
};
var expand$2 = (ast, options2 = {}) => {
const rangeLimit = options2.rangeLimit === void 0 ? 1e3 : options2.rangeLimit;
const walk2 = (node2, parent = {}) => {
node2.queue = [];
let p = parent;
let q = parent.queue;
while (p.type !== "brace" && p.type !== "root" && p.parent) {
p = p.parent;
q = p.queue;
}
if (node2.invalid || node2.dollar) {
q.push(append$1(q.pop(), stringify$5(node2, options2)));
return;
}
if (node2.type === "brace" && node2.invalid !== true && node2.nodes.length === 2) {
q.push(append$1(q.pop(), ["{}"]));
return;
}
if (node2.nodes && node2.ranges > 0) {
const args = utils$c.reduce(node2.nodes);
if (utils$c.exceedsLimit(...args, options2.step, rangeLimit)) {
throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
}
let range2 = fill(...args, options2);
if (range2.length === 0) {
range2 = stringify$5(node2, options2);
}
q.push(append$1(q.pop(), range2));
node2.nodes = [];
return;
}
const enclose = utils$c.encloseBrace(node2);
let queue2 = node2.queue;
let block = node2;
while (block.type !== "brace" && block.type !== "root" && block.parent) {
block = block.parent;
queue2 = block.queue;
}
for (let i = 0; i < node2.nodes.length; i++) {
const child = node2.nodes[i];
if (child.type === "comma" && node2.type === "brace") {
if (i === 1) queue2.push("");
queue2.push("");
continue;
}
if (child.type === "close") {
q.push(append$1(q.pop(), queue2, enclose));
continue;
}
if (child.value && child.type !== "open") {
queue2.push(append$1(queue2.pop(), child.value));
continue;
}
if (child.nodes) {
walk2(child, node2);
}
}
return queue2;
};
return utils$c.flatten(walk2(ast));
};
var expand_1$1 = expand$2;
var constants$3 = {
MAX_LENGTH: 1e4,
// Digits
CHAR_0: "0",
/* 0 */
CHAR_9: "9",
/* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: "A",
/* A */
CHAR_LOWERCASE_A: "a",
/* a */
CHAR_UPPERCASE_Z: "Z",
/* Z */
CHAR_LOWERCASE_Z: "z",
/* z */
CHAR_LEFT_PARENTHESES: "(",
/* ( */
CHAR_RIGHT_PARENTHESES: ")",
/* ) */
CHAR_ASTERISK: "*",
/* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: "&",
/* & */
CHAR_AT: "@",
/* @ */
CHAR_BACKSLASH: "\\",
/* \ */
CHAR_BACKTICK: "`",
/* ` */
CHAR_CARRIAGE_RETURN: "\r",
/* \r */
CHAR_CIRCUMFLEX_ACCENT: "^",
/* ^ */
CHAR_COLON: ":",
/* : */
CHAR_COMMA: ",",
/* , */
CHAR_DOLLAR: "$",
/* . */
CHAR_DOT: ".",
/* . */
CHAR_DOUBLE_QUOTE: '"',
/* " */
CHAR_EQUAL: "=",
/* = */
CHAR_EXCLAMATION_MARK: "!",
/* ! */
CHAR_FORM_FEED: "\f",
/* \f */
CHAR_FORWARD_SLASH: "/",
/* / */
CHAR_HASH: "#",
/* # */
CHAR_HYPHEN_MINUS: "-",
/* - */
CHAR_LEFT_ANGLE_BRACKET: "<",
/* < */
CHAR_LEFT_CURLY_BRACE: "{",
/* { */
CHAR_LEFT_SQUARE_BRACKET: "[",
/* [ */
CHAR_LINE_FEED: "\n",
/* \n */
CHAR_NO_BREAK_SPACE: " ",
/* \u00A0 */
CHAR_PERCENT: "%",
/* % */
CHAR_PLUS: "+",
/* + */
CHAR_QUESTION_MARK: "?",
/* ? */
CHAR_RIGHT_ANGLE_BRACKET: ">",
/* > */
CHAR_RIGHT_CURLY_BRACE: "}",
/* } */
CHAR_RIGHT_SQUARE_BRACKET: "]",
/* ] */
CHAR_SEMICOLON: ";",
/* ; */
CHAR_SINGLE_QUOTE: "'",
/* ' */
CHAR_SPACE: " ",
/* */
CHAR_TAB: " ",
/* \t */
CHAR_UNDERSCORE: "_",
/* _ */
CHAR_VERTICAL_LINE: "|",
/* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF"
/* \uFEFF */
};
var stringify$4 = stringify$7;
var {
MAX_LENGTH,
CHAR_BACKSLASH,
/* \ */
CHAR_BACKTICK,
/* ` */
CHAR_COMMA,
/* , */
CHAR_DOT,
/* . */
CHAR_LEFT_PARENTHESES,
/* ( */
CHAR_RIGHT_PARENTHESES,
/* ) */
CHAR_LEFT_CURLY_BRACE,
/* { */
CHAR_RIGHT_CURLY_BRACE,
/* } */
CHAR_LEFT_SQUARE_BRACKET,
/* [ */
CHAR_RIGHT_SQUARE_BRACKET,
/* ] */
CHAR_DOUBLE_QUOTE,
/* " */
CHAR_SINGLE_QUOTE,
/* ' */
CHAR_NO_BREAK_SPACE,
CHAR_ZERO_WIDTH_NOBREAK_SPACE
} = constants$3;
var parse$c = (input, options2 = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
const opts = options2 || {};
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
if (input.length > max) {
throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
}
const ast = { type: "root", input, nodes: [] };
const stack = [ast];
let block = ast;
let prev = ast;
let brackets = 0;
const length = input.length;
let index = 0;
let depth2 = 0;
let value2;
const advance = () => input[index++];
const push2 = (node2) => {
if (node2.type === "text" && prev.type === "dot") {
prev.type = "text";
}
if (prev && prev.type === "text" && node2.type === "text") {
prev.value += node2.value;
return;
}
block.nodes.push(node2);
node2.parent = block;
node2.prev = prev;
prev = node2;
return node2;
};
push2({ type: "bos" });
while (index < length) {
block = stack[stack.length - 1];
value2 = advance();
if (value2 === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value2 === CHAR_NO_BREAK_SPACE) {
continue;
}
if (value2 === CHAR_BACKSLASH) {
push2({ type: "text", value: (options2.keepEscaping ? value2 : "") + advance() });
continue;
}
if (value2 === CHAR_RIGHT_SQUARE_BRACKET) {
push2({ type: "text", value: "\\" + value2 });
continue;
}
if (value2 === CHAR_LEFT_SQUARE_BRACKET) {
brackets++;
let next;
while (index < length && (next = advance())) {
value2 += next;
if (next === CHAR_LEFT_SQUARE_BRACKET) {
brackets++;
continue;
}
if (next === CHAR_BACKSLASH) {
value2 += advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
brackets--;
if (brackets === 0) {
break;
}
}
}
push2({ type: "text", value: value2 });
continue;
}
if (value2 === CHAR_LEFT_PARENTHESES) {
block = push2({ type: "paren", nodes: [] });
stack.push(block);
push2({ type: "text", value: value2 });
continue;
}
if (value2 === CHAR_RIGHT_PARENTHESES) {
if (block.type !== "paren") {
push2({ type: "text", value: value2 });
continue;
}
block = stack.pop();
push2({ type: "text", value: value2 });
block = stack[stack.length - 1];
continue;
}
if (value2 === CHAR_DOUBLE_QUOTE || value2 === CHAR_SINGLE_QUOTE || value2 === CHAR_BACKTICK) {
const open2 = value2;
let next;
if (options2.keepQuotes !== true) {
value2 = "";
}
while (index < length && (next = advance())) {
if (next === CHAR_BACKSLASH) {
value2 += next + advance();
continue;
}
if (next === open2) {
if (options2.keepQuotes === true) value2 += next;
break;
}
value2 += next;
}
push2({ type: "text", value: value2 });
continue;
}
if (value2 === CHAR_LEFT_CURLY_BRACE) {
depth2++;
const dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true;
const brace = {
type: "brace",
open: true,
close: false,
dollar,
depth: depth2,
commas: 0,
ranges: 0,
nodes: []
};
block = push2(brace);
stack.push(block);
push2({ type: "open", value: value2 });
continue;
}
if (value2 === CHAR_RIGHT_CURLY_BRACE) {
if (block.type !== "brace") {
push2({ type: "text", value: value2 });
continue;
}
const type = "close";
block = stack.pop();
block.close = true;
push2({ type, value: value2 });
depth2--;
block = stack[stack.length - 1];
continue;
}
if (value2 === CHAR_COMMA && depth2 > 0) {
if (block.ranges > 0) {
block.ranges = 0;
const open2 = block.nodes.shift();
block.nodes = [open2, { type: "text", value: stringify$4(block) }];
}
push2({ type: "comma", value: value2 });
block.commas++;
continue;
}
if (value2 === CHAR_DOT && depth2 > 0 && block.commas === 0) {
const siblings = block.nodes;
if (depth2 === 0 || siblings.length === 0) {
push2({ type: "text", value: value2 });
continue;
}
if (prev.type === "dot") {
block.range = [];
prev.value += value2;
prev.type = "range";
if (block.nodes.length !== 3 && block.nodes.length !== 5) {
block.invalid = true;
block.ranges = 0;
prev.type = "text";
continue;
}
block.ranges++;
block.args = [];
continue;
}
if (prev.type === "range") {
siblings.pop();
const before = siblings[siblings.length - 1];
before.value += prev.value + value2;
prev = before;
block.ranges--;
continue;
}
push2({ type: "dot", value: value2 });
continue;
}
push2({ type: "text", value: value2 });
}
do {
block = stack.pop();
if (block.type !== "root") {
block.nodes.forEach((node2) => {
if (!node2.nodes) {
if (node2.type === "open") node2.isOpen = true;
if (node2.type === "close") node2.isClose = true;
if (!node2.nodes) node2.type = "text";
node2.invalid = true;
}
});
const parent = stack[stack.length - 1];
const index2 = parent.nodes.indexOf(block);
parent.nodes.splice(index2, 1, ...block.nodes);
}
} while (stack.length > 0);
push2({ type: "eos" });
return ast;
};
var parse_1$2 = parse$c;
var stringify$3 = stringify$7;
var compile = compile_1;
var expand$1 = expand_1$1;
var parse$b = parse_1$2;
var braces$2 = (input, options2 = {}) => {
let output = [];
if (Array.isArray(input)) {
for (const pattern2 of input) {
const result = braces$2.create(pattern2, options2);
if (Array.isArray(result)) {
output.push(...result);
} else {
output.push(result);
}
}
} else {
output = [].concat(braces$2.create(input, options2));
}
if (options2 && options2.expand === true && options2.nodupes === true) {
output = [...new Set(output)];
}
return output;
};
braces$2.parse = (input, options2 = {}) => parse$b(input, options2);
braces$2.stringify = (input, options2 = {}) => {
if (typeof input === "string") {
return stringify$3(braces$2.parse(input, options2), options2);
}
return stringify$3(input, options2);
};
braces$2.compile = (input, options2 = {}) => {
if (typeof input === "string") {
input = braces$2.parse(input, options2);
}
return compile(input, options2);
};
braces$2.expand = (input, options2 = {}) => {
if (typeof input === "string") {
input = braces$2.parse(input, options2);
}
let result = expand$1(input, options2);
if (options2.noempty === true) {
result = result.filter(Boolean);
}
if (options2.nodupes === true) {
result = [...new Set(result)];
}
return result;
};
braces$2.create = (input, options2 = {}) => {
if (input === "" || input.length < 3) {
return [input];
}
return options2.expand !== true ? braces$2.compile(input, options2) : braces$2.expand(input, options2);
};
var braces_1 = braces$2;
var util = import_util.default;
var braces$1 = braces_1;
var picomatch$2 = picomatch$3;
var utils$b = utils$k;
var isEmptyString = (val) => val === "" || val === "./";
var micromatch$1 = (list, patterns, options2) => {
patterns = [].concat(patterns);
list = [].concat(list);
let omit = /* @__PURE__ */ new Set();
let keep = /* @__PURE__ */ new Set();
let items = /* @__PURE__ */ new Set();
let negatives = 0;
let onResult = (state) => {
items.add(state.output);
if (options2 && options2.onResult) {
options2.onResult(state);
}
};
for (let i = 0; i < patterns.length; i++) {
let isMatch2 = picomatch$2(String(patterns[i]), { ...options2, onResult }, true);
let negated = isMatch2.state.negated || isMatch2.state.negatedExtglob;
if (negated) negatives++;
for (let item of list) {
let matched = isMatch2(item, true);
let match2 = negated ? !matched.isMatch : matched.isMatch;
if (!match2) continue;
if (negated) {
omit.add(matched.output);
} else {
omit.delete(matched.output);
keep.add(matched.output);
}
}
}
let result = negatives === patterns.length ? [...items] : [...keep];
let matches2 = result.filter((item) => !omit.has(item));
if (options2 && matches2.length === 0) {
if (options2.failglob === true) {
throw new Error(`No matches found for "${patterns.join(", ")}"`);
}
if (options2.nonull === true || options2.nullglob === true) {
return options2.unescape ? patterns.map((p) => p.replace(/\\/g, "")) : patterns;
}
}
return matches2;
};
micromatch$1.match = micromatch$1;
micromatch$1.matcher = (pattern2, options2) => picomatch$2(pattern2, options2);
micromatch$1.isMatch = (str, patterns, options2) => picomatch$2(patterns, options2)(str);
micromatch$1.any = micromatch$1.isMatch;
micromatch$1.not = (list, patterns, options2 = {}) => {
patterns = [].concat(patterns).map(String);
let result = /* @__PURE__ */ new Set();
let items = [];
let onResult = (state) => {
if (options2.onResult) options2.onResult(state);
items.push(state.output);
};
let matches2 = new Set(micromatch$1(list, patterns, { ...options2, onResult }));
for (let item of items) {
if (!matches2.has(item)) {
result.add(item);
}
}
return [...result];
};
micromatch$1.contains = (str, pattern2, options2) => {
if (typeof str !== "string") {
throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
}
if (Array.isArray(pattern2)) {
return pattern2.some((p) => micromatch$1.contains(str, p, options2));
}
if (typeof pattern2 === "string") {
if (isEmptyString(str) || isEmptyString(pattern2)) {
return false;
}
if (str.includes(pattern2) || str.startsWith("./") && str.slice(2).includes(pattern2)) {
return true;
}
}
return micromatch$1.isMatch(str, pattern2, { ...options2, contains: true });
};
micromatch$1.matchKeys = (obj, patterns, options2) => {
if (!utils$b.isObject(obj)) {
throw new TypeError("Expected the first argument to be an object");
}
let keys = micromatch$1(Object.keys(obj), patterns, options2);
let res = {};
for (let key of keys) res[key] = obj[key];
return res;
};
micromatch$1.some = (list, patterns, options2) => {
let items = [].concat(list);
for (let pattern2 of [].concat(patterns)) {
let isMatch2 = picomatch$2(String(pattern2), options2);
if (items.some((item) => isMatch2(item))) {
return true;
}
}
return false;
};
micromatch$1.every = (list, patterns, options2) => {
let items = [].concat(list);
for (let pattern2 of [].concat(patterns)) {
let isMatch2 = picomatch$2(String(pattern2), options2);
if (!items.every((item) => isMatch2(item))) {
return false;
}
}
return true;
};
micromatch$1.all = (str, patterns, options2) => {
if (typeof str !== "string") {
throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
}
return [].concat(patterns).every((p) => picomatch$2(p, options2)(str));
};
micromatch$1.capture = (glob2, input, options2) => {
let posix2 = utils$b.isWindows(options2);
let regex2 = picomatch$2.makeRe(String(glob2), { ...options2, capture: true });
let match2 = regex2.exec(posix2 ? utils$b.toPosixSlashes(input) : input);
if (match2) {
return match2.slice(1).map((v) => v === void 0 ? "" : v);
}
};
micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args);
micromatch$1.scan = (...args) => picomatch$2.scan(...args);
micromatch$1.parse = (patterns, options2) => {
let res = [];
for (let pattern2 of [].concat(patterns || [])) {
for (let str of braces$1(String(pattern2), options2)) {
res.push(picomatch$2.parse(str, options2));
}
}
return res;
};
micromatch$1.braces = (pattern2, options2) => {
if (typeof pattern2 !== "string") throw new TypeError("Expected a string");
if (options2 && options2.nobrace === true || !/\{.*\}/.test(pattern2)) {
return [pattern2];
}
return braces$1(pattern2, options2);
};
micromatch$1.braceExpand = (pattern2, options2) => {
if (typeof pattern2 !== "string") throw new TypeError("Expected a string");
return micromatch$1.braces(pattern2, { ...options2, expand: true });
};
var micromatch_1 = micromatch$1;
var micromatch$2 = getDefaultExportFromCjs(micromatch_1);
Object.defineProperty(pattern$1, "__esModule", { value: true });
pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
var path$g = import_path.default;
var globParent$1 = globParent$2;
var micromatch = micromatch_1;
var GLOBSTAR$1 = "**";
var ESCAPE_SYMBOL = "\\";
var COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
var REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
var REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
var GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
var BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
var DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g;
function isStaticPattern(pattern2, options2 = {}) {
return !isDynamicPattern(pattern2, options2);
}
pattern$1.isStaticPattern = isStaticPattern;
function isDynamicPattern(pattern2, options2 = {}) {
if (pattern2 === "") {
return false;
}
if (options2.caseSensitiveMatch === false || pattern2.includes(ESCAPE_SYMBOL)) {
return true;
}
if (COMMON_GLOB_SYMBOLS_RE.test(pattern2) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern2) || REGEX_GROUP_SYMBOLS_RE.test(pattern2)) {
return true;
}
if (options2.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern2)) {
return true;
}
if (options2.braceExpansion !== false && hasBraceExpansion(pattern2)) {
return true;
}
return false;
}
pattern$1.isDynamicPattern = isDynamicPattern;
function hasBraceExpansion(pattern2) {
const openingBraceIndex = pattern2.indexOf("{");
if (openingBraceIndex === -1) {
return false;
}
const closingBraceIndex = pattern2.indexOf("}", openingBraceIndex + 1);
if (closingBraceIndex === -1) {
return false;
}
const braceContent = pattern2.slice(openingBraceIndex, closingBraceIndex);
return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
}
function convertToPositivePattern(pattern2) {
return isNegativePattern(pattern2) ? pattern2.slice(1) : pattern2;
}
pattern$1.convertToPositivePattern = convertToPositivePattern;
function convertToNegativePattern(pattern2) {
return "!" + pattern2;
}
pattern$1.convertToNegativePattern = convertToNegativePattern;
function isNegativePattern(pattern2) {
return pattern2.startsWith("!") && pattern2[1] !== "(";
}
pattern$1.isNegativePattern = isNegativePattern;
function isPositivePattern(pattern2) {
return !isNegativePattern(pattern2);
}
pattern$1.isPositivePattern = isPositivePattern;
function getNegativePatterns(patterns) {
return patterns.filter(isNegativePattern);
}
pattern$1.getNegativePatterns = getNegativePatterns;
function getPositivePatterns$1(patterns) {
return patterns.filter(isPositivePattern);
}
pattern$1.getPositivePatterns = getPositivePatterns$1;
function getPatternsInsideCurrentDirectory(patterns) {
return patterns.filter((pattern2) => !isPatternRelatedToParentDirectory(pattern2));
}
pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
function getPatternsOutsideCurrentDirectory(patterns) {
return patterns.filter(isPatternRelatedToParentDirectory);
}
pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
function isPatternRelatedToParentDirectory(pattern2) {
return pattern2.startsWith("..") || pattern2.startsWith("./..");
}
pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
function getBaseDirectory(pattern2) {
return globParent$1(pattern2, { flipBackslashes: false });
}
pattern$1.getBaseDirectory = getBaseDirectory;
function hasGlobStar(pattern2) {
return pattern2.includes(GLOBSTAR$1);
}
pattern$1.hasGlobStar = hasGlobStar;
function endsWithSlashGlobStar(pattern2) {
return pattern2.endsWith("/" + GLOBSTAR$1);
}
pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
function isAffectDepthOfReadingPattern(pattern2) {
const basename2 = path$g.basename(pattern2);
return endsWithSlashGlobStar(pattern2) || isStaticPattern(basename2);
}
pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
function expandPatternsWithBraceExpansion(patterns) {
return patterns.reduce((collection, pattern2) => {
return collection.concat(expandBraceExpansion(pattern2));
}, []);
}
pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
function expandBraceExpansion(pattern2) {
const patterns = micromatch.braces(pattern2, { expand: true, nodupes: true, keepEscaping: true });
patterns.sort((a, b) => a.length - b.length);
return patterns.filter((pattern3) => pattern3 !== "");
}
pattern$1.expandBraceExpansion = expandBraceExpansion;
function getPatternParts(pattern2, options2) {
let { parts } = micromatch.scan(pattern2, Object.assign(Object.assign({}, options2), { parts: true }));
if (parts.length === 0) {
parts = [pattern2];
}
if (parts[0].startsWith("/")) {
parts[0] = parts[0].slice(1);
parts.unshift("");
}
return parts;
}
pattern$1.getPatternParts = getPatternParts;
function makeRe(pattern2, options2) {
return micromatch.makeRe(pattern2, options2);
}
pattern$1.makeRe = makeRe;
function convertPatternsToRe(patterns, options2) {
return patterns.map((pattern2) => makeRe(pattern2, options2));
}
pattern$1.convertPatternsToRe = convertPatternsToRe;
function matchAny(entry2, patternsRe) {
return patternsRe.some((patternRe) => patternRe.test(entry2));
}
pattern$1.matchAny = matchAny;
function removeDuplicateSlashes(pattern2) {
return pattern2.replace(DOUBLE_SLASH_RE$1, "/");
}
pattern$1.removeDuplicateSlashes = removeDuplicateSlashes;
var stream$4 = {};
var Stream = import_stream.default;
var PassThrough = Stream.PassThrough;
var slice = Array.prototype.slice;
var merge2_1 = merge2$1;
function merge2$1() {
const streamsQueue = [];
const args = slice.call(arguments);
let merging = false;
let options2 = args[args.length - 1];
if (options2 && !Array.isArray(options2) && options2.pipe == null) {
args.pop();
} else {
options2 = {};
}
const doEnd = options2.end !== false;
const doPipeError = options2.pipeError === true;
if (options2.objectMode == null) {
options2.objectMode = true;
}
if (options2.highWaterMark == null) {
options2.highWaterMark = 64 * 1024;
}
const mergedStream = PassThrough(options2);
function addStream() {
for (let i = 0, len = arguments.length; i < len; i++) {
streamsQueue.push(pauseStreams(arguments[i], options2));
}
mergeStream();
return this;
}
function mergeStream() {
if (merging) {
return;
}
merging = true;
let streams = streamsQueue.shift();
if (!streams) {
process.nextTick(endStream);
return;
}
if (!Array.isArray(streams)) {
streams = [streams];
}
let pipesCount = streams.length + 1;
function next() {
if (--pipesCount > 0) {
return;
}
merging = false;
mergeStream();
}
function pipe(stream4) {
function onend() {
stream4.removeListener("merge2UnpipeEnd", onend);
stream4.removeListener("end", onend);
if (doPipeError) {
stream4.removeListener("error", onerror);
}
next();
}
function onerror(err2) {
mergedStream.emit("error", err2);
}
if (stream4._readableState.endEmitted) {
return next();
}
stream4.on("merge2UnpipeEnd", onend);
stream4.on("end", onend);
if (doPipeError) {
stream4.on("error", onerror);
}
stream4.pipe(mergedStream, { end: false });
stream4.resume();
}
for (let i = 0; i < streams.length; i++) {
pipe(streams[i]);
}
next();
}
function endStream() {
merging = false;
mergedStream.emit("queueDrain");
if (doEnd) {
mergedStream.end();
}
}
mergedStream.setMaxListeners(0);
mergedStream.add = addStream;
mergedStream.on("unpipe", function(stream4) {
stream4.emit("merge2UnpipeEnd");
});
if (args.length) {
addStream.apply(null, args);
}
return mergedStream;
}
function pauseStreams(streams, options2) {
if (!Array.isArray(streams)) {
if (!streams._readableState && streams.pipe) {
streams = streams.pipe(PassThrough(options2));
}
if (!streams._readableState || !streams.pause || !streams.pipe) {
throw new Error("Only readable stream can be merged.");
}
streams.pause();
} else {
for (let i = 0, len = streams.length; i < len; i++) {
streams[i] = pauseStreams(streams[i], options2);
}
}
return streams;
}
Object.defineProperty(stream$4, "__esModule", { value: true });
stream$4.merge = void 0;
var merge2 = merge2_1;
function merge$1(streams) {
const mergedStream = merge2(streams);
streams.forEach((stream4) => {
stream4.once("error", (error2) => mergedStream.emit("error", error2));
});
mergedStream.once("close", () => propagateCloseEventToSources(streams));
mergedStream.once("end", () => propagateCloseEventToSources(streams));
return mergedStream;
}
stream$4.merge = merge$1;
function propagateCloseEventToSources(streams) {
streams.forEach((stream4) => stream4.emit("close"));
}
var string$2 = {};
Object.defineProperty(string$2, "__esModule", { value: true });
string$2.isEmpty = string$2.isString = void 0;
function isString$1(input) {
return typeof input === "string";
}
string$2.isString = isString$1;
function isEmpty$1(input) {
return input === "";
}
string$2.isEmpty = isEmpty$1;
Object.defineProperty(utils$g, "__esModule", { value: true });
utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0;
var array = array$1;
utils$g.array = array;
var errno = errno$1;
utils$g.errno = errno;
var fs$h = fs$i;
utils$g.fs = fs$h;
var path$f = path$i;
utils$g.path = path$f;
var pattern = pattern$1;
utils$g.pattern = pattern;
var stream$3 = stream$4;
utils$g.stream = stream$3;
var string$1 = string$2;
utils$g.string = string$1;
Object.defineProperty(tasks, "__esModule", { value: true });
tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
var utils$a = utils$g;
function generate(input, settings2) {
const patterns = processPatterns(input, settings2);
const ignore = processPatterns(settings2.ignore, settings2);
const positivePatterns = getPositivePatterns(patterns);
const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
const staticPatterns = positivePatterns.filter((pattern2) => utils$a.pattern.isStaticPattern(pattern2, settings2));
const dynamicPatterns = positivePatterns.filter((pattern2) => utils$a.pattern.isDynamicPattern(pattern2, settings2));
const staticTasks = convertPatternsToTasks(
staticPatterns,
negativePatterns,
/* dynamic */
false
);
const dynamicTasks = convertPatternsToTasks(
dynamicPatterns,
negativePatterns,
/* dynamic */
true
);
return staticTasks.concat(dynamicTasks);
}
tasks.generate = generate;
function processPatterns(input, settings2) {
let patterns = input;
if (settings2.braceExpansion) {
patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns);
}
if (settings2.baseNameMatch) {
patterns = patterns.map((pattern2) => pattern2.includes("/") ? pattern2 : `**/${pattern2}`);
}
return patterns.map((pattern2) => utils$a.pattern.removeDuplicateSlashes(pattern2));
}
function convertPatternsToTasks(positive, negative, dynamic) {
const tasks2 = [];
const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
tasks2.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
if ("." in insideCurrentDirectoryGroup) {
tasks2.push(convertPatternGroupToTask(".", patternsInsideCurrentDirectory, negative, dynamic));
} else {
tasks2.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
}
return tasks2;
}
tasks.convertPatternsToTasks = convertPatternsToTasks;
function getPositivePatterns(patterns) {
return utils$a.pattern.getPositivePatterns(patterns);
}
tasks.getPositivePatterns = getPositivePatterns;
function getNegativePatternsAsPositive(patterns, ignore) {
const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
const positive = negative.map(utils$a.pattern.convertToPositivePattern);
return positive;
}
tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
function groupPatternsByBaseDirectory(patterns) {
const group = {};
return patterns.reduce((collection, pattern2) => {
const base = utils$a.pattern.getBaseDirectory(pattern2);
if (base in collection) {
collection[base].push(pattern2);
} else {
collection[base] = [pattern2];
}
return collection;
}, group);
}
tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
function convertPatternGroupsToTasks(positive, negative, dynamic) {
return Object.keys(positive).map((base) => {
return convertPatternGroupToTask(base, positive[base], negative, dynamic);
});
}
tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
function convertPatternGroupToTask(base, positive, negative, dynamic) {
return {
dynamic,
positive,
negative,
base,
patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
};
}
tasks.convertPatternGroupToTask = convertPatternGroupToTask;
var async$7 = {};
var async$6 = {};
var out$3 = {};
var async$5 = {};
var async$4 = {};
var out$2 = {};
var async$3 = {};
var out$1 = {};
var async$2 = {};
Object.defineProperty(async$2, "__esModule", { value: true });
async$2.read = void 0;
function read$3(path3, settings2, callback) {
settings2.fs.lstat(path3, (lstatError, lstat2) => {
if (lstatError !== null) {
callFailureCallback$2(callback, lstatError);
return;
}
if (!lstat2.isSymbolicLink() || !settings2.followSymbolicLink) {
callSuccessCallback$2(callback, lstat2);
return;
}
settings2.fs.stat(path3, (statError, stat2) => {
if (statError !== null) {
if (settings2.throwErrorOnBrokenSymbolicLink) {
callFailureCallback$2(callback, statError);
return;
}
callSuccessCallback$2(callback, lstat2);
return;
}
if (settings2.markSymbolicLink) {
stat2.isSymbolicLink = () => true;
}
callSuccessCallback$2(callback, stat2);
});
});
}
async$2.read = read$3;
function callFailureCallback$2(callback, error2) {
callback(error2);
}
function callSuccessCallback$2(callback, result) {
callback(null, result);
}
var sync$8 = {};
Object.defineProperty(sync$8, "__esModule", { value: true });
sync$8.read = void 0;
function read$2(path3, settings2) {
const lstat2 = settings2.fs.lstatSync(path3);
if (!lstat2.isSymbolicLink() || !settings2.followSymbolicLink) {
return lstat2;
}
try {
const stat2 = settings2.fs.statSync(path3);
if (settings2.markSymbolicLink) {
stat2.isSymbolicLink = () => true;
}
return stat2;
} catch (error2) {
if (!settings2.throwErrorOnBrokenSymbolicLink) {
return lstat2;
}
throw error2;
}
}
sync$8.read = read$2;
var settings$3 = {};
var fs$g = {};
(function(exports2) {
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0;
const fs2 = import_fs.default;
exports2.FILE_SYSTEM_ADAPTER = {
lstat: fs2.lstat,
stat: fs2.stat,
lstatSync: fs2.lstatSync,
statSync: fs2.statSync
};
function createFileSystemAdapter(fsMethods) {
if (fsMethods === void 0) {
return exports2.FILE_SYSTEM_ADAPTER;
}
return Object.assign(Object.assign({}, exports2.FILE_SYSTEM_ADAPTER), fsMethods);
}
exports2.createFileSystemAdapter = createFileSystemAdapter;
})(fs$g);
Object.defineProperty(settings$3, "__esModule", { value: true });
var fs$f = fs$g;
var Settings$2 = class Settings {
constructor(_options2 = {}) {
this._options = _options2;
this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
this.fs = fs$f.createFileSystemAdapter(this._options.fs);
this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
}
_getValue(option, value2) {
return option !== null && option !== void 0 ? option : value2;
}
};
settings$3.default = Settings$2;
Object.defineProperty(out$1, "__esModule", { value: true });
out$1.statSync = out$1.stat = out$1.Settings = void 0;
var async$1 = async$2;
var sync$7 = sync$8;
var settings_1$3 = settings$3;
out$1.Settings = settings_1$3.default;
function stat$4(path3, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === "function") {
async$1.read(path3, getSettings$2(), optionsOrSettingsOrCallback);
return;
}
async$1.read(path3, getSettings$2(optionsOrSettingsOrCallback), callback);
}
out$1.stat = stat$4;
function statSync2(path3, optionsOrSettings) {
const settings2 = getSettings$2(optionsOrSettings);
return sync$7.read(path3, settings2);
}
out$1.statSync = statSync2;
function getSettings$2(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1$3.default) {
return settingsOrOptions;
}
return new settings_1$3.default(settingsOrOptions);
}
var promise;
var queueMicrotask_1 = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : commonjsGlobal) : (cb) => (promise || (promise = Promise.resolve())).then(cb).catch((err2) => setTimeout(() => {
throw err2;
}, 0));
var runParallel_1 = runParallel;
var queueMicrotask$1 = queueMicrotask_1;
function runParallel(tasks2, cb) {
let results, pending, keys;
let isSync = true;
if (Array.isArray(tasks2)) {
results = [];
pending = tasks2.length;
} else {
keys = Object.keys(tasks2);
results = {};
pending = keys.length;
}
function done(err2) {
function end() {
if (cb) cb(err2, results);
cb = null;
}
if (isSync) queueMicrotask$1(end);
else end();
}
function each(i, err2, result) {
results[i] = result;
if (--pending === 0 || err2) {
done(err2);
}
}
if (!pending) {
done(null);
} else if (keys) {
keys.forEach(function(key) {
tasks2[key](function(err2, result) {
each(key, err2, result);
});
});
} else {
tasks2.forEach(function(task, i) {
task(function(err2, result) {
each(i, err2, result);
});
});
}
isSync = false;
}
var constants$2 = {};
Object.defineProperty(constants$2, "__esModule", { value: true });
constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
var NODE_PROCESS_VERSION_PARTS = process.versions.node.split(".");
if (NODE_PROCESS_VERSION_PARTS[0] === void 0 || NODE_PROCESS_VERSION_PARTS[1] === void 0) {
throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
}
var MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
var MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
var SUPPORTED_MAJOR_VERSION = 10;
var SUPPORTED_MINOR_VERSION = 10;
var IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
var IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
var utils$9 = {};
var fs$e = {};
Object.defineProperty(fs$e, "__esModule", { value: true });
fs$e.createDirentFromStats = void 0;
var DirentFromStats2 = class {
constructor(name2, stats) {
this.name = name2;
this.isBlockDevice = stats.isBlockDevice.bind(stats);
this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
this.isDirectory = stats.isDirectory.bind(stats);
this.isFIFO = stats.isFIFO.bind(stats);
this.isFile = stats.isFile.bind(stats);
this.isSocket = stats.isSocket.bind(stats);
this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
}
};
function createDirentFromStats(name2, stats) {
return new DirentFromStats2(name2, stats);
}
fs$e.createDirentFromStats = createDirentFromStats;
Object.defineProperty(utils$9, "__esModule", { value: true });
utils$9.fs = void 0;
var fs$d = fs$e;
utils$9.fs = fs$d;
var common$a = {};
Object.defineProperty(common$a, "__esModule", { value: true });
common$a.joinPathSegments = void 0;
function joinPathSegments$1(a, b, separator) {
if (a.endsWith(separator)) {
return a + b;
}
return a + separator + b;
}
common$a.joinPathSegments = joinPathSegments$1;
Object.defineProperty(async$3, "__esModule", { value: true });
async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0;
var fsStat$5 = out$1;
var rpl = runParallel_1;
var constants_1$1 = constants$2;
var utils$8 = utils$9;
var common$9 = common$a;
function read$1(directory, settings2, callback) {
if (!settings2.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
readdirWithFileTypes$1(directory, settings2, callback);
return;
}
readdir$3(directory, settings2, callback);
}
async$3.read = read$1;
function readdirWithFileTypes$1(directory, settings2, callback) {
settings2.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
if (readdirError !== null) {
callFailureCallback$1(callback, readdirError);
return;
}
const entries = dirents.map((dirent) => ({
dirent,
name: dirent.name,
path: common$9.joinPathSegments(directory, dirent.name, settings2.pathSegmentSeparator)
}));
if (!settings2.followSymbolicLinks) {
callSuccessCallback$1(callback, entries);
return;
}
const tasks2 = entries.map((entry2) => makeRplTaskEntry(entry2, settings2));
rpl(tasks2, (rplError, rplEntries) => {
if (rplError !== null) {
callFailureCallback$1(callback, rplError);
return;
}
callSuccessCallback$1(callback, rplEntries);
});
});
}
async$3.readdirWithFileTypes = readdirWithFileTypes$1;
function makeRplTaskEntry(entry2, settings2) {
return (done) => {
if (!entry2.dirent.isSymbolicLink()) {
done(null, entry2);
return;
}
settings2.fs.stat(entry2.path, (statError, stats) => {
if (statError !== null) {
if (settings2.throwErrorOnBrokenSymbolicLink) {
done(statError);
return;
}
done(null, entry2);
return;
}
entry2.dirent = utils$8.fs.createDirentFromStats(entry2.name, stats);
done(null, entry2);
});
};
}
function readdir$3(directory, settings2, callback) {
settings2.fs.readdir(directory, (readdirError, names) => {
if (readdirError !== null) {
callFailureCallback$1(callback, readdirError);
return;
}
const tasks2 = names.map((name2) => {
const path3 = common$9.joinPathSegments(directory, name2, settings2.pathSegmentSeparator);
return (done) => {
fsStat$5.stat(path3, settings2.fsStatSettings, (error2, stats) => {
if (error2 !== null) {
done(error2);
return;
}
const entry2 = {
name: name2,
path: path3,
dirent: utils$8.fs.createDirentFromStats(name2, stats)
};
if (settings2.stats) {
entry2.stats = stats;
}
done(null, entry2);
});
};
});
rpl(tasks2, (rplError, entries) => {
if (rplError !== null) {
callFailureCallback$1(callback, rplError);
return;
}
callSuccessCallback$1(callback, entries);
});
});
}
async$3.readdir = readdir$3;
function callFailureCallback$1(callback, error2) {
callback(error2);
}
function callSuccessCallback$1(callback, result) {
callback(null, result);
}
var sync$6 = {};
Object.defineProperty(sync$6, "__esModule", { value: true });
sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0;
var fsStat$4 = out$1;
var constants_1 = constants$2;
var utils$7 = utils$9;
var common$8 = common$a;
function read(directory, settings2) {
if (!settings2.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
return readdirWithFileTypes(directory, settings2);
}
return readdir$2(directory, settings2);
}
sync$6.read = read;
function readdirWithFileTypes(directory, settings2) {
const dirents = settings2.fs.readdirSync(directory, { withFileTypes: true });
return dirents.map((dirent) => {
const entry2 = {
dirent,
name: dirent.name,
path: common$8.joinPathSegments(directory, dirent.name, settings2.pathSegmentSeparator)
};
if (entry2.dirent.isSymbolicLink() && settings2.followSymbolicLinks) {
try {
const stats = settings2.fs.statSync(entry2.path);
entry2.dirent = utils$7.fs.createDirentFromStats(entry2.name, stats);
} catch (error2) {
if (settings2.throwErrorOnBrokenSymbolicLink) {
throw error2;
}
}
}
return entry2;
});
}
sync$6.readdirWithFileTypes = readdirWithFileTypes;
function readdir$2(directory, settings2) {
const names = settings2.fs.readdirSync(directory);
return names.map((name2) => {
const entryPath = common$8.joinPathSegments(directory, name2, settings2.pathSegmentSeparator);
const stats = fsStat$4.statSync(entryPath, settings2.fsStatSettings);
const entry2 = {
name: name2,
path: entryPath,
dirent: utils$7.fs.createDirentFromStats(name2, stats)
};
if (settings2.stats) {
entry2.stats = stats;
}
return entry2;
});
}
sync$6.readdir = readdir$2;
var settings$2 = {};
var fs$c = {};
(function(exports2) {
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0;
const fs2 = import_fs.default;
exports2.FILE_SYSTEM_ADAPTER = {
lstat: fs2.lstat,
stat: fs2.stat,
lstatSync: fs2.lstatSync,
statSync: fs2.statSync,
readdir: fs2.readdir,
readdirSync: fs2.readdirSync
};
function createFileSystemAdapter(fsMethods) {
if (fsMethods === void 0) {
return exports2.FILE_SYSTEM_ADAPTER;
}
return Object.assign(Object.assign({}, exports2.FILE_SYSTEM_ADAPTER), fsMethods);
}
exports2.createFileSystemAdapter = createFileSystemAdapter;
})(fs$c);
Object.defineProperty(settings$2, "__esModule", { value: true });
var path$e = import_path.default;
var fsStat$3 = out$1;
var fs$b = fs$c;
var Settings$1 = class Settings2 {
constructor(_options2 = {}) {
this._options = _options2;
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
this.fs = fs$b.createFileSystemAdapter(this._options.fs);
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$e.sep);
this.stats = this._getValue(this._options.stats, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
this.fsStatSettings = new fsStat$3.Settings({
followSymbolicLink: this.followSymbolicLinks,
fs: this.fs,
throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
});
}
_getValue(option, value2) {
return option !== null && option !== void 0 ? option : value2;
}
};
settings$2.default = Settings$1;
Object.defineProperty(out$2, "__esModule", { value: true });
out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
var async = async$3;
var sync$5 = sync$6;
var settings_1$2 = settings$2;
out$2.Settings = settings_1$2.default;
function scandir(path3, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === "function") {
async.read(path3, getSettings$1(), optionsOrSettingsOrCallback);
return;
}
async.read(path3, getSettings$1(optionsOrSettingsOrCallback), callback);
}
out$2.scandir = scandir;
function scandirSync(path3, optionsOrSettings) {
const settings2 = getSettings$1(optionsOrSettings);
return sync$5.read(path3, settings2);
}
out$2.scandirSync = scandirSync;
function getSettings$1(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1$2.default) {
return settingsOrOptions;
}
return new settings_1$2.default(settingsOrOptions);
}
var queue = { exports: {} };
function reusify$1(Constructor) {
var head = new Constructor();
var tail = head;
function get2() {
var current = head;
if (current.next) {
head = current.next;
} else {
head = new Constructor();
tail = head;
}
current.next = null;
return current;
}
function release(obj) {
tail.next = obj;
tail = obj;
}
return {
get: get2,
release
};
}
var reusify_1 = reusify$1;
var reusify = reusify_1;
function fastqueue(context, worker, _concurrency) {
if (typeof context === "function") {
_concurrency = worker;
worker = context;
context = null;
}
if (!(_concurrency >= 1)) {
throw new Error("fastqueue concurrency must be equal to or greater than 1");
}
var cache = reusify(Task);
var queueHead = null;
var queueTail = null;
var _running = 0;
var errorHandler = null;
var self2 = {
push: push2,
drain: noop$4,
saturated: noop$4,
pause,
paused: false,
get concurrency() {
return _concurrency;
},
set concurrency(value2) {
if (!(value2 >= 1)) {
throw new Error("fastqueue concurrency must be equal to or greater than 1");
}
_concurrency = value2;
if (self2.paused) return;
for (; queueHead && _running < _concurrency; ) {
_running++;
release();
}
},
running,
resume: resume2,
idle,
length,
getQueue,
unshift,
empty: noop$4,
kill,
killAndDrain,
error: error2
};
return self2;
function running() {
return _running;
}
function pause() {
self2.paused = true;
}
function length() {
var current = queueHead;
var counter = 0;
while (current) {
current = current.next;
counter++;
}
return counter;
}
function getQueue() {
var current = queueHead;
var tasks2 = [];
while (current) {
tasks2.push(current.value);
current = current.next;
}
return tasks2;
}
function resume2() {
if (!self2.paused) return;
self2.paused = false;
if (queueHead === null) {
_running++;
release();
return;
}
for (; queueHead && _running < _concurrency; ) {
_running++;
release();
}
}
function idle() {
return _running === 0 && self2.length() === 0;
}
function push2(value2, done) {
var current = cache.get();
current.context = context;
current.release = release;
current.value = value2;
current.callback = done || noop$4;
current.errorHandler = errorHandler;
if (_running >= _concurrency || self2.paused) {
if (queueTail) {
queueTail.next = current;
queueTail = current;
} else {
queueHead = current;
queueTail = current;
self2.saturated();
}
} else {
_running++;
worker.call(context, current.value, current.worked);
}
}
function unshift(value2, done) {
var current = cache.get();
current.context = context;
current.release = release;
current.value = value2;
current.callback = done || noop$4;
current.errorHandler = errorHandler;
if (_running >= _concurrency || self2.paused) {
if (queueHead) {
current.next = queueHead;
queueHead = current;
} else {
queueHead = current;
queueTail = current;
self2.saturated();
}
} else {
_running++;
worker.call(context, current.value, current.worked);
}
}
function release(holder) {
if (holder) {
cache.release(holder);
}
var next = queueHead;
if (next && _running <= _concurrency) {
if (!self2.paused) {
if (queueTail === queueHead) {
queueTail = null;
}
queueHead = next.next;
next.next = null;
worker.call(context, next.value, next.worked);
if (queueTail === null) {
self2.empty();
}
} else {
_running--;
}
} else if (--_running === 0) {
self2.drain();
}
}
function kill() {
queueHead = null;
queueTail = null;
self2.drain = noop$4;
}
function killAndDrain() {
queueHead = null;
queueTail = null;
self2.drain();
self2.drain = noop$4;
}
function error2(handler) {
errorHandler = handler;
}
}
function noop$4() {
}
function Task() {
this.value = null;
this.callback = noop$4;
this.next = null;
this.release = noop$4;
this.context = null;
this.errorHandler = null;
var self2 = this;
this.worked = function worked(err2, result) {
var callback = self2.callback;
var errorHandler = self2.errorHandler;
var val = self2.value;
self2.value = null;
self2.callback = noop$4;
if (self2.errorHandler) {
errorHandler(err2, val);
}
callback.call(self2.context, err2, result);
self2.release(self2);
};
}
function queueAsPromised(context, worker, _concurrency) {
if (typeof context === "function") {
_concurrency = worker;
worker = context;
context = null;
}
function asyncWrapper(arg, cb) {
worker.call(this, arg).then(function(res) {
cb(null, res);
}, cb);
}
var queue2 = fastqueue(context, asyncWrapper, _concurrency);
var pushCb = queue2.push;
var unshiftCb = queue2.unshift;
queue2.push = push2;
queue2.unshift = unshift;
queue2.drained = drained;
return queue2;
function push2(value2) {
var p = new Promise(function(resolve3, reject) {
pushCb(value2, function(err2, result) {
if (err2) {
reject(err2);
return;
}
resolve3(result);
});
});
p.catch(noop$4);
return p;
}
function unshift(value2) {
var p = new Promise(function(resolve3, reject) {
unshiftCb(value2, function(err2, result) {
if (err2) {
reject(err2);
return;
}
resolve3(result);
});
});
p.catch(noop$4);
return p;
}
function drained() {
if (queue2.idle()) {
return new Promise(function(resolve3) {
resolve3();
});
}
var previousDrain = queue2.drain;
var p = new Promise(function(resolve3) {
queue2.drain = function() {
previousDrain();
resolve3();
};
});
return p;
}
}
queue.exports = fastqueue;
queue.exports.promise = queueAsPromised;
var queueExports = queue.exports;
var common$7 = {};
Object.defineProperty(common$7, "__esModule", { value: true });
common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0;
function isFatalError(settings2, error2) {
if (settings2.errorFilter === null) {
return true;
}
return !settings2.errorFilter(error2);
}
common$7.isFatalError = isFatalError;
function isAppliedFilter(filter2, value2) {
return filter2 === null || filter2(value2);
}
common$7.isAppliedFilter = isAppliedFilter;
function replacePathSegmentSeparator(filepath, separator) {
return filepath.split(/[/\\]/).join(separator);
}
common$7.replacePathSegmentSeparator = replacePathSegmentSeparator;
function joinPathSegments(a, b, separator) {
if (a === "") {
return b;
}
if (a.endsWith(separator)) {
return a + b;
}
return a + separator + b;
}
common$7.joinPathSegments = joinPathSegments;
var reader$1 = {};
Object.defineProperty(reader$1, "__esModule", { value: true });
var common$6 = common$7;
var Reader$1 = class Reader {
constructor(_root2, _settings) {
this._root = _root2;
this._settings = _settings;
this._root = common$6.replacePathSegmentSeparator(_root2, _settings.pathSegmentSeparator);
}
};
reader$1.default = Reader$1;
Object.defineProperty(async$4, "__esModule", { value: true });
var events_1 = import_events.default;
var fsScandir$2 = out$2;
var fastq = queueExports;
var common$5 = common$7;
var reader_1$4 = reader$1;
var AsyncReader = class extends reader_1$4.default {
constructor(_root2, _settings) {
super(_root2, _settings);
this._settings = _settings;
this._scandir = fsScandir$2.scandir;
this._emitter = new events_1.EventEmitter();
this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
this._isFatalError = false;
this._isDestroyed = false;
this._queue.drain = () => {
if (!this._isFatalError) {
this._emitter.emit("end");
}
};
}
read() {
this._isFatalError = false;
this._isDestroyed = false;
setImmediate(() => {
this._pushToQueue(this._root, this._settings.basePath);
});
return this._emitter;
}
get isDestroyed() {
return this._isDestroyed;
}
destroy() {
if (this._isDestroyed) {
throw new Error("The reader is already destroyed");
}
this._isDestroyed = true;
this._queue.killAndDrain();
}
onEntry(callback) {
this._emitter.on("entry", callback);
}
onError(callback) {
this._emitter.once("error", callback);
}
onEnd(callback) {
this._emitter.once("end", callback);
}
_pushToQueue(directory, base) {
const queueItem = { directory, base };
this._queue.push(queueItem, (error2) => {
if (error2 !== null) {
this._handleError(error2);
}
});
}
_worker(item, done) {
this._scandir(item.directory, this._settings.fsScandirSettings, (error2, entries) => {
if (error2 !== null) {
done(error2, void 0);
return;
}
for (const entry2 of entries) {
this._handleEntry(entry2, item.base);
}
done(null, void 0);
});
}
_handleError(error2) {
if (this._isDestroyed || !common$5.isFatalError(this._settings, error2)) {
return;
}
this._isFatalError = true;
this._isDestroyed = true;
this._emitter.emit("error", error2);
}
_handleEntry(entry2, base) {
if (this._isDestroyed || this._isFatalError) {
return;
}
const fullpath = entry2.path;
if (base !== void 0) {
entry2.path = common$5.joinPathSegments(base, entry2.name, this._settings.pathSegmentSeparator);
}
if (common$5.isAppliedFilter(this._settings.entryFilter, entry2)) {
this._emitEntry(entry2);
}
if (entry2.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry2)) {
this._pushToQueue(fullpath, base === void 0 ? void 0 : entry2.path);
}
}
_emitEntry(entry2) {
this._emitter.emit("entry", entry2);
}
};
async$4.default = AsyncReader;
Object.defineProperty(async$5, "__esModule", { value: true });
var async_1$4 = async$4;
var AsyncProvider = class {
constructor(_root2, _settings) {
this._root = _root2;
this._settings = _settings;
this._reader = new async_1$4.default(this._root, this._settings);
this._storage = [];
}
read(callback) {
this._reader.onError((error2) => {
callFailureCallback(callback, error2);
});
this._reader.onEntry((entry2) => {
this._storage.push(entry2);
});
this._reader.onEnd(() => {
callSuccessCallback(callback, this._storage);
});
this._reader.read();
}
};
async$5.default = AsyncProvider;
function callFailureCallback(callback, error2) {
callback(error2);
}
function callSuccessCallback(callback, entries) {
callback(null, entries);
}
var stream$2 = {};
Object.defineProperty(stream$2, "__esModule", { value: true });
var stream_1$5 = import_stream.default;
var async_1$3 = async$4;
var StreamProvider = class {
constructor(_root2, _settings) {
this._root = _root2;
this._settings = _settings;
this._reader = new async_1$3.default(this._root, this._settings);
this._stream = new stream_1$5.Readable({
objectMode: true,
read: () => {
},
destroy: () => {
if (!this._reader.isDestroyed) {
this._reader.destroy();
}
}
});
}
read() {
this._reader.onError((error2) => {
this._stream.emit("error", error2);
});
this._reader.onEntry((entry2) => {
this._stream.push(entry2);
});
this._reader.onEnd(() => {
this._stream.push(null);
});
this._reader.read();
return this._stream;
}
};
stream$2.default = StreamProvider;
var sync$4 = {};
var sync$3 = {};
Object.defineProperty(sync$3, "__esModule", { value: true });
var fsScandir$1 = out$2;
var common$4 = common$7;
var reader_1$3 = reader$1;
var SyncReader = class extends reader_1$3.default {
constructor() {
super(...arguments);
this._scandir = fsScandir$1.scandirSync;
this._storage = [];
this._queue = /* @__PURE__ */ new Set();
}
read() {
this._pushToQueue(this._root, this._settings.basePath);
this._handleQueue();
return this._storage;
}
_pushToQueue(directory, base) {
this._queue.add({ directory, base });
}
_handleQueue() {
for (const item of this._queue.values()) {
this._handleDirectory(item.directory, item.base);
}
}
_handleDirectory(directory, base) {
try {
const entries = this._scandir(directory, this._settings.fsScandirSettings);
for (const entry2 of entries) {
this._handleEntry(entry2, base);
}
} catch (error2) {
this._handleError(error2);
}
}
_handleError(error2) {
if (!common$4.isFatalError(this._settings, error2)) {
return;
}
throw error2;
}
_handleEntry(entry2, base) {
const fullpath = entry2.path;
if (base !== void 0) {
entry2.path = common$4.joinPathSegments(base, entry2.name, this._settings.pathSegmentSeparator);
}
if (common$4.isAppliedFilter(this._settings.entryFilter, entry2)) {
this._pushToStorage(entry2);
}
if (entry2.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry2)) {
this._pushToQueue(fullpath, base === void 0 ? void 0 : entry2.path);
}
}
_pushToStorage(entry2) {
this._storage.push(entry2);
}
};
sync$3.default = SyncReader;
Object.defineProperty(sync$4, "__esModule", { value: true });
var sync_1$3 = sync$3;
var SyncProvider = class {
constructor(_root2, _settings) {
this._root = _root2;
this._settings = _settings;
this._reader = new sync_1$3.default(this._root, this._settings);
}
read() {
return this._reader.read();
}
};
sync$4.default = SyncProvider;
var settings$1 = {};
Object.defineProperty(settings$1, "__esModule", { value: true });
var path$d = import_path.default;
var fsScandir = out$2;
var Settings3 = class {
constructor(_options2 = {}) {
this._options = _options2;
this.basePath = this._getValue(this._options.basePath, void 0);
this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
this.deepFilter = this._getValue(this._options.deepFilter, null);
this.entryFilter = this._getValue(this._options.entryFilter, null);
this.errorFilter = this._getValue(this._options.errorFilter, null);
this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep);
this.fsScandirSettings = new fsScandir.Settings({
followSymbolicLinks: this._options.followSymbolicLinks,
fs: this._options.fs,
pathSegmentSeparator: this._options.pathSegmentSeparator,
stats: this._options.stats,
throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
});
}
_getValue(option, value2) {
return option !== null && option !== void 0 ? option : value2;
}
};
settings$1.default = Settings3;
Object.defineProperty(out$3, "__esModule", { value: true });
out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
var async_1$2 = async$5;
var stream_1$4 = stream$2;
var sync_1$2 = sync$4;
var settings_1$1 = settings$1;
out$3.Settings = settings_1$1.default;
function walk$2(directory, optionsOrSettingsOrCallback, callback) {
if (typeof optionsOrSettingsOrCallback === "function") {
new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
return;
}
new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
}
out$3.walk = walk$2;
function walkSync(directory, optionsOrSettings) {
const settings2 = getSettings(optionsOrSettings);
const provider2 = new sync_1$2.default(directory, settings2);
return provider2.read();
}
out$3.walkSync = walkSync;
function walkStream(directory, optionsOrSettings) {
const settings2 = getSettings(optionsOrSettings);
const provider2 = new stream_1$4.default(directory, settings2);
return provider2.read();
}
out$3.walkStream = walkStream;
function getSettings(settingsOrOptions = {}) {
if (settingsOrOptions instanceof settings_1$1.default) {
return settingsOrOptions;
}
return new settings_1$1.default(settingsOrOptions);
}
var reader = {};
Object.defineProperty(reader, "__esModule", { value: true });
var path$c = import_path.default;
var fsStat$2 = out$1;
var utils$6 = utils$g;
var Reader2 = class {
constructor(_settings) {
this._settings = _settings;
this._fsStatSettings = new fsStat$2.Settings({
followSymbolicLink: this._settings.followSymbolicLinks,
fs: this._settings.fs,
throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
});
}
_getFullEntryPath(filepath) {
return path$c.resolve(this._settings.cwd, filepath);
}
_makeEntry(stats, pattern2) {
const entry2 = {
name: pattern2,
path: pattern2,
dirent: utils$6.fs.createDirentFromStats(pattern2, stats)
};
if (this._settings.stats) {
entry2.stats = stats;
}
return entry2;
}
_isFatalError(error2) {
return !utils$6.errno.isEnoentCodeError(error2) && !this._settings.suppressErrors;
}
};
reader.default = Reader2;
var stream$1 = {};
Object.defineProperty(stream$1, "__esModule", { value: true });
var stream_1$3 = import_stream.default;
var fsStat$1 = out$1;
var fsWalk$2 = out$3;
var reader_1$2 = reader;
var ReaderStream = class extends reader_1$2.default {
constructor() {
super(...arguments);
this._walkStream = fsWalk$2.walkStream;
this._stat = fsStat$1.stat;
}
dynamic(root, options2) {
return this._walkStream(root, options2);
}
static(patterns, options2) {
const filepaths = patterns.map(this._getFullEntryPath, this);
const stream4 = new stream_1$3.PassThrough({ objectMode: true });
stream4._write = (index, _enc, done) => {
return this._getEntry(filepaths[index], patterns[index], options2).then((entry2) => {
if (entry2 !== null && options2.entryFilter(entry2)) {
stream4.push(entry2);
}
if (index === filepaths.length - 1) {
stream4.end();
}
done();
}).catch(done);
};
for (let i = 0; i < filepaths.length; i++) {
stream4.write(i);
}
return stream4;
}
_getEntry(filepath, pattern2, options2) {
return this._getStat(filepath).then((stats) => this._makeEntry(stats, pattern2)).catch((error2) => {
if (options2.errorFilter(error2)) {
return null;
}
throw error2;
});
}
_getStat(filepath) {
return new Promise((resolve3, reject) => {
this._stat(filepath, this._fsStatSettings, (error2, stats) => {
return error2 === null ? resolve3(stats) : reject(error2);
});
});
}
};
stream$1.default = ReaderStream;
Object.defineProperty(async$6, "__esModule", { value: true });
var fsWalk$1 = out$3;
var reader_1$1 = reader;
var stream_1$2 = stream$1;
var ReaderAsync = class extends reader_1$1.default {
constructor() {
super(...arguments);
this._walkAsync = fsWalk$1.walk;
this._readerStream = new stream_1$2.default(this._settings);
}
dynamic(root, options2) {
return new Promise((resolve3, reject) => {
this._walkAsync(root, options2, (error2, entries) => {
if (error2 === null) {
resolve3(entries);
} else {
reject(error2);
}
});
});
}
async static(patterns, options2) {
const entries = [];
const stream4 = this._readerStream.static(patterns, options2);
return new Promise((resolve3, reject) => {
stream4.once("error", reject);
stream4.on("data", (entry2) => entries.push(entry2));
stream4.once("end", () => resolve3(entries));
});
}
};
async$6.default = ReaderAsync;
var provider = {};
var deep = {};
var partial = {};
var matcher = {};
Object.defineProperty(matcher, "__esModule", { value: true });
var utils$5 = utils$g;
var Matcher = class {
constructor(_patterns, _settings, _micromatchOptions) {
this._patterns = _patterns;
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this._storage = [];
this._fillStorage();
}
_fillStorage() {
for (const pattern2 of this._patterns) {
const segments = this._getPatternSegments(pattern2);
const sections = this._splitSegmentsIntoSections(segments);
this._storage.push({
complete: sections.length <= 1,
pattern: pattern2,
segments,
sections
});
}
}
_getPatternSegments(pattern2) {
const parts = utils$5.pattern.getPatternParts(pattern2, this._micromatchOptions);
return parts.map((part) => {
const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
if (!dynamic) {
return {
dynamic: false,
pattern: part
};
}
return {
dynamic: true,
pattern: part,
patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
};
});
}
_splitSegmentsIntoSections(segments) {
return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
}
};
matcher.default = Matcher;
Object.defineProperty(partial, "__esModule", { value: true });
var matcher_1 = matcher;
var PartialMatcher = class extends matcher_1.default {
match(filepath) {
const parts = filepath.split("/");
const levels = parts.length;
const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
for (const pattern2 of patterns) {
const section = pattern2.sections[0];
if (!pattern2.complete && levels > section.length) {
return true;
}
const match2 = parts.every((part, index) => {
const segment = pattern2.segments[index];
if (segment.dynamic && segment.patternRe.test(part)) {
return true;
}
if (!segment.dynamic && segment.pattern === part) {
return true;
}
return false;
});
if (match2) {
return true;
}
}
return false;
}
};
partial.default = PartialMatcher;
Object.defineProperty(deep, "__esModule", { value: true });
var utils$4 = utils$g;
var partial_1 = partial;
var DeepFilter = class {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
}
getFilter(basePath, positive, negative) {
const matcher2 = this._getMatcher(positive);
const negativeRe = this._getNegativePatternsRe(negative);
return (entry2) => this._filter(basePath, entry2, matcher2, negativeRe);
}
_getMatcher(patterns) {
return new partial_1.default(patterns, this._settings, this._micromatchOptions);
}
_getNegativePatternsRe(patterns) {
const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
}
_filter(basePath, entry2, matcher2, negativeRe) {
if (this._isSkippedByDeep(basePath, entry2.path)) {
return false;
}
if (this._isSkippedSymbolicLink(entry2)) {
return false;
}
const filepath = utils$4.path.removeLeadingDotSegment(entry2.path);
if (this._isSkippedByPositivePatterns(filepath, matcher2)) {
return false;
}
return this._isSkippedByNegativePatterns(filepath, negativeRe);
}
_isSkippedByDeep(basePath, entryPath) {
if (this._settings.deep === Infinity) {
return false;
}
return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
}
_getEntryLevel(basePath, entryPath) {
const entryPathDepth = entryPath.split("/").length;
if (basePath === "") {
return entryPathDepth;
}
const basePathDepth = basePath.split("/").length;
return entryPathDepth - basePathDepth;
}
_isSkippedSymbolicLink(entry2) {
return !this._settings.followSymbolicLinks && entry2.dirent.isSymbolicLink();
}
_isSkippedByPositivePatterns(entryPath, matcher2) {
return !this._settings.baseNameMatch && !matcher2.match(entryPath);
}
_isSkippedByNegativePatterns(entryPath, patternsRe) {
return !utils$4.pattern.matchAny(entryPath, patternsRe);
}
};
deep.default = DeepFilter;
var entry$1 = {};
Object.defineProperty(entry$1, "__esModule", { value: true });
var utils$3 = utils$g;
var EntryFilter = class {
constructor(_settings, _micromatchOptions) {
this._settings = _settings;
this._micromatchOptions = _micromatchOptions;
this.index = /* @__PURE__ */ new Map();
}
getFilter(positive, negative) {
const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }));
return (entry2) => this._filter(entry2, positiveRe, negativeRe);
}
_filter(entry2, positiveRe, negativeRe) {
const filepath = utils$3.path.removeLeadingDotSegment(entry2.path);
if (this._settings.unique && this._isDuplicateEntry(filepath)) {
return false;
}
if (this._onlyFileFilter(entry2) || this._onlyDirectoryFilter(entry2)) {
return false;
}
if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) {
return false;
}
const isDirectory2 = entry2.dirent.isDirectory();
const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory2) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory2);
if (this._settings.unique && isMatched) {
this._createIndexRecord(filepath);
}
return isMatched;
}
_isDuplicateEntry(filepath) {
return this.index.has(filepath);
}
_createIndexRecord(filepath) {
this.index.set(filepath, void 0);
}
_onlyFileFilter(entry2) {
return this._settings.onlyFiles && !entry2.dirent.isFile();
}
_onlyDirectoryFilter(entry2) {
return this._settings.onlyDirectories && !entry2.dirent.isDirectory();
}
_isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
if (!this._settings.absolute) {
return false;
}
const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
return utils$3.pattern.matchAny(fullpath, patternsRe);
}
_isMatchToPatterns(filepath, patternsRe, isDirectory2) {
const isMatched = utils$3.pattern.matchAny(filepath, patternsRe);
if (!isMatched && isDirectory2) {
return utils$3.pattern.matchAny(filepath + "/", patternsRe);
}
return isMatched;
}
};
entry$1.default = EntryFilter;
var error$1 = {};
Object.defineProperty(error$1, "__esModule", { value: true });
var utils$2 = utils$g;
var ErrorFilter = class {
constructor(_settings) {
this._settings = _settings;
}
getFilter() {
return (error2) => this._isNonFatalError(error2);
}
_isNonFatalError(error2) {
return utils$2.errno.isEnoentCodeError(error2) || this._settings.suppressErrors;
}
};
error$1.default = ErrorFilter;
var entry = {};
Object.defineProperty(entry, "__esModule", { value: true });
var utils$1 = utils$g;
var EntryTransformer = class {
constructor(_settings) {
this._settings = _settings;
}
getTransformer() {
return (entry2) => this._transform(entry2);
}
_transform(entry2) {
let filepath = entry2.path;
if (this._settings.absolute) {
filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
filepath = utils$1.path.unixify(filepath);
}
if (this._settings.markDirectories && entry2.dirent.isDirectory()) {
filepath += "/";
}
if (!this._settings.objectMode) {
return filepath;
}
return Object.assign(Object.assign({}, entry2), { path: filepath });
}
};
entry.default = EntryTransformer;
Object.defineProperty(provider, "__esModule", { value: true });
var path$b = import_path.default;
var deep_1 = deep;
var entry_1 = entry$1;
var error_1 = error$1;
var entry_2 = entry;
var Provider = class {
constructor(_settings) {
this._settings = _settings;
this.errorFilter = new error_1.default(this._settings);
this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
this.entryTransformer = new entry_2.default(this._settings);
}
_getRootDirectory(task) {
return path$b.resolve(this._settings.cwd, task.base);
}
_getReaderOptions(task) {
const basePath = task.base === "." ? "" : task.base;
return {
basePath,
pathSegmentSeparator: "/",
concurrency: this._settings.concurrency,
deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
errorFilter: this.errorFilter.getFilter(),
followSymbolicLinks: this._settings.followSymbolicLinks,
fs: this._settings.fs,
stats: this._settings.stats,
throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
transform: this.entryTransformer.getTransformer()
};
}
_getMicromatchOptions() {
return {
dot: this._settings.dot,
matchBase: this._settings.baseNameMatch,
nobrace: !this._settings.braceExpansion,
nocase: !this._settings.caseSensitiveMatch,
noext: !this._settings.extglob,
noglobstar: !this._settings.globstar,
posix: true,
strictSlashes: false
};
}
};
provider.default = Provider;
Object.defineProperty(async$7, "__esModule", { value: true });
var async_1$1 = async$6;
var provider_1$2 = provider;
var ProviderAsync = class extends provider_1$2.default {
constructor() {
super(...arguments);
this._reader = new async_1$1.default(this._settings);
}
async read(task) {
const root = this._getRootDirectory(task);
const options2 = this._getReaderOptions(task);
const entries = await this.api(root, task, options2);
return entries.map((entry2) => options2.transform(entry2));
}
api(root, task, options2) {
if (task.dynamic) {
return this._reader.dynamic(root, options2);
}
return this._reader.static(task.patterns, options2);
}
};
async$7.default = ProviderAsync;
var stream = {};
Object.defineProperty(stream, "__esModule", { value: true });
var stream_1$1 = import_stream.default;
var stream_2 = stream$1;
var provider_1$1 = provider;
var ProviderStream = class extends provider_1$1.default {
constructor() {
super(...arguments);
this._reader = new stream_2.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options2 = this._getReaderOptions(task);
const source = this.api(root, task, options2);
const destination = new stream_1$1.Readable({ objectMode: true, read: () => {
} });
source.once("error", (error2) => destination.emit("error", error2)).on("data", (entry2) => destination.emit("data", options2.transform(entry2))).once("end", () => destination.emit("end"));
destination.once("close", () => source.destroy());
return destination;
}
api(root, task, options2) {
if (task.dynamic) {
return this._reader.dynamic(root, options2);
}
return this._reader.static(task.patterns, options2);
}
};
stream.default = ProviderStream;
var sync$2 = {};
var sync$1 = {};
Object.defineProperty(sync$1, "__esModule", { value: true });
var fsStat = out$1;
var fsWalk = out$3;
var reader_1 = reader;
var ReaderSync = class extends reader_1.default {
constructor() {
super(...arguments);
this._walkSync = fsWalk.walkSync;
this._statSync = fsStat.statSync;
}
dynamic(root, options2) {
return this._walkSync(root, options2);
}
static(patterns, options2) {
const entries = [];
for (const pattern2 of patterns) {
const filepath = this._getFullEntryPath(pattern2);
const entry2 = this._getEntry(filepath, pattern2, options2);
if (entry2 === null || !options2.entryFilter(entry2)) {
continue;
}
entries.push(entry2);
}
return entries;
}
_getEntry(filepath, pattern2, options2) {
try {
const stats = this._getStat(filepath);
return this._makeEntry(stats, pattern2);
} catch (error2) {
if (options2.errorFilter(error2)) {
return null;
}
throw error2;
}
}
_getStat(filepath) {
return this._statSync(filepath, this._fsStatSettings);
}
};
sync$1.default = ReaderSync;
Object.defineProperty(sync$2, "__esModule", { value: true });
var sync_1$1 = sync$1;
var provider_1 = provider;
var ProviderSync = class extends provider_1.default {
constructor() {
super(...arguments);
this._reader = new sync_1$1.default(this._settings);
}
read(task) {
const root = this._getRootDirectory(task);
const options2 = this._getReaderOptions(task);
const entries = this.api(root, task, options2);
return entries.map(options2.transform);
}
api(root, task, options2) {
if (task.dynamic) {
return this._reader.dynamic(root, options2);
}
return this._reader.static(task.patterns, options2);
}
};
sync$2.default = ProviderSync;
var settings = {};
(function(exports2) {
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
const fs2 = import_fs.default;
const os2 = import_os.default;
const CPU_COUNT = Math.max(os2.cpus().length, 1);
exports2.DEFAULT_FILE_SYSTEM_ADAPTER = {
lstat: fs2.lstat,
lstatSync: fs2.lstatSync,
stat: fs2.stat,
statSync: fs2.statSync,
readdir: fs2.readdir,
readdirSync: fs2.readdirSync
};
class Settings4 {
constructor(_options2 = {}) {
this._options = _options2;
this.absolute = this._getValue(this._options.absolute, false);
this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
this.braceExpansion = this._getValue(this._options.braceExpansion, true);
this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
this.cwd = this._getValue(this._options.cwd, process.cwd());
this.deep = this._getValue(this._options.deep, Infinity);
this.dot = this._getValue(this._options.dot, false);
this.extglob = this._getValue(this._options.extglob, true);
this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
this.fs = this._getFileSystemMethods(this._options.fs);
this.globstar = this._getValue(this._options.globstar, true);
this.ignore = this._getValue(this._options.ignore, []);
this.markDirectories = this._getValue(this._options.markDirectories, false);
this.objectMode = this._getValue(this._options.objectMode, false);
this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
this.onlyFiles = this._getValue(this._options.onlyFiles, true);
this.stats = this._getValue(this._options.stats, false);
this.suppressErrors = this._getValue(this._options.suppressErrors, false);
this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
this.unique = this._getValue(this._options.unique, true);
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
this.ignore = [].concat(this.ignore);
}
_getValue(option, value2) {
return option === void 0 ? value2 : option;
}
_getFileSystemMethods(methods = {}) {
return Object.assign(Object.assign({}, exports2.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
}
}
exports2.default = Settings4;
})(settings);
var taskManager = tasks;
var async_1 = async$7;
var stream_1 = stream;
var sync_1 = sync$2;
var settings_1 = settings;
var utils = utils$g;
async function FastGlob(source, options2) {
assertPatternsInput(source);
const works = getWorks(source, async_1.default, options2);
const result = await Promise.all(works);
return utils.array.flatten(result);
}
(function(FastGlob2) {
FastGlob2.glob = FastGlob2;
FastGlob2.globSync = sync2;
FastGlob2.globStream = stream4;
FastGlob2.async = FastGlob2;
function sync2(source, options2) {
assertPatternsInput(source);
const works = getWorks(source, sync_1.default, options2);
return utils.array.flatten(works);
}
FastGlob2.sync = sync2;
function stream4(source, options2) {
assertPatternsInput(source);
const works = getWorks(source, stream_1.default, options2);
return utils.stream.merge(works);
}
FastGlob2.stream = stream4;
function generateTasks(source, options2) {
assertPatternsInput(source);
const patterns = [].concat(source);
const settings2 = new settings_1.default(options2);
return taskManager.generate(patterns, settings2);
}
FastGlob2.generateTasks = generateTasks;
function isDynamicPattern2(source, options2) {
assertPatternsInput(source);
const settings2 = new settings_1.default(options2);
return utils.pattern.isDynamicPattern(source, settings2);
}
FastGlob2.isDynamicPattern = isDynamicPattern2;
function escapePath(source) {
assertPatternsInput(source);
return utils.path.escape(source);
}
FastGlob2.escapePath = escapePath;
function convertPathToPattern(source) {
assertPatternsInput(source);
return utils.path.convertPathToPattern(source);
}
FastGlob2.convertPathToPattern = convertPathToPattern;
(function(posix2) {
function escapePath2(source) {
assertPatternsInput(source);
return utils.path.escapePosixPath(source);
}
posix2.escapePath = escapePath2;
function convertPathToPattern2(source) {
assertPatternsInput(source);
return utils.path.convertPosixPathToPattern(source);
}
posix2.convertPathToPattern = convertPathToPattern2;
})(FastGlob2.posix || (FastGlob2.posix = {}));
(function(win322) {
function escapePath2(source) {
assertPatternsInput(source);
return utils.path.escapeWindowsPath(source);
}
win322.escapePath = escapePath2;
function convertPathToPattern2(source) {
assertPatternsInput(source);
return utils.path.convertWindowsPathToPattern(source);
}
win322.convertPathToPattern = convertPathToPattern2;
})(FastGlob2.win32 || (FastGlob2.win32 = {}));
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options2) {
const patterns = [].concat(source);
const settings2 = new settings_1.default(options2);
const tasks2 = taskManager.generate(patterns, settings2);
const provider2 = new _Provider(settings2);
return tasks2.map(provider2.read, provider2);
}
function assertPatternsInput(input) {
const source = [].concat(input);
const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
if (!isValidSource) {
throw new TypeError("Patterns must be a string (non empty) or an array of strings");
}
}
var out = FastGlob;
var glob = getDefaultExportFromCjs(out);
var src$2 = {};
var path$a = import_path.default;
var fs$a = import_fs.default;
var os$3 = import_os.default;
var fsReadFileAsync = fs$a.promises.readFile;
function getDefaultSearchPlaces(name2, sync2) {
return [
"package.json",
`.${name2}rc.json`,
`.${name2}rc.js`,
`.${name2}rc.cjs`,
...sync2 ? [] : [`.${name2}rc.mjs`],
`.config/${name2}rc`,
`.config/${name2}rc.json`,
`.config/${name2}rc.js`,
`.config/${name2}rc.cjs`,
...sync2 ? [] : [`.config/${name2}rc.mjs`],
`${name2}.config.js`,
`${name2}.config.cjs`,
...sync2 ? [] : [`${name2}.config.mjs`]
];
}
function parentDir(p) {
return path$a.dirname(p) || path$a.sep;
}
var jsonLoader = (_, content) => JSON.parse(content);
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require2;
var defaultLoadersSync = Object.freeze({
".js": requireFunc,
".json": requireFunc,
".cjs": requireFunc,
noExt: jsonLoader
});
src$2.defaultLoadersSync = defaultLoadersSync;
var dynamicImport = async (id) => {
try {
const mod = await import(
/* webpackIgnore: true */
id
);
return mod.default;
} catch (e2) {
try {
return requireFunc(id);
} catch (requireE) {
if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) {
throw e2;
}
throw requireE;
}
}
};
var defaultLoaders = Object.freeze({
".js": dynamicImport,
".mjs": dynamicImport,
".cjs": dynamicImport,
".json": jsonLoader,
noExt: jsonLoader
});
src$2.defaultLoaders = defaultLoaders;
function getOptions(name2, options2, sync2) {
const conf = {
stopDir: os$3.homedir(),
searchPlaces: getDefaultSearchPlaces(name2, sync2),
ignoreEmptySearchPlaces: true,
cache: true,
transform: (x) => x,
packageProp: [name2],
...options2,
loaders: {
...sync2 ? defaultLoadersSync : defaultLoaders,
...options2.loaders
}
};
conf.searchPlaces.forEach((place) => {
const key = path$a.extname(place) || "noExt";
const loader = conf.loaders[key];
if (!loader) {
throw new Error(`Missing loader for extension "${place}"`);
}
if (typeof loader !== "function") {
throw new Error(
`Loader for extension "${place}" is not a function: Received ${typeof loader}.`
);
}
});
return conf;
}
function getPackageProp(props, obj) {
if (typeof props === "string" && props in obj) return obj[props];
return (Array.isArray(props) ? props : props.split(".")).reduce(
(acc, prop) => acc === void 0 ? acc : acc[prop],
obj
) || null;
}
function validateFilePath(filepath) {
if (!filepath) throw new Error("load must pass a non-empty string");
}
function validateLoader(loader, ext2) {
if (!loader) throw new Error(`No loader specified for extension "${ext2}"`);
if (typeof loader !== "function") throw new Error("loader is not a function");
}
var makeEmplace = (enableCache) => (c, filepath, res) => {
if (enableCache) c.set(filepath, res);
return res;
};
src$2.lilconfig = function lilconfig(name2, options2) {
const {
ignoreEmptySearchPlaces,
loaders,
packageProp,
searchPlaces,
stopDir,
transform: transform2,
cache
} = getOptions(name2, options2 ?? {}, false);
const searchCache = /* @__PURE__ */ new Map();
const loadCache = /* @__PURE__ */ new Map();
const emplace = makeEmplace(cache);
return {
async search(searchFrom = process.cwd()) {
const result = {
config: null,
filepath: ""
};
const visited = /* @__PURE__ */ new Set();
let dir = searchFrom;
dirLoop: while (true) {
if (cache) {
const r2 = searchCache.get(dir);
if (r2 !== void 0) {
for (const p of visited) searchCache.set(p, r2);
return r2;
}
visited.add(dir);
}
for (const searchPlace of searchPlaces) {
const filepath = path$a.join(dir, searchPlace);
try {
await fs$a.promises.access(filepath);
} catch {
continue;
}
const content = String(await fsReadFileAsync(filepath));
const loaderKey = path$a.extname(searchPlace) || "noExt";
const loader = loaders[loaderKey];
if (searchPlace === "package.json") {
const pkg = await loader(filepath, content);
const maybeConfig = getPackageProp(packageProp, pkg);
if (maybeConfig != null) {
result.config = maybeConfig;
result.filepath = filepath;
break dirLoop;
}
continue;
}
const isEmpty2 = content.trim() === "";
if (isEmpty2 && ignoreEmptySearchPlaces) continue;
if (isEmpty2) {
result.isEmpty = true;
result.config = void 0;
} else {
validateLoader(loader, loaderKey);
result.config = await loader(filepath, content);
}
result.filepath = filepath;
break dirLoop;
}
if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
dir = parentDir(dir);
}
const transformed = (
// not found
result.filepath === "" && result.config === null ? transform2(null) : transform2(result)
);
if (cache) {
for (const p of visited) searchCache.set(p, transformed);
}
return transformed;
},
async load(filepath) {
validateFilePath(filepath);
const absPath = path$a.resolve(process.cwd(), filepath);
if (cache && loadCache.has(absPath)) {
return loadCache.get(absPath);
}
const { base, ext: ext2 } = path$a.parse(absPath);
const loaderKey = ext2 || "noExt";
const loader = loaders[loaderKey];
validateLoader(loader, loaderKey);
const content = String(await fsReadFileAsync(absPath));
if (base === "package.json") {
const pkg = await loader(absPath, content);
return emplace(
loadCache,
absPath,
transform2({
config: getPackageProp(packageProp, pkg),
filepath: absPath
})
);
}
const result = {
config: null,
filepath: absPath
};
const isEmpty2 = content.trim() === "";
if (isEmpty2 && ignoreEmptySearchPlaces)
return emplace(
loadCache,
absPath,
transform2({
config: void 0,
filepath: absPath,
isEmpty: true
})
);
result.config = isEmpty2 ? void 0 : await loader(absPath, content);
return emplace(
loadCache,
absPath,
transform2(isEmpty2 ? { ...result, isEmpty: isEmpty2, config: void 0 } : result)
);
},
clearLoadCache() {
if (cache) loadCache.clear();
},
clearSearchCache() {
if (cache) searchCache.clear();
},
clearCaches() {
if (cache) {
loadCache.clear();
searchCache.clear();
}
}
};
};
src$2.lilconfigSync = function lilconfigSync(name2, options2) {
const {
ignoreEmptySearchPlaces,
loaders,
packageProp,
searchPlaces,
stopDir,
transform: transform2,
cache
} = getOptions(name2, options2 ?? {}, true);
const searchCache = /* @__PURE__ */ new Map();
const loadCache = /* @__PURE__ */ new Map();
const emplace = makeEmplace(cache);
return {
search(searchFrom = process.cwd()) {
const result = {
config: null,
filepath: ""
};
const visited = /* @__PURE__ */ new Set();
let dir = searchFrom;
dirLoop: while (true) {
if (cache) {
const r2 = searchCache.get(dir);
if (r2 !== void 0) {
for (const p of visited) searchCache.set(p, r2);
return r2;
}
visited.add(dir);
}
for (const searchPlace of searchPlaces) {
const filepath = path$a.join(dir, searchPlace);
try {
fs$a.accessSync(filepath);
} catch {
continue;
}
const loaderKey = path$a.extname(searchPlace) || "noExt";
const loader = loaders[loaderKey];
const content = String(fs$a.readFileSync(filepath));
if (searchPlace === "package.json") {
const pkg = loader(filepath, content);
const maybeConfig = getPackageProp(packageProp, pkg);
if (maybeConfig != null) {
result.config = maybeConfig;
result.filepath = filepath;
break dirLoop;
}
continue;
}
const isEmpty2 = content.trim() === "";
if (isEmpty2 && ignoreEmptySearchPlaces) continue;
if (isEmpty2) {
result.isEmpty = true;
result.config = void 0;
} else {
validateLoader(loader, loaderKey);
result.config = loader(filepath, content);
}
result.filepath = filepath;
break dirLoop;
}
if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
dir = parentDir(dir);
}
const transformed = (
// not found
result.filepath === "" && result.config === null ? transform2(null) : transform2(result)
);
if (cache) {
for (const p of visited) searchCache.set(p, transformed);
}
return transformed;
},
load(filepath) {
validateFilePath(filepath);
const absPath = path$a.resolve(process.cwd(), filepath);
if (cache && loadCache.has(absPath)) {
return loadCache.get(absPath);
}
const { base, ext: ext2 } = path$a.parse(absPath);
const loaderKey = ext2 || "noExt";
const loader = loaders[loaderKey];
validateLoader(loader, loaderKey);
const content = String(fs$a.readFileSync(absPath));
if (base === "package.json") {
const pkg = loader(absPath, content);
return transform2({
config: getPackageProp(packageProp, pkg),
filepath: absPath
});
}
const result = {
config: null,
filepath: absPath
};
const isEmpty2 = content.trim() === "";
if (isEmpty2 && ignoreEmptySearchPlaces)
return emplace(
loadCache,
absPath,
transform2({
filepath: absPath,
config: void 0,
isEmpty: true
})
);
result.config = isEmpty2 ? void 0 : loader(absPath, content);
return emplace(
loadCache,
absPath,
transform2(isEmpty2 ? { ...result, isEmpty: isEmpty2, config: void 0 } : result)
);
},
clearLoadCache() {
if (cache) loadCache.clear();
},
clearSearchCache() {
if (cache) searchCache.clear();
},
clearCaches() {
if (cache) {
loadCache.clear();
searchCache.clear();
}
}
};
};
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR$1 = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === ALIAS;
var isDocument = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === DOC;
var isMap = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === MAP;
var isPair = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === PAIR;
var isScalar$1 = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SCALAR$1;
var isSeq = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SEQ;
function isCollection$1(node2) {
if (node2 && typeof node2 === "object")
switch (node2[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode$1(node2) {
if (node2 && typeof node2 === "object")
switch (node2[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR$1:
case SEQ:
return true;
}
return false;
}
var hasAnchor = (node2) => (isScalar$1(node2) || isCollection$1(node2)) && !!node2.anchor;
var BREAK$1 = Symbol("break visit");
var SKIP$1 = Symbol("skip children");
var REMOVE$1 = Symbol("remove node");
function visit$1(node2, visitor) {
const visitor_ = initVisitor(visitor);
if (isDocument(node2)) {
const cd = visit_(null, node2.contents, visitor_, Object.freeze([node2]));
if (cd === REMOVE$1)
node2.contents = null;
} else
visit_(null, node2, visitor_, Object.freeze([]));
}
visit$1.BREAK = BREAK$1;
visit$1.SKIP = SKIP$1;
visit$1.REMOVE = REMOVE$1;
function visit_(key, node2, visitor, path3) {
const ctrl = callVisitor(key, node2, visitor, path3);
if (isNode$1(ctrl) || isPair(ctrl)) {
replaceNode(key, path3, ctrl);
return visit_(key, ctrl, visitor, path3);
}
if (typeof ctrl !== "symbol") {
if (isCollection$1(node2)) {
path3 = Object.freeze(path3.concat(node2));
for (let i = 0; i < node2.items.length; ++i) {
const ci = visit_(i, node2.items[i], visitor, path3);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK$1)
return BREAK$1;
else if (ci === REMOVE$1) {
node2.items.splice(i, 1);
i -= 1;
}
}
} else if (isPair(node2)) {
path3 = Object.freeze(path3.concat(node2));
const ck = visit_("key", node2.key, visitor, path3);
if (ck === BREAK$1)
return BREAK$1;
else if (ck === REMOVE$1)
node2.key = null;
const cv = visit_("value", node2.value, visitor, path3);
if (cv === BREAK$1)
return BREAK$1;
else if (cv === REMOVE$1)
node2.value = null;
}
}
return ctrl;
}
async function visitAsync(node2, visitor) {
const visitor_ = initVisitor(visitor);
if (isDocument(node2)) {
const cd = await visitAsync_(null, node2.contents, visitor_, Object.freeze([node2]));
if (cd === REMOVE$1)
node2.contents = null;
} else
await visitAsync_(null, node2, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK$1;
visitAsync.SKIP = SKIP$1;
visitAsync.REMOVE = REMOVE$1;
async function visitAsync_(key, node2, visitor, path3) {
const ctrl = await callVisitor(key, node2, visitor, path3);
if (isNode$1(ctrl) || isPair(ctrl)) {
replaceNode(key, path3, ctrl);
return visitAsync_(key, ctrl, visitor, path3);
}
if (typeof ctrl !== "symbol") {
if (isCollection$1(node2)) {
path3 = Object.freeze(path3.concat(node2));
for (let i = 0; i < node2.items.length; ++i) {
const ci = await visitAsync_(i, node2.items[i], visitor, path3);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK$1)
return BREAK$1;
else if (ci === REMOVE$1) {
node2.items.splice(i, 1);
i -= 1;
}
}
} else if (isPair(node2)) {
path3 = Object.freeze(path3.concat(node2));
const ck = await visitAsync_("key", node2.key, visitor, path3);
if (ck === BREAK$1)
return BREAK$1;
else if (ck === REMOVE$1)
node2.key = null;
const cv = await visitAsync_("value", node2.value, visitor, path3);
if (cv === BREAK$1)
return BREAK$1;
else if (cv === REMOVE$1)
node2.value = null;
}
}
return ctrl;
}
function initVisitor(visitor) {
if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
return Object.assign({
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
}, visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
}, visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
}, visitor);
}
return visitor;
}
function callVisitor(key, node2, visitor, path3) {
var _a4, _b3, _c2, _d2, _e2;
if (typeof visitor === "function")
return visitor(key, node2, path3);
if (isMap(node2))
return (_a4 = visitor.Map) == null ? void 0 : _a4.call(visitor, key, node2, path3);
if (isSeq(node2))
return (_b3 = visitor.Seq) == null ? void 0 : _b3.call(visitor, key, node2, path3);
if (isPair(node2))
return (_c2 = visitor.Pair) == null ? void 0 : _c2.call(visitor, key, node2, path3);
if (isScalar$1(node2))
return (_d2 = visitor.Scalar) == null ? void 0 : _d2.call(visitor, key, node2, path3);
if (isAlias(node2))
return (_e2 = visitor.Alias) == null ? void 0 : _e2.call(visitor, key, node2, path3);
return void 0;
}
function replaceNode(key, path3, node2) {
const parent = path3[path3.length - 1];
if (isCollection$1(parent)) {
parent.items[key] = node2;
} else if (isPair(parent)) {
if (key === "key")
parent.key = node2;
else
parent.value = node2;
} else if (isDocument(parent)) {
parent.contents = node2;
} else {
const pt = isAlias(parent) ? "alias" : "scalar";
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
var escapeChars = {
"!": "%21",
",": "%2C",
"[": "%5B",
"]": "%5D",
"{": "%7B",
"}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
constructor(yaml2, tags) {
this.docStart = null;
this.docEnd = false;
this.yaml = Object.assign({}, _Directives.defaultYaml, yaml2);
this.tags = Object.assign({}, _Directives.defaultTags, tags);
}
clone() {
const copy = new _Directives(this.yaml, this.tags);
copy.docStart = this.docStart;
return copy;
}
/**
* During parsing, get a Directives instance for the current document and
* update the stream state according to the current version's spec.
*/
atDocument() {
const res = new _Directives(this.yaml, this.tags);
switch (this.yaml.version) {
case "1.1":
this.atNextDocument = true;
break;
case "1.2":
this.atNextDocument = false;
this.yaml = {
explicit: _Directives.defaultYaml.explicit,
version: "1.2"
};
this.tags = Object.assign({}, _Directives.defaultTags);
break;
}
return res;
}
/**
* @param onError - May be called even if the action was successful
* @returns `true` on success
*/
add(line, onError2) {
if (this.atNextDocument) {
this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
this.tags = Object.assign({}, _Directives.defaultTags);
this.atNextDocument = false;
}
const parts = line.trim().split(/[ \t]+/);
const name2 = parts.shift();
switch (name2) {
case "%TAG": {
if (parts.length !== 2) {
onError2(0, "%TAG directive should contain exactly two parts");
if (parts.length < 2)
return false;
}
const [handle2, prefix] = parts;
this.tags[handle2] = prefix;
return true;
}
case "%YAML": {
this.yaml.explicit = true;
if (parts.length !== 1) {
onError2(0, "%YAML directive should contain exactly one part");
return false;
}
const [version3] = parts;
if (version3 === "1.1" || version3 === "1.2") {
this.yaml.version = version3;
return true;
} else {
const isValid = /^\d+\.\d+$/.test(version3);
onError2(6, `Unsupported YAML version ${version3}`, isValid);
return false;
}
}
default:
onError2(0, `Unknown directive ${name2}`, true);
return false;
}
}
/**
* Resolves a tag, matching handles to those defined in %TAG directives.
*
* @returns Resolved tag, which may also be the non-specific tag `'!'` or a
* `'!local'` tag, or `null` if unresolvable.
*/
tagName(source, onError2) {
if (source === "!")
return "!";
if (source[0] !== "!") {
onError2(`Not a valid tag: ${source}`);
return null;
}
if (source[1] === "<") {
const verbatim = source.slice(2, -1);
if (verbatim === "!" || verbatim === "!!") {
onError2(`Verbatim tags aren't resolved, so ${source} is invalid.`);
return null;
}
if (source[source.length - 1] !== ">")
onError2("Verbatim tags must end with a >");
return verbatim;
}
const [, handle2, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError2(`The ${source} tag has no suffix`);
const prefix = this.tags[handle2];
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
} catch (error2) {
onError2(String(error2));
return null;
}
}
if (handle2 === "!")
return source;
onError2(`Could not resolve tag: ${source}`);
return null;
}
/**
* Given a fully resolved tag, returns its printable string form,
* taking into account current tag prefixes and defaults.
*/
tagString(tag) {
for (const [handle2, prefix] of Object.entries(this.tags)) {
if (tag.startsWith(prefix))
return handle2 + escapeTagName(tag.substring(prefix.length));
}
return tag[0] === "!" ? tag : `!<${tag}>`;
}
toString(doc) {
const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && isNode$1(doc.contents)) {
const tags = {};
visit$1(doc.contents, (_key, node2) => {
if (isNode$1(node2) && node2.tag)
tags[node2.tag] = true;
});
tagNames = Object.keys(tags);
} else
tagNames = [];
for (const [handle2, prefix] of tagEntries) {
if (handle2 === "!!" && prefix === "tag:yaml.org,2002:")
continue;
if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
lines.push(`%TAG ${handle2} ${prefix}`);
}
return lines.join("\n");
}
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
function anchorIsValid(anchor) {
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
const sa = JSON.stringify(anchor);
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
throw new Error(msg);
}
return true;
}
function anchorNames(root) {
const anchors = /* @__PURE__ */ new Set();
visit$1(root, {
Value(_key, node2) {
if (node2.anchor)
anchors.add(node2.anchor);
}
});
return anchors;
}
function findNewAnchor(prefix, exclude) {
for (let i = 1; true; ++i) {
const name2 = `${prefix}${i}`;
if (!exclude.has(name2))
return name2;
}
}
function createNodeAnchors(doc, prefix) {
const aliasObjects = [];
const sourceObjects = /* @__PURE__ */ new Map();
let prevAnchors = null;
return {
onAnchor: (source) => {
aliasObjects.push(source);
if (!prevAnchors)
prevAnchors = anchorNames(doc);
const anchor = findNewAnchor(prefix, prevAnchors);
prevAnchors.add(anchor);
return anchor;
},
/**
* With circular references, the source node is only resolved after all
* of its child nodes are. This is why anchors are set only after all of
* the nodes have been created.
*/
setAnchors: () => {
for (const source of aliasObjects) {
const ref = sourceObjects.get(source);
if (typeof ref === "object" && ref.anchor && (isScalar$1(ref.node) || isCollection$1(ref.node))) {
ref.node.anchor = ref.anchor;
} else {
const error2 = new Error("Failed to resolve repeated object (this should not happen)");
error2.source = source;
throw error2;
}
}
},
sourceObjects
};
}
function applyReviver(reviver, obj, key, val) {
if (val && typeof val === "object") {
if (Array.isArray(val)) {
for (let i = 0, len = val.length; i < len; ++i) {
const v0 = val[i];
const v1 = applyReviver(reviver, val, String(i), v0);
if (v1 === void 0)
delete val[i];
else if (v1 !== v0)
val[i] = v1;
}
} else if (val instanceof Map) {
for (const k of Array.from(val.keys())) {
const v0 = val.get(k);
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
val.delete(k);
else if (v1 !== v0)
val.set(k, v1);
}
} else if (val instanceof Set) {
for (const v0 of Array.from(val)) {
const v1 = applyReviver(reviver, val, v0, v0);
if (v1 === void 0)
val.delete(v0);
else if (v1 !== v0) {
val.delete(v0);
val.add(v1);
}
}
} else {
for (const [k, v0] of Object.entries(val)) {
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
delete val[k];
else if (v1 !== v0)
val[k] = v1;
}
}
}
return reviver.call(obj, key, val);
}
function toJS(value2, arg, ctx) {
if (Array.isArray(value2))
return value2.map((v, i) => toJS(v, String(i), ctx));
if (value2 && typeof value2.toJSON === "function") {
if (!ctx || !hasAnchor(value2))
return value2.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: void 0 };
ctx.anchors.set(value2, data);
ctx.onCreate = (res2) => {
data.res = res2;
delete ctx.onCreate;
};
const res = value2.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value2 === "bigint" && !(ctx == null ? void 0 : ctx.keep))
return Number(value2);
return value2;
}
var NodeBase = class {
constructor(type) {
Object.defineProperty(this, NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!isDocument(doc))
throw new TypeError("A document argument is required");
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS(this, "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
}
};
var Alias = class extends NodeBase {
constructor(source) {
super(ALIAS);
this.source = source;
Object.defineProperty(this, "tag", {
set() {
throw new Error("Alias nodes cannot have tags");
}
});
}
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc) {
let found2 = void 0;
visit$1(doc, {
Node: (_key, node2) => {
if (node2 === this)
return visit$1.BREAK;
if (node2.anchor === this.source)
found2 = node2;
}
});
return found2;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const { anchors, doc, maxAliasCount } = ctx;
const source = this.resolve(doc);
if (!source) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
let data = anchors.get(source);
if (!data) {
toJS(source, null, ctx);
data = anchors.get(source);
}
if (!data || data.res === void 0) {
const msg = "This should not happen: Alias anchor was not resolved?";
throw new ReferenceError(msg);
}
if (maxAliasCount >= 0) {
data.count += 1;
if (data.aliasCount === 0)
data.aliasCount = getAliasCount(doc, source, anchors);
if (data.count * data.aliasCount > maxAliasCount) {
const msg = "Excessive alias count indicates a resource exhaustion attack";
throw new ReferenceError(msg);
}
}
return data.res;
}
toString(ctx, _onComment, _onChompKeep) {
const src2 = `*${this.source}`;
if (ctx) {
anchorIsValid(this.source);
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new Error(msg);
}
if (ctx.implicitKey)
return `${src2} `;
}
return src2;
}
};
function getAliasCount(doc, node2, anchors) {
if (isAlias(node2)) {
const source = node2.resolve(doc);
const anchor = anchors && source && anchors.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
} else if (isCollection$1(node2)) {
let count = 0;
for (const item of node2.items) {
const c = getAliasCount(doc, item, anchors);
if (c > count)
count = c;
}
return count;
} else if (isPair(node2)) {
const kc = getAliasCount(doc, node2.key, anchors);
const vc = getAliasCount(doc, node2.value, anchors);
return Math.max(kc, vc);
}
return 1;
}
var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object";
var Scalar = class extends NodeBase {
constructor(value2) {
super(SCALAR$1);
this.value = value2;
}
toJSON(arg, ctx) {
return (ctx == null ? void 0 : ctx.keep) ? this.value : toJS(this.value, arg, ctx);
}
toString() {
return String(this.value);
}
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value2, tagName, tags) {
if (tagName) {
const match2 = tags.filter((t2) => t2.tag === tagName);
const tagObj = match2.find((t2) => !t2.format) ?? match2[0];
if (!tagObj)
throw new Error(`Tag ${tagName} not found`);
return tagObj;
}
return tags.find((t2) => {
var _a4;
return ((_a4 = t2.identify) == null ? void 0 : _a4.call(t2, value2)) && !t2.format;
});
}
function createNode(value2, tagName, ctx) {
var _a4, _b3, _c2;
if (isDocument(value2))
value2 = value2.contents;
if (isNode$1(value2))
return value2;
if (isPair(value2)) {
const map2 = (_b3 = (_a4 = ctx.schema[MAP]).createNode) == null ? void 0 : _b3.call(_a4, ctx.schema, null, ctx);
map2.items.push(value2);
return map2;
}
if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) {
value2 = value2.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema2, sourceObjects } = ctx;
let ref = void 0;
if (aliasDuplicateObjects && value2 && typeof value2 === "object") {
ref = sourceObjects.get(value2);
if (ref) {
if (!ref.anchor)
ref.anchor = onAnchor(value2);
return new Alias(ref.anchor);
} else {
ref = { anchor: null, node: null };
sourceObjects.set(value2, ref);
}
}
if (tagName == null ? void 0 : tagName.startsWith("!!"))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value2, tagName, schema2.tags);
if (!tagObj) {
if (value2 && typeof value2.toJSON === "function") {
value2 = value2.toJSON();
}
if (!value2 || typeof value2 !== "object") {
const node3 = new Scalar(value2);
if (ref)
ref.node = node3;
return node3;
}
tagObj = value2 instanceof Map ? schema2[MAP] : Symbol.iterator in Object(value2) ? schema2[SEQ] : schema2[MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node2 = (tagObj == null ? void 0 : tagObj.createNode) ? tagObj.createNode(ctx.schema, value2, ctx) : typeof ((_c2 = tagObj == null ? void 0 : tagObj.nodeClass) == null ? void 0 : _c2.from) === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2);
if (tagName)
node2.tag = tagName;
else if (!tagObj.default)
node2.tag = tagObj.tag;
if (ref)
ref.node = node2;
return node2;
}
function collectionFromPath(schema2, path3, value2) {
let v = value2;
for (let i = path3.length - 1; i >= 0; --i) {
const k = path3[i];
if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
const a = [];
a[k] = v;
v = a;
} else {
v = /* @__PURE__ */ new Map([[k, v]]);
}
}
return createNode(v, void 0, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error("This should not happen, please report a bug.");
},
schema: schema2,
sourceObjects: /* @__PURE__ */ new Map()
});
}
var isEmptyPath = (path3) => path3 == null || typeof path3 === "object" && !!path3[Symbol.iterator]().next().done;
var Collection = class extends NodeBase {
constructor(type, schema2) {
super(type);
Object.defineProperty(this, "schema", {
value: schema2,
configurable: true,
enumerable: false,
writable: true
});
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema2) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema2)
copy.schema = schema2;
copy.items = copy.items.map((it) => isNode$1(it) || isPair(it) ? it.clone(schema2) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
}
/**
* Adds a value to the collection. For `!!map` and `!!omap` the value must
* be a Pair instance or a `{ key, value }` object, which may not have a key
* that already exists in the map.
*/
addIn(path3, value2) {
if (isEmptyPath(path3))
this.add(value2);
else {
const [key, ...rest] = path3;
const node2 = this.get(key, true);
if (isCollection$1(node2))
node2.addIn(rest, value2);
else if (node2 === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value2));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
deleteIn(path3) {
const [key, ...rest] = path3;
if (rest.length === 0)
return this.delete(key);
const node2 = this.get(key, true);
if (isCollection$1(node2))
return node2.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path3, keepScalar) {
const [key, ...rest] = path3;
const node2 = this.get(key, true);
if (rest.length === 0)
return !keepScalar && isScalar$1(node2) ? node2.value : node2;
else
return isCollection$1(node2) ? node2.getIn(rest, keepScalar) : void 0;
}
hasAllNullValues(allowScalar) {
return this.items.every((node2) => {
if (!isPair(node2))
return false;
const n2 = node2.value;
return n2 == null || allowScalar && isScalar$1(n2) && n2.value == null && !n2.commentBefore && !n2.comment && !n2.tag;
});
}
/**
* Checks if the collection includes a value with the key `key`.
*/
hasIn(path3) {
const [key, ...rest] = path3;
if (rest.length === 0)
return this.has(key);
const node2 = this.get(key, true);
return isCollection$1(node2) ? node2.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path3, value2) {
const [key, ...rest] = path3;
if (rest.length === 0) {
this.set(key, value2);
} else {
const node2 = this.get(key, true);
if (isCollection$1(node2))
node2.setIn(rest, value2);
else if (node2 === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value2));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
};
Collection.maxFlowStringSingleLineLength = 60;
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
if (/^\n+$/.test(comment))
return comment.substring(1);
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text, indent, mode2 = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
if (!lineWidth || lineWidth < 0)
return text;
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
if (text.length <= endStep)
return text;
const folds = [];
const escapedFolds = {};
let end = lineWidth - indent.length;
if (typeof indentAtStart === "number") {
if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
folds.push(0);
else
end = lineWidth - indentAtStart;
}
let split = void 0;
let prev = void 0;
let overflow = false;
let i = -1;
let escStart = -1;
let escEnd = -1;
if (mode2 === FOLD_BLOCK) {
i = consumeMoreIndentedLines(text, i, indent.length);
if (i !== -1)
end = i + endStep;
}
for (let ch; ch = text[i += 1]; ) {
if (mode2 === FOLD_QUOTED && ch === "\\") {
escStart = i;
switch (text[i + 1]) {
case "x":
i += 3;
break;
case "u":
i += 5;
break;
case "U":
i += 9;
break;
default:
i += 1;
}
escEnd = i;
}
if (ch === "\n") {
if (mode2 === FOLD_BLOCK)
i = consumeMoreIndentedLines(text, i, indent.length);
end = i + indent.length + endStep;
split = void 0;
} else {
if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") {
const next = text[i + 1];
if (next && next !== " " && next !== "\n" && next !== " ")
split = i;
}
if (i >= end) {
if (split) {
folds.push(split);
end = split + endStep;
split = void 0;
} else if (mode2 === FOLD_QUOTED) {
while (prev === " " || prev === " ") {
prev = ch;
ch = text[i += 1];
overflow = true;
}
const j = i > escEnd + 1 ? i - 2 : escStart - 1;
if (escapedFolds[j])
return text;
folds.push(j);
escapedFolds[j] = true;
end = j + endStep;
split = void 0;
} else {
overflow = true;
}
}
}
prev = ch;
}
if (overflow && onOverflow)
onOverflow();
if (folds.length === 0)
return text;
if (onFold)
onFold();
let res = text.slice(0, folds[0]);
for (let i2 = 0; i2 < folds.length; ++i2) {
const fold = folds[i2];
const end2 = folds[i2 + 1] || text.length;
if (fold === 0)
res = `
${indent}${text.slice(0, end2)}`;
else {
if (mode2 === FOLD_QUOTED && escapedFolds[fold])
res += `${text[fold]}\\`;
res += `
${indent}${text.slice(fold + 1, end2)}`;
}
}
return res;
}
function consumeMoreIndentedLines(text, i, indent) {
let end = i;
let start = i + 1;
let ch = text[start];
while (ch === " " || ch === " ") {
if (i < start + indent) {
ch = text[++i];
} else {
do {
ch = text[++i];
} while (ch && ch !== "\n");
end = i;
start = i + 1;
ch = text[start];
}
}
return end;
}
var getFoldOptions = (ctx, isBlock2) => ({
indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
if (!lineWidth || lineWidth < 0)
return false;
const limit = lineWidth - indentLength;
const strLen = str.length;
if (strLen <= limit)
return false;
for (let i = 0, start = 0; i < strLen; ++i) {
if (str[i] === "\n") {
if (i - start > limit)
return true;
start = i + 1;
if (strLen - start <= limit)
return false;
}
}
return true;
}
function doubleQuotedString(value2, ctx) {
const json = JSON.stringify(value2);
if (ctx.options.doubleQuotedAsJSON)
return json;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : "");
let str = "";
let start = 0;
for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
str += json.slice(start, i) + "\\ ";
i += 1;
start = i;
ch = "\\";
}
if (ch === "\\")
switch (json[i + 1]) {
case "u":
{
str += json.slice(start, i);
const code = json.substr(i + 2, 4);
switch (code) {
case "0000":
str += "\\0";
break;
case "0007":
str += "\\a";
break;
case "000b":
str += "\\v";
break;
case "001b":
str += "\\e";
break;
case "0085":
str += "\\N";
break;
case "00a0":
str += "\\_";
break;
case "2028":
str += "\\L";
break;
case "2029":
str += "\\P";
break;
default:
if (code.substr(0, 2) === "00")
str += "\\x" + code.substr(2);
else
str += json.substr(i, 6);
}
i += 5;
start = i + 1;
}
break;
case "n":
if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
i += 1;
} else {
str += json.slice(start, i) + "\n\n";
while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
str += "\n";
i += 2;
}
str += indent;
if (json[i + 2] === " ")
str += "\\";
i += 1;
start = i + 1;
}
break;
default:
i += 1;
}
}
str = start ? str + json.slice(start) : json;
return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value2, ctx) {
if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2))
return doubleQuotedString(value2, ctx);
const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : "");
const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value2, ctx) {
const { singleQuote } = ctx.options;
let qs2;
if (singleQuote === false)
qs2 = doubleQuotedString;
else {
const hasDouble = value2.includes('"');
const hasSingle = value2.includes("'");
if (hasDouble && !hasSingle)
qs2 = singleQuotedString;
else if (hasSingle && !hasDouble)
qs2 = doubleQuotedString;
else
qs2 = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs2(value2, ctx);
}
var blockEndNewlines;
try {
blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value: value2 }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
if (!blockQuote || /\n[\t ]+$/.test(value2) || /^\s*$/.test(value2)) {
return quotedString(value2, ctx);
}
const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value2) ? " " : "");
const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value2, lineWidth, indent.length);
if (!value2)
return literal ? "|\n" : ">\n";
let chomp;
let endStart;
for (endStart = value2.length; endStart > 0; --endStart) {
const ch = value2[endStart - 1];
if (ch !== "\n" && ch !== " " && ch !== " ")
break;
}
let end = value2.substring(endStart);
const endNlPos = end.indexOf("\n");
if (endNlPos === -1) {
chomp = "-";
} else if (value2 === end || endNlPos !== end.length - 1) {
chomp = "+";
if (onChompKeep)
onChompKeep();
} else {
chomp = "";
}
if (end) {
value2 = value2.slice(0, -end.length);
if (end[end.length - 1] === "\n")
end = end.slice(0, -1);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
let startWithSpace = false;
let startEnd;
let startNlPos = -1;
for (startEnd = 0; startEnd < value2.length; ++startEnd) {
const ch = value2[startEnd];
if (ch === " ")
startWithSpace = true;
else if (ch === "\n")
startNlPos = startEnd;
else
break;
}
let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value2 = value2.substring(start.length);
start = start.replace(/\n+/g, `$&${indent}`);
}
const indentSize = indent ? "2" : "1";
let header = (literal ? "|" : ">") + (startWithSpace ? indentSize : "") + chomp;
if (comment) {
header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
if (onComment)
onComment();
}
if (literal) {
value2 = value2.replace(/\n+/g, `$&${indent}`);
return `${header}
${indent}${start}${value2}${end}`;
}
value2 = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines(`${start}${value2}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true));
return `${header}
${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value: value2 } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) {
return quotedString(value2, ctx);
}
if (!value2 || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) {
return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) {
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value2)) {
if (indent === "") {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
} else if (implicitKey && indent === indentStep) {
return quotedString(value2, ctx);
}
}
const str = value2.replace(/\n+/g, `$&
${indent}`);
if (actualString) {
const test = (tag) => {
var _a4;
return tag.default && tag.tag !== "tag:yaml.org,2002:str" && ((_a4 = tag.test) == null ? void 0 : _a4.test(str));
};
const { compat, tags } = ctx.doc.schema;
if (tags.some(test) || (compat == null ? void 0 : compat.some(test)))
return quotedString(value2, ctx);
}
return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;
const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
let { type } = item;
if (type !== Scalar.QUOTE_DOUBLE) {
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type2) => {
switch (_type2) {
case Scalar.BLOCK_FOLDED:
case Scalar.BLOCK_LITERAL:
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
case Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case Scalar.PLAIN:
return plainString(ss, ctx, onComment, onChompKeep);
default:
return null;
}
};
let res = _stringify(type);
if (res === null) {
const { defaultKeyType, defaultStringType } = ctx.options;
const t2 = implicitKey && defaultKeyType || defaultStringType;
res = _stringify(t2);
if (res === null)
throw new Error(`Unsupported default string type ${t2}`);
}
return res;
}
function createStringifyContext(doc, options2) {
const opt = Object.assign({
blockQuote: true,
commentString: stringifyComment,
defaultKeyType: null,
defaultStringType: "PLAIN",
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: "false",
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: "null",
simpleKeys: false,
singleQuote: null,
trueStr: "true",
verifyAliasOrder: true
}, doc.schema.toStringOptions, options2);
let inFlow;
switch (opt.collectionStyle) {
case "block":
inFlow = false;
break;
case "flow":
inFlow = true;
break;
default:
inFlow = null;
}
return {
anchors: /* @__PURE__ */ new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
indent: "",
indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ",
inFlow,
options: opt
};
}
function getTagObject(tags, item) {
var _a4;
if (item.tag) {
const match2 = tags.filter((t2) => t2.tag === item.tag);
if (match2.length > 0)
return match2.find((t2) => t2.format === item.format) ?? match2[0];
}
let tagObj = void 0;
let obj;
if (isScalar$1(item)) {
obj = item.value;
const match2 = tags.filter((t2) => {
var _a5;
return (_a5 = t2.identify) == null ? void 0 : _a5.call(t2, obj);
});
tagObj = match2.find((t2) => t2.format === item.format) ?? match2.find((t2) => !t2.format);
} else {
obj = item;
tagObj = tags.find((t2) => t2.nodeClass && obj instanceof t2.nodeClass);
}
if (!tagObj) {
const name2 = ((_a4 = obj == null ? void 0 : obj.constructor) == null ? void 0 : _a4.name) ?? typeof obj;
throw new Error(`Tag not resolved for ${name2} value`);
}
return tagObj;
}
function stringifyProps(node2, tagObj, { anchors, doc }) {
if (!doc.directives)
return "";
const props = [];
const anchor = (isScalar$1(node2) || isCollection$1(node2)) && node2.anchor;
if (anchor && anchorIsValid(anchor)) {
anchors.add(anchor);
props.push(`&${anchor}`);
}
const tag = node2.tag ? node2.tag : tagObj.default ? null : tagObj.tag;
if (tag)
props.push(doc.directives.tagString(tag));
return props.join(" ");
}
function stringify$2(item, ctx, onComment, onChompKeep) {
var _a4;
if (isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if ((_a4 = ctx.resolvedAliases) == null ? void 0 : _a4.has(item)) {
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
} else {
if (ctx.resolvedAliases)
ctx.resolvedAliases.add(item);
else
ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
item = item.resolve(ctx.doc);
}
}
let tagObj = void 0;
const node2 = isNode$1(item) ? item : ctx.doc.createNode(item, { onTagObj: (o2) => tagObj = o2 });
if (!tagObj)
tagObj = getTagObject(ctx.doc.schema.tags, node2);
const props = stringifyProps(node2, tagObj, ctx);
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node2, ctx, onComment, onChompKeep) : isScalar$1(node2) ? stringifyString(node2, ctx, onComment, onChompKeep) : node2.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return isScalar$1(node2) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = isNode$1(key) && key.comment || null;
if (simpleKeys) {
if (keyComment) {
throw new Error("With simple keys, key nodes cannot have comments");
}
if (isCollection$1(key) || !isNode$1(key) && typeof key === "object") {
const msg = "With simple keys, collection cannot be used as a key value";
throw new Error(msg);
}
}
let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection$1(key) || (isScalar$1(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object"));
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
});
let keyCommentDone = false;
let chompKeep = false;
let str = stringify$2(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
explicitKey = true;
}
if (ctx.inFlow) {
if (allNullValues || value2 == null) {
if (keyCommentDone && onComment)
onComment();
return str === "" ? "?" : explicitKey ? `? ${str}` : str;
}
} else if (allNullValues && !simpleKeys || value2 == null && explicitKey) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += lineComment(str, ctx.indent, commentString(keyComment));
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}
${indent}:`;
} else {
str = `${str}:`;
if (keyComment)
str += lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (isNode$1(value2)) {
vsb = !!value2.spaceBefore;
vcb = value2.commentBefore;
valueComment = value2.comment;
} else {
vsb = false;
vcb = null;
valueComment = null;
if (value2 && typeof value2 === "object")
value2 = doc.createNode(value2);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && isScalar$1(value2))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) {
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify$2(value2, ctx, () => valueCommentDone = true, () => chompKeep = true);
let ws = " ";
if (keyComment || vsb || vcb) {
ws = vsb ? "\n" : "";
if (vcb) {
const cs = commentString(vcb);
ws += `
${indentComment(cs, ctx.indent)}`;
}
if (valueStr === "" && !ctx.inFlow) {
if (ws === "\n")
ws = "\n\n";
} else {
ws += `
${ctx.indent}`;
}
} else if (!explicitKey && isCollection$1(value2)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf("\n");
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === "&" || vs0 === "!")) {
let sp0 = valueStr.indexOf(" ");
if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
sp0 = valueStr.indexOf(" ", sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `
${ctx.indent}`;
}
} else if (valueStr === "" || valueStr[0] === "\n") {
ws = "";
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)
onComment();
} else if (valueComment && !valueCommentDone) {
str += lineComment(str, ctx.indent, commentString(valueComment));
} else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
function warn(logLevel, warning) {
if (logLevel === "debug" || logLevel === "warn") {
if (typeof process !== "undefined" && process.emitWarning)
process.emitWarning(warning);
else
console.warn(warning);
}
}
var MERGE_KEY = "<<";
function addPairToJSMap(ctx, map2, { key, value: value2 }) {
if ((ctx == null ? void 0 : ctx.doc.schema.merge) && isMergeKey(key)) {
value2 = isAlias(value2) ? value2.resolve(ctx.doc) : value2;
if (isSeq(value2))
for (const it of value2.items)
mergeToJSMap(ctx, map2, it);
else if (Array.isArray(value2))
for (const it of value2)
mergeToJSMap(ctx, map2, it);
else
mergeToJSMap(ctx, map2, value2);
} else {
const jsKey = toJS(key, "", ctx);
if (map2 instanceof Map) {
map2.set(jsKey, toJS(value2, jsKey, ctx));
} else if (map2 instanceof Set) {
map2.add(jsKey);
} else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS(value2, stringKey, ctx);
if (stringKey in map2)
Object.defineProperty(map2, stringKey, {
value: jsValue,
writable: true,
enumerable: true,
configurable: true
});
else
map2[stringKey] = jsValue;
}
}
return map2;
}
var isMergeKey = (key) => key === MERGE_KEY || isScalar$1(key) && key.value === MERGE_KEY && (!key.type || key.type === Scalar.PLAIN);
function mergeToJSMap(ctx, map2, value2) {
const source = ctx && isAlias(value2) ? value2.resolve(ctx.doc) : value2;
if (!isMap(source))
throw new Error("Merge sources must be maps or map aliases");
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value3] of srcMap) {
if (map2 instanceof Map) {
if (!map2.has(key))
map2.set(key, value3);
} else if (map2 instanceof Set) {
map2.add(key);
} else if (!Object.prototype.hasOwnProperty.call(map2, key)) {
Object.defineProperty(map2, key, {
value: value3,
writable: true,
enumerable: true,
configurable: true
});
}
}
return map2;
}
function stringifyKey(key, jsKey, ctx) {
if (jsKey === null)
return "";
if (typeof jsKey !== "object")
return String(jsKey);
if (isNode$1(key) && (ctx == null ? void 0 : ctx.doc)) {
const strCtx = createStringifyContext(ctx.doc, {});
strCtx.anchors = /* @__PURE__ */ new Set();
for (const node2 of ctx.anchors.keys())
strCtx.anchors.add(node2.anchor);
strCtx.inFlow = true;
strCtx.inStringifyKey = true;
const strKey = key.toString(strCtx);
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey);
if (jsonStr.length > 40)
jsonStr = jsonStr.substring(0, 36) + '..."';
warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
ctx.mapKeyWarned = true;
}
return strKey;
}
return JSON.stringify(jsKey);
}
function createPair(key, value2, ctx) {
const k = createNode(key, void 0, ctx);
const v = createNode(value2, void 0, ctx);
return new Pair(k, v);
}
var Pair = class _Pair {
constructor(key, value2 = null) {
Object.defineProperty(this, NODE_TYPE, { value: PAIR });
this.key = key;
this.value = value2;
}
clone(schema2) {
let { key, value: value2 } = this;
if (isNode$1(key))
key = key.clone(schema2);
if (isNode$1(value2))
value2 = value2.clone(schema2);
return new _Pair(key, value2);
}
toJSON(_, ctx) {
const pair = (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {};
return addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return (ctx == null ? void 0 : ctx.doc) ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
}
};
function stringifyCollection(collection, ctx, options2) {
const flow = ctx.inFlow ?? collection.flow;
const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify2(collection, ctx, options2);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
const { indent, options: { commentString } } = ctx;
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
let chompKeep = false;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment2 = null;
if (isNode$1(item)) {
if (!chompKeep && item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment2 = item.comment;
} else if (isPair(item)) {
const ik = isNode$1(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str2 = stringify$2(item, itemCtx, () => comment2 = null, () => chompKeep = true);
if (comment2)
str2 += lineComment(str2, itemIndent, commentString(comment2));
if (chompKeep && comment2)
chompKeep = false;
lines.push(blockItemPrefix + str2);
}
let str;
if (lines.length === 0) {
str = flowChars.start + flowChars.end;
} else {
str = lines[0];
for (let i = 1; i < lines.length; ++i) {
const line = lines[i];
str += line ? `
${indent}${line}` : "\n";
}
}
if (comment) {
str += "\n" + indentComment(commentString(comment), indent);
if (onComment)
onComment();
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
inFlow: true,
type: null
});
let reqNewline = false;
let linesAtValue = 0;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (isNode$1(item)) {
if (item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
} else if (isPair(item)) {
const ik = isNode$1(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, false);
if (ik.comment)
reqNewline = true;
}
const iv = isNode$1(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
} else if (item.value == null && (ik == null ? void 0 : ik.comment)) {
comment = ik.comment;
}
}
if (comment)
reqNewline = true;
let str = stringify$2(item, itemCtx, () => comment = null);
if (i < items.length - 1)
str += ",";
if (comment)
str += lineComment(str, itemIndent, commentString(comment));
if (!reqNewline && (lines.length > linesAtValue || str.includes("\n")))
reqNewline = true;
lines.push(str);
linesAtValue = lines.length;
}
const { start, end } = flowChars;
if (lines.length === 0) {
return start + end;
} else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
}
if (reqNewline) {
let str = start;
for (const line of lines)
str += line ? `
${indentStep}${indent}${line}` : "\n";
return `${str}
${indent}${end}`;
} else {
return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
}
}
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
if (comment && chompKeep)
comment = comment.replace(/^\n+/, "");
if (comment) {
const ic = indentComment(commentString(comment), indent);
lines.push(ic.trimStart());
}
}
function findPair(items, key) {
const k = isScalar$1(key) ? key.value : key;
for (const it of items) {
if (isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (isScalar$1(it.key) && it.key.value === k)
return it;
}
}
return void 0;
}
var YAMLMap = class extends Collection {
static get tagName() {
return "tag:yaml.org,2002:map";
}
constructor(schema2) {
super(MAP, schema2);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema2, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map2 = new this(schema2);
const add = (key, value2) => {
if (typeof replacer === "function")
value2 = replacer.call(obj, key, value2);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value2 !== void 0 || keepUndefined)
map2.items.push(createPair(key, value2, ctx));
};
if (obj instanceof Map) {
for (const [key, value2] of obj)
add(key, value2);
} else if (obj && typeof obj === "object") {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema2.sortMapEntries === "function") {
map2.items.sort(schema2.sortMapEntries);
}
return map2;
}
/**
* Adds a value to the collection.
*
* @param overwrite - If not set `true`, using a key that is already in the
* collection will throw. Otherwise, overwrites the previous value.
*/
add(pair, overwrite) {
var _a4;
let _pair;
if (isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
_pair = new Pair(pair, pair == null ? void 0 : pair.value);
} else
_pair = new Pair(pair.key, pair.value);
const prev = findPair(this.items, _pair.key);
const sortEntries = (_a4 = this.schema) == null ? void 0 : _a4.sortMapEntries;
if (prev) {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
if (isScalar$1(prev.value) && isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
} else if (sortEntries) {
const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
if (i === -1)
this.items.push(_pair);
else
this.items.splice(i, 0, _pair);
} else {
this.items.push(_pair);
}
}
delete(key) {
const it = findPair(this.items, key);
if (!it)
return false;
const del = this.items.splice(this.items.indexOf(it), 1);
return del.length > 0;
}
get(key, keepScalar) {
const it = findPair(this.items, key);
const node2 = it == null ? void 0 : it.value;
return (!keepScalar && isScalar$1(node2) ? node2.value : node2) ?? void 0;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value2) {
this.add(new Pair(key, value2), true);
}
/**
* @param ctx - Conversion context, originally set in Document#toJS()
* @param {Class} Type - If set, forces the returned collection type
* @returns Instance of Type, Map, or Object
*/
toJSON(_, ctx, Type) {
const map2 = Type ? new Type() : (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {};
if (ctx == null ? void 0 : ctx.onCreate)
ctx.onCreate(map2);
for (const item of this.items)
addPairToJSMap(ctx, map2, item);
return map2;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))
ctx = Object.assign({}, ctx, { allNullValues: true });
return stringifyCollection(this, ctx, {
blockItemPrefix: "",
flowChars: { start: "{", end: "}" },
itemIndent: ctx.indent || "",
onChompKeep,
onComment
});
}
};
var map$1 = {
collection: "map",
default: true,
nodeClass: YAMLMap,
tag: "tag:yaml.org,2002:map",
resolve(map2, onError2) {
if (!isMap(map2))
onError2("Expected a mapping for this tag");
return map2;
},
createNode: (schema2, obj, ctx) => YAMLMap.from(schema2, obj, ctx)
};
var YAMLSeq = class extends Collection {
static get tagName() {
return "tag:yaml.org,2002:seq";
}
constructor(schema2) {
super(SEQ, schema2);
this.items = [];
}
add(value2) {
this.items.push(value2);
}
/**
* Removes a value from the collection.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*
* @returns `true` if the item was found and removed.
*/
delete(key) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return false;
const del = this.items.splice(idx, 1);
return del.length > 0;
}
get(key, keepScalar) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return void 0;
const it = this.items[idx];
return !keepScalar && isScalar$1(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*/
has(key) {
const idx = asItemIndex(key);
return typeof idx === "number" && idx < this.items.length;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*
* If `key` does not contain a representation of an integer, this will throw.
* It may be wrapped in a `Scalar`.
*/
set(key, value2) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (isScalar$1(prev) && isScalarValue(value2))
prev.value = value2;
else
this.items[idx] = value2;
}
toJSON(_, ctx) {
const seq2 = [];
if (ctx == null ? void 0 : ctx.onCreate)
ctx.onCreate(seq2);
let i = 0;
for (const item of this.items)
seq2.push(toJS(item, String(i++), ctx));
return seq2;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection(this, ctx, {
blockItemPrefix: "- ",
flowChars: { start: "[", end: "]" },
itemIndent: (ctx.indent || "") + " ",
onChompKeep,
onComment
});
}
static from(schema2, obj, ctx) {
const { replacer } = ctx;
const seq2 = new this(schema2);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === "function") {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq2.items.push(createNode(it, void 0, ctx));
}
}
return seq2;
}
};
function asItemIndex(key) {
let idx = isScalar$1(key) ? key.value : key;
if (idx && typeof idx === "string")
idx = Number(idx);
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
var seq = {
collection: "seq",
default: true,
nodeClass: YAMLSeq,
tag: "tag:yaml.org,2002:seq",
resolve(seq2, onError2) {
if (!isSeq(seq2))
onError2("Expected a sequence for this tag");
return seq2;
},
createNode: (schema2, obj, ctx) => YAMLSeq.from(schema2, obj, ctx)
};
var string = {
identify: (value2) => typeof value2 === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify(item, ctx, onComment, onChompKeep) {
ctx = Object.assign({ actualString: true }, ctx);
return stringifyString(item, ctx, onComment, onChompKeep);
}
};
var nullTag = {
identify: (value2) => value2 == null,
createNode: () => new Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^(?:~|[Nn]ull|NULL)?$/,
resolve: () => new Scalar(null),
stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};
var boolTag = {
identify: (value2) => typeof value2 === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"),
stringify({ source, value: value2 }, ctx) {
if (source && boolTag.test.test(source)) {
const sv = source[0] === "t" || source[0] === "T";
if (value2 === sv)
return source;
}
return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
};
function stringifyNumber({ format: format2, minFractionDigits, tag, value: value2 }) {
if (typeof value2 === "bigint")
return String(value2);
const num = typeof value2 === "number" ? value2 : Number(value2);
if (!isFinite(num))
return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
let n2 = JSON.stringify(value2);
if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n2)) {
let i = n2.indexOf(".");
if (i < 0) {
i = n2.length;
n2 += ".";
}
let d = minFractionDigits - (n2.length - i - 1);
while (d-- > 0)
n2 += "0";
}
return n2;
}
var floatNaN$1 = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber
};
var floatExp$1 = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str),
stringify(node2) {
const num = Number(node2.value);
return isFinite(num) ? num.toExponential() : stringifyNumber(node2);
}
};
var float$1 = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
resolve(str) {
const node2 = new Scalar(parseFloat(str));
const dot = str.indexOf(".");
if (dot !== -1 && str[str.length - 1] === "0")
node2.minFractionDigits = str.length - dot - 1;
return node2;
},
stringify: stringifyNumber
};
var intIdentify$2 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
var intResolve$1 = (str, offset2, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset2), radix);
function intStringify$1(node2, radix, prefix) {
const { value: value2 } = node2;
if (intIdentify$2(value2) && value2 >= 0)
return prefix + value2.toString(radix);
return stringifyNumber(node2);
}
var intOct$1 = {
identify: (value2) => intIdentify$2(value2) && value2 >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^0o[0-7]+$/,
resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
stringify: (node2) => intStringify$1(node2, 8, "0o")
};
var int$1 = {
identify: intIdentify$2,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9]+$/,
resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
stringify: stringifyNumber
};
var intHex$1 = {
identify: (value2) => intIdentify$2(value2) && value2 >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^0x[0-9a-fA-F]+$/,
resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
stringify: (node2) => intStringify$1(node2, 16, "0x")
};
var schema$2 = [
map$1,
seq,
string,
nullTag,
boolTag,
intOct$1,
int$1,
intHex$1,
floatNaN$1,
floatExp$1,
float$1
];
function intIdentify$1(value2) {
return typeof value2 === "bigint" || Number.isInteger(value2);
}
var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2);
var jsonScalars = [
{
identify: (value2) => typeof value2 === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify: stringifyJSON
},
{
identify: (value2) => value2 == null,
createNode: () => new Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: (value2) => typeof value2 === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^true|false$/,
resolve: (str) => str === "true",
stringify: stringifyJSON
},
{
identify: intIdentify$1,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^-?(?:0|[1-9][0-9]*)$/,
resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
stringify: ({ value: value2 }) => intIdentify$1(value2) ? value2.toString() : JSON.stringify(value2)
},
{
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
resolve: (str) => parseFloat(str),
stringify: stringifyJSON
}
];
var jsonError = {
default: true,
tag: "",
test: /^/,
resolve(str, onError2) {
onError2(`Unresolved plain scalar ${JSON.stringify(str)}`);
return str;
}
};
var schema$1 = [map$1, seq].concat(jsonScalars, jsonError);
var binary = {
identify: (value2) => value2 instanceof Uint8Array,
// Buffer inherits from Uint8Array
default: false,
tag: "tag:yaml.org,2002:binary",
/**
* Returns a Buffer in node and an Uint8Array in browsers
*
* To use the resulting buffer as an image, you'll want to do something like:
*
* const blob = new Blob([buffer], { type: 'image/jpeg' })
* document.querySelector('#photo').src = URL.createObjectURL(blob)
*/
resolve(src2, onError2) {
if (typeof Buffer === "function") {
return Buffer.from(src2, "base64");
} else if (typeof atob === "function") {
const str = atob(src2.replace(/[\n\r]/g, ""));
const buffer = new Uint8Array(str.length);
for (let i = 0; i < str.length; ++i)
buffer[i] = str.charCodeAt(i);
return buffer;
} else {
onError2("This environment does not support reading binary tags; either Buffer or atob is required");
return src2;
}
},
stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) {
const buf = value2;
let str;
if (typeof Buffer === "function") {
str = buf instanceof Buffer ? buf.toString("base64") : Buffer.from(buf.buffer).toString("base64");
} else if (typeof btoa === "function") {
let s = "";
for (let i = 0; i < buf.length; ++i)
s += String.fromCharCode(buf[i]);
str = btoa(s);
} else {
throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
}
if (!type)
type = Scalar.BLOCK_LITERAL;
if (type !== Scalar.QUOTE_DOUBLE) {
const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
const n2 = Math.ceil(str.length / lineWidth);
const lines = new Array(n2);
for (let i = 0, o2 = 0; i < n2; ++i, o2 += lineWidth) {
lines[i] = str.substr(o2, lineWidth);
}
str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " ");
}
return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
}
};
function resolvePairs(seq2, onError2) {
if (isSeq(seq2)) {
for (let i = 0; i < seq2.items.length; ++i) {
let item = seq2.items[i];
if (isPair(item))
continue;
else if (isMap(item)) {
if (item.items.length > 1)
onError2("Each pair must have its own sequence indicator");
const pair = item.items[0] || new Pair(new Scalar(null));
if (item.commentBefore)
pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
if (item.comment) {
const cn = pair.value ?? pair.key;
cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
}
item = pair;
}
seq2.items[i] = isPair(item) ? item : new Pair(item);
}
} else
onError2("Expected a sequence for this tag");
return seq2;
}
function createPairs(schema2, iterable, ctx) {
const { replacer } = ctx;
const pairs2 = new YAMLSeq(schema2);
pairs2.tag = "tag:yaml.org,2002:pairs";
let i = 0;
if (iterable && Symbol.iterator in Object(iterable))
for (let it of iterable) {
if (typeof replacer === "function")
it = replacer.call(iterable, String(i++), it);
let key, value2;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value2 = it[1];
} else
throw new TypeError(`Expected [key, value] tuple: ${it}`);
} else if (it && it instanceof Object) {
const keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value2 = it[key];
} else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
} else {
key = it;
}
pairs2.items.push(createPair(key, value2, ctx));
}
return pairs2;
}
var pairs = {
collection: "seq",
default: false,
tag: "tag:yaml.org,2002:pairs",
resolve: resolvePairs,
createNode: createPairs
};
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
constructor() {
super();
this.add = YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.prototype.has.bind(this);
this.set = YAMLMap.prototype.set.bind(this);
this.tag = _YAMLOMap.tag;
}
/**
* If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
* but TypeScript won't allow widening the signature of a child method.
*/
toJSON(_, ctx) {
if (!ctx)
return super.toJSON(_);
const map2 = /* @__PURE__ */ new Map();
if (ctx == null ? void 0 : ctx.onCreate)
ctx.onCreate(map2);
for (const pair of this.items) {
let key, value2;
if (isPair(pair)) {
key = toJS(pair.key, "", ctx);
value2 = toJS(pair.value, key, ctx);
} else {
key = toJS(pair, "", ctx);
}
if (map2.has(key))
throw new Error("Ordered maps must not include duplicate keys");
map2.set(key, value2);
}
return map2;
}
static from(schema2, iterable, ctx) {
const pairs2 = createPairs(schema2, iterable, ctx);
const omap2 = new this();
omap2.items = pairs2.items;
return omap2;
}
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
collection: "seq",
identify: (value2) => value2 instanceof Map,
nodeClass: YAMLOMap,
default: false,
tag: "tag:yaml.org,2002:omap",
resolve(seq2, onError2) {
const pairs2 = resolvePairs(seq2, onError2);
const seenKeys = [];
for (const { key } of pairs2.items) {
if (isScalar$1(key)) {
if (seenKeys.includes(key.value)) {
onError2(`Ordered maps must not include duplicate keys: ${key.value}`);
} else {
seenKeys.push(key.value);
}
}
}
return Object.assign(new YAMLOMap(), pairs2);
},
createNode: (schema2, iterable, ctx) => YAMLOMap.from(schema2, iterable, ctx)
};
function boolStringify({ value: value2, source }, ctx) {
const boolObj = value2 ? trueTag : falseTag;
if (source && boolObj.test.test(source))
return source;
return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
identify: (value2) => value2 === true,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
resolve: () => new Scalar(true),
stringify: boolStringify
};
var falseTag = {
identify: (value2) => value2 === false,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
resolve: () => new Scalar(false),
stringify: boolStringify
};
var floatNaN = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber
};
var floatExp = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str.replace(/_/g, "")),
stringify(node2) {
const num = Number(node2.value);
return isFinite(num) ? num.toExponential() : stringifyNumber(node2);
}
};
var float = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
resolve(str) {
const node2 = new Scalar(parseFloat(str.replace(/_/g, "")));
const dot = str.indexOf(".");
if (dot !== -1) {
const f2 = str.substring(dot + 1).replace(/_/g, "");
if (f2[f2.length - 1] === "0")
node2.minFractionDigits = f2.length;
}
return node2;
},
stringify: stringifyNumber
};
var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
function intResolve(str, offset2, radix, { intAsBigInt }) {
const sign = str[0];
if (sign === "-" || sign === "+")
offset2 += 1;
str = str.substring(offset2).replace(/_/g, "");
if (intAsBigInt) {
switch (radix) {
case 2:
str = `0b${str}`;
break;
case 8:
str = `0o${str}`;
break;
case 16:
str = `0x${str}`;
break;
}
const n3 = BigInt(str);
return sign === "-" ? BigInt(-1) * n3 : n3;
}
const n2 = parseInt(str, radix);
return sign === "-" ? -1 * n2 : n2;
}
function intStringify(node2, radix, prefix) {
const { value: value2 } = node2;
if (intIdentify(value2)) {
const str = value2.toString(radix);
return value2 < 0 ? "-" + prefix + str.substr(1) : prefix + str;
}
return stringifyNumber(node2);
}
var intBin = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "BIN",
test: /^[-+]?0b[0-1_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
stringify: (node2) => intStringify(node2, 2, "0b")
};
var intOct = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^[-+]?0[0-7_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
stringify: (node2) => intStringify(node2, 8, "0")
};
var int = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9][0-9_]*$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber
};
var intHex = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^[-+]?0x[0-9a-fA-F_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node2) => intStringify(node2, 16, "0x")
};
var YAMLSet = class _YAMLSet extends YAMLMap {
constructor(schema2) {
super(schema2);
this.tag = _YAMLSet.tag;
}
add(key) {
let pair;
if (isPair(key))
pair = key;
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
pair = new Pair(key.key, null);
else
pair = new Pair(key, null);
const prev = findPair(this.items, pair.key);
if (!prev)
this.items.push(pair);
}
/**
* If `keepPair` is `true`, returns the Pair matching `key`.
* Otherwise, returns the value of that Pair's key.
*/
get(key, keepPair) {
const pair = findPair(this.items, key);
return !keepPair && isPair(pair) ? isScalar$1(pair.key) ? pair.key.value : pair.key : pair;
}
set(key, value2) {
if (typeof value2 !== "boolean")
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`);
const prev = findPair(this.items, key);
if (prev && !value2) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value2) {
this.items.push(new Pair(key));
}
}
toJSON(_, ctx) {
return super.toJSON(_, ctx, Set);
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
if (this.hasAllNullValues(true))
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
else
throw new Error("Set items must all have null values");
}
static from(schema2, iterable, ctx) {
const { replacer } = ctx;
const set2 = new this(schema2);
if (iterable && Symbol.iterator in Object(iterable))
for (let value2 of iterable) {
if (typeof replacer === "function")
value2 = replacer.call(iterable, value2, value2);
set2.items.push(createPair(value2, null, ctx));
}
return set2;
}
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set = {
collection: "map",
identify: (value2) => value2 instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: "tag:yaml.org,2002:set",
createNode: (schema2, iterable, ctx) => YAMLSet.from(schema2, iterable, ctx),
resolve(map2, onError2) {
if (isMap(map2)) {
if (map2.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map2);
else
onError2("Set items must all have null values");
} else
onError2("Expected a mapping for this tag");
return map2;
}
};
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
const num = (n2) => asBigInt ? BigInt(n2) : Number(n2);
const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node2) {
let { value: value2 } = node2;
let num = (n2) => n2;
if (typeof value2 === "bigint")
num = (n2) => BigInt(n2);
else if (isNaN(value2) || !isFinite(value2))
return stringifyNumber(node2);
let sign = "";
if (value2 < 0) {
sign = "-";
value2 *= num(-1);
}
const _60 = num(60);
const parts = [value2 % _60];
if (value2 < 60) {
parts.unshift(0);
} else {
value2 = (value2 - parts[0]) / _60;
parts.unshift(value2 % _60);
if (value2 >= 60) {
value2 = (value2 - parts[0]) / _60;
parts.unshift(value2);
}
}
return sign + parts.map((n2) => String(n2).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2),
default: true,
tag: "tag:yaml.org,2002:int",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
stringify: stringifySexagesimal
};
var floatTime = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
resolve: (str) => parseSexagesimal(str, false),
stringify: stringifySexagesimal
};
var timestamp = {
identify: (value2) => value2 instanceof Date,
default: true,
tag: "tag:yaml.org,2002:timestamp",
// If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
// may be omitted altogether, resulting in a date format. In such a case, the time part is
// assumed to be 00:00:00Z (start of day, UTC).
test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
resolve(str) {
const match2 = str.match(timestamp.test);
if (!match2)
throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
const [, year, month, day, hour, minute, second] = match2.map(Number);
const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0;
let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
const tz = match2[8];
if (tz && tz !== "Z") {
let d = parseSexagesimal(tz, false);
if (Math.abs(d) < 30)
d *= 60;
date -= 6e4 * d;
}
return new Date(date);
},
stringify: ({ value: value2 }) => value2.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "")
};
var schema = [
map$1,
seq,
string,
nullTag,
trueTag,
falseTag,
intBin,
intOct,
int,
intHex,
floatNaN,
floatExp,
float,
binary,
omap,
pairs,
set,
intTime,
floatTime,
timestamp
];
var schemas = /* @__PURE__ */ new Map([
["core", schema$2],
["failsafe", [map$1, seq, string]],
["json", schema$1],
["yaml11", schema],
["yaml-1.1", schema]
]);
var tagsByName = {
binary,
bool: boolTag,
float: float$1,
floatExp: floatExp$1,
floatNaN: floatNaN$1,
floatTime,
int: int$1,
intHex: intHex$1,
intOct: intOct$1,
intTime,
map: map$1,
null: nullTag,
omap,
pairs,
seq,
set,
timestamp
};
var coreKnownTags = {
"tag:yaml.org,2002:binary": binary,
"tag:yaml.org,2002:omap": omap,
"tag:yaml.org,2002:pairs": pairs,
"tag:yaml.org,2002:set": set,
"tag:yaml.org,2002:timestamp": timestamp
};
function getTags(customTags, schemaName) {
let tags = schemas.get(schemaName);
if (!tags) {
if (Array.isArray(customTags))
tags = [];
else {
const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
}
}
if (Array.isArray(customTags)) {
for (const tag of customTags)
tags = tags.concat(tag);
} else if (typeof customTags === "function") {
tags = customTags(tags.slice());
}
return tags.map((tag) => {
if (typeof tag !== "string")
return tag;
const tagObj = tagsByName[tag];
if (tagObj)
return tagObj;
const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
});
}
var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
var Schema = class _Schema {
constructor({ compat, customTags, merge: merge3, resolveKnownTags, schema: schema2, sortMapEntries, toStringDefaults }) {
this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null;
this.merge = !!merge3;
this.name = typeof schema2 === "string" && schema2 || "core";
this.knownTags = resolveKnownTags ? coreKnownTags : {};
this.tags = getTags(customTags, this.name);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, MAP, { value: map$1 });
Object.defineProperty(this, SCALAR$1, { value: string });
Object.defineProperty(this, SEQ, { value: seq });
this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
}
clone() {
const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
copy.tags = this.tags.slice();
return copy;
}
};
function stringifyDocument(doc, options2) {
var _a4;
const lines = [];
let hasDirectives = options2.directives === true;
if (options2.directives !== false && doc.directives) {
const dir = doc.directives.toString(doc);
if (dir) {
lines.push(dir);
hasDirectives = true;
} else if (doc.directives.docStart)
hasDirectives = true;
}
if (hasDirectives)
lines.push("---");
const ctx = createStringifyContext(doc, options2);
const { commentString } = ctx.options;
if (doc.commentBefore) {
if (lines.length !== 1)
lines.unshift("");
const cs = commentString(doc.commentBefore);
lines.unshift(indentComment(cs, ""));
}
let chompKeep = false;
let contentComment = null;
if (doc.contents) {
if (isNode$1(doc.contents)) {
if (doc.contents.spaceBefore && hasDirectives)
lines.push("");
if (doc.contents.commentBefore) {
const cs = commentString(doc.contents.commentBefore);
lines.push(indentComment(cs, ""));
}
ctx.forceBlockIndent = !!doc.comment;
contentComment = doc.contents.comment;
}
const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
let body = stringify$2(doc.contents, ctx, () => contentComment = null, onChompKeep);
if (contentComment)
body += lineComment(body, "", commentString(contentComment));
if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
lines[lines.length - 1] = `--- ${body}`;
} else
lines.push(body);
} else {
lines.push(stringify$2(doc.contents, ctx));
}
if ((_a4 = doc.directives) == null ? void 0 : _a4.docEnd) {
if (doc.comment) {
const cs = commentString(doc.comment);
if (cs.includes("\n")) {
lines.push("...");
lines.push(indentComment(cs, ""));
} else {
lines.push(`... ${cs}`);
}
} else {
lines.push("...");
}
} else {
let dc = doc.comment;
if (dc && chompKeep)
dc = dc.replace(/^\n+/, "");
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
lines.push("");
lines.push(indentComment(commentString(dc), ""));
}
}
return lines.join("\n") + "\n";
}
var Document = class _Document {
constructor(value2, replacer, options2) {
this.commentBefore = null;
this.comment = null;
this.errors = [];
this.warnings = [];
Object.defineProperty(this, NODE_TYPE, { value: DOC });
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options2 === void 0 && replacer) {
options2 = replacer;
replacer = void 0;
}
const opt = Object.assign({
intAsBigInt: false,
keepSourceTokens: false,
logLevel: "warn",
prettyErrors: true,
strict: true,
uniqueKeys: true,
version: "1.2"
}, options2);
this.options = opt;
let { version: version3 } = opt;
if (options2 == null ? void 0 : options2._directives) {
this.directives = options2._directives.atDocument();
if (this.directives.yaml.explicit)
version3 = this.directives.yaml.version;
} else
this.directives = new Directives({ version: version3 });
this.setSchema(version3, options2);
this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options2);
}
/**
* Create a deep copy of this Document and its contents.
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone() {
const copy = Object.create(_Document.prototype, {
[NODE_TYPE]: { value: DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
copy.errors = this.errors.slice();
copy.warnings = this.warnings.slice();
copy.options = Object.assign({}, this.options);
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = isNode$1(this.contents) ? this.contents.clone(copy.schema) : this.contents;
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** Adds a value to the document. */
add(value2) {
if (assertCollection(this.contents))
this.contents.add(value2);
}
/** Adds a value to the document. */
addIn(path3, value2) {
if (assertCollection(this.contents))
this.contents.addIn(path3, value2);
}
/**
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
*
* If `node` already has an anchor, `name` is ignored.
* Otherwise, the `node.anchor` value will be set to `name`,
* or if an anchor with that name is already present in the document,
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node2, name2) {
if (!node2.anchor) {
const prev = anchorNames(this);
node2.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
!name2 || prev.has(name2) ? findNewAnchor(name2 || "a", prev) : name2;
}
return new Alias(node2.anchor);
}
createNode(value2, replacer, options2) {
let _replacer = void 0;
if (typeof replacer === "function") {
value2 = replacer.call({ "": value2 }, "", value2);
_replacer = replacer;
} else if (Array.isArray(replacer)) {
const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
const asStr = replacer.filter(keyToStr).map(String);
if (asStr.length > 0)
replacer = replacer.concat(asStr);
_replacer = replacer;
} else if (options2 === void 0 && replacer) {
options2 = replacer;
replacer = void 0;
}
const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options2 ?? {};
const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(
this,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
anchorPrefix || "a"
);
const ctx = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
};
const node2 = createNode(value2, tag, ctx);
if (flow && isCollection$1(node2))
node2.flow = true;
setAnchors();
return node2;
}
/**
* Convert a key and a value into a `Pair` using the current schema,
* recursively wrapping all values as `Scalar` or `Collection` nodes.
*/
createPair(key, value2, options2 = {}) {
const k = this.createNode(key, null, options2);
const v = this.createNode(value2, null, options2);
return new Pair(k, v);
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
delete(key) {
return assertCollection(this.contents) ? this.contents.delete(key) : false;
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
deleteIn(path3) {
if (isEmptyPath(path3)) {
if (this.contents == null)
return false;
this.contents = null;
return true;
}
return assertCollection(this.contents) ? this.contents.deleteIn(path3) : false;
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return isCollection$1(this.contents) ? this.contents.get(key, keepScalar) : void 0;
}
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path3, keepScalar) {
if (isEmptyPath(path3))
return !keepScalar && isScalar$1(this.contents) ? this.contents.value : this.contents;
return isCollection$1(this.contents) ? this.contents.getIn(path3, keepScalar) : void 0;
}
/**
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return isCollection$1(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
*/
hasIn(path3) {
if (isEmptyPath(path3))
return this.contents !== void 0;
return isCollection$1(this.contents) ? this.contents.hasIn(path3) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
set(key, value2) {
if (this.contents == null) {
this.contents = collectionFromPath(this.schema, [key], value2);
} else if (assertCollection(this.contents)) {
this.contents.set(key, value2);
}
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path3, value2) {
if (isEmptyPath(path3)) {
this.contents = value2;
} else if (this.contents == null) {
this.contents = collectionFromPath(this.schema, Array.from(path3), value2);
} else if (assertCollection(this.contents)) {
this.contents.setIn(path3, value2);
}
}
/**
* Change the YAML version and schema used by the document.
* A `null` version disables support for directives, explicit tags, anchors, and aliases.
* It also requires the `schema` option to be given as a `Schema` instance value.
*
* Overrides all previously set schema options.
*/
setSchema(version3, options2 = {}) {
if (typeof version3 === "number")
version3 = String(version3);
let opt;
switch (version3) {
case "1.1":
if (this.directives)
this.directives.yaml.version = "1.1";
else
this.directives = new Directives({ version: "1.1" });
opt = { merge: true, resolveKnownTags: false, schema: "yaml-1.1" };
break;
case "1.2":
case "next":
if (this.directives)
this.directives.yaml.version = version3;
else
this.directives = new Directives({ version: version3 });
opt = { merge: false, resolveKnownTags: true, schema: "core" };
break;
case null:
if (this.directives)
delete this.directives;
opt = null;
break;
default: {
const sv = JSON.stringify(version3);
throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
}
}
if (options2.schema instanceof Object)
this.schema = options2.schema;
else if (opt)
this.schema = new Schema(Object.assign(opt, options2));
else
throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
}
// json & jsonArg are only used from toJSON()
toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc: this,
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS(this.contents, jsonArg ?? "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
}
/**
* A JSON representation of the document `contents`.
*
* @param jsonArg Used by `JSON.stringify` to indicate the array index or
* property name.
*/
toJSON(jsonArg, onAnchor) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
}
/** A YAML representation of the document. */
toString(options2 = {}) {
if (this.errors.length > 0)
throw new Error("Document with errors cannot be stringified");
if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) {
const s = JSON.stringify(options2.indent);
throw new Error(`"indent" option must be a positive integer, not ${s}`);
}
return stringifyDocument(this, options2);
}
};
function assertCollection(contents) {
if (isCollection$1(contents))
return true;
throw new Error("Expected a YAML collection as document contents");
}
var YAMLError = class extends Error {
constructor(name2, pos, code, message) {
super();
this.name = name2;
this.code = code;
this.message = message;
this.pos = pos;
}
};
var YAMLParseError = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLParseError", pos, code, message);
}
};
var YAMLWarning = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLWarning", pos, code, message);
}
};
var prettifyError = (src2, lc) => (error2) => {
if (error2.pos[0] === -1)
return;
error2.linePos = error2.pos.map((pos) => lc.linePos(pos));
const { line, col } = error2.linePos[0];
error2.message += ` at line ${line}, column ${col}`;
let ci = col - 1;
let lineStr = src2.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
if (ci >= 60 && lineStr.length > 80) {
const trimStart = Math.min(ci - 39, lineStr.length - 79);
lineStr = "…" + lineStr.substring(trimStart);
ci -= trimStart - 1;
}
if (lineStr.length > 80)
lineStr = lineStr.substring(0, 79) + "…";
if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
let prev = src2.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
if (prev.length > 80)
prev = prev.substring(0, 79) + "…\n";
lineStr = prev + lineStr;
}
if (/[^ ]/.test(lineStr)) {
let count = 1;
const end = error2.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = " ".repeat(ci) + "^".repeat(count);
error2.message += `:
${lineStr}
${pointer}
`;
}
};
function resolveProps(tokens, { flow, indicator, next, offset: offset2, onError: onError2, parentIndent, startOnNewline }) {
let spaceBefore = false;
let atNewline = startOnNewline;
let hasSpace = startOnNewline;
let comment = "";
let commentSep = "";
let hasNewline = false;
let hasNewlineAfterProp = false;
let reqSpace = false;
let tab = null;
let anchor = null;
let tag = null;
let comma2 = null;
let found2 = null;
let start = null;
for (const token of tokens) {
if (reqSpace) {
if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
onError2(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
reqSpace = false;
}
if (tab) {
if (atNewline && token.type !== "comment" && token.type !== "newline") {
onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
}
tab = null;
}
switch (token.type) {
case "space":
if (!flow && (indicator !== "doc-start" || (next == null ? void 0 : next.type) !== "flow-collection") && token.source.includes(" ")) {
tab = token;
}
hasSpace = true;
break;
case "comment": {
if (!hasSpace)
onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = token.source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += commentSep + cb;
commentSep = "";
atNewline = false;
break;
}
case "newline":
if (atNewline) {
if (comment)
comment += token.source;
else
spaceBefore = true;
} else
commentSep += token.source;
atNewline = true;
hasNewline = true;
if (anchor || tag)
hasNewlineAfterProp = true;
hasSpace = true;
break;
case "anchor":
if (anchor)
onError2(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
if (token.source.endsWith(":"))
onError2(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
anchor = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
case "tag": {
if (tag)
onError2(token, "MULTIPLE_TAGS", "A node can have at most one tag");
tag = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
}
case indicator:
if (anchor || tag)
onError2(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
if (found2)
onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
found2 = token;
atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
hasSpace = false;
break;
case "comma":
if (flow) {
if (comma2)
onError2(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
comma2 = token;
atNewline = false;
hasSpace = false;
break;
}
default:
onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
atNewline = false;
hasSpace = false;
}
}
const last = tokens[tokens.length - 1];
const end = last ? last.offset + last.source.length : offset2;
if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
}
if (tab && (atNewline && tab.indent <= parentIndent || (next == null ? void 0 : next.type) === "block-map" || (next == null ? void 0 : next.type) === "block-seq"))
onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
return {
comma: comma2,
found: found2,
spaceBefore,
comment,
hasNewline,
hasNewlineAfterProp,
anchor,
tag,
end,
start: start ?? end
};
}
function containsNewline(key) {
if (!key)
return null;
switch (key.type) {
case "alias":
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
if (key.source.includes("\n"))
return true;
if (key.end) {
for (const st of key.end)
if (st.type === "newline")
return true;
}
return false;
case "flow-collection":
for (const it of key.items) {
for (const st of it.start)
if (st.type === "newline")
return true;
if (it.sep) {
for (const st of it.sep)
if (st.type === "newline")
return true;
}
if (containsNewline(it.key) || containsNewline(it.value))
return true;
}
return false;
default:
return true;
}
}
function flowIndentCheck(indent, fc, onError2) {
if ((fc == null ? void 0 : fc.type) === "flow-collection") {
const end = fc.end[0];
if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) {
const msg = "Flow end indicator should be more indented than parent";
onError2(end, "BAD_INDENT", msg, true);
}
}
}
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
if (uniqueKeys === false)
return false;
const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar$1(a) && isScalar$1(b) && a.value === b.value && !(a.value === "<<" && ctx.schema.merge);
return items.some((pair) => isEqual(pair.key, search));
}
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError2, tag) {
var _a4;
const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLMap;
const map2 = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset2 = bm.offset;
let commentEnd = null;
for (const collItem of bm.items) {
const { start, key, sep: sep2, value: value2 } = collItem;
const keyProps = resolveProps(start, {
indicator: "explicit-key-ind",
next: key ?? (sep2 == null ? void 0 : sep2[0]),
offset: offset2,
onError: onError2,
parentIndent: bm.indent,
startOnNewline: true
});
const implicitKey = !keyProps.found;
if (implicitKey) {
if (key) {
if (key.type === "block-seq")
onError2(offset2, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
else if ("indent" in key && key.indent !== bm.indent)
onError2(offset2, "BAD_INDENT", startColMsg);
}
if (!keyProps.anchor && !keyProps.tag && !sep2) {
commentEnd = keyProps.end;
if (keyProps.comment) {
if (map2.comment)
map2.comment += "\n" + keyProps.comment;
else
map2.comment = keyProps.comment;
}
continue;
}
if (keyProps.hasNewlineAfterProp || containsNewline(key)) {
onError2(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
}
} else if (((_a4 = keyProps.found) == null ? void 0 : _a4.indent) !== bm.indent) {
onError2(offset2, "BAD_INDENT", startColMsg);
}
const keyStart = keyProps.end;
const keyNode = key ? composeNode2(ctx, key, keyProps, onError2) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError2);
if (ctx.schema.compat)
flowIndentCheck(bm.indent, key, onError2);
if (mapIncludes(ctx, map2.items, keyNode))
onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
const valueProps = resolveProps(sep2 ?? [], {
indicator: "map-value-ind",
next: value2,
offset: keyNode.range[2],
onError: onError2,
parentIndent: bm.indent,
startOnNewline: !key || key.type === "block-scalar"
});
offset2 = valueProps.end;
if (valueProps.found) {
if (implicitKey) {
if ((value2 == null ? void 0 : value2.type) === "block-map" && !valueProps.hasNewline)
onError2(offset2, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
}
const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError2) : composeEmptyNode2(ctx, offset2, sep2, null, valueProps, onError2);
if (ctx.schema.compat)
flowIndentCheck(bm.indent, value2, onError2);
offset2 = valueNode.range[2];
const pair = new Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map2.items.push(pair);
} else {
if (implicitKey)
onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair(keyNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map2.items.push(pair);
}
}
if (commentEnd && commentEnd < offset2)
onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
map2.range = [bm.offset, offset2, commentEnd ?? offset2];
return map2;
}
function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError2, tag) {
const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLSeq;
const seq2 = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset2 = bs.offset;
let commentEnd = null;
for (const { start, value: value2 } of bs.items) {
const props = resolveProps(start, {
indicator: "seq-item-ind",
next: value2,
offset: offset2,
onError: onError2,
parentIndent: bs.indent,
startOnNewline: true
});
if (!props.found) {
if (props.anchor || props.tag || value2) {
if (value2 && value2.type === "block-seq")
onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column");
else
onError2(offset2, "MISSING_CHAR", "Sequence item without - indicator");
} else {
commentEnd = props.end;
if (props.comment)
seq2.comment = props.comment;
continue;
}
}
const node2 = value2 ? composeNode2(ctx, value2, props, onError2) : composeEmptyNode2(ctx, props.end, start, null, props, onError2);
if (ctx.schema.compat)
flowIndentCheck(bs.indent, value2, onError2);
offset2 = node2.range[2];
seq2.items.push(node2);
}
seq2.range = [bs.offset, offset2, commentEnd ?? offset2];
return seq2;
}
function resolveEnd(end, offset2, reqSpace, onError2) {
let comment = "";
if (end) {
let hasSpace = false;
let sep2 = "";
for (const token of end) {
const { source, type } = token;
switch (type) {
case "space":
hasSpace = true;
break;
case "comment": {
if (reqSpace && !hasSpace)
onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += sep2 + cb;
sep2 = "";
break;
}
case "newline":
if (comment)
sep2 += source;
hasSpace = true;
break;
default:
onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
}
offset2 += source.length;
}
}
return { comment, offset: offset2 };
}
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock$1 = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError2, tag) {
const isMap2 = fc.start.source === "{";
const fcName = isMap2 ? "flow map" : "flow sequence";
const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? (isMap2 ? YAMLMap : YAMLSeq);
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
ctx.atRoot = false;
let offset2 = fc.offset + fc.start.source.length;
for (let i = 0; i < fc.items.length; ++i) {
const collItem = fc.items[i];
const { start, key, sep: sep2, value: value2 } = collItem;
const props = resolveProps(start, {
flow: fcName,
indicator: "explicit-key-ind",
next: key ?? (sep2 == null ? void 0 : sep2[0]),
offset: offset2,
onError: onError2,
parentIndent: fc.indent,
startOnNewline: false
});
if (!props.found) {
if (!props.anchor && !props.tag && !sep2 && !value2) {
if (i === 0 && props.comma)
onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
else if (i < fc.items.length - 1)
onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
if (props.comment) {
if (coll.comment)
coll.comment += "\n" + props.comment;
else
coll.comment = props.comment;
}
offset2 = props.end;
continue;
}
if (!isMap2 && ctx.options.strict && containsNewline(key))
onError2(
key,
// checked by containsNewline()
"MULTILINE_IMPLICIT_KEY",
"Implicit keys of flow sequence pairs need to be on a single line"
);
}
if (i === 0) {
if (props.comma)
onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
} else {
if (!props.comma)
onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
if (props.comment) {
let prevItemComment = "";
loop: for (const st of start) {
switch (st.type) {
case "comma":
case "space":
break;
case "comment":
prevItemComment = st.source.substring(1);
break loop;
default:
break loop;
}
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += "\n" + prevItemComment;
else
prev.comment = prevItemComment;
props.comment = props.comment.substring(prevItemComment.length + 1);
}
}
}
if (!isMap2 && !sep2 && !props.found) {
const valueNode = value2 ? composeNode2(ctx, value2, props, onError2) : composeEmptyNode2(ctx, props.end, sep2, null, props, onError2);
coll.items.push(valueNode);
offset2 = valueNode.range[2];
if (isBlock$1(value2))
onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else {
const keyStart = props.end;
const keyNode = key ? composeNode2(ctx, key, props, onError2) : composeEmptyNode2(ctx, keyStart, start, null, props, onError2);
if (isBlock$1(key))
onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
const valueProps = resolveProps(sep2 ?? [], {
flow: fcName,
indicator: "map-value-ind",
next: value2,
offset: keyNode.range[2],
onError: onError2,
parentIndent: fc.indent,
startOnNewline: false
});
if (valueProps.found) {
if (!isMap2 && !props.found && ctx.options.strict) {
if (sep2)
for (const st of sep2) {
if (st === valueProps.found)
break;
if (st.type === "newline") {
onError2(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
break;
}
}
if (props.start < valueProps.found.offset - 1024)
onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
}
} else if (value2) {
if ("source" in value2 && value2.source && value2.source[0] === ":")
onError2(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`);
else
onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
}
const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError2) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep2, null, valueProps, onError2) : null;
if (valueNode) {
if (isBlock$1(value2))
onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
if (isMap2) {
const map2 = coll;
if (mapIncludes(ctx, map2.items, keyNode))
onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
map2.items.push(pair);
} else {
const map2 = new YAMLMap(ctx.schema);
map2.flow = true;
map2.items.push(pair);
coll.items.push(map2);
}
offset2 = valueNode ? valueNode.range[2] : valueProps.end;
}
}
const expectedEnd = isMap2 ? "}" : "]";
const [ce, ...ee] = fc.end;
let cePos = offset2;
if (ce && ce.source === expectedEnd)
cePos = ce.offset + ce.source.length;
else {
const name2 = fcName[0].toUpperCase() + fcName.substring(1);
const msg = atRoot ? `${name2} must end with a ${expectedEnd}` : `${name2} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
onError2(offset2, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
if (ce && ce.source.length !== 1)
ee.unshift(ce);
}
if (ee.length > 0) {
const end = resolveEnd(ee, cePos, ctx.options.strict, onError2);
if (end.comment) {
if (coll.comment)
coll.comment += "\n" + end.comment;
else
coll.comment = end.comment;
}
coll.range = [fc.offset, cePos, end.offset];
} else {
coll.range = [fc.offset, cePos, cePos];
}
return coll;
}
function resolveCollection(CN2, ctx, token, onError2, tagName, tag) {
const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError2, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError2, tag) : resolveFlowCollection(CN2, ctx, token, onError2, tag);
const Coll = coll.constructor;
if (tagName === "!" || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN2, ctx, token, tagToken, onError2) {
var _a4;
const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg));
const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq" || !expType) {
return resolveCollection(CN2, ctx, token, onError2, tagName);
}
let tag = ctx.schema.tags.find((t2) => t2.tag === tagName && t2.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
tag = kt;
} else {
if (kt == null ? void 0 : kt.collection) {
onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
} else {
onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN2, ctx, token, onError2, tagName);
}
}
const coll = resolveCollection(CN2, ctx, token, onError2, tagName, tag);
const res = ((_a4 = tag.resolve) == null ? void 0 : _a4.call(tag, coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options)) ?? coll;
const node2 = isNode$1(res) ? res : new Scalar(res);
node2.range = coll.range;
node2.tag = tagName;
if (tag == null ? void 0 : tag.format)
node2.format = tag.format;
return node2;
}
function resolveBlockScalar(ctx, scalar, onError2) {
const start = scalar.offset;
const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2);
if (!header)
return { value: "", type: null, comment: "", range: [start, start, start] };
const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
const lines = scalar.source ? splitLines(scalar.source) : [];
let chompStart = lines.length;
for (let i = lines.length - 1; i >= 0; --i) {
const content = lines[i][1];
if (content === "" || content === "\r")
chompStart = i;
else
break;
}
if (chompStart === 0) {
const value3 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
let end2 = start + header.length;
if (scalar.source)
end2 += scalar.source.length;
return { value: value3, type, comment: header.comment, range: [start, end2, end2] };
}
let trimIndent = scalar.indent + header.indent;
let offset2 = scalar.offset + header.length;
let contentStart = 0;
for (let i = 0; i < chompStart; ++i) {
const [indent, content] = lines[i];
if (content === "" || content === "\r") {
if (header.indent === 0 && indent.length > trimIndent)
trimIndent = indent.length;
} else {
if (indent.length < trimIndent) {
const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
onError2(offset2 + indent.length, "MISSING_CHAR", message);
}
if (header.indent === 0)
trimIndent = indent.length;
contentStart = i;
if (trimIndent === 0 && !ctx.atRoot) {
const message = "Block scalar values in collections must be indented";
onError2(offset2, "BAD_INDENT", message);
}
break;
}
offset2 += indent.length + content.length + 1;
}
for (let i = lines.length - 1; i >= chompStart; --i) {
if (lines[i][0].length > trimIndent)
chompStart = i + 1;
}
let value2 = "";
let sep2 = "";
let prevMoreIndented = false;
for (let i = 0; i < contentStart; ++i)
value2 += lines[i][0].slice(trimIndent) + "\n";
for (let i = contentStart; i < chompStart; ++i) {
let [indent, content] = lines[i];
offset2 += indent.length + content.length + 1;
const crlf = content[content.length - 1] === "\r";
if (crlf)
content = content.slice(0, -1);
if (content && indent.length < trimIndent) {
const src2 = header.indent ? "explicit indentation indicator" : "first line";
const message = `Block scalar lines must not be less indented than their ${src2}`;
onError2(offset2 - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
indent = "";
}
if (type === Scalar.BLOCK_LITERAL) {
value2 += sep2 + indent.slice(trimIndent) + content;
sep2 = "\n";
} else if (indent.length > trimIndent || content[0] === " ") {
if (sep2 === " ")
sep2 = "\n";
else if (!prevMoreIndented && sep2 === "\n")
sep2 = "\n\n";
value2 += sep2 + indent.slice(trimIndent) + content;
sep2 = "\n";
prevMoreIndented = true;
} else if (content === "") {
if (sep2 === "\n")
value2 += "\n";
else
sep2 = "\n";
} else {
value2 += sep2 + content;
sep2 = " ";
prevMoreIndented = false;
}
}
switch (header.chomp) {
case "-":
break;
case "+":
for (let i = chompStart; i < lines.length; ++i)
value2 += "\n" + lines[i][0].slice(trimIndent);
if (value2[value2.length - 1] !== "\n")
value2 += "\n";
break;
default:
value2 += "\n";
}
const end = start + header.length + scalar.source.length;
return { value: value2, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset: offset2, props }, strict, onError2) {
if (props[0].type !== "block-scalar-header") {
onError2(props[0], "IMPOSSIBLE", "Block scalar header not found");
return null;
}
const { source } = props[0];
const mode2 = source[0];
let indent = 0;
let chomp = "";
let error2 = -1;
for (let i = 1; i < source.length; ++i) {
const ch = source[i];
if (!chomp && (ch === "-" || ch === "+"))
chomp = ch;
else {
const n2 = Number(ch);
if (!indent && n2)
indent = n2;
else if (error2 === -1)
error2 = offset2 + i;
}
}
if (error2 !== -1)
onError2(error2, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
let hasSpace = false;
let comment = "";
let length = source.length;
for (let i = 1; i < props.length; ++i) {
const token = props[i];
switch (token.type) {
case "space":
hasSpace = true;
case "newline":
length += token.source.length;
break;
case "comment":
if (strict && !hasSpace) {
const message = "Comments must be separated from other tokens by white space characters";
onError2(token, "MISSING_CHAR", message);
}
length += token.source.length;
comment = token.source.substring(1);
break;
case "error":
onError2(token, "UNEXPECTED_TOKEN", token.message);
length += token.source.length;
break;
default: {
const message = `Unexpected token in block scalar header: ${token.type}`;
onError2(token, "UNEXPECTED_TOKEN", message);
const ts = token.source;
if (ts && typeof ts === "string")
length += ts.length;
}
}
}
return { mode: mode2, indent, chomp, comment, length };
}
function splitLines(source) {
const split = source.split(/\n( *)/);
const first2 = split[0];
const m = first2.match(/^( *)/);
const line0 = (m == null ? void 0 : m[1]) ? [m[1], first2.slice(m[1].length)] : ["", first2];
const lines = [line0];
for (let i = 1; i < split.length; i += 2)
lines.push([split[i], split[i + 1]]);
return lines;
}
function resolveFlowScalar(scalar, strict, onError2) {
const { offset: offset2, type, source, end } = scalar;
let _type2;
let value2;
const _onError = (rel, code, msg) => onError2(offset2 + rel, code, msg);
switch (type) {
case "scalar":
_type2 = Scalar.PLAIN;
value2 = plainValue(source, _onError);
break;
case "single-quoted-scalar":
_type2 = Scalar.QUOTE_SINGLE;
value2 = singleQuotedValue(source, _onError);
break;
case "double-quoted-scalar":
_type2 = Scalar.QUOTE_DOUBLE;
value2 = doubleQuotedValue(source, _onError);
break;
default:
onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
return {
value: "",
type: null,
comment: "",
range: [offset2, offset2 + source.length, offset2 + source.length]
};
}
const valueEnd = offset2 + source.length;
const re = resolveEnd(end, valueEnd, strict, onError2);
return {
value: value2,
type: _type2,
comment: re.comment,
range: [offset2, valueEnd, re.offset]
};
}
function plainValue(source, onError2) {
let badChar = "";
switch (source[0]) {
case " ":
badChar = "a tab character";
break;
case ",":
badChar = "flow indicator character ,";
break;
case "%":
badChar = "directive indicator character %";
break;
case "|":
case ">": {
badChar = `block scalar indicator ${source[0]}`;
break;
}
case "@":
case "`": {
badChar = `reserved character ${source[0]}`;
break;
}
}
if (badChar)
onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
return foldLines(source);
}
function singleQuotedValue(source, onError2) {
if (source[source.length - 1] !== "'" || source.length === 1)
onError2(source.length, "MISSING_CHAR", "Missing closing 'quote");
return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
let first2, line;
try {
first2 = new RegExp("(.*?)(?<![ ])[ ]*\r?\n", "sy");
line = new RegExp("[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?\n", "sy");
} catch (_) {
first2 = /(.*?)[ \t]*\r?\n/sy;
line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
}
let match2 = first2.exec(source);
if (!match2)
return source;
let res = match2[1];
let sep2 = " ";
let pos = first2.lastIndex;
line.lastIndex = pos;
while (match2 = line.exec(source)) {
if (match2[1] === "") {
if (sep2 === "\n")
res += sep2;
else
sep2 = "\n";
} else {
res += sep2 + match2[1];
sep2 = " ";
}
pos = line.lastIndex;
}
const last = /[ \t]*(.*)/sy;
last.lastIndex = pos;
match2 = last.exec(source);
return res + sep2 + ((match2 == null ? void 0 : match2[1]) ?? "");
}
function doubleQuotedValue(source, onError2) {
let res = "";
for (let i = 1; i < source.length - 1; ++i) {
const ch = source[i];
if (ch === "\r" && source[i + 1] === "\n")
continue;
if (ch === "\n") {
const { fold, offset: offset2 } = foldNewline(source, i);
res += fold;
i = offset2;
} else if (ch === "\\") {
let next = source[++i];
const cc = escapeCodes[next];
if (cc)
res += cc;
else if (next === "\n") {
next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "\r" && source[i + 1] === "\n") {
next = source[++i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "x" || next === "u" || next === "U") {
const length = { x: 2, u: 4, U: 8 }[next];
res += parseCharCode(source, i + 1, length, onError2);
i += length;
} else {
const raw = source.substr(i - 1, 2);
onError2(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
res += raw;
}
} else if (ch === " " || ch === " ") {
const wsStart = i;
let next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
if (next !== "\n" && !(next === "\r" && source[i + 2] === "\n"))
res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
} else {
res += ch;
}
}
if (source[source.length - 1] !== '"' || source.length === 1)
onError2(source.length, "MISSING_CHAR", 'Missing closing "quote');
return res;
}
function foldNewline(source, offset2) {
let fold = "";
let ch = source[offset2 + 1];
while (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
if (ch === "\r" && source[offset2 + 2] !== "\n")
break;
if (ch === "\n")
fold += "\n";
offset2 += 1;
ch = source[offset2 + 1];
}
if (!fold)
fold = " ";
return { fold, offset: offset2 };
}
var escapeCodes = {
"0": "\0",
// null character
a: "\x07",
// bell character
b: "\b",
// backspace
e: "\x1B",
// escape character
f: "\f",
// form feed
n: "\n",
// line feed
r: "\r",
// carriage return
t: " ",
// horizontal tab
v: "\v",
// vertical tab
N: "…",
// Unicode next line
_: " ",
// Unicode non-breaking space
L: "\u2028",
// Unicode line separator
P: "\u2029",
// Unicode paragraph separator
" ": " ",
'"': '"',
"/": "/",
"\\": "\\",
" ": " "
};
function parseCharCode(source, offset2, length, onError2) {
const cc = source.substr(offset2, length);
const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
const code = ok ? parseInt(cc, 16) : NaN;
if (isNaN(code)) {
const raw = source.substr(offset2 - 2, length + 2);
onError2(offset2 - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
return raw;
}
return String.fromCodePoint(code);
}
function composeScalar(ctx, token, tagToken, onError2) {
const { value: value2, type, comment, range: range2 } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError2) : resolveFlowScalar(token, ctx.options.strict, onError2);
const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
const tag = tagToken && tagName ? findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError2) : token.type === "scalar" ? findScalarTagByTest(ctx, value2, token, onError2) : ctx.schema[SCALAR$1];
let scalar;
try {
const res = tag.resolve(value2, (msg) => onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
scalar = isScalar$1(res) ? res : new Scalar(res);
} catch (error2) {
const msg = error2 instanceof Error ? error2.message : String(error2);
onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
scalar = new Scalar(value2);
}
scalar.range = range2;
scalar.source = value2;
if (type)
scalar.type = type;
if (tagName)
scalar.tag = tagName;
if (tag.format)
scalar.format = tag.format;
if (comment)
scalar.comment = comment;
return scalar;
}
function findScalarTagByName(schema2, value2, tagName, tagToken, onError2) {
var _a4;
if (tagName === "!")
return schema2[SCALAR$1];
const matchWithTest = [];
for (const tag of schema2.tags) {
if (!tag.collection && tag.tag === tagName) {
if (tag.default && tag.test)
matchWithTest.push(tag);
else
return tag;
}
}
for (const tag of matchWithTest)
if ((_a4 = tag.test) == null ? void 0 : _a4.test(value2))
return tag;
const kt = schema2.knownTags[tagName];
if (kt && !kt.collection) {
schema2.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
return kt;
}
onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
return schema2[SCALAR$1];
}
function findScalarTagByTest({ directives, schema: schema2 }, value2, token, onError2) {
const tag = schema2.tags.find((tag2) => {
var _a4;
return tag2.default && ((_a4 = tag2.test) == null ? void 0 : _a4.test(value2));
}) || schema2[SCALAR$1];
if (schema2.compat) {
const compat = schema2.compat.find((tag2) => {
var _a4;
return tag2.default && ((_a4 = tag2.test) == null ? void 0 : _a4.test(value2));
}) ?? schema2[SCALAR$1];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);
const msg = `Value may be parsed as either ${ts} or ${cs}`;
onError2(token, "TAG_RESOLVE_FAILED", msg, true);
}
}
return tag;
}
function emptyScalarPosition(offset2, before, pos) {
if (before) {
if (pos === null)
pos = before.length;
for (let i = pos - 1; i >= 0; --i) {
let st = before[i];
switch (st.type) {
case "space":
case "comment":
case "newline":
offset2 -= st.source.length;
continue;
}
st = before[++i];
while ((st == null ? void 0 : st.type) === "space") {
offset2 += st.source.length;
st = before[++i];
}
break;
}
}
return offset2;
}
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError2) {
const { spaceBefore, comment, anchor, tag } = props;
let node2;
let isSrcToken = true;
switch (token.type) {
case "alias":
node2 = composeAlias(ctx, token, onError2);
if (anchor || tag)
onError2(token, "ALIAS_PROPS", "An alias node must not specify any properties");
break;
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "block-scalar":
node2 = composeScalar(ctx, token, tag, onError2);
if (anchor)
node2.anchor = anchor.source.substring(1);
break;
case "block-map":
case "block-seq":
case "flow-collection":
node2 = composeCollection(CN, ctx, token, tag, onError2);
if (anchor)
node2.anchor = anchor.source.substring(1);
break;
default: {
const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
onError2(token, "UNEXPECTED_TOKEN", message);
node2 = composeEmptyNode(ctx, token.offset, void 0, null, props, onError2);
isSrcToken = false;
}
}
if (anchor && node2.anchor === "")
onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
if (spaceBefore)
node2.spaceBefore = true;
if (comment) {
if (token.type === "scalar" && token.source === "")
node2.comment = comment;
else
node2.commentBefore = comment;
}
if (ctx.options.keepSourceTokens && isSrcToken)
node2.srcToken = token;
return node2;
}
function composeEmptyNode(ctx, offset2, before, pos, { spaceBefore, comment, anchor, tag, end }, onError2) {
const token = {
type: "scalar",
offset: emptyScalarPosition(offset2, before, pos),
indent: -1,
source: ""
};
const node2 = composeScalar(ctx, token, tag, onError2);
if (anchor) {
node2.anchor = anchor.source.substring(1);
if (node2.anchor === "")
onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
}
if (spaceBefore)
node2.spaceBefore = true;
if (comment) {
node2.comment = comment;
node2.range[2] = end;
}
return node2;
}
function composeAlias({ options: options2 }, { offset: offset2, source, end }, onError2) {
const alias2 = new Alias(source.substring(1));
if (alias2.source === "")
onError2(offset2, "BAD_ALIAS", "Alias cannot be an empty string");
if (alias2.source.endsWith(":"))
onError2(offset2 + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
const valueEnd = offset2 + source.length;
const re = resolveEnd(end, valueEnd, options2.strict, onError2);
alias2.range = [offset2, valueEnd, re.offset];
if (re.comment)
alias2.comment = re.comment;
return alias2;
}
function composeDoc(options2, directives, { offset: offset2, start, value: value2, end }, onError2) {
const opts = Object.assign({ _directives: directives }, options2);
const doc = new Document(void 0, opts);
const ctx = {
atRoot: true,
directives: doc.directives,
options: doc.options,
schema: doc.schema
};
const props = resolveProps(start, {
indicator: "doc-start",
next: value2 ?? (end == null ? void 0 : end[0]),
offset: offset2,
onError: onError2,
parentIndent: 0,
startOnNewline: true
});
if (props.found) {
doc.directives.docStart = true;
if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline)
onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
}
doc.contents = value2 ? composeNode(ctx, value2, props, onError2) : composeEmptyNode(ctx, props.end, start, null, props, onError2);
const contentEnd = doc.contents.range[2];
const re = resolveEnd(end, contentEnd, false, onError2);
if (re.comment)
doc.comment = re.comment;
doc.range = [offset2, contentEnd, re.offset];
return doc;
}
function getErrorPos(src2) {
if (typeof src2 === "number")
return [src2, src2 + 1];
if (Array.isArray(src2))
return src2.length === 2 ? src2 : [src2[0], src2[1]];
const { offset: offset2, source } = src2;
return [offset2, offset2 + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
var _a4;
let comment = "";
let atComment = false;
let afterEmptyLine = false;
for (let i = 0; i < prelude.length; ++i) {
const source = prelude[i];
switch (source[0]) {
case "#":
comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
atComment = true;
afterEmptyLine = false;
break;
case "%":
if (((_a4 = prelude[i + 1]) == null ? void 0 : _a4[0]) !== "#")
i += 1;
atComment = false;
break;
default:
if (!atComment)
afterEmptyLine = true;
atComment = false;
}
}
return { comment, afterEmptyLine };
}
var Composer = class {
constructor(options2 = {}) {
this.doc = null;
this.atDirectives = false;
this.prelude = [];
this.errors = [];
this.warnings = [];
this.onError = (source, code, message, warning) => {
const pos = getErrorPos(source);
if (warning)
this.warnings.push(new YAMLWarning(pos, code, message));
else
this.errors.push(new YAMLParseError(pos, code, message));
};
this.directives = new Directives({ version: options2.version || "1.2" });
this.options = options2;
}
decorate(doc, afterDoc) {
const { comment, afterEmptyLine } = parsePrelude(this.prelude);
if (comment) {
const dc = doc.contents;
if (afterDoc) {
doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
} else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
} else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}
${cb}` : comment;
} else {
const cb = dc.commentBefore;
dc.commentBefore = cb ? `${comment}
${cb}` : comment;
}
}
if (afterDoc) {
Array.prototype.push.apply(doc.errors, this.errors);
Array.prototype.push.apply(doc.warnings, this.warnings);
} else {
doc.errors = this.errors;
doc.warnings = this.warnings;
}
this.prelude = [];
this.errors = [];
this.warnings = [];
}
/**
* Current stream status information.
*
* Mostly useful at the end of input for an empty stream.
*/
streamInfo() {
return {
comment: parsePrelude(this.prelude).comment,
directives: this.directives,
errors: this.errors,
warnings: this.warnings
};
}
/**
* Compose tokens into documents.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*compose(tokens, forceDoc = false, endOffset = -1) {
for (const token of tokens)
yield* this.next(token);
yield* this.end(forceDoc, endOffset);
}
/** Advance the composer by one CST token. */
*next(token) {
switch (token.type) {
case "directive":
this.directives.add(token.source, (offset2, message, warning) => {
const pos = getErrorPos(token);
pos[0] += offset2;
this.onError(pos, "BAD_DIRECTIVE", message, warning);
});
this.prelude.push(token.source);
this.atDirectives = true;
break;
case "document": {
const doc = composeDoc(this.options, this.directives, token, this.onError);
if (this.atDirectives && !doc.directives.docStart)
this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
this.decorate(doc, false);
if (this.doc)
yield this.doc;
this.doc = doc;
this.atDirectives = false;
break;
}
case "byte-order-mark":
case "space":
break;
case "comment":
case "newline":
this.prelude.push(token.source);
break;
case "error": {
const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
const error2 = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
if (this.atDirectives || !this.doc)
this.errors.push(error2);
else
this.doc.errors.push(error2);
break;
}
case "doc-end": {
if (!this.doc) {
const msg = "Unexpected doc-end without preceding document";
this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
break;
}
this.doc.directives.docEnd = true;
const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
this.decorate(this.doc, true);
if (end.comment) {
const dc = this.doc.comment;
this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
}
this.doc.range[2] = end.offset;
break;
}
default:
this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
}
}
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*end(forceDoc = false, endOffset = -1) {
if (this.doc) {
this.decorate(this.doc, true);
yield this.doc;
this.doc = null;
} else if (forceDoc) {
const opts = Object.assign({ _directives: this.directives }, this.options);
const doc = new Document(void 0, opts);
if (this.atDirectives)
this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
doc.range = [0, endOffset, endOffset];
this.decorate(doc, false);
yield doc;
}
}
};
function resolveAsScalar(token, strict = true, onError2) {
if (token) {
const _onError = (pos, code, message) => {
const offset2 = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
if (onError2)
onError2(offset2, code, message);
else
throw new YAMLParseError([offset2, offset2 + 1], code, message);
};
switch (token.type) {
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return resolveFlowScalar(token, strict, _onError);
case "block-scalar":
return resolveBlockScalar({ options: { strict } }, token, _onError);
}
}
return null;
}
function createScalarToken(value2, context) {
const { implicitKey = false, indent, inFlow = false, offset: offset2 = -1, type = "PLAIN" } = context;
const source = stringifyString({ type, value: value2 }, {
implicitKey,
indent: indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
const end = context.end ?? [
{ type: "newline", offset: -1, indent, source: "\n" }
];
switch (source[0]) {
case "|":
case ">": {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
const props = [
{ type: "block-scalar-header", offset: offset2, indent, source: head }
];
if (!addEndtoBlockProps(props, end))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
return { type: "block-scalar", offset: offset2, indent, props, source: body };
}
case '"':
return { type: "double-quoted-scalar", offset: offset2, indent, source, end };
case "'":
return { type: "single-quoted-scalar", offset: offset2, indent, source, end };
default:
return { type: "scalar", offset: offset2, indent, source, end };
}
}
function setScalarValue(token, value2, context = {}) {
let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
let indent = "indent" in token ? token.indent : null;
if (afterKey && typeof indent === "number")
indent += 2;
if (!type)
switch (token.type) {
case "single-quoted-scalar":
type = "QUOTE_SINGLE";
break;
case "double-quoted-scalar":
type = "QUOTE_DOUBLE";
break;
case "block-scalar": {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
break;
}
default:
type = "PLAIN";
}
const source = stringifyString({ type, value: value2 }, {
implicitKey: implicitKey || indent === null,
indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
switch (source[0]) {
case "|":
case ">":
setBlockScalarValue(token, source);
break;
case '"':
setFlowScalarValue(token, source, "double-quoted-scalar");
break;
case "'":
setFlowScalarValue(token, source, "single-quoted-scalar");
break;
default:
setFlowScalarValue(token, source, "scalar");
}
}
function setBlockScalarValue(token, source) {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
if (token.type === "block-scalar") {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
header.source = head;
token.source = body;
} else {
const { offset: offset2 } = token;
const indent = "indent" in token ? token.indent : -1;
const props = [
{ type: "block-scalar-header", offset: offset2, indent, source: head }
];
if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type: "block-scalar", indent, props, source: body });
}
}
function addEndtoBlockProps(props, end) {
if (end)
for (const st of end)
switch (st.type) {
case "space":
case "comment":
props.push(st);
break;
case "newline":
props.push(st);
return true;
}
return false;
}
function setFlowScalarValue(token, source, type) {
switch (token.type) {
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
token.type = type;
token.source = source;
break;
case "block-scalar": {
const end = token.props.slice(1);
let oa = source.length;
if (token.props[0].type === "block-scalar-header")
oa -= token.props[0].source.length;
for (const tok of end)
tok.offset += oa;
delete token.props;
Object.assign(token, { type, source, end });
break;
}
case "block-map":
case "block-seq": {
const offset2 = token.offset + source.length;
const nl = { type: "newline", offset: offset2, indent: token.indent, source: "\n" };
delete token.items;
Object.assign(token, { type, source, end: [nl] });
break;
}
default: {
const indent = "indent" in token ? token.indent : -1;
const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type, indent, source, end });
}
}
}
var stringify$1 = (cst2) => "type" in cst2 ? stringifyToken(cst2) : stringifyItem(cst2);
function stringifyToken(token) {
switch (token.type) {
case "block-scalar": {
let res = "";
for (const tok of token.props)
res += stringifyToken(tok);
return res + token.source;
}
case "block-map":
case "block-seq": {
let res = "";
for (const item of token.items)
res += stringifyItem(item);
return res;
}
case "flow-collection": {
let res = token.start.source;
for (const item of token.items)
res += stringifyItem(item);
for (const st of token.end)
res += st.source;
return res;
}
case "document": {
let res = stringifyItem(token);
if (token.end)
for (const st of token.end)
res += st.source;
return res;
}
default: {
let res = token.source;
if ("end" in token && token.end)
for (const st of token.end)
res += st.source;
return res;
}
}
}
function stringifyItem({ start, key, sep: sep2, value: value2 }) {
let res = "";
for (const st of start)
res += st.source;
if (key)
res += stringifyToken(key);
if (sep2)
for (const st of sep2)
res += st.source;
if (value2)
res += stringifyToken(value2);
return res;
}
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove item");
function visit(cst2, visitor) {
if ("type" in cst2 && cst2.type === "document")
cst2 = { start: cst2.start, value: cst2.value };
_visit(Object.freeze([]), cst2, visitor);
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
visit.itemAtPath = (cst2, path3) => {
let item = cst2;
for (const [field, index] of path3) {
const tok = item == null ? void 0 : item[field];
if (tok && "items" in tok) {
item = tok.items[index];
} else
return void 0;
}
return item;
};
visit.parentCollection = (cst2, path3) => {
const parent = visit.itemAtPath(cst2, path3.slice(0, -1));
const field = path3[path3.length - 1][0];
const coll = parent == null ? void 0 : parent[field];
if (coll && "items" in coll)
return coll;
throw new Error("Parent collection not found");
};
function _visit(path3, item, visitor) {
let ctrl = visitor(item, path3);
if (typeof ctrl === "symbol")
return ctrl;
for (const field of ["key", "value"]) {
const token = item[field];
if (token && "items" in token) {
for (let i = 0; i < token.items.length; ++i) {
const ci = _visit(Object.freeze(path3.concat([[field, i]])), token.items[i], visitor);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
token.items.splice(i, 1);
i -= 1;
}
}
if (typeof ctrl === "function" && field === "key")
ctrl = ctrl(item, path3);
}
}
return typeof ctrl === "function" ? ctrl(item, path3) : ctrl;
}
var BOM = "\uFEFF";
var DOCUMENT = "";
var FLOW_END = "";
var SCALAR = "";
var isCollection = (token) => !!token && "items" in token;
var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
switch (token) {
case BOM:
return "<BOM>";
case DOCUMENT:
return "<DOC>";
case FLOW_END:
return "<FLOW_END>";
case SCALAR:
return "<SCALAR>";
default:
return JSON.stringify(token);
}
}
function tokenType(source) {
switch (source) {
case BOM:
return "byte-order-mark";
case DOCUMENT:
return "doc-mode";
case FLOW_END:
return "flow-error-end";
case SCALAR:
return "scalar";
case "---":
return "doc-start";
case "...":
return "doc-end";
case "":
case "\n":
case "\r\n":
return "newline";
case "-":
return "seq-item-ind";
case "?":
return "explicit-key-ind";
case ":":
return "map-value-ind";
case "{":
return "flow-map-start";
case "}":
return "flow-map-end";
case "[":
return "flow-seq-start";
case "]":
return "flow-seq-end";
case ",":
return "comma";
}
switch (source[0]) {
case " ":
case " ":
return "space";
case "#":
return "comment";
case "%":
return "directive-line";
case "*":
return "alias";
case "&":
return "anchor";
case "!":
return "tag";
case "'":
return "single-quoted-scalar";
case '"':
return "double-quoted-scalar";
case "|":
case ">":
return "block-scalar-header";
}
return null;
}
var cst = {
__proto__: null,
BOM,
DOCUMENT,
FLOW_END,
SCALAR,
createScalarToken,
isCollection,
isScalar,
prettyToken,
resolveAsScalar,
setScalarValue,
stringify: stringify$1,
tokenType,
visit
};
function isEmpty(ch) {
switch (ch) {
case void 0:
case " ":
case "\n":
case "\r":
case " ":
return true;
default:
return false;
}
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r ");
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
var Lexer = class {
constructor() {
this.atEnd = false;
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
this.buffer = "";
this.flowKey = false;
this.flowLevel = 0;
this.indentNext = 0;
this.indentValue = 0;
this.lineEndPos = null;
this.next = null;
this.pos = 0;
}
/**
* Generate YAML tokens from the `source` string. If `incomplete`,
* a part of the last line may be left as a buffer for the next call.
*
* @returns A generator of lexical tokens
*/
*lex(source, incomplete = false) {
if (source) {
if (typeof source !== "string")
throw TypeError("source is not a string");
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = this.next ?? "stream";
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i = this.pos;
let ch = this.buffer[i];
while (ch === " " || ch === " ")
ch = this.buffer[++i];
if (!ch || ch === "#" || ch === "\n")
return true;
if (ch === "\r")
return this.buffer[i + 1] === "\n";
return false;
}
charAt(n2) {
return this.buffer[this.pos + n2];
}
continueScalar(offset2) {
let ch = this.buffer[offset2];
if (this.indentNext > 0) {
let indent = 0;
while (ch === " ")
ch = this.buffer[++indent + offset2];
if (ch === "\r") {
const next = this.buffer[indent + offset2 + 1];
if (next === "\n" || !next && !this.atEnd)
return offset2 + indent + 1;
}
return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset2 + indent : -1;
}
if (ch === "-" || ch === ".") {
const dt = this.buffer.substr(offset2, 3);
if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset2 + 3]))
return -1;
}
return offset2;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== "number" || end !== -1 && end < this.pos) {
end = this.buffer.indexOf("\n", this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === "\r")
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n2) {
return this.pos + n2 <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n2) {
return this.buffer.substr(this.pos, n2);
}
*parseNext(next) {
switch (next) {
case "stream":
return yield* this.parseStream();
case "line-start":
return yield* this.parseLineStart();
case "block-start":
return yield* this.parseBlockStart();
case "doc":
return yield* this.parseDocument();
case "flow":
return yield* this.parseFlowCollection();
case "quoted-scalar":
return yield* this.parseQuotedScalar();
case "block-scalar":
return yield* this.parseBlockScalar();
case "plain-scalar":
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext("stream");
if (line[0] === BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === "%") {
let dirEnd = line.length;
let cs = line.indexOf("#");
while (cs !== -1) {
const ch = line[cs - 1];
if (ch === " " || ch === " ") {
dirEnd = cs - 1;
break;
} else {
cs = line.indexOf("#", cs + 1);
}
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === " " || ch === " ")
dirEnd -= 1;
else
break;
}
const n2 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n2);
this.pushNewline();
return "stream";
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return "stream";
}
yield DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext("line-start");
if (ch === "-" || ch === ".") {
if (!this.atEnd && !this.hasChars(4))
return this.setNext("line-start");
const s = this.peek(3);
if (s === "---" && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return "doc";
} else if (s === "..." && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
return "stream";
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext("block-start");
if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
const n2 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n2;
return yield* this.parseBlockStart();
}
return "doc";
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext("doc");
let n2 = yield* this.pushIndicators();
switch (line[n2]) {
case "#":
yield* this.pushCount(line.length - n2);
case void 0:
yield* this.pushNewline();
return yield* this.parseLineStart();
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
return "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "doc";
case '"':
case "'":
return yield* this.parseQuotedScalar();
case "|":
case ">":
n2 += yield* this.parseBlockScalarHeader();
n2 += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n2);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
} else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext("flow");
if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
if (!atFlowEndMarker) {
this.flowLevel = 0;
yield FLOW_END;
return yield* this.parseLineStart();
}
}
let n2 = 0;
while (line[n2] === ",") {
n2 += yield* this.pushCount(1);
n2 += yield* this.pushSpaces(true);
this.flowKey = false;
}
n2 += yield* this.pushIndicators();
switch (line[n2]) {
case void 0:
return "flow";
case "#":
yield* this.pushCount(line.length - n2);
return "flow";
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? "flow" : "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "flow";
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ":": {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ",") {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return "flow";
}
}
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote3 = this.charAt(0);
let end = this.buffer.indexOf(quote3, this.pos + 1);
if (quote3 === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
} else {
while (end !== -1) {
let n2 = 0;
while (this.buffer[end - 1 - n2] === "\\")
n2 += 1;
if (n2 % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf("\n", this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf("\n", cs);
}
if (nl !== -1) {
end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext("quoted-scalar");
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? "flow" : "doc";
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i = this.pos;
while (true) {
const ch = this.buffer[++i];
if (ch === "+")
this.blockScalarKeep = true;
else if (ch > "0" && ch <= "9")
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== "-")
break;
}
return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
}
*parseBlockScalar() {
let nl = this.pos - 1;
let indent = 0;
let ch;
loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
switch (ch) {
case " ":
indent += 1;
break;
case "\n":
nl = i2;
indent = 0;
break;
case "\r": {
const next = this.buffer[i2 + 1];
if (!next && !this.atEnd)
return this.setNext("block-scalar");
if (next === "\n")
break;
}
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext("block-scalar");
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else {
this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
}
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf("\n", cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext("block-scalar");
nl = this.buffer.length;
}
}
let i = nl + 1;
ch = this.buffer[i];
while (ch === " ")
ch = this.buffer[++i];
if (ch === " ") {
while (ch === " " || ch === " " || ch === "\r" || ch === "\n")
ch = this.buffer[++i];
nl = i - 1;
} else if (!this.blockScalarKeep) {
do {
let i2 = nl - 1;
let ch2 = this.buffer[i2];
if (ch2 === "\r")
ch2 = this.buffer[--i2];
const lastChar = i2;
while (ch2 === " ")
ch2 = this.buffer[--i2];
if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
nl = i2;
else
break;
} while (true);
}
yield SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i = this.pos - 1;
let ch;
while (ch = this.buffer[++i]) {
if (ch === ":") {
const next = this.buffer[i + 1];
if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
break;
end = i;
} else if (isEmpty(ch)) {
let next = this.buffer[i + 1];
if (ch === "\r") {
if (next === "\n") {
i += 1;
ch = "\n";
next = this.buffer[i + 1];
} else
end = i;
}
if (next === "#" || inFlow && flowIndicatorChars.has(next))
break;
if (ch === "\n") {
const cs = this.continueScalar(i + 1);
if (cs === -1)
break;
i = Math.max(i, cs - 2);
}
} else {
if (inFlow && flowIndicatorChars.has(ch))
break;
end = i;
}
}
if (!ch && !this.atEnd)
return this.setNext("plain-scalar");
yield SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? "flow" : "doc";
}
*pushCount(n2) {
if (n2 > 0) {
yield this.buffer.substr(this.pos, n2);
this.pos += n2;
return n2;
}
return 0;
}
*pushToIndex(i, allowEmpty) {
const s = this.buffer.slice(this.pos, i);
if (s) {
yield s;
this.pos += s.length;
return s.length;
} else if (allowEmpty)
yield "";
return 0;
}
*pushIndicators() {
switch (this.charAt(0)) {
case "!":
return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "&":
return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "-":
case "?":
case ":": {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
}
}
}
return 0;
}
*pushTag() {
if (this.charAt(1) === "<") {
let i = this.pos + 2;
let ch = this.buffer[i];
while (!isEmpty(ch) && ch !== ">")
ch = this.buffer[++i];
return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
} else {
let i = this.pos + 1;
let ch = this.buffer[i];
while (ch) {
if (tagChars.has(ch))
ch = this.buffer[++i];
else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
ch = this.buffer[i += 3];
} else
break;
}
return yield* this.pushToIndex(i, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === "\n")
return yield* this.pushCount(1);
else if (ch === "\r" && this.charAt(1) === "\n")
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i = this.pos - 1;
let ch;
do {
ch = this.buffer[++i];
} while (ch === " " || allowTabs && ch === " ");
const n2 = i - this.pos;
if (n2 > 0) {
yield this.buffer.substr(this.pos, n2);
this.pos = i;
}
return n2;
}
*pushUntil(test) {
let i = this.pos;
let ch = this.buffer[i];
while (!test(ch))
ch = this.buffer[++i];
return yield* this.pushToIndex(i, false);
}
};
var LineCounter = class {
constructor() {
this.lineStarts = [];
this.addNewLine = (offset2) => this.lineStarts.push(offset2);
this.linePos = (offset2) => {
let low = 0;
let high = this.lineStarts.length;
while (low < high) {
const mid = low + high >> 1;
if (this.lineStarts[mid] < offset2)
low = mid + 1;
else
high = mid;
}
if (this.lineStarts[low] === offset2)
return { line: low + 1, col: 1 };
if (low === 0)
return { line: 0, col: offset2 };
const start = this.lineStarts[low - 1];
return { line: low, col: offset2 - start + 1 };
};
}
};
function includesToken(list, type) {
for (let i = 0; i < list.length; ++i)
if (list[i].type === type)
return true;
return false;
}
function findNonEmptyIndex(list) {
for (let i = 0; i < list.length; ++i) {
switch (list[i].type) {
case "space":
case "comment":
case "newline":
break;
default:
return i;
}
}
return -1;
}
function isFlowToken(token) {
switch (token == null ? void 0 : token.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "flow-collection":
return true;
default:
return false;
}
}
function getPrevProps(parent) {
switch (parent.type) {
case "document":
return parent.start;
case "block-map": {
const it = parent.items[parent.items.length - 1];
return it.sep ?? it.start;
}
case "block-seq":
return parent.items[parent.items.length - 1].start;
default:
return [];
}
}
function getFirstKeyStartProps(prev) {
var _a4;
if (prev.length === 0)
return [];
let i = prev.length;
loop: while (--i >= 0) {
switch (prev[i].type) {
case "doc-start":
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
case "newline":
break loop;
}
}
while (((_a4 = prev[++i]) == null ? void 0 : _a4.type) === "space") {
}
return prev.splice(i, prev.length);
}
function fixFlowSeqItems(fc) {
if (fc.start.type === "flow-seq-start") {
for (const it of fc.items) {
if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
if (it.key)
it.value = it.key;
delete it.key;
if (isFlowToken(it.value)) {
if (it.value.end)
Array.prototype.push.apply(it.value.end, it.sep);
else
it.value.end = it.sep;
} else
Array.prototype.push.apply(it.start, it.sep);
delete it.sep;
}
}
}
}
var Parser = class {
/**
* @param onNewLine - If defined, called separately with the start position of
* each new line (in `parse()`, including the start of input).
*/
constructor(onNewLine) {
this.atNewLine = true;
this.atScalar = false;
this.indent = 0;
this.offset = 0;
this.onKeyLine = false;
this.stack = [];
this.source = "";
this.type = "";
this.lexer = new Lexer();
this.onNewLine = onNewLine;
}
/**
* Parse `source` as a YAML stream.
* If `incomplete`, a part of the last line may be left as a buffer for the next call.
*
* Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
*
* @returns A generator of tokens representing each directive, document, and other structure.
*/
*parse(source, incomplete = false) {
if (this.onNewLine && this.offset === 0)
this.onNewLine(0);
for (const lexeme of this.lexer.lex(source, incomplete))
yield* this.next(lexeme);
if (!incomplete)
yield* this.end();
}
/**
* Advance the parser by the `source` of one lexical token.
*/
*next(source) {
this.source = source;
if (this.atScalar) {
this.atScalar = false;
yield* this.step();
this.offset += source.length;
return;
}
const type = tokenType(source);
if (!type) {
const message = `Not a YAML token: ${source}`;
yield* this.pop({ type: "error", offset: this.offset, message, source });
this.offset += source.length;
} else if (type === "scalar") {
this.atNewLine = false;
this.atScalar = true;
this.type = "scalar";
} else {
this.type = type;
yield* this.step();
switch (type) {
case "newline":
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine)
this.onNewLine(this.offset + source.length);
break;
case "space":
if (this.atNewLine && source[0] === " ")
this.indent += source.length;
break;
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
if (this.atNewLine)
this.indent += source.length;
break;
case "doc-mode":
case "flow-error-end":
return;
default:
this.atNewLine = false;
}
this.offset += source.length;
}
}
/** Call at end of input to push out any remaining constructions */
*end() {
while (this.stack.length > 0)
yield* this.pop();
}
get sourceToken() {
const st = {
type: this.type,
offset: this.offset,
indent: this.indent,
source: this.source
};
return st;
}
*step() {
const top = this.peek(1);
if (this.type === "doc-end" && (!top || top.type !== "doc-end")) {
while (this.stack.length > 0)
yield* this.pop();
this.stack.push({
type: "doc-end",
offset: this.offset,
source: this.source
});
return;
}
if (!top)
return yield* this.stream();
switch (top.type) {
case "document":
return yield* this.document(top);
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return yield* this.scalar(top);
case "block-scalar":
return yield* this.blockScalar(top);
case "block-map":
return yield* this.blockMap(top);
case "block-seq":
return yield* this.blockSequence(top);
case "flow-collection":
return yield* this.flowCollection(top);
case "doc-end":
return yield* this.documentEnd(top);
}
yield* this.pop();
}
peek(n2) {
return this.stack[this.stack.length - n2];
}
*pop(error2) {
const token = error2 ?? this.stack.pop();
if (!token) {
const message = "Tried to pop an empty stack";
yield { type: "error", offset: this.offset, source: "", message };
} else if (this.stack.length === 0) {
yield token;
} else {
const top = this.peek(1);
if (token.type === "block-scalar") {
token.indent = "indent" in top ? top.indent : 0;
} else if (token.type === "flow-collection" && top.type === "document") {
token.indent = 0;
}
if (token.type === "flow-collection")
fixFlowSeqItems(token);
switch (top.type) {
case "document":
top.value = token;
break;
case "block-scalar":
top.props.push(token);
break;
case "block-map": {
const it = top.items[top.items.length - 1];
if (it.value) {
top.items.push({ start: [], key: token, sep: [] });
this.onKeyLine = true;
return;
} else if (it.sep) {
it.value = token;
} else {
Object.assign(it, { key: token, sep: [] });
this.onKeyLine = !it.explicitKey;
return;
}
break;
}
case "block-seq": {
const it = top.items[top.items.length - 1];
if (it.value)
top.items.push({ start: [], value: token });
else
it.value = token;
break;
}
case "flow-collection": {
const it = top.items[top.items.length - 1];
if (!it || it.value)
top.items.push({ start: [], key: token, sep: [] });
else if (it.sep)
it.value = token;
else
Object.assign(it, { key: token, sep: [] });
return;
}
default:
yield* this.pop();
yield* this.pop(token);
}
if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
const last = token.items[token.items.length - 1];
if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
if (top.type === "document")
top.end = last.start;
else
top.items.push({ start: last.start });
token.items.splice(-1, 1);
}
}
}
}
*stream() {
switch (this.type) {
case "directive-line":
yield { type: "directive", offset: this.offset, source: this.source };
return;
case "byte-order-mark":
case "space":
case "comment":
case "newline":
yield this.sourceToken;
return;
case "doc-mode":
case "doc-start": {
const doc = {
type: "document",
offset: this.offset,
start: []
};
if (this.type === "doc-start")
doc.start.push(this.sourceToken);
this.stack.push(doc);
return;
}
}
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML stream`,
source: this.source
};
}
*document(doc) {
if (doc.value)
return yield* this.lineEnd(doc);
switch (this.type) {
case "doc-start": {
if (findNonEmptyIndex(doc.start) !== -1) {
yield* this.pop();
yield* this.step();
} else
doc.start.push(this.sourceToken);
return;
}
case "anchor":
case "tag":
case "space":
case "comment":
case "newline":
doc.start.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(doc);
if (bv)
this.stack.push(bv);
else {
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML document`,
source: this.source
};
}
}
*scalar(scalar) {
if (this.type === "map-value-ind") {
const prev = getPrevProps(this.peek(2));
const start = getFirstKeyStartProps(prev);
let sep2;
if (scalar.end) {
sep2 = scalar.end;
sep2.push(this.sourceToken);
delete scalar.end;
} else
sep2 = [this.sourceToken];
const map2 = {
type: "block-map",
offset: scalar.offset,
indent: scalar.indent,
items: [{ start, key: scalar, sep: sep2 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map2;
} else
yield* this.lineEnd(scalar);
}
*blockScalar(scalar) {
switch (this.type) {
case "space":
case "comment":
case "newline":
scalar.props.push(this.sourceToken);
return;
case "scalar":
scalar.source = this.source;
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
yield* this.pop();
break;
default:
yield* this.pop();
yield* this.step();
}
}
*blockMap(map2) {
var _a4;
const it = map2.items[map2.items.length - 1];
switch (this.type) {
case "newline":
this.onKeyLine = false;
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if ((last == null ? void 0 : last.type) === "comment")
end == null ? void 0 : end.push(this.sourceToken);
else
map2.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "space":
case "comment":
if (it.value) {
map2.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
if (this.atIndentedComment(it.start, map2.indent)) {
const prev = map2.items[map2.items.length - 2];
const end = (_a4 = prev == null ? void 0 : prev.value) == null ? void 0 : _a4.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
map2.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
}
if (this.indent >= map2.indent) {
const atMapIndent = !this.onKeyLine && this.indent === map2.indent;
const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
let start = [];
if (atNextItem && it.sep && !it.value) {
const nl = [];
for (let i = 0; i < it.sep.length; ++i) {
const st = it.sep[i];
switch (st.type) {
case "newline":
nl.push(i);
break;
case "space":
break;
case "comment":
if (st.indent > map2.indent)
nl.length = 0;
break;
default:
nl.length = 0;
}
}
if (nl.length >= 2)
start = it.sep.splice(nl[1]);
}
switch (this.type) {
case "anchor":
case "tag":
if (atNextItem || it.value) {
start.push(this.sourceToken);
map2.items.push({ start });
this.onKeyLine = true;
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "explicit-key-ind":
if (!it.sep && !it.explicitKey) {
it.start.push(this.sourceToken);
it.explicitKey = true;
} else if (atNextItem || it.value) {
start.push(this.sourceToken);
map2.items.push({ start, explicitKey: true });
} else {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken], explicitKey: true }]
});
}
this.onKeyLine = true;
return;
case "map-value-ind":
if (it.explicitKey) {
if (!it.sep) {
if (includesToken(it.start, "newline")) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else {
const start2 = getFirstKeyStartProps(it.start);
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key: null, sep: [this.sourceToken] }]
});
}
} else if (it.value) {
map2.items.push({ start: [], key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
} else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
const start2 = getFirstKeyStartProps(it.start);
const key = it.key;
const sep2 = it.sep;
sep2.push(this.sourceToken);
delete it.key, delete it.sep;
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key, sep: sep2 }]
});
} else if (start.length > 0) {
it.sep = it.sep.concat(start, this.sourceToken);
} else {
it.sep.push(this.sourceToken);
}
} else {
if (!it.sep) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else if (it.value || atNextItem) {
map2.items.push({ start, key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
});
} else {
it.sep.push(this.sourceToken);
}
}
this.onKeyLine = true;
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs2 = this.flowScalar(this.type);
if (atNextItem || it.value) {
map2.items.push({ start, key: fs2, sep: [] });
this.onKeyLine = true;
} else if (it.sep) {
this.stack.push(fs2);
} else {
Object.assign(it, { key: fs2, sep: [] });
this.onKeyLine = true;
}
return;
}
default: {
const bv = this.startBlockValue(map2);
if (bv) {
if (atMapIndent && bv.type !== "block-seq") {
map2.items.push({ start });
}
this.stack.push(bv);
return;
}
}
}
}
yield* this.pop();
yield* this.step();
}
*blockSequence(seq2) {
var _a4;
const it = seq2.items[seq2.items.length - 1];
switch (this.type) {
case "newline":
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if ((last == null ? void 0 : last.type) === "comment")
end == null ? void 0 : end.push(this.sourceToken);
else
seq2.items.push({ start: [this.sourceToken] });
} else
it.start.push(this.sourceToken);
return;
case "space":
case "comment":
if (it.value)
seq2.items.push({ start: [this.sourceToken] });
else {
if (this.atIndentedComment(it.start, seq2.indent)) {
const prev = seq2.items[seq2.items.length - 2];
const end = (_a4 = prev == null ? void 0 : prev.value) == null ? void 0 : _a4.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
seq2.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
case "anchor":
case "tag":
if (it.value || this.indent <= seq2.indent)
break;
it.start.push(this.sourceToken);
return;
case "seq-item-ind":
if (this.indent !== seq2.indent)
break;
if (it.value || includesToken(it.start, "seq-item-ind"))
seq2.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
}
if (this.indent > seq2.indent) {
const bv = this.startBlockValue(seq2);
if (bv) {
this.stack.push(bv);
return;
}
}
yield* this.pop();
yield* this.step();
}
*flowCollection(fc) {
const it = fc.items[fc.items.length - 1];
if (this.type === "flow-error-end") {
let top;
do {
yield* this.pop();
top = this.peek(1);
} while (top && top.type === "flow-collection");
} else if (fc.end.length === 0) {
switch (this.type) {
case "comma":
case "explicit-key-ind":
if (!it || it.sep)
fc.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
case "map-value-ind":
if (!it || it.value)
fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
Object.assign(it, { key: null, sep: [this.sourceToken] });
return;
case "space":
case "comment":
case "newline":
case "anchor":
case "tag":
if (!it || it.value)
fc.items.push({ start: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
it.start.push(this.sourceToken);
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs2 = this.flowScalar(this.type);
if (!it || it.value)
fc.items.push({ start: [], key: fs2, sep: [] });
else if (it.sep)
this.stack.push(fs2);
else
Object.assign(it, { key: fs2, sep: [] });
return;
}
case "flow-map-end":
case "flow-seq-end":
fc.end.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(fc);
if (bv)
this.stack.push(bv);
else {
yield* this.pop();
yield* this.step();
}
} else {
const parent = this.peek(2);
if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
yield* this.pop();
yield* this.step();
} else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
fixFlowSeqItems(fc);
const sep2 = fc.end.splice(1, fc.end.length);
sep2.push(this.sourceToken);
const map2 = {
type: "block-map",
offset: fc.offset,
indent: fc.indent,
items: [{ start, key: fc, sep: sep2 }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map2;
} else {
yield* this.lineEnd(fc);
}
}
}
flowScalar(type) {
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
};
}
startBlockValue(parent) {
switch (this.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return this.flowScalar(this.type);
case "block-scalar-header":
return {
type: "block-scalar",
offset: this.offset,
indent: this.indent,
props: [this.sourceToken],
source: ""
};
case "flow-map-start":
case "flow-seq-start":
return {
type: "flow-collection",
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
};
case "seq-item-ind":
return {
type: "block-seq",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
};
case "explicit-key-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
start.push(this.sourceToken);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, explicitKey: true }]
};
}
case "map-value-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
};
}
}
return null;
}
atIndentedComment(start, indent) {
if (this.type !== "comment")
return false;
if (this.indent <= indent)
return false;
return start.every((st) => st.type === "newline" || st.type === "space");
}
*documentEnd(docEnd) {
if (this.type !== "doc-mode") {
if (docEnd.end)
docEnd.end.push(this.sourceToken);
else
docEnd.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
*lineEnd(token) {
switch (this.type) {
case "comma":
case "doc-start":
case "doc-end":
case "flow-seq-end":
case "flow-map-end":
case "map-value-ind":
yield* this.pop();
yield* this.step();
break;
case "newline":
this.onKeyLine = false;
case "space":
case "comment":
default:
if (token.end)
token.end.push(this.sourceToken);
else
token.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
};
function parseOptions(options2) {
const prettyErrors = options2.prettyErrors !== false;
const lineCounter = options2.lineCounter || prettyErrors && new LineCounter() || null;
return { lineCounter, prettyErrors };
}
function parseAllDocuments(source, options2 = {}) {
const { lineCounter, prettyErrors } = parseOptions(options2);
const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine);
const composer = new Composer(options2);
const docs = Array.from(composer.compose(parser.parse(source)));
if (prettyErrors && lineCounter)
for (const doc of docs) {
doc.errors.forEach(prettifyError(source, lineCounter));
doc.warnings.forEach(prettifyError(source, lineCounter));
}
if (docs.length > 0)
return docs;
return Object.assign([], { empty: true }, composer.streamInfo());
}
function parseDocument(source, options2 = {}) {
const { lineCounter, prettyErrors } = parseOptions(options2);
const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine);
const composer = new Composer(options2);
let doc = null;
for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
if (!doc)
doc = _doc;
else if (doc.options.logLevel !== "silent") {
doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
break;
}
}
if (prettyErrors && lineCounter) {
doc.errors.forEach(prettifyError(source, lineCounter));
doc.warnings.forEach(prettifyError(source, lineCounter));
}
return doc;
}
function parse$a(src2, reviver, options2) {
let _reviver = void 0;
if (typeof reviver === "function") {
_reviver = reviver;
} else if (options2 === void 0 && reviver && typeof reviver === "object") {
options2 = reviver;
}
const doc = parseDocument(src2, options2);
if (!doc)
return null;
doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning));
if (doc.errors.length > 0) {
if (doc.options.logLevel !== "silent")
throw doc.errors[0];
else
doc.errors = [];
}
return doc.toJS(Object.assign({ reviver: _reviver }, options2));
}
function stringify(value2, replacer, options2) {
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options2 === void 0 && replacer) {
options2 = replacer;
}
if (typeof options2 === "string")
options2 = options2.length;
if (typeof options2 === "number") {
const indent = Math.round(options2);
options2 = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
}
if (value2 === void 0) {
const { keepUndefined } = options2 ?? replacer ?? {};
if (!keepUndefined)
return void 0;
}
return new Document(value2, _replacer, options2).toString(options2);
}
var YAML = {
__proto__: null,
Alias,
CST: cst,
Composer,
Document,
Lexer,
LineCounter,
Pair,
Parser,
Scalar,
Schema,
YAMLError,
YAMLMap,
YAMLParseError,
YAMLSeq,
YAMLWarning,
isAlias,
isCollection: isCollection$1,
isDocument,
isMap,
isNode: isNode$1,
isPair,
isScalar: isScalar$1,
isSeq,
parse: parse$a,
parseAllDocuments,
parseDocument,
stringify,
visit: visit$1,
visitAsync
};
var browser$2 = {
__proto__: null,
Alias,
CST: cst,
Composer,
Document,
Lexer,
LineCounter,
Pair,
Parser,
Scalar,
Schema,
YAMLError,
YAMLMap,
YAMLParseError,
YAMLSeq,
YAMLWarning,
default: YAML,
isAlias,
isCollection: isCollection$1,
isDocument,
isMap,
isNode: isNode$1,
isPair,
isScalar: isScalar$1,
isSeq,
parse: parse$a,
parseAllDocuments,
parseDocument,
stringify,
visit: visit$1,
visitAsync
};
var require$$3 = getAugmentedNamespace(browser$2);
var { createRequire, createRequireFromPath } = import_module.default;
function req$2(name2, rootFile) {
const create = createRequire || createRequireFromPath;
const require3 = create(rootFile);
return require3(name2);
}
var req_1 = req$2;
var req$1 = req_1;
var options = (config2, file) => {
if (config2.parser && typeof config2.parser === "string") {
try {
config2.parser = req$1(config2.parser, file);
} catch (err2) {
throw new Error(`Loading PostCSS Parser failed: ${err2.message}
(@${file})`);
}
}
if (config2.syntax && typeof config2.syntax === "string") {
try {
config2.syntax = req$1(config2.syntax, file);
} catch (err2) {
throw new Error(`Loading PostCSS Syntax failed: ${err2.message}
(@${file})`);
}
}
if (config2.stringifier && typeof config2.stringifier === "string") {
try {
config2.stringifier = req$1(config2.stringifier, file);
} catch (err2) {
throw new Error(`Loading PostCSS Stringifier failed: ${err2.message}
(@${file})`);
}
}
if (config2.plugins) {
delete config2.plugins;
}
return config2;
};
var options_1 = options;
var req = req_1;
var load = (plugin, options2, file) => {
try {
if (options2 === null || options2 === void 0 || Object.keys(options2).length === 0) {
return req(plugin, file);
} else {
return req(plugin, file)(options2);
}
} catch (err2) {
throw new Error(`Loading PostCSS Plugin failed: ${err2.message}
(@${file})`);
}
};
var plugins = (config2, file) => {
let plugins2 = [];
if (Array.isArray(config2.plugins)) {
plugins2 = config2.plugins.filter(Boolean);
} else {
plugins2 = Object.keys(config2.plugins).filter((plugin) => {
return config2.plugins[plugin] !== false ? plugin : "";
}).map((plugin) => {
return load(plugin, config2.plugins[plugin], file);
});
}
if (plugins2.length && plugins2.length > 0) {
plugins2.forEach((plugin, i) => {
if (plugin.default) {
plugin = plugin.default;
}
if (plugin.postcss === true) {
plugin = plugin();
} else if (plugin.postcss) {
plugin = plugin.postcss;
}
if (
// eslint-disable-next-line
!(typeof plugin === "object" && Array.isArray(plugin.plugins) || typeof plugin === "object" && plugin.postcssPlugin || typeof plugin === "function")
) {
throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]
(@${file})`);
}
});
}
return plugins2;
};
var plugins_1 = plugins;
var resolve2 = import_path.default.resolve;
var url$4 = import_url.default;
var config$1 = src$2;
var yaml = require$$3;
var loadOptions = options_1;
var loadPlugins = plugins_1;
var interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
var processResult = (ctx, result) => {
const file = result.filepath || "";
let config2 = interopRequireDefault(result.config).default || {};
if (typeof config2 === "function") {
config2 = config2(ctx);
} else {
config2 = Object.assign({}, config2, ctx);
}
if (!config2.plugins) {
config2.plugins = [];
}
return {
plugins: loadPlugins(config2, file),
options: loadOptions(config2, file),
file
};
};
var createContext = (ctx) => {
ctx = Object.assign({
cwd: process.cwd(),
env: "development"
}, ctx);
if (!ctx.env) {
process.env.NODE_ENV = "development";
}
return ctx;
};
var importDefault = async (filepath) => {
const module = await import(url$4.pathToFileURL(filepath).href);
return module.default;
};
var addTypeScriptLoader = (options2 = {}, loader) => {
const moduleName = "postcss";
return {
...options2,
searchPlaces: [
...options2.searchPlaces || [],
"package.json",
`.${moduleName}rc`,
`.${moduleName}rc.json`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.ts`,
`.${moduleName}rc.cts`,
`.${moduleName}rc.js`,
`.${moduleName}rc.cjs`,
`.${moduleName}rc.mjs`,
`${moduleName}.config.ts`,
`${moduleName}.config.cts`,
`${moduleName}.config.js`,
`${moduleName}.config.cjs`,
`${moduleName}.config.mjs`
],
loaders: {
...options2.loaders,
".yaml": (filepath, content) => yaml.parse(content),
".yml": (filepath, content) => yaml.parse(content),
".js": importDefault,
".cjs": importDefault,
".mjs": importDefault,
".ts": loader,
".cts": loader
}
};
};
var withTypeScriptLoader = (rcFunc) => {
return (ctx, path3, options2) => {
return rcFunc(ctx, path3, addTypeScriptLoader(options2, (configFile) => {
let registerer = { enabled() {
} };
try {
registerer = __require2("ts-node").register({
// transpile to cjs even if compilerOptions.module in tsconfig is not Node16/NodeNext.
moduleTypes: { "**/*.cts": "cjs" }
});
return __require2(configFile);
} catch (err2) {
if (err2.code === "MODULE_NOT_FOUND") {
throw new Error(
`'ts-node' is required for the TypeScript configuration files. Make sure it is installed
Error: ${err2.message}`
);
}
throw err2;
} finally {
registerer.enabled(false);
}
}));
};
};
var rc = withTypeScriptLoader((ctx, path3, options2) => {
ctx = createContext(ctx);
path3 = path3 ? resolve2(path3) : process.cwd();
return config$1.lilconfig("postcss", options2).search(path3).then((result) => {
if (!result) {
throw new Error(`No PostCSS Config found in: ${path3}`);
}
return processResult(ctx, result);
});
});
var src$1 = rc;
var postcssrc = getDefaultExportFromCjs(src$1);
var HashbangComment;
var Identifier;
var JSXIdentifier;
var JSXPunctuator;
var JSXString;
var JSXText;
var KeywordsWithExpressionAfter;
var KeywordsWithNoLineTerminatorAfter;
var LineTerminatorSequence;
var MultiLineComment;
var Newline;
var NumericLiteral;
var Punctuator;
var RegularExpressionLiteral;
var SingleLineComment;
var StringLiteral;
var Template;
var TokensNotPrecedingObjectLiteral;
var TokensPrecedingExpression;
var WhiteSpace;
RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
HashbangComment = /^#!.*/;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
var jsTokens_1 = function* (input, { jsx = false } = {}) {
var braces2, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match2, mode2, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
({ length } = input);
lastIndex = 0;
lastSignificantToken = "";
stack = [
{ tag: "JS" }
];
braces2 = [];
parenNesting = 0;
postfixIncDec = false;
if (match2 = HashbangComment.exec(input)) {
yield {
type: "HashbangComment",
value: match2[0]
};
lastIndex = match2[0].length;
}
while (lastIndex < length) {
mode2 = stack[stack.length - 1];
switch (mode2.tag) {
case "JS":
case "JSNonExpressionParen":
case "InterpolationInTemplate":
case "InterpolationInJSX":
if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
RegularExpressionLiteral.lastIndex = lastIndex;
if (match2 = RegularExpressionLiteral.exec(input)) {
lastIndex = RegularExpressionLiteral.lastIndex;
lastSignificantToken = match2[0];
postfixIncDec = true;
yield {
type: "RegularExpressionLiteral",
value: match2[0],
closed: match2[1] !== void 0 && match2[1] !== "\\"
};
continue;
}
}
Punctuator.lastIndex = lastIndex;
if (match2 = Punctuator.exec(input)) {
punctuator = match2[0];
nextLastIndex = Punctuator.lastIndex;
nextLastSignificantToken = punctuator;
switch (punctuator) {
case "(":
if (lastSignificantToken === "?NonExpressionParenKeyword") {
stack.push({
tag: "JSNonExpressionParen",
nesting: parenNesting
});
}
parenNesting++;
postfixIncDec = false;
break;
case ")":
parenNesting--;
postfixIncDec = true;
if (mode2.tag === "JSNonExpressionParen" && parenNesting === mode2.nesting) {
stack.pop();
nextLastSignificantToken = "?NonExpressionParenEnd";
postfixIncDec = false;
}
break;
case "{":
Punctuator.lastIndex = 0;
isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
braces2.push(isExpression);
postfixIncDec = false;
break;
case "}":
switch (mode2.tag) {
case "InterpolationInTemplate":
if (braces2.length === mode2.nesting) {
Template.lastIndex = lastIndex;
match2 = Template.exec(input);
lastIndex = Template.lastIndex;
lastSignificantToken = match2[0];
if (match2[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
postfixIncDec = false;
yield {
type: "TemplateMiddle",
value: match2[0]
};
} else {
stack.pop();
postfixIncDec = true;
yield {
type: "TemplateTail",
value: match2[0],
closed: match2[1] === "`"
};
}
continue;
}
break;
case "InterpolationInJSX":
if (braces2.length === mode2.nesting) {
stack.pop();
lastIndex += 1;
lastSignificantToken = "}";
yield {
type: "JSXPunctuator",
value: "}"
};
continue;
}
}
postfixIncDec = braces2.pop();
nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
break;
case "]":
postfixIncDec = true;
break;
case "++":
case "--":
nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
break;
case "<":
if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
stack.push({ tag: "JSXTag" });
lastIndex += 1;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: punctuator
};
continue;
}
postfixIncDec = false;
break;
default:
postfixIncDec = false;
}
lastIndex = nextLastIndex;
lastSignificantToken = nextLastSignificantToken;
yield {
type: "Punctuator",
value: punctuator
};
continue;
}
Identifier.lastIndex = lastIndex;
if (match2 = Identifier.exec(input)) {
lastIndex = Identifier.lastIndex;
nextLastSignificantToken = match2[0];
switch (match2[0]) {
case "for":
case "if":
case "while":
case "with":
if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
nextLastSignificantToken = "?NonExpressionParenKeyword";
}
}
lastSignificantToken = nextLastSignificantToken;
postfixIncDec = !KeywordsWithExpressionAfter.test(match2[0]);
yield {
type: match2[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
value: match2[0]
};
continue;
}
StringLiteral.lastIndex = lastIndex;
if (match2 = StringLiteral.exec(input)) {
lastIndex = StringLiteral.lastIndex;
lastSignificantToken = match2[0];
postfixIncDec = true;
yield {
type: "StringLiteral",
value: match2[0],
closed: match2[2] !== void 0
};
continue;
}
NumericLiteral.lastIndex = lastIndex;
if (match2 = NumericLiteral.exec(input)) {
lastIndex = NumericLiteral.lastIndex;
lastSignificantToken = match2[0];
postfixIncDec = true;
yield {
type: "NumericLiteral",
value: match2[0]
};
continue;
}
Template.lastIndex = lastIndex;
if (match2 = Template.exec(input)) {
lastIndex = Template.lastIndex;
lastSignificantToken = match2[0];
if (match2[1] === "${") {
lastSignificantToken = "?InterpolationInTemplate";
stack.push({
tag: "InterpolationInTemplate",
nesting: braces2.length
});
postfixIncDec = false;
yield {
type: "TemplateHead",
value: match2[0]
};
} else {
postfixIncDec = true;
yield {
type: "NoSubstitutionTemplate",
value: match2[0],
closed: match2[1] === "`"
};
}
continue;
}
break;
case "JSXTag":
case "JSXTagEnd":
JSXPunctuator.lastIndex = lastIndex;
if (match2 = JSXPunctuator.exec(input)) {
lastIndex = JSXPunctuator.lastIndex;
nextLastSignificantToken = match2[0];
switch (match2[0]) {
case "<":
stack.push({ tag: "JSXTag" });
break;
case ">":
stack.pop();
if (lastSignificantToken === "/" || mode2.tag === "JSXTagEnd") {
nextLastSignificantToken = "?JSX";
postfixIncDec = true;
} else {
stack.push({ tag: "JSXChildren" });
}
break;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces2.length
});
nextLastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
break;
case "/":
if (lastSignificantToken === "<") {
stack.pop();
if (stack[stack.length - 1].tag === "JSXChildren") {
stack.pop();
}
stack.push({ tag: "JSXTagEnd" });
}
}
lastSignificantToken = nextLastSignificantToken;
yield {
type: "JSXPunctuator",
value: match2[0]
};
continue;
}
JSXIdentifier.lastIndex = lastIndex;
if (match2 = JSXIdentifier.exec(input)) {
lastIndex = JSXIdentifier.lastIndex;
lastSignificantToken = match2[0];
yield {
type: "JSXIdentifier",
value: match2[0]
};
continue;
}
JSXString.lastIndex = lastIndex;
if (match2 = JSXString.exec(input)) {
lastIndex = JSXString.lastIndex;
lastSignificantToken = match2[0];
yield {
type: "JSXString",
value: match2[0],
closed: match2[2] !== void 0
};
continue;
}
break;
case "JSXChildren":
JSXText.lastIndex = lastIndex;
if (match2 = JSXText.exec(input)) {
lastIndex = JSXText.lastIndex;
lastSignificantToken = match2[0];
yield {
type: "JSXText",
value: match2[0]
};
continue;
}
switch (input[lastIndex]) {
case "<":
stack.push({ tag: "JSXTag" });
lastIndex++;
lastSignificantToken = "<";
yield {
type: "JSXPunctuator",
value: "<"
};
continue;
case "{":
stack.push({
tag: "InterpolationInJSX",
nesting: braces2.length
});
lastIndex++;
lastSignificantToken = "?InterpolationInJSX";
postfixIncDec = false;
yield {
type: "JSXPunctuator",
value: "{"
};
continue;
}
}
WhiteSpace.lastIndex = lastIndex;
if (match2 = WhiteSpace.exec(input)) {
lastIndex = WhiteSpace.lastIndex;
yield {
type: "WhiteSpace",
value: match2[0]
};
continue;
}
LineTerminatorSequence.lastIndex = lastIndex;
if (match2 = LineTerminatorSequence.exec(input)) {
lastIndex = LineTerminatorSequence.lastIndex;
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
yield {
type: "LineTerminatorSequence",
value: match2[0]
};
continue;
}
MultiLineComment.lastIndex = lastIndex;
if (match2 = MultiLineComment.exec(input)) {
lastIndex = MultiLineComment.lastIndex;
if (Newline.test(match2[0])) {
postfixIncDec = false;
if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
lastSignificantToken = "?NoLineTerminatorHere";
}
}
yield {
type: "MultiLineComment",
value: match2[0],
closed: match2[1] !== void 0
};
continue;
}
SingleLineComment.lastIndex = lastIndex;
if (match2 = SingleLineComment.exec(input)) {
lastIndex = SingleLineComment.lastIndex;
postfixIncDec = false;
yield {
type: "SingleLineComment",
value: match2[0]
};
continue;
}
firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
lastIndex += firstCodePoint.length;
lastSignificantToken = firstCodePoint;
postfixIncDec = false;
yield {
type: mode2.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
value: firstCodePoint
};
}
return void 0;
};
var jsTokens = getDefaultExportFromCjs(jsTokens_1);
function stripLiteralJsTokens(code, options2) {
const FILL = " ";
const FILL_COMMENT = " ";
let result = "";
const tokens = [];
for (const token of jsTokens(code, { jsx: false })) {
tokens.push(token);
if (token.type === "SingleLineComment") {
result += FILL_COMMENT.repeat(token.value.length);
continue;
}
if (token.type === "MultiLineComment") {
result += token.value.replace(/[^\n]/g, FILL_COMMENT);
continue;
}
if (token.type === "StringLiteral") {
if (!token.closed) {
result += token.value;
continue;
}
const body = token.value.slice(1, -1);
{
result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
continue;
}
}
if (token.type === "NoSubstitutionTemplate") {
const body = token.value.slice(1, -1);
{
result += `\`${body.replace(/[^\n]/g, FILL)}\``;
continue;
}
}
if (token.type === "RegularExpressionLiteral") {
const body = token.value;
{
result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
continue;
}
}
if (token.type === "TemplateHead") {
const body = token.value.slice(1, -2);
{
result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
continue;
}
}
if (token.type === "TemplateTail") {
const body = token.value.slice(0, -2);
{
result += `}${body.replace(/[^\n]/g, FILL)}\``;
continue;
}
}
if (token.type === "TemplateMiddle") {
const body = token.value.slice(1, -2);
{
result += `}${body.replace(/[^\n]/g, FILL)}\${`;
continue;
}
}
result += token.value;
}
return {
result,
tokens
};
}
function stripLiteral(code, options2) {
return stripLiteralDetailed(code).result;
}
function stripLiteralDetailed(code, options2) {
return stripLiteralJsTokens(code);
}
var main$1 = { exports: {} };
var name = "dotenv";
var version$1 = "16.4.5";
var description = "Loads environment variables from .env file";
var main = "lib/main.js";
var types = "lib/main.d.ts";
var exports = {
".": {
types: "./lib/main.d.ts",
require: "./lib/main.js",
"default": "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
};
var scripts = {
"dts-check": "tsc --project tests/types/tsconfig.json",
lint: "standard",
"lint-readme": "standard-markdown",
pretest: "npm run lint && npm run dts-check",
test: "tap tests/*.js --100 -Rspec",
"test:coverage": "tap --coverage-report=lcov",
prerelease: "npm test",
release: "standard-version"
};
var repository = {
type: "git",
url: "git://github.com/motdotla/dotenv.git"
};
var funding = "https://dotenvx.com";
var keywords = [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
];
var readmeFilename = "README.md";
var license = "BSD-2-Clause";
var devDependencies = {
"@definitelytyped/dtslint": "^0.0.133",
"@types/node": "^18.11.3",
decache: "^4.6.1",
sinon: "^14.0.1",
standard: "^17.0.0",
"standard-markdown": "^7.1.0",
"standard-version": "^9.5.0",
tap: "^16.3.0",
tar: "^6.1.11",
typescript: "^4.8.4"
};
var engines = {
node: ">=12"
};
var browser$1 = {
fs: false
};
var require$$4 = {
name,
version: version$1,
description,
main,
types,
exports,
scripts,
repository,
funding,
keywords,
readmeFilename,
license,
devDependencies,
engines,
browser: browser$1
};
var fs$9 = import_fs.default;
var path$9 = import_path.default;
var os$2 = import_os.default;
var crypto$1 = import_crypto.default;
var packageJson = require$$4;
var version2 = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse$9(src2) {
const obj = {};
let lines = src2.toString();
lines = lines.replace(/\r\n?/mg, "\n");
let match2;
while ((match2 = LINE.exec(lines)) != null) {
const key = match2[1];
let value2 = match2[2] || "";
value2 = value2.trim();
const maybeQuote = value2[0];
value2 = value2.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === '"') {
value2 = value2.replace(/\\n/g, "\n");
value2 = value2.replace(/\\r/g, "\r");
}
obj[key] = value2;
}
return obj;
}
function _parseVault(options2) {
const vaultPath = _vaultPath(options2);
const result = DotenvModule.configDotenv({ path: vaultPath });
if (!result.parsed) {
const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
err2.code = "MISSING_DATA";
throw err2;
}
const keys = _dotenvKey(options2).split(",");
const length = keys.length;
let decrypted;
for (let i = 0; i < length; i++) {
try {
const key = keys[i].trim();
const attrs = _instructions(result, key);
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
break;
} catch (error2) {
if (i + 1 >= length) {
throw error2;
}
}
}
return DotenvModule.parse(decrypted);
}
function _log(message) {
console.log(`[dotenv@${version2}][INFO] ${message}`);
}
function _warn(message) {
console.log(`[dotenv@${version2}][WARN] ${message}`);
}
function _debug(message) {
console.log(`[dotenv@${version2}][DEBUG] ${message}`);
}
function _dotenvKey(options2) {
if (options2 && options2.DOTENV_KEY && options2.DOTENV_KEY.length > 0) {
return options2.DOTENV_KEY;
}
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY;
}
return "";
}
function _instructions(result, dotenvKey) {
let uri;
try {
uri = new URL(dotenvKey);
} catch (error2) {
if (error2.code === "ERR_INVALID_URL") {
const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
throw error2;
}
const key = uri.password;
if (!key) {
const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
const environment = uri.searchParams.get("environment");
if (!environment) {
const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
}
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
const ciphertext = result.parsed[environmentKey];
if (!ciphertext) {
const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
throw err2;
}
return { ciphertext, key };
}
function _vaultPath(options2) {
let possibleVaultPath = null;
if (options2 && options2.path && options2.path.length > 0) {
if (Array.isArray(options2.path)) {
for (const filepath of options2.path) {
if (fs$9.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
}
}
} else {
possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
}
} else {
possibleVaultPath = path$9.resolve(process.cwd(), ".env.vault");
}
if (fs$9.existsSync(possibleVaultPath)) {
return possibleVaultPath;
}
return null;
}
function _resolveHome(envPath) {
return envPath[0] === "~" ? path$9.join(os$2.homedir(), envPath.slice(1)) : envPath;
}
function _configVault(options2) {
_log("Loading env from encrypted .env.vault");
const parsed = DotenvModule._parseVault(options2);
let processEnv = process.env;
if (options2 && options2.processEnv != null) {
processEnv = options2.processEnv;
}
DotenvModule.populate(processEnv, parsed, options2);
return { parsed };
}
function configDotenv(options2) {
const dotenvPath = path$9.resolve(process.cwd(), ".env");
let encoding = "utf8";
const debug2 = Boolean(options2 && options2.debug);
if (options2 && options2.encoding) {
encoding = options2.encoding;
} else {
if (debug2) {
_debug("No encoding is specified. UTF-8 is used by default");
}
}
let optionPaths = [dotenvPath];
if (options2 && options2.path) {
if (!Array.isArray(options2.path)) {
optionPaths = [_resolveHome(options2.path)];
} else {
optionPaths = [];
for (const filepath of options2.path) {
optionPaths.push(_resolveHome(filepath));
}
}
}
let lastError;
const parsedAll = {};
for (const path3 of optionPaths) {
try {
const parsed = DotenvModule.parse(fs$9.readFileSync(path3, { encoding }));
DotenvModule.populate(parsedAll, parsed, options2);
} catch (e2) {
if (debug2) {
_debug(`Failed to load ${path3} ${e2.message}`);
}
lastError = e2;
}
}
let processEnv = process.env;
if (options2 && options2.processEnv != null) {
processEnv = options2.processEnv;
}
DotenvModule.populate(processEnv, parsedAll, options2);
if (lastError) {
return { parsed: parsedAll, error: lastError };
} else {
return { parsed: parsedAll };
}
}
function config(options2) {
if (_dotenvKey(options2).length === 0) {
return DotenvModule.configDotenv(options2);
}
const vaultPath = _vaultPath(options2);
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
return DotenvModule.configDotenv(options2);
}
return DotenvModule._configVault(options2);
}
function decrypt(encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), "hex");
let ciphertext = Buffer.from(encrypted, "base64");
const nonce = ciphertext.subarray(0, 12);
const authTag = ciphertext.subarray(-16);
ciphertext = ciphertext.subarray(12, -16);
try {
const aesgcm = crypto$1.createDecipheriv("aes-256-gcm", key, nonce);
aesgcm.setAuthTag(authTag);
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
} catch (error2) {
const isRange = error2 instanceof RangeError;
const invalidKeyLength = error2.message === "Invalid key length";
const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
if (isRange || invalidKeyLength) {
const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
err2.code = "INVALID_DOTENV_KEY";
throw err2;
} else if (decryptionFailed) {
const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
err2.code = "DECRYPTION_FAILED";
throw err2;
} else {
throw error2;
}
}
}
function populate(processEnv, parsed, options2 = {}) {
const debug2 = Boolean(options2 && options2.debug);
const override = Boolean(options2 && options2.override);
if (typeof parsed !== "object") {
const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
err2.code = "OBJECT_REQUIRED";
throw err2;
}
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key];
}
if (debug2) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`);
} else {
_debug(`"${key}" is already defined and was NOT overwritten`);
}
}
} else {
processEnv[key] = parsed[key];
}
}
}
var DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse: parse$9,
populate
};
main$1.exports.configDotenv = DotenvModule.configDotenv;
main$1.exports._configVault = DotenvModule._configVault;
main$1.exports._parseVault = DotenvModule._parseVault;
main$1.exports.config = DotenvModule.config;
main$1.exports.decrypt = DotenvModule.decrypt;
var parse_1$1 = main$1.exports.parse = DotenvModule.parse;
main$1.exports.populate = DotenvModule.populate;
main$1.exports = DotenvModule;
var DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;
function _resolveEscapeSequences(value2) {
return value2.replace(/\\\$/g, "$");
}
function interpolate(value2, processEnv, parsed) {
return value2.replace(DOTENV_SUBSTITUTION_REGEX, (match2, escaped2, dollarSign, openBrace, key, defaultValue, closeBrace) => {
if (escaped2 === "\\") {
return match2.slice(1);
} else {
if (processEnv[key]) {
if (processEnv[key] === parsed[key]) {
return processEnv[key];
} else {
return interpolate(processEnv[key], processEnv, parsed);
}
}
if (parsed[key]) {
if (parsed[key] === value2) {
return parsed[key];
} else {
return interpolate(parsed[key], processEnv, parsed);
}
}
if (defaultValue) {
if (defaultValue.startsWith("$")) {
return interpolate(defaultValue, processEnv, parsed);
} else {
return defaultValue;
}
}
return "";
}
});
}
function expand(options2) {
let processEnv = process.env;
if (options2 && options2.processEnv != null) {
processEnv = options2.processEnv;
}
for (const key in options2.parsed) {
let value2 = options2.parsed[key];
const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key);
if (inProcessEnv) {
if (processEnv[key] === options2.parsed[key]) {
value2 = interpolate(value2, processEnv, options2.parsed);
} else {
value2 = processEnv[key];
}
} else {
value2 = interpolate(value2, processEnv, options2.parsed);
}
options2.parsed[key] = _resolveEscapeSequences(value2);
}
for (const processKey in options2.parsed) {
processEnv[processKey] = options2.parsed[processKey];
}
return options2;
}
var expand_1 = expand;
function getEnvFilesForMode(mode2, envDir) {
return [
/** default file */
`.env`,
/** local file */
`.env.local`,
/** mode file */
`.env.${mode2}`,
/** mode local file */
`.env.${mode2}.local`
].map((file) => normalizePath$3(import_node_path3.default.join(envDir, file)));
}
function loadEnv(mode2, envDir, prefixes = "VITE_") {
if (mode2 === "local") {
throw new Error(
`"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`
);
}
prefixes = arraify(prefixes);
const env2 = {};
const envFiles = getEnvFilesForMode(mode2, envDir);
const parsed = Object.fromEntries(
envFiles.flatMap((filePath) => {
var _a4;
if (!((_a4 = tryStatSync(filePath)) == null ? void 0 : _a4.isFile())) return [];
return Object.entries(parse_1$1(import_node_fs2.default.readFileSync(filePath)));
})
);
if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) {
process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
}
if (parsed.BROWSER && process.env.BROWSER === void 0) {
process.env.BROWSER = parsed.BROWSER;
}
if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) {
process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
}
const processEnv = { ...process.env };
expand_1({ parsed, processEnv });
for (const [key, value2] of Object.entries(parsed)) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env2[key] = value2;
}
}
for (const key in process.env) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env2[key] = process.env[key];
}
}
return env2;
}
function resolveEnvPrefix({
envPrefix = "VITE_"
}) {
envPrefix = arraify(envPrefix);
if (envPrefix.includes("")) {
throw new Error(
`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
);
}
return envPrefix;
}
var modulePreloadPolyfillId = "vite/modulepreload-polyfill";
var resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
function modulePreloadPolyfillPlugin(config2) {
const skip = config2.command !== "build" || config2.build.ssr;
let polyfillString;
return {
name: "vite:modulepreload-polyfill",
resolveId(id) {
if (id === modulePreloadPolyfillId) {
return resolvedModulePreloadPolyfillId;
}
},
load(id) {
if (id === resolvedModulePreloadPolyfillId) {
if (skip) {
return "";
}
if (!polyfillString) {
polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
}
return { code: polyfillString, moduleSideEffects: true };
}
}
};
}
function polyfill() {
const relList = document.createElement("link").relList;
if (relList && relList.supports && relList.supports("modulepreload")) {
return;
}
for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
processPreload(link);
}
new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type !== "childList") {
continue;
}
for (const node2 of mutation.addedNodes) {
if (node2.tagName === "LINK" && node2.rel === "modulepreload")
processPreload(node2);
}
}
}).observe(document, { childList: true, subtree: true });
function getFetchOpts(link) {
const fetchOpts = {};
if (link.integrity) fetchOpts.integrity = link.integrity;
if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
if (link.crossOrigin === "use-credentials")
fetchOpts.credentials = "include";
else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
else fetchOpts.credentials = "same-origin";
return fetchOpts;
}
function processPreload(link) {
if (link.ep)
return;
link.ep = true;
const fetchOpts = getFetchOpts(link);
fetch(link.href, fetchOpts);
}
}
var htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/;
var isHtmlProxyRE = /\?html-proxy\b/;
var inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
var inlineImportRE = new RegExp(`(?<!(?<!\\.\\.)\\.)\\bimport\\s*\\(("(?:[^"]|(?<=\\\\)")*"|'(?:[^']|(?<=\\\\)')*')\\)`, "dg");
var htmlLangRE = /\.(?:html|htm)$/;
var spaceRe = /[\t\n\f\r ]/;
var importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
var moduleScriptRE = /[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
var modulePreloadLinkRE = /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
var importMapAppendRE = new RegExp(
[moduleScriptRE, modulePreloadLinkRE].map((r2) => r2.source).join("|"),
"i"
);
var isHTMLProxy = (id) => isHtmlProxyRE.test(id);
var isHTMLRequest = (request) => htmlLangRE.test(request);
var htmlProxyMap = /* @__PURE__ */ new WeakMap();
var htmlProxyResult = /* @__PURE__ */ new Map();
function htmlInlineProxyPlugin(config2) {
htmlProxyMap.set(config2, /* @__PURE__ */ new Map());
return {
name: "vite:html-inline-proxy",
resolveId(id) {
if (isHTMLProxy(id)) {
return id;
}
},
load(id) {
var _a4;
const proxyMatch = id.match(htmlProxyRE$1);
if (proxyMatch) {
const index = Number(proxyMatch[1]);
const file = cleanUrl(id);
const url2 = file.replace(normalizePath$3(config2.root), "");
const result = (_a4 = htmlProxyMap.get(config2).get(url2)) == null ? void 0 : _a4[index];
if (result) {
return result;
} else {
throw new Error(`No matching HTML proxy module found from ${id}`);
}
}
}
};
}
function addToHTMLProxyCache(config2, filePath, index, result) {
if (!htmlProxyMap.get(config2)) {
htmlProxyMap.set(config2, /* @__PURE__ */ new Map());
}
if (!htmlProxyMap.get(config2).get(filePath)) {
htmlProxyMap.get(config2).set(filePath, []);
}
htmlProxyMap.get(config2).get(filePath)[index] = result;
}
function addToHTMLProxyTransformResult(hash2, code) {
htmlProxyResult.set(hash2, code);
}
var assetAttrsConfig = {
link: ["href"],
video: ["src", "poster"],
source: ["src", "srcset"],
img: ["src", "srcset"],
image: ["xlink:href", "href"],
use: ["xlink:href", "href"]
};
var noInlineLinkRels = /* @__PURE__ */ new Set([
"icon",
"apple-touch-icon",
"apple-touch-startup-image",
"manifest"
]);
var isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
function nodeIsElement(node2) {
return node2.nodeName[0] !== "#";
}
function traverseNodes(node2, visitor) {
visitor(node2);
if (nodeIsElement(node2) || node2.nodeName === "#document" || node2.nodeName === "#document-fragment") {
node2.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
}
}
async function traverseHtml(html, filePath, visitor) {
const { parse: parse4 } = await import("./dep-D-7KCb9p-QLXNKUUS.js");
const ast = parse4(html, {
scriptingEnabled: false,
// parse inside <noscript>
sourceCodeLocationInfo: true,
onParseError: (e2) => {
handleParseError(e2, html, filePath);
}
});
traverseNodes(ast, visitor);
}
function getScriptInfo(node2) {
var _a4;
let src2;
let sourceCodeLocation;
let isModule = false;
let isAsync = false;
for (const p of node2.attrs) {
if (p.prefix !== void 0) continue;
if (p.name === "src") {
if (!src2) {
src2 = p;
sourceCodeLocation = (_a4 = node2.sourceCodeLocation) == null ? void 0 : _a4.attrs["src"];
}
} else if (p.name === "type" && p.value && p.value === "module") {
isModule = true;
} else if (p.name === "async") {
isAsync = true;
}
}
return { src: src2, sourceCodeLocation, isModule, isAsync };
}
var attrValueStartRE = /=\s*(.)/;
function overwriteAttrValue(s, sourceCodeLocation, newValue) {
const srcString = s.slice(
sourceCodeLocation.startOffset,
sourceCodeLocation.endOffset
);
const valueStart = srcString.match(attrValueStartRE);
if (!valueStart) {
throw new Error(
`[vite:html] internal error, failed to overwrite attribute value`
);
}
const wrapOffset = valueStart[1] === '"' || valueStart[1] === "'" ? 1 : 0;
const valueOffset = valueStart.index + valueStart[0].length - 1;
s.update(
sourceCodeLocation.startOffset + valueOffset + wrapOffset,
sourceCodeLocation.endOffset - wrapOffset,
newValue
);
return s;
}
function formatParseError(parserError, id, html) {
const formattedError = {
code: parserError.code,
message: `parse5 error code ${parserError.code}`,
frame: generateCodeFrame(
html,
parserError.startOffset,
parserError.endOffset
),
loc: {
file: id,
line: parserError.startLine,
column: parserError.startCol
}
};
return formattedError;
}
function handleParseError(parserError, html, filePath) {
switch (parserError.code) {
case "missing-doctype":
return;
case "abandoned-head-element-child":
return;
case "duplicate-attribute":
return;
case "non-void-html-element-start-tag-with-trailing-solidus":
return;
}
const parseError = formatParseError(parserError, filePath, html);
throw new Error(
`Unable to parse HTML; ${parseError.message}
at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}
${parseError.frame}`
);
}
function buildHtmlPlugin(config2) {
const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
config2.plugins,
config2.logger
);
preHooks.unshift(injectCspNonceMetaTagHook(config2));
preHooks.unshift(preImportMapHook(config2));
preHooks.push(htmlEnvHook(config2));
postHooks.push(injectNonceAttributeTagHook(config2));
postHooks.push(postImportMapHook());
const processedHtml = /* @__PURE__ */ new Map();
const isExcludedUrl = (url2) => url2[0] === "#" || isExternalUrl(url2) || isDataUrl(url2);
isAsyncScriptMap.set(config2, /* @__PURE__ */ new Map());
return {
name: "vite:build-html",
async transform(html, id) {
var _a4, _b3;
if (id.endsWith(".html")) {
id = normalizePath$3(id);
const relativeUrlPath = import_node_path3.default.posix.relative(config2.root, id);
const publicPath = `/${relativeUrlPath}`;
const publicBase = getBaseInHTML(relativeUrlPath, config2);
const publicToRelative = (filename, importer) => publicBase + filename;
const toOutputPublicFilePath = (url2) => toOutputFilePathInHtml(
url2.slice(1),
"public",
relativeUrlPath,
"html",
config2,
publicToRelative
);
const nodeStartWithLeadingWhitespace = (node2) => {
const startOffset = node2.sourceCodeLocation.startOffset;
if (startOffset === 0) return 0;
const lineStartOffset = startOffset - node2.sourceCodeLocation.startCol;
let isLineEmpty = false;
try {
const line = s.slice(Math.max(0, lineStartOffset), startOffset);
isLineEmpty = !line.trim();
} catch {
}
return isLineEmpty ? lineStartOffset : startOffset;
};
html = await applyHtmlTransforms(html, preHooks, {
path: publicPath,
filename: id
});
let js = "";
const s = new MagicString(html);
const scriptUrls = [];
const styleUrls = [];
let inlineModuleIndex = -1;
let everyScriptIsAsync = true;
let someScriptsAreAsync = false;
let someScriptsAreDefer = false;
const assetUrlsPromises = [];
const namedOutput = Object.keys(
((_b3 = (_a4 = config2 == null ? void 0 : config2.build) == null ? void 0 : _a4.rollupOptions) == null ? void 0 : _b3.input) || {}
);
const processAssetUrl = async (url2, shouldInline2) => {
if (url2 !== "" && // Empty attribute
!namedOutput.includes(url2) && // Direct reference to named output
!namedOutput.includes(removeLeadingSlash(url2))) {
try {
return await urlToBuiltUrl(url2, id, config2, this, shouldInline2);
} catch (e2) {
if (e2.code !== "ENOENT") {
throw e2;
}
}
}
return url2;
};
await traverseHtml(html, id, (node2) => {
if (!nodeIsElement(node2)) {
return;
}
let shouldRemove = false;
if (node2.nodeName === "script") {
const { src: src2, sourceCodeLocation, isModule, isAsync } = getScriptInfo(node2);
const url2 = src2 && src2.value;
const isPublicFile = !!(url2 && checkPublicFile(url2, config2));
if (isPublicFile) {
overwriteAttrValue(
s,
sourceCodeLocation,
partialEncodeURIPath(toOutputPublicFilePath(url2))
);
}
if (isModule) {
inlineModuleIndex++;
if (url2 && !isExcludedUrl(url2) && !isPublicFile) {
js += `
import ${JSON.stringify(url2)}`;
shouldRemove = true;
} else if (node2.childNodes.length) {
const scriptNode = node2.childNodes.pop();
const contents = scriptNode.value;
const filePath = id.replace(normalizePath$3(config2.root), "");
addToHTMLProxyCache(config2, filePath, inlineModuleIndex, {
code: contents
});
js += `
import "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
shouldRemove = true;
}
everyScriptIsAsync && (everyScriptIsAsync = isAsync);
someScriptsAreAsync || (someScriptsAreAsync = isAsync);
someScriptsAreDefer || (someScriptsAreDefer = !isAsync);
} else if (url2 && !isPublicFile) {
if (!isExcludedUrl(url2)) {
config2.logger.warn(
`<script src="${url2}"> in "${publicPath}" can't be bundled without type="module" attribute`
);
}
} else if (node2.childNodes.length) {
const scriptNode = node2.childNodes.pop();
scriptUrls.push(
...extractImportExpressionFromClassicScript(scriptNode)
);
}
}
const assetAttrs = assetAttrsConfig[node2.nodeName];
if (assetAttrs) {
for (const p of node2.attrs) {
const attrKey = getAttrKey(p);
if (p.value && assetAttrs.includes(attrKey)) {
if (attrKey === "srcset") {
assetUrlsPromises.push(
(async () => {
const processedEncodedUrl = await processSrcSet(
p.value,
async ({ url: url2 }) => {
const decodedUrl = decodeURI(url2);
if (!isExcludedUrl(decodedUrl)) {
const result = await processAssetUrl(url2);
return result !== decodedUrl ? encodeURIPath(result) : url2;
}
return url2;
}
);
if (processedEncodedUrl !== p.value) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node2, attrKey),
processedEncodedUrl
);
}
})()
);
} else {
const url2 = decodeURI(p.value);
if (checkPublicFile(url2, config2)) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node2, attrKey),
partialEncodeURIPath(toOutputPublicFilePath(url2))
);
} else if (!isExcludedUrl(url2)) {
if (node2.nodeName === "link" && isCSSRequest(url2) && // should not be converted if following attributes are present (#6748)
!node2.attrs.some(
(p2) => p2.prefix === void 0 && (p2.name === "media" || p2.name === "disabled")
)) {
const importExpression = `
import ${JSON.stringify(url2)}`;
styleUrls.push({
url: url2,
start: nodeStartWithLeadingWhitespace(node2),
end: node2.sourceCodeLocation.endOffset
});
js += importExpression;
} else {
const isNoInlineLink = node2.nodeName === "link" && node2.attrs.some(
(p2) => p2.name === "rel" && parseRelAttr(p2.value).some(
(v) => noInlineLinkRels.has(v)
)
);
const shouldInline2 = isNoInlineLink ? false : void 0;
assetUrlsPromises.push(
(async () => {
const processedUrl = await processAssetUrl(
url2,
shouldInline2
);
if (processedUrl !== url2) {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node2, attrKey),
partialEncodeURIPath(processedUrl)
);
}
})()
);
}
}
}
}
}
}
const inlineStyle = findNeedTransformStyleAttribute(node2);
if (inlineStyle) {
inlineModuleIndex++;
const code = inlineStyle.attr.value;
const filePath = id.replace(normalizePath$3(config2.root), "");
addToHTMLProxyCache(config2, filePath, inlineModuleIndex, { code });
js += `
import "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
const hash2 = getHash(cleanUrl(id));
overwriteAttrValue(
s,
inlineStyle.location,
`__VITE_INLINE_CSS__${hash2}_${inlineModuleIndex}__`
);
}
if (node2.nodeName === "style" && node2.childNodes.length) {
const styleNode = node2.childNodes.pop();
const filePath = id.replace(normalizePath$3(config2.root), "");
inlineModuleIndex++;
addToHTMLProxyCache(config2, filePath, inlineModuleIndex, {
code: styleNode.value
});
js += `
import "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
const hash2 = getHash(cleanUrl(id));
s.update(
styleNode.sourceCodeLocation.startOffset,
styleNode.sourceCodeLocation.endOffset,
`__VITE_INLINE_CSS__${hash2}_${inlineModuleIndex}__`
);
}
if (shouldRemove) {
s.remove(
nodeStartWithLeadingWhitespace(node2),
node2.sourceCodeLocation.endOffset
);
}
});
isAsyncScriptMap.get(config2).set(id, everyScriptIsAsync);
if (someScriptsAreAsync && someScriptsAreDefer) {
config2.logger.warn(
`
Mixed async and defer script modules in ${id}, output script will fallback to defer. Every script, including inline ones, need to be marked as async for your output script to be async.`
);
}
await Promise.all(assetUrlsPromises);
for (const { start, end, url: url2 } of scriptUrls) {
if (checkPublicFile(url2, config2)) {
s.update(
start,
end,
partialEncodeURIPath(toOutputPublicFilePath(url2))
);
} else if (!isExcludedUrl(url2)) {
s.update(
start,
end,
partialEncodeURIPath(await urlToBuiltUrl(url2, id, config2, this))
);
}
}
const resolvedStyleUrls = await Promise.all(
styleUrls.map(async (styleUrl) => ({
...styleUrl,
resolved: await this.resolve(styleUrl.url, id)
}))
);
for (const { start, end, url: url2, resolved } of resolvedStyleUrls) {
if (resolved == null) {
config2.logger.warnOnce(
`
${url2} doesn't exist at build time, it will remain unchanged to be resolved at runtime`
);
const importExpression = `
import ${JSON.stringify(url2)}`;
js = js.replace(importExpression, "");
} else {
s.remove(start, end);
}
}
processedHtml.set(id, s.toString());
const { modulePreload } = config2.build;
if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) {
js = `import "${modulePreloadPolyfillId}";
${js}`;
}
return { code: js, moduleSideEffects: "no-treeshake" };
}
},
async generateBundle(options2, bundle) {
const analyzedChunk = /* @__PURE__ */ new Map();
const inlineEntryChunk = /* @__PURE__ */ new Set();
const getImportedChunks = (chunk, seen2 = /* @__PURE__ */ new Set()) => {
const chunks = [];
chunk.imports.forEach((file) => {
const importee = bundle[file];
if ((importee == null ? void 0 : importee.type) === "chunk" && !seen2.has(file)) {
seen2.add(file);
chunks.push(...getImportedChunks(importee, seen2));
chunks.push(importee);
}
});
return chunks;
};
const toScriptTag = (chunk, toOutputPath, isAsync) => ({
tag: "script",
attrs: {
...isAsync ? { async: true } : {},
type: "module",
// crossorigin must be set not only for serving assets in a different origin
// but also to make it possible to preload the script using `<link rel="preload">`.
// `<script type="module">` used to fetch the script with credential mode `omit`,
// however `crossorigin` attribute cannot specify that value.
// https://developer.chrome.com/blog/modulepreload/#ok-so-why-doesnt-link-relpreload-work-for-modules:~:text=For%20%3Cscript%3E,of%20other%20modules.
// Now `<script type="module">` uses `same origin`: https://github.com/whatwg/html/pull/3656#:~:text=Module%20scripts%20are%20always%20fetched%20with%20credentials%20mode%20%22same%2Dorigin%22%20by%20default%20and%20can%20no%20longer%0Ause%20%22omit%22
crossorigin: true,
src: toOutputPath(chunk.fileName)
}
});
const toPreloadTag = (filename, toOutputPath) => ({
tag: "link",
attrs: {
rel: "modulepreload",
crossorigin: true,
href: toOutputPath(filename)
}
});
const getCssTagsForChunk = (chunk, toOutputPath, seen2 = /* @__PURE__ */ new Set()) => {
const tags = [];
if (!analyzedChunk.has(chunk)) {
analyzedChunk.set(chunk, 1);
chunk.imports.forEach((file) => {
const importee = bundle[file];
if ((importee == null ? void 0 : importee.type) === "chunk") {
tags.push(...getCssTagsForChunk(importee, toOutputPath, seen2));
}
});
}
chunk.viteMetadata.importedCss.forEach((file) => {
if (!seen2.has(file)) {
seen2.add(file);
tags.push({
tag: "link",
attrs: {
rel: "stylesheet",
crossorigin: true,
href: toOutputPath(file)
}
});
}
});
return tags;
};
for (const [normalizedId, html] of processedHtml) {
const relativeUrlPath = import_node_path3.default.posix.relative(config2.root, normalizedId);
const assetsBase = getBaseInHTML(relativeUrlPath, config2);
const toOutputFilePath = (filename, type) => {
if (isExternalUrl(filename)) {
return filename;
} else {
return toOutputFilePathInHtml(
filename,
type,
relativeUrlPath,
"html",
config2,
(filename2, importer) => assetsBase + filename2
);
}
};
const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
const isAsync = isAsyncScriptMap.get(config2).get(normalizedId);
let result = html;
const chunk = Object.values(bundle).find(
(chunk2) => chunk2.type === "chunk" && chunk2.isEntry && chunk2.facadeModuleId && normalizePath$3(chunk2.facadeModuleId) === normalizedId
);
let canInlineEntry = false;
if (chunk) {
if (options2.format === "es" && isEntirelyImport(chunk.code)) {
canInlineEntry = true;
}
const imports = getImportedChunks(chunk);
let assetTags;
if (canInlineEntry) {
assetTags = imports.map(
(chunk2) => toScriptTag(chunk2, toOutputAssetFilePath, isAsync)
);
} else {
assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
const { modulePreload } = config2.build;
if (modulePreload !== false) {
const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
const importsFileNames = imports.map((chunk2) => chunk2.fileName);
const resolvedDeps = resolveDependencies ? resolveDependencies(chunk.fileName, importsFileNames, {
hostId: relativeUrlPath,
hostType: "html"
}) : importsFileNames;
assetTags.push(
...resolvedDeps.map(
(i) => toPreloadTag(i, toOutputAssetFilePath)
)
);
}
}
assetTags.push(...getCssTagsForChunk(chunk, toOutputAssetFilePath));
result = injectToHead(result, assetTags);
}
if (!config2.build.cssCodeSplit) {
const cssChunk = Object.values(bundle).find(
(chunk2) => chunk2.type === "asset" && chunk2.name === "style.css"
);
if (cssChunk) {
result = injectToHead(result, [
{
tag: "link",
attrs: {
rel: "stylesheet",
crossorigin: true,
href: toOutputAssetFilePath(cssChunk.fileName)
}
}
]);
}
}
let match2;
let s;
inlineCSSRE$1.lastIndex = 0;
while (match2 = inlineCSSRE$1.exec(result)) {
s || (s = new MagicString(result));
const { 0: full, 1: scopedName } = match2;
const cssTransformedCode = htmlProxyResult.get(scopedName);
s.update(match2.index, match2.index + full.length, cssTransformedCode);
}
if (s) {
result = s.toString();
}
result = await applyHtmlTransforms(
result,
[...normalHooks, ...postHooks],
{
path: "/" + relativeUrlPath,
filename: normalizedId,
bundle,
chunk
}
);
result = result.replace(assetUrlRE, (_, fileHash, postfix = "") => {
const file = this.getFileName(fileHash);
if (chunk) {
chunk.viteMetadata.importedAssets.add(cleanUrl(file));
}
return encodeURIPath(toOutputAssetFilePath(file)) + postfix;
});
result = result.replace(publicAssetUrlRE, (_, fileHash) => {
const publicAssetPath = toOutputPublicAssetFilePath(
getPublicAssetFilename(fileHash, config2)
);
return encodeURIPath(
urlCanParse(publicAssetPath) ? publicAssetPath : normalizePath$3(publicAssetPath)
);
});
if (chunk && canInlineEntry) {
inlineEntryChunk.add(chunk.fileName);
}
const shortEmitName = normalizePath$3(
import_node_path3.default.relative(config2.root, normalizedId)
);
this.emitFile({
type: "asset",
fileName: shortEmitName,
source: result
});
}
for (const fileName of inlineEntryChunk) {
delete bundle[fileName];
}
}
};
}
function parseRelAttr(attr) {
return attr.split(spaceRe).map((v) => v.toLowerCase());
}
function findNeedTransformStyleAttribute(node2) {
var _a4, _b3;
const attr = node2.attrs.find(
(prop) => prop.prefix === void 0 && prop.name === "style" && // only url(...) or image-set(...) in css need to emit file
(prop.value.includes("url(") || prop.value.includes("image-set("))
);
if (!attr) return void 0;
const location2 = (_b3 = (_a4 = node2.sourceCodeLocation) == null ? void 0 : _a4.attrs) == null ? void 0 : _b3["style"];
return { attr, location: location2 };
}
function extractImportExpressionFromClassicScript(scriptTextNode) {
const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
const cleanCode = stripLiteral(scriptTextNode.value);
const scriptUrls = [];
let match2;
inlineImportRE.lastIndex = 0;
while (match2 = inlineImportRE.exec(cleanCode)) {
const [, [urlStart, urlEnd]] = match2.indices;
const start = urlStart + 1;
const end = urlEnd - 1;
scriptUrls.push({
start: start + startOffset,
end: end + startOffset,
url: scriptTextNode.value.slice(start, end)
});
}
return scriptUrls;
}
function preImportMapHook(config2) {
return (html, ctx) => {
const importMapIndex = html.search(importMapRE);
if (importMapIndex < 0) return;
const importMapAppendIndex = html.search(importMapAppendRE);
if (importMapAppendIndex < 0) return;
if (importMapAppendIndex < importMapIndex) {
const relativeHtml = normalizePath$3(
import_node_path3.default.relative(config2.root, ctx.filename)
);
config2.logger.warnOnce(
colors$1.yellow(
colors$1.bold(
`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`
)
)
);
}
};
}
function postImportMapHook() {
return (html) => {
if (!importMapAppendRE.test(html)) return;
let importMap;
html = html.replace(importMapRE, (match2) => {
importMap = match2;
return "";
});
if (importMap) {
html = html.replace(
importMapAppendRE,
(match2) => `${importMap}
${match2}`
);
}
return html;
};
}
function injectCspNonceMetaTagHook(config2) {
return () => {
var _a4;
if (!((_a4 = config2.html) == null ? void 0 : _a4.cspNonce)) return;
return [
{
tag: "meta",
injectTo: "head",
// use nonce attribute so that it's hidden
// https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce#accessing_nonces_and_nonce_hiding
attrs: { property: "csp-nonce", nonce: config2.html.cspNonce }
}
];
};
}
function htmlEnvHook(config2) {
const pattern2 = /%(\S+?)%/g;
const envPrefix = resolveEnvPrefix({ envPrefix: config2.envPrefix });
const env2 = { ...config2.env };
for (const key in config2.define) {
if (key.startsWith(`import.meta.env.`)) {
const val = config2.define[key];
if (typeof val === "string") {
try {
const parsed = JSON.parse(val);
env2[key.slice(16)] = typeof parsed === "string" ? parsed : val;
} catch {
env2[key.slice(16)] = val;
}
} else {
env2[key.slice(16)] = JSON.stringify(val);
}
}
}
return (html, ctx) => {
return html.replace(pattern2, (text, key) => {
if (key in env2) {
return env2[key];
} else {
if (envPrefix.some((prefix) => key.startsWith(prefix))) {
const relativeHtml = normalizePath$3(
import_node_path3.default.relative(config2.root, ctx.filename)
);
config2.logger.warn(
colors$1.yellow(
colors$1.bold(
`(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`
)
)
);
}
return text;
}
});
};
}
function injectNonceAttributeTagHook(config2) {
const processRelType = /* @__PURE__ */ new Set(["stylesheet", "modulepreload", "preload"]);
return async (html, { filename }) => {
var _a4;
const nonce = (_a4 = config2.html) == null ? void 0 : _a4.cspNonce;
if (!nonce) return;
const s = new MagicString(html);
await traverseHtml(html, filename, (node2) => {
if (!nodeIsElement(node2)) {
return;
}
const { nodeName, attrs, sourceCodeLocation } = node2;
if (nodeName === "script" || nodeName === "style" || nodeName === "link" && attrs.some(
(attr) => attr.name === "rel" && parseRelAttr(attr.value).some((a) => processRelType.has(a))
)) {
if (attrs.some(({ name: name2 }) => name2 === "nonce")) {
return;
}
const startTagEndOffset = sourceCodeLocation.startTag.endOffset;
const appendOffset = html[startTagEndOffset - 2] === "/" ? 2 : 1;
s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`);
}
});
return s.toString();
};
}
function resolveHtmlTransforms(plugins2, logger) {
const preHooks = [];
const normalHooks = [];
const postHooks = [];
for (const plugin of plugins2) {
const hook = plugin.transformIndexHtml;
if (!hook) continue;
if (typeof hook === "function") {
normalHooks.push(hook);
} else {
if (!("order" in hook) && "enforce" in hook) {
logger.warnOnce(
colors$1.yellow(
`plugin '${plugin.name}' uses deprecated 'enforce' option. Use 'order' option instead.`
)
);
}
if (!("handler" in hook) && "transform" in hook) {
logger.warnOnce(
colors$1.yellow(
`plugin '${plugin.name}' uses deprecated 'transform' option. Use 'handler' option instead.`
)
);
}
const order = hook.order ?? (hook.enforce === "pre" ? "pre" : void 0);
const handler = hook.handler ?? hook.transform;
if (order === "pre") {
preHooks.push(handler);
} else if (order === "post") {
postHooks.push(handler);
} else {
normalHooks.push(handler);
}
}
}
return [preHooks, normalHooks, postHooks];
}
var elementsAllowedInHead = /* @__PURE__ */ new Set([
"title",
"base",
"link",
"style",
"meta",
"script",
"noscript",
"template"
]);
function headTagInsertCheck(tags, ctx) {
var _a4;
if (!tags.length) return;
const { logger } = ((_a4 = ctx.server) == null ? void 0 : _a4.config) || {};
const disallowedTags = tags.filter(
(tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag)
);
if (disallowedTags.length) {
const dedupedTags = unique(
disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`)
);
logger == null ? void 0 : logger.warn(
colors$1.yellow(
colors$1.bold(
`[${dedupedTags.join(",")}] can not be used inside the <head> Element, please check the 'injectTo' value`
)
)
);
}
}
async function applyHtmlTransforms(html, hooks, ctx) {
for (const hook of hooks) {
const res = await hook(html, ctx);
if (!res) {
continue;
}
if (typeof res === "string") {
html = res;
} else {
let tags;
if (Array.isArray(res)) {
tags = res;
} else {
html = res.html || html;
tags = res.tags;
}
let headTags;
let headPrependTags;
let bodyTags;
let bodyPrependTags;
for (const tag of tags) {
switch (tag.injectTo) {
case "body":
(bodyTags ?? (bodyTags = [])).push(tag);
break;
case "body-prepend":
(bodyPrependTags ?? (bodyPrependTags = [])).push(tag);
break;
case "head":
(headTags ?? (headTags = [])).push(tag);
break;
default:
(headPrependTags ?? (headPrependTags = [])).push(tag);
}
}
headTagInsertCheck([...headTags || [], ...headPrependTags || []], ctx);
if (headPrependTags) html = injectToHead(html, headPrependTags, true);
if (headTags) html = injectToHead(html, headTags);
if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true);
if (bodyTags) html = injectToBody(html, bodyTags);
}
}
return html;
}
var importRE = /\bimport\s*("[^"]*[^\\]"|'[^']*[^\\]');*/g;
var commentRE$1 = /\/\*[\s\S]*?\*\/|\/\/.*$/gm;
function isEntirelyImport(code) {
return !code.replace(importRE, "").replace(commentRE$1, "").trim().length;
}
function getBaseInHTML(urlRelativePath, config2) {
return config2.base === "./" || config2.base === "" ? import_node_path3.default.posix.join(
import_node_path3.default.posix.relative(urlRelativePath, "").slice(0, -2),
"./"
) : config2.base;
}
var headInjectRE = /([ \t]*)<\/head>/i;
var headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
var htmlInjectRE = /<\/html>/i;
var htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
var bodyInjectRE = /([ \t]*)<\/body>/i;
var bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
var doctypePrependInjectRE = /<!doctype html>/i;
function injectToHead(html, tags, prepend = false) {
if (tags.length === 0) return html;
if (prepend) {
if (headPrependInjectRE.test(html)) {
return html.replace(
headPrependInjectRE,
(match2, p1) => `${match2}
${serializeTags(tags, incrementIndent(p1))}`
);
}
} else {
if (headInjectRE.test(html)) {
return html.replace(
headInjectRE,
(match2, p1) => `${serializeTags(tags, incrementIndent(p1))}${match2}`
);
}
if (bodyPrependInjectRE.test(html)) {
return html.replace(
bodyPrependInjectRE,
(match2, p1) => `${serializeTags(tags, p1)}
${match2}`
);
}
}
return prependInjectFallback(html, tags);
}
function injectToBody(html, tags, prepend = false) {
if (tags.length === 0) return html;
if (prepend) {
if (bodyPrependInjectRE.test(html)) {
return html.replace(
bodyPrependInjectRE,
(match2, p1) => `${match2}
${serializeTags(tags, incrementIndent(p1))}`
);
}
if (headInjectRE.test(html)) {
return html.replace(
headInjectRE,
(match2, p1) => `${match2}
${serializeTags(tags, p1)}`
);
}
return prependInjectFallback(html, tags);
} else {
if (bodyInjectRE.test(html)) {
return html.replace(
bodyInjectRE,
(match2, p1) => `${serializeTags(tags, incrementIndent(p1))}${match2}`
);
}
if (htmlInjectRE.test(html)) {
return html.replace(htmlInjectRE, `${serializeTags(tags)}
$&`);
}
return html + `
` + serializeTags(tags);
}
}
function prependInjectFallback(html, tags) {
if (htmlPrependInjectRE.test(html)) {
return html.replace(htmlPrependInjectRE, `$&
${serializeTags(tags)}`);
}
if (doctypePrependInjectRE.test(html)) {
return html.replace(doctypePrependInjectRE, `$&
${serializeTags(tags)}`);
}
return serializeTags(tags) + html;
}
var unaryTags = /* @__PURE__ */ new Set(["link", "meta", "base"]);
function serializeTag({ tag, attrs, children }, indent = "") {
if (unaryTags.has(tag)) {
return `<${tag}${serializeAttrs(attrs)}>`;
} else {
return `<${tag}${serializeAttrs(attrs)}>${serializeTags(
children,
incrementIndent(indent)
)}</${tag}>`;
}
}
function serializeTags(tags, indent = "") {
if (typeof tags === "string") {
return tags;
} else if (tags && tags.length) {
return tags.map((tag) => `${indent}${serializeTag(tag, indent)}
`).join("");
}
return "";
}
function serializeAttrs(attrs) {
let res = "";
for (const key in attrs) {
if (typeof attrs[key] === "boolean") {
res += attrs[key] ? ` ${key}` : ``;
} else {
res += ` ${key}=${JSON.stringify(attrs[key])}`;
}
}
return res;
}
function incrementIndent(indent = "") {
return `${indent}${indent[0] === " " ? " " : " "}`;
}
function getAttrKey(attr) {
return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
}
function getAttrSourceCodeLocation(node2, attrKey) {
return node2.sourceCodeLocation.attrs[attrKey];
}
var decoder = new TextDecoder();
function resolveCSSOptions(options2) {
var _a4;
if ((options2 == null ? void 0 : options2.transformer) === "lightningcss") {
return {
...options2,
lightningcss: {
...options2.lightningcss,
targets: ((_a4 = options2.lightningcss) == null ? void 0 : _a4.targets) ?? convertTargets(ESBUILD_MODULES_TARGET)
}
};
}
return { ...options2, lightningcss: void 0 };
}
var cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
var directRequestRE = /[?&]direct\b/;
var htmlProxyRE = /[?&]html-proxy\b/;
var htmlProxyIndexRE = /&index=(\d+)/;
var commonjsProxyRE = /\?commonjs-proxy/;
var inlineRE$1 = /[?&]inline\b/;
var inlineCSSRE = /[?&]inline-css\b/;
var styleAttrRE = /[?&]style-attr\b/;
var functionCallRE = /^[A-Z_][\w-]*\(/i;
var transformOnlyRE = /[?&]transform-only\b/;
var nonEscapedDoubleQuoteRe = new RegExp('(?<!\\\\)(")', "g");
var cssBundleName = "style.css";
var isCSSRequest = (request) => CSS_LANGS_RE.test(request);
var isModuleCSSRequest = (request) => cssModuleRE.test(request);
var isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
var isDirectRequest = (request) => directRequestRE.test(request);
var cssModulesCache = /* @__PURE__ */ new WeakMap();
var removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
var postcssConfigCache = /* @__PURE__ */ new WeakMap();
function encodePublicUrlsInCSS(config2) {
return config2.command === "build";
}
var cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
function cssPlugin(config2) {
var _a4;
const isBuild = config2.command === "build";
let moduleCache;
const resolveUrl2 = config2.createResolver({
preferRelative: true,
tryIndex: false,
extensions: []
});
let preprocessorWorkerController;
if (((_a4 = config2.css) == null ? void 0 : _a4.transformer) !== "lightningcss") {
resolvePostcssConfig(config2);
}
return {
name: "vite:css",
buildStart() {
moduleCache = /* @__PURE__ */ new Map();
cssModulesCache.set(config2, moduleCache);
removedPureCssFilesCache.set(config2, /* @__PURE__ */ new Map());
preprocessorWorkerController = createPreprocessorWorkerController(
normalizeMaxWorkers(config2.css.preprocessorMaxWorkers)
);
preprocessorWorkerControllerCache.set(
config2,
preprocessorWorkerController
);
},
buildEnd() {
preprocessorWorkerController == null ? void 0 : preprocessorWorkerController.close();
},
async load(id) {
if (!isCSSRequest(id)) return;
if (urlRE.test(id)) {
if (isModuleCSSRequest(id)) {
throw new Error(
`?url is not supported with CSS modules. (tried to import ${JSON.stringify(
id
)})`
);
}
if (isBuild) {
id = injectQuery(removeUrlQuery(id), "transform-only");
return `import ${JSON.stringify(id)};export default "__VITE_CSS_URL__${Buffer.from(id).toString(
"hex"
)}__"`;
}
}
},
async transform(raw, id) {
if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
return;
}
const urlReplacer = async (url2, importer) => {
const decodedUrl = decodeURI(url2);
if (checkPublicFile(decodedUrl, config2)) {
if (encodePublicUrlsInCSS(config2)) {
return publicFileToBuiltUrl(decodedUrl, config2);
} else {
return joinUrlSegments(config2.base, decodedUrl);
}
}
const [id2, fragment] = decodedUrl.split("#");
let resolved = await resolveUrl2(id2, importer);
if (resolved) {
if (fragment) resolved += "#" + fragment;
return fileToUrl$1(resolved, config2, this);
}
if (config2.command === "build") {
const isExternal2 = config2.build.rollupOptions.external ? resolveUserExternal(
config2.build.rollupOptions.external,
decodedUrl,
// use URL as id since id could not be resolved
id2,
false
) : false;
if (!isExternal2) {
config2.logger.warnOnce(
`
${decodedUrl} referenced in ${id2} didn't resolve at build time, it will remain unchanged to be resolved at runtime`
);
}
}
return url2;
};
const {
code: css,
modules,
deps,
map: map2
} = await compileCSS(
id,
raw,
config2,
preprocessorWorkerController,
urlReplacer
);
if (modules) {
moduleCache.set(id, modules);
}
if (deps) {
for (const file of deps) {
this.addWatchFile(file);
}
}
return {
code: css,
map: map2
};
}
};
}
function cssPostPlugin(config2) {
var _a4;
const styles = /* @__PURE__ */ new Map();
let codeSplitEmitQueue = createSerialPromiseQueue();
const urlEmitQueue = createSerialPromiseQueue();
let pureCssChunks;
let hasEmitted = false;
let chunkCSSMap;
const rollupOptionsOutput = config2.build.rollupOptions.output;
const assetFileNames = (_a4 = Array.isArray(rollupOptionsOutput) ? rollupOptionsOutput[0] : rollupOptionsOutput) == null ? void 0 : _a4.assetFileNames;
const getCssAssetDirname = (cssAssetName) => {
const cssAssetNameDir = import_node_path3.default.dirname(cssAssetName);
if (!assetFileNames) {
return import_node_path3.default.join(config2.build.assetsDir, cssAssetNameDir);
} else if (typeof assetFileNames === "string") {
return import_node_path3.default.join(import_node_path3.default.dirname(assetFileNames), cssAssetNameDir);
} else {
return import_node_path3.default.dirname(
assetFileNames({
name: cssAssetName,
type: "asset",
source: "/* vite internal call, ignore */"
})
);
}
};
return {
name: "vite:css-post",
renderStart() {
pureCssChunks = /* @__PURE__ */ new Set();
hasEmitted = false;
chunkCSSMap = /* @__PURE__ */ new Map();
codeSplitEmitQueue = createSerialPromiseQueue();
},
async transform(css, id, options2) {
var _a5;
if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
return;
}
css = stripBomTag(css);
const inlineCSS = inlineCSSRE.test(id);
const isHTMLProxy2 = htmlProxyRE.test(id);
if (inlineCSS && isHTMLProxy2) {
if (styleAttrRE.test(id)) {
css = css.replace(/"/g, "&quot;");
}
const index = (_a5 = htmlProxyIndexRE.exec(id)) == null ? void 0 : _a5[1];
if (index == null) {
throw new Error(`HTML proxy index in "${id}" not found`);
}
addToHTMLProxyTransformResult(
`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`,
css
);
return `export default ''`;
}
const inlined = inlineRE$1.test(id);
const modules = cssModulesCache.get(config2).get(id);
const modulesCode = modules && !inlined && dataToEsm(modules, { namedExports: true, preferConst: true });
if (config2.command === "serve") {
const getContentWithSourcemap = async (content) => {
var _a6;
if ((_a6 = config2.css) == null ? void 0 : _a6.devSourcemap) {
const sourcemap = this.getCombinedSourcemap();
if (sourcemap.mappings) {
await injectSourcesContent(sourcemap, cleanUrl(id), config2.logger);
}
return getCodeWithSourcemap("css", content, sourcemap);
}
return content;
};
if (isDirectCSSRequest(id)) {
return null;
}
if (options2 == null ? void 0 : options2.ssr) {
return modulesCode || `export default ${JSON.stringify(css)}`;
}
if (inlined) {
return `export default ${JSON.stringify(css)}`;
}
const cssContent = await getContentWithSourcemap(css);
const code2 = [
`import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(
import_node_path3.default.posix.join(config2.base, CLIENT_PUBLIC_PATH)
)}`,
`const __vite__id = ${JSON.stringify(id)}`,
`const __vite__css = ${JSON.stringify(cssContent)}`,
`__vite__updateStyle(__vite__id, __vite__css)`,
// css modules exports change on edit so it can't self accept
`${modulesCode || "import.meta.hot.accept()"}`,
`import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
].join("\n");
return { code: code2, map: { mappings: "" } };
}
if (!inlined) {
styles.set(id, css);
}
let code;
if (modulesCode) {
code = modulesCode;
} else if (inlined) {
let content = css;
if (config2.build.cssMinify) {
content = await minifyCSS(content, config2, true);
}
code = `export default ${JSON.stringify(content)}`;
} else {
code = "";
}
return {
code,
map: { mappings: "" },
// avoid the css module from being tree-shaken so that we can retrieve
// it in renderChunk()
moduleSideEffects: modulesCode || inlined ? false : "no-treeshake"
};
},
async renderChunk(code, chunk, opts) {
var _a5;
let chunkCSS = "";
const isJsChunkEmpty = code === "" && !chunk.isEntry;
let isPureCssChunk = true;
const ids = Object.keys(chunk.modules);
for (const id of ids) {
if (styles.has(id)) {
if (!transformOnlyRE.test(id)) {
chunkCSS += styles.get(id);
if (cssModuleRE.test(id)) {
isPureCssChunk = false;
}
}
} else if (!isJsChunkEmpty) {
isPureCssChunk = false;
}
}
const publicAssetUrlMap = publicAssetUrlCache.get(config2);
const resolveAssetUrlsInCss = (chunkCSS2, cssAssetName) => {
const encodedPublicUrls = encodePublicUrlsInCSS(config2);
const relative2 = config2.base === "./" || config2.base === "";
const cssAssetDirname = encodedPublicUrls || relative2 ? slash$1(getCssAssetDirname(cssAssetName)) : void 0;
const toRelative = (filename) => {
const relativePath = import_node_path3.default.posix.relative(cssAssetDirname, filename);
return relativePath[0] === "." ? relativePath : "./" + relativePath;
};
chunkCSS2 = chunkCSS2.replace(assetUrlRE, (_, fileHash, postfix = "") => {
const filename = this.getFileName(fileHash) + postfix;
chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
return encodeURIPath(
toOutputFilePathInCss(
filename,
"asset",
cssAssetName,
"css",
config2,
toRelative
)
);
});
if (encodedPublicUrls) {
const relativePathToPublicFromCSS = import_node_path3.default.posix.relative(
cssAssetDirname,
""
);
chunkCSS2 = chunkCSS2.replace(publicAssetUrlRE, (_, hash2) => {
const publicUrl = publicAssetUrlMap.get(hash2).slice(1);
return encodeURIPath(
toOutputFilePathInCss(
publicUrl,
"public",
cssAssetName,
"css",
config2,
() => `${relativePathToPublicFromCSS}/${publicUrl}`
)
);
});
}
return chunkCSS2;
};
function ensureFileExt(name2, ext2) {
return normalizePath$3(
import_node_path3.default.format({ ...import_node_path3.default.parse(name2), base: void 0, ext: ext2 })
);
}
let s;
const urlEmitTasks = [];
if (code.includes("__VITE_CSS_URL__")) {
let match2;
cssUrlAssetRE.lastIndex = 0;
while (match2 = cssUrlAssetRE.exec(code)) {
const [full, idHex] = match2;
const id = Buffer.from(idHex, "hex").toString();
const originalFilename = cleanUrl(id);
const cssAssetName = ensureFileExt(
import_node_path3.default.basename(originalFilename),
".css"
);
if (!styles.has(id)) {
throw new Error(
`css content for ${JSON.stringify(id)} was not found`
);
}
let cssContent = styles.get(id);
cssContent = resolveAssetUrlsInCss(cssContent, cssAssetName);
urlEmitTasks.push({
cssAssetName,
originalFilename,
content: cssContent,
start: match2.index,
end: match2.index + full.length
});
}
}
await urlEmitQueue.run(
async () => Promise.all(
urlEmitTasks.map(async (info) => {
info.content = await finalizeCss(info.content, true, config2);
})
)
);
if (urlEmitTasks.length > 0) {
const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
opts.format,
config2.isWorker
);
s || (s = new MagicString(code));
for (const {
cssAssetName,
originalFilename,
content,
start,
end
} of urlEmitTasks) {
const referenceId = this.emitFile({
name: cssAssetName,
type: "asset",
source: content
});
generatedAssets.get(config2).set(referenceId, { originalName: originalFilename });
const filename = this.getFileName(referenceId);
chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
const replacement = toOutputFilePathInJS(
filename,
"asset",
chunk.fileName,
"js",
config2,
toRelativeRuntime
);
const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
s.update(start, end, replacementString);
}
}
if (chunkCSS) {
if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) {
pureCssChunks.add(chunk);
}
if (config2.build.cssCodeSplit) {
if (opts.format === "es" || opts.format === "cjs") {
const isEntry = chunk.isEntry && isPureCssChunk;
const cssFullAssetName = ensureFileExt(chunk.name, ".css");
const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? import_node_path3.default.basename(cssFullAssetName) : cssFullAssetName;
const originalFilename = getChunkOriginalFileName(
chunk,
config2.root,
opts.format
);
chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName);
chunkCSS = await codeSplitEmitQueue.run(async () => {
return finalizeCss(chunkCSS, true, config2);
});
const referenceId = this.emitFile({
name: cssAssetName,
type: "asset",
source: chunkCSS
});
generatedAssets.get(config2).set(referenceId, { originalName: originalFilename, isEntry });
chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
} else if (!config2.build.ssr) {
chunkCSS = await finalizeCss(chunkCSS, true, config2);
let cssString = JSON.stringify(chunkCSS);
cssString = ((_a5 = renderAssetUrlInJS(
this,
config2,
chunk,
opts,
cssString
)) == null ? void 0 : _a5.toString()) || cssString;
const style = `__vite_style__`;
const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
let injectionPoint;
const wrapIdx = code.indexOf("System.register");
if (wrapIdx >= 0) {
const executeFnStart = code.indexOf("execute:", wrapIdx);
injectionPoint = code.indexOf("{", executeFnStart) + 1;
} else {
const insertMark = "'use strict';";
injectionPoint = code.indexOf(insertMark) + insertMark.length;
}
s || (s = new MagicString(code));
s.appendRight(injectionPoint, injectCode);
}
} else {
chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName);
chunkCSSMap.set(chunk.fileName, chunkCSS);
}
}
if (s) {
if (config2.build.sourcemap) {
return {
code: s.toString(),
map: s.generateMap({ hires: "boundary" })
};
} else {
return { code: s.toString() };
}
}
return null;
},
augmentChunkHash(chunk) {
var _a5;
if ((_a5 = chunk.viteMetadata) == null ? void 0 : _a5.importedCss.size) {
let hash2 = "";
for (const id of chunk.viteMetadata.importedCss) {
hash2 += id;
}
return hash2;
}
},
async generateBundle(opts, bundle) {
if (opts.__vite_skip_asset_emit__) {
return;
}
function extractCss() {
let css = "";
const collected = /* @__PURE__ */ new Set();
const dynamicImports = /* @__PURE__ */ new Set();
function collect(chunk) {
if (!chunk || chunk.type !== "chunk" || collected.has(chunk)) return;
collected.add(chunk);
chunk.imports.forEach((importName) => collect(bundle[importName]));
chunk.dynamicImports.forEach(
(importName) => dynamicImports.add(importName)
);
css += chunkCSSMap.get(chunk.preliminaryFileName) ?? "";
}
for (const chunk of Object.values(bundle)) {
if (chunk.type === "chunk" && chunk.isEntry) {
collect(chunk);
}
}
for (const chunkName of dynamicImports) {
collect(bundle[chunkName]);
}
return css;
}
let extractedCss = !hasEmitted && extractCss();
if (extractedCss) {
hasEmitted = true;
extractedCss = await finalizeCss(extractedCss, true, config2);
this.emitFile({
name: cssBundleName,
type: "asset",
source: extractedCss
});
}
if (pureCssChunks.size) {
const prelimaryNameToChunkMap = Object.fromEntries(
Object.values(bundle).filter((chunk) => chunk.type === "chunk").map((chunk) => [chunk.preliminaryFileName, chunk.fileName])
);
const pureCssChunkNames = [...pureCssChunks].map((pureCssChunk) => prelimaryNameToChunkMap[pureCssChunk.fileName]).filter(Boolean);
const replaceEmptyChunk = getEmptyChunkReplacer(
pureCssChunkNames,
opts.format
);
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk") {
let chunkImportsPureCssChunk = false;
chunk.imports = chunk.imports.filter((file2) => {
if (pureCssChunkNames.includes(file2)) {
const { importedCss, importedAssets } = bundle[file2].viteMetadata;
importedCss.forEach(
(file3) => chunk.viteMetadata.importedCss.add(file3)
);
importedAssets.forEach(
(file3) => chunk.viteMetadata.importedAssets.add(file3)
);
chunkImportsPureCssChunk = true;
return false;
}
return true;
});
if (chunkImportsPureCssChunk) {
chunk.code = replaceEmptyChunk(chunk.code);
}
}
}
const removedPureCssFiles = removedPureCssFilesCache.get(config2);
pureCssChunkNames.forEach((fileName) => {
removedPureCssFiles.set(fileName, bundle[fileName]);
delete bundle[fileName];
delete bundle[`${fileName}.map`];
});
}
}
};
}
function cssAnalysisPlugin(config2) {
let server2;
return {
name: "vite:css-analysis",
configureServer(_server) {
server2 = _server;
},
async transform(_, id, options2) {
var _a4, _b3;
if (!isCSSRequest(id) || commonjsProxyRE.test(id) || SPECIAL_QUERY_RE.test(id)) {
return;
}
const ssr = (options2 == null ? void 0 : options2.ssr) === true;
const { moduleGraph } = server2;
const thisModule = moduleGraph.getModuleById(id);
if (thisModule) {
const isSelfAccepting = !((_a4 = cssModulesCache.get(config2)) == null ? void 0 : _a4.get(id)) && !inlineRE$1.test(id) && !htmlProxyRE.test(id);
const pluginImports = this._addedImports;
if (pluginImports) {
const depModules = /* @__PURE__ */ new Set();
const devBase = config2.base;
for (const file of pluginImports) {
depModules.add(
isCSSRequest(file) ? moduleGraph.createFileOnlyEntry(file) : await moduleGraph.ensureEntryFromUrl(
stripBase(
await fileToUrl$1(file, config2, this),
(((_b3 = config2.server) == null ? void 0 : _b3.origin) ?? "") + devBase
),
ssr
)
);
}
moduleGraph.updateModuleInfo(
thisModule,
depModules,
null,
// The root CSS proxy module is self-accepting and should not
// have an explicit accept list
/* @__PURE__ */ new Set(),
null,
isSelfAccepting,
ssr
);
} else {
thisModule.isSelfAccepting = isSelfAccepting;
}
}
}
};
}
function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
const emptyChunkFiles = pureCssChunkNames.map((file) => import_node_path3.default.basename(file)).join("|").replace(/\./g, "\\.");
const emptyChunkRE = new RegExp(
outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'][^"']*(?:${emptyChunkFiles})["']\\)(;|,)`,
"g"
);
return (code) => code.replace(
emptyChunkRE,
// remove css import while preserving source map location
(m) => outputFormat === "es" ? `/* empty css ${"".padEnd(m.length - 15)}*/` : `${m.at(-1)}/* empty css ${"".padEnd(m.length - 16)}*/`
);
}
function createCSSResolvers(config2) {
let cssResolve;
let sassResolve;
let lessResolve;
return {
get css() {
return cssResolve || (cssResolve = config2.createResolver({
extensions: [".css"],
mainFields: ["style"],
conditions: ["style"],
tryIndex: false,
preferRelative: true
}));
},
get sass() {
return sassResolve || (sassResolve = config2.createResolver({
extensions: [".scss", ".sass", ".css"],
mainFields: ["sass", "style"],
conditions: ["sass", "style"],
tryIndex: true,
tryPrefix: "_",
preferRelative: true
}));
},
get less() {
return lessResolve || (lessResolve = config2.createResolver({
extensions: [".less", ".css"],
mainFields: ["less", "style"],
conditions: ["less", "style"],
tryIndex: false,
preferRelative: true
}));
}
};
}
function getCssResolversKeys(resolvers) {
return Object.keys(resolvers);
}
async function compileCSSPreprocessors(id, lang, code, config2, workerController) {
const { preprocessorOptions, devSourcemap } = config2.css ?? {};
const atImportResolvers = getAtImportResolvers(config2);
const preProcessor = workerController[lang];
let opts = preprocessorOptions && preprocessorOptions[lang] || {};
switch (lang) {
case "scss":
case "sass":
opts = {
includePaths: ["node_modules"],
alias: config2.resolve.alias,
...opts
};
break;
case "less":
case "styl":
case "stylus":
opts = {
paths: ["node_modules"],
alias: config2.resolve.alias,
...opts
};
}
opts.filename = cleanUrl(id);
opts.enableSourcemap = devSourcemap ?? false;
const preprocessResult = await preProcessor(
code,
config2.root,
opts,
atImportResolvers
);
if (preprocessResult.error) {
throw preprocessResult.error;
}
let deps;
if (preprocessResult.deps) {
const normalizedFilename = normalizePath$3(opts.filename);
deps = new Set(
[...preprocessResult.deps].filter(
(dep) => normalizePath$3(dep) !== normalizedFilename
)
);
}
return {
code: preprocessResult.code,
map: combineSourcemapsIfExists(
opts.filename,
preprocessResult.map,
preprocessResult.additionalMap
),
deps
};
}
var configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
function getAtImportResolvers(config2) {
let atImportResolvers = configToAtImportResolvers.get(config2);
if (!atImportResolvers) {
atImportResolvers = createCSSResolvers(config2);
configToAtImportResolvers.set(config2, atImportResolvers);
}
return atImportResolvers;
}
async function compileCSS(id, code, config2, workerController, urlReplacer) {
var _a4, _b3, _c2;
if (((_a4 = config2.css) == null ? void 0 : _a4.transformer) === "lightningcss") {
return compileLightningCSS(id, code, config2, urlReplacer);
}
const { modules: modulesOptions, devSourcemap } = config2.css || {};
const isModule = modulesOptions !== false && cssModuleRE.test(id);
const needInlineImport = code.includes("@import");
const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
const lang = (_b3 = id.match(CSS_LANGS_RE)) == null ? void 0 : _b3[1];
const postcssConfig = await resolvePostcssConfig(config2);
if (lang === "css" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) {
return { code, map: null };
}
let modules;
const deps = /* @__PURE__ */ new Set();
let preprocessorMap;
if (isPreProcessor(lang)) {
const preprocessorResult = await compileCSSPreprocessors(
id,
lang,
code,
config2,
workerController
);
code = preprocessorResult.code;
preprocessorMap = preprocessorResult.map;
(_c2 = preprocessorResult.deps) == null ? void 0 : _c2.forEach((dep) => deps.add(dep));
}
const atImportResolvers = getAtImportResolvers(config2);
const postcssOptions = postcssConfig && postcssConfig.options || {};
const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [];
if (needInlineImport) {
postcssPlugins.unshift(
(await importPostcssImport()).default({
async resolve(id2, basedir) {
const publicFile = checkPublicFile(id2, config2);
if (publicFile) {
return publicFile;
}
const resolved = await atImportResolvers.css(
id2,
import_node_path3.default.join(basedir, "*")
);
if (resolved) {
return import_node_path3.default.resolve(resolved);
}
if (!import_node_path3.default.isAbsolute(id2)) {
config2.logger.error(
colors$1.red(
`Unable to resolve \`@import "${id2}"\` from ${basedir}`
)
);
}
return id2;
},
async load(id2) {
var _a5, _b4;
const code2 = await import_node_fs2.default.promises.readFile(id2, "utf-8");
const lang2 = (_a5 = id2.match(CSS_LANGS_RE)) == null ? void 0 : _a5[1];
if (isPreProcessor(lang2)) {
const result = await compileCSSPreprocessors(
id2,
lang2,
code2,
config2,
workerController
);
(_b4 = result.deps) == null ? void 0 : _b4.forEach((dep) => deps.add(dep));
return result.code;
}
return code2;
},
nameLayer(index) {
return `vite--anon-layer-${getHash(id)}-${index}`;
}
})
);
}
if (urlReplacer) {
postcssPlugins.push(
UrlRewritePostcssPlugin({
replacer: urlReplacer,
logger: config2.logger
})
);
}
if (isModule) {
postcssPlugins.unshift(
(await importPostcssModules()).default({
...modulesOptions,
localsConvention: modulesOptions == null ? void 0 : modulesOptions.localsConvention,
getJSON(cssFileName, _modules, outputFileName) {
modules = _modules;
if (modulesOptions && typeof modulesOptions.getJSON === "function") {
modulesOptions.getJSON(cssFileName, _modules, outputFileName);
}
},
async resolve(id2, importer) {
for (const key of getCssResolversKeys(atImportResolvers)) {
const resolved = await atImportResolvers[key](id2, importer);
if (resolved) {
return import_node_path3.default.resolve(resolved);
}
}
return id2;
}
})
);
}
if (!postcssPlugins.length) {
return {
code,
map: preprocessorMap,
deps
};
}
let postcssResult;
try {
const source = removeDirectQuery(id);
const postcss = await importPostcss();
postcssResult = await postcss.default(postcssPlugins).process(code, {
...postcssOptions,
parser: lang === "sss" ? loadSss(config2.root) : postcssOptions.parser,
to: source,
from: source,
...devSourcemap ? {
map: {
inline: false,
annotation: false,
// postcss may return virtual files
// we cannot obtain content of them, so this needs to be enabled
sourcesContent: true
// when "prev: preprocessorMap", the result map may include duplicate filename in `postcssResult.map.sources`
// prev: preprocessorMap,
}
} : {}
});
for (const message of postcssResult.messages) {
if (message.type === "dependency") {
deps.add(normalizePath$3(message.file));
} else if (message.type === "dir-dependency") {
const { dir, glob: globPattern = "**" } = message;
const pattern2 = glob.escapePath(normalizePath$3(import_node_path3.default.resolve(import_node_path3.default.dirname(id), dir))) + `/` + globPattern;
const files = glob.sync(pattern2, {
ignore: ["**/node_modules/**"]
});
for (let i = 0; i < files.length; i++) {
deps.add(files[i]);
}
} else if (message.type === "warning") {
const warning = message;
let msg = `[vite:css] ${warning.text}`;
msg += `
${generateCodeFrame(
code,
{
line: warning.line,
column: warning.column - 1
// 1-based
},
warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
line: warning.endLine,
column: warning.endColumn - 1
// 1-based
} : void 0
)}`;
config2.logger.warn(colors$1.yellow(msg));
}
}
} catch (e2) {
e2.message = `[postcss] ${e2.message}`;
e2.code = code;
e2.loc = {
file: e2.file,
line: e2.line,
column: e2.column - 1
// 1-based
};
throw e2;
}
if (!devSourcemap) {
return {
ast: postcssResult,
code: postcssResult.css,
map: { mappings: "" },
modules,
deps
};
}
const rawPostcssMap = postcssResult.map.toJSON();
const postcssMap = await formatPostcssSourceMap(
// version property of rawPostcssMap is declared as string
// but actually it is a number
rawPostcssMap,
cleanUrl(id)
);
return {
ast: postcssResult,
code: postcssResult.css,
map: combineSourcemapsIfExists(cleanUrl(id), postcssMap, preprocessorMap),
modules,
deps
};
}
function createCachedImport(imp) {
let cached;
return () => {
if (!cached) {
cached = imp().then((module) => {
cached = module;
return module;
});
}
return cached;
};
}
var importPostcssImport = createCachedImport(() => import("./dep-VqAwxVIc-WZUMGT3D.js").then(function(n2) {
return n2.i;
}));
var importPostcssModules = createCachedImport(() => import("./dep-CjZz522d-UKJ7SIID.js").then(function(n2) {
return n2.i;
}));
var importPostcss = createCachedImport(() => import("./postcss-EOMQEHKO.js"));
var preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
var alwaysFakeWorkerWorkerControllerCache;
async function preprocessCSS(code, filename, config2) {
let workerController = preprocessorWorkerControllerCache.get(config2);
if (!workerController) {
alwaysFakeWorkerWorkerControllerCache || (alwaysFakeWorkerWorkerControllerCache = createPreprocessorWorkerController(0));
workerController = alwaysFakeWorkerWorkerControllerCache;
}
return await compileCSS(filename, code, config2, workerController);
}
async function formatPostcssSourceMap(rawMap, file) {
const inputFileDir = import_node_path3.default.dirname(file);
const sources = rawMap.sources.map((source) => {
const cleanSource = cleanUrl(decodeURIComponent(source));
if (cleanSource[0] === "<" && cleanSource[cleanSource.length - 1] === ">") {
return `\0${cleanSource}`;
}
return normalizePath$3(import_node_path3.default.resolve(inputFileDir, cleanSource));
});
return {
file,
mappings: rawMap.mappings,
names: rawMap.names,
sources,
sourcesContent: rawMap.sourcesContent,
version: rawMap.version
};
}
function combineSourcemapsIfExists(filename, map1, map2) {
return map1 && map2 ? combineSourcemaps(filename, [
// type of version property of ExistingRawSourceMap is number
// but it is always 3
map1,
map2
]) : map1;
}
async function finalizeCss(css, minify, config2) {
if (css.includes("@import") || css.includes("@charset")) {
css = await hoistAtRules(css);
}
if (config2.build.cssMinify) {
css = await minifyCSS(css, config2, false);
}
return css;
}
async function resolvePostcssConfig(config2) {
var _a4;
let result = postcssConfigCache.get(config2);
if (result !== void 0) {
return await result;
}
const inlineOptions = (_a4 = config2.css) == null ? void 0 : _a4.postcss;
if (isObject$1(inlineOptions)) {
const options2 = { ...inlineOptions };
delete options2.plugins;
result = {
options: options2,
plugins: inlineOptions.plugins || []
};
} else {
const searchPath = typeof inlineOptions === "string" ? inlineOptions : config2.root;
result = postcssrc({}, searchPath).catch((e2) => {
if (!e2.message.includes("No PostCSS Config found")) {
if (e2 instanceof Error) {
const { name: name2, message, stack } = e2;
e2.name = "Failed to load PostCSS config";
e2.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name2}] ${message}
${stack}`;
e2.stack = "";
throw e2;
} else {
throw new Error(`Failed to load PostCSS config: ${e2}`);
}
}
return null;
});
result.then((resolved) => {
postcssConfigCache.set(config2, resolved);
});
}
postcssConfigCache.set(config2, result);
return result;
}
var cssUrlRE = new RegExp(`(?<=^|[^\\w\\-\\u0080-\\uffff])url\\((\\s*('[^']+'|"[^"]+")\\s*|[^'")]+)\\)`);
var cssDataUriRE = new RegExp(`(?<=^|[^\\w\\-\\u0080-\\uffff])data-uri\\((\\s*('[^']+'|"[^"]+")\\s*|[^'")]+)\\)`);
var importCssRE = /@import ('[^']+\.css'|"[^"]+\.css"|[^'")]+\.css)/;
var cssImageSetRE = new RegExp("(?<=image-set\\()((?:[\\w\\-]{1,256}\\([^)]*\\)|[^)])*)(?=\\))");
var UrlRewritePostcssPlugin = (opts) => {
if (!opts) {
throw new Error("base or replace is required");
}
return {
postcssPlugin: "vite-url-rewrite",
Once(root) {
const promises2 = [];
root.walkDecls((declaration) => {
var _a4;
const importer = (_a4 = declaration.source) == null ? void 0 : _a4.input.file;
if (!importer) {
opts.logger.warnOnce(
"\nA PostCSS plugin did not pass the `from` option to `postcss.parse`. This may cause imported assets to be incorrectly transformed. If you've recently added a PostCSS plugin that raised this warning, please contact the package author to fix the issue."
);
}
const isCssUrl = cssUrlRE.test(declaration.value);
const isCssImageSet = cssImageSetRE.test(declaration.value);
if (isCssUrl || isCssImageSet) {
const replacerForDeclaration = (rawUrl) => {
return opts.replacer(rawUrl, importer);
};
const rewriterToUse = isCssImageSet ? rewriteCssImageSet : rewriteCssUrls;
promises2.push(
rewriterToUse(declaration.value, replacerForDeclaration).then(
(url2) => {
declaration.value = url2;
}
)
);
}
});
if (promises2.length) {
return Promise.all(promises2);
}
}
};
};
UrlRewritePostcssPlugin.postcss = true;
function rewriteCssUrls(css, replacer) {
return asyncReplace(css, cssUrlRE, async (match2) => {
const [matched, rawUrl] = match2;
return await doUrlReplace(rawUrl.trim(), matched, replacer);
});
}
function rewriteCssDataUris(css, replacer) {
return asyncReplace(css, cssDataUriRE, async (match2) => {
const [matched, rawUrl] = match2;
return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
});
}
function rewriteImportCss(css, replacer) {
return asyncReplace(css, importCssRE, async (match2) => {
const [matched, rawUrl] = match2;
return await doImportCSSReplace(rawUrl, matched, replacer);
});
}
var cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
async function rewriteCssImageSet(css, replacer) {
return await asyncReplace(css, cssImageSetRE, async (match2) => {
const [, rawUrl] = match2;
const url2 = await processSrcSet(rawUrl, async ({ url: url22 }) => {
if (cssUrlRE.test(url22)) {
return await rewriteCssUrls(url22, replacer);
}
if (!cssNotProcessedRE.test(url22)) {
return await doUrlReplace(url22, url22, replacer);
}
return url22;
});
return url2;
});
}
function skipUrlReplacer(rawUrl) {
return isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === "#" || functionCallRE.test(rawUrl);
}
async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
let wrap2 = "";
const first2 = rawUrl[0];
if (first2 === `"` || first2 === `'`) {
wrap2 = first2;
rawUrl = rawUrl.slice(1, -1);
}
if (skipUrlReplacer(rawUrl)) {
return matched;
}
let newUrl = await replacer(rawUrl);
if (wrap2 === "" && newUrl !== encodeURI(newUrl)) {
wrap2 = '"';
}
if (wrap2 === "'" && newUrl.includes("'")) {
wrap2 = '"';
}
if (wrap2 === '"' && newUrl.includes('"')) {
newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, '\\"');
}
return `${funcName}(${wrap2}${newUrl}${wrap2})`;
}
async function doImportCSSReplace(rawUrl, matched, replacer) {
let wrap2 = "";
const first2 = rawUrl[0];
if (first2 === `"` || first2 === `'`) {
wrap2 = first2;
rawUrl = rawUrl.slice(1, -1);
}
if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl[0] === "#") {
return matched;
}
return `@import ${wrap2}${await replacer(rawUrl)}${wrap2}`;
}
async function minifyCSS(css, config2, inlined) {
var _a4;
if (config2.build.cssMinify === "lightningcss") {
const { code, warnings } = (await importLightningCSS()).transform({
...(_a4 = config2.css) == null ? void 0 : _a4.lightningcss,
targets: convertTargets(config2.build.cssTarget),
cssModules: void 0,
filename: cssBundleName,
code: Buffer.from(css),
minify: true
});
if (warnings.length) {
config2.logger.warn(
colors$1.yellow(
`warnings when minifying css:
${warnings.map((w) => w.message).join("\n")}`
)
);
}
return decoder.decode(code) + (inlined ? "" : "\n");
}
try {
const { code, warnings } = await (0, import_esbuild.transform)(css, {
loader: "css",
target: config2.build.cssTarget || void 0,
...resolveMinifyCssEsbuildOptions(config2.esbuild || {})
});
if (warnings.length) {
const msgs = await (0, import_esbuild.formatMessages)(warnings, { kind: "warning" });
config2.logger.warn(
colors$1.yellow(`warnings when minifying css:
${msgs.join("\n")}`)
);
}
return inlined ? code.trimEnd() : code;
} catch (e2) {
if (e2.errors) {
e2.message = "[esbuild css minify] " + e2.message;
const msgs = await (0, import_esbuild.formatMessages)(e2.errors, { kind: "error" });
e2.frame = "\n" + msgs.join("\n");
e2.loc = e2.errors[0].location;
}
throw e2;
}
}
function resolveMinifyCssEsbuildOptions(options2) {
const base = {
charset: options2.charset ?? "utf8",
logLevel: options2.logLevel,
logLimit: options2.logLimit,
logOverride: options2.logOverride,
legalComments: options2.legalComments
};
if (options2.minifyIdentifiers != null || options2.minifySyntax != null || options2.minifyWhitespace != null) {
return {
...base,
minifyIdentifiers: options2.minifyIdentifiers ?? true,
minifySyntax: options2.minifySyntax ?? true,
minifyWhitespace: options2.minifyWhitespace ?? true
};
} else {
return { ...base, minify: true };
}
}
var atImportRE = new RegExp(`@import(?:\\s*(?:url\\([^)]*\\)|"(?:[^"]|(?<=\\\\)")*"|'(?:[^']|(?<=\\\\)')*').*?|[^;]*);`, "g");
var atCharsetRE = new RegExp(`@charset(?:\\s*(?:"(?:[^"]|(?<=\\\\)")*"|'(?:[^']|(?<=\\\\)')*').*?|[^;]*);`, "g");
async function hoistAtRules(css) {
const s = new MagicString(css);
const cleanCss = emptyCssComments(css);
let match2;
atImportRE.lastIndex = 0;
while (match2 = atImportRE.exec(cleanCss)) {
s.remove(match2.index, match2.index + match2[0].length);
s.appendLeft(0, match2[0]);
}
atCharsetRE.lastIndex = 0;
let foundCharset = false;
while (match2 = atCharsetRE.exec(cleanCss)) {
s.remove(match2.index, match2.index + match2[0].length);
if (!foundCharset) {
s.prepend(match2[0]);
foundCharset = true;
}
}
return s.toString();
}
var loadedPreprocessorPath = {};
function loadPreprocessorPath(lang, root) {
const cached = loadedPreprocessorPath[lang];
if (cached) {
return cached;
}
try {
const resolved = requireResolveFromRootWithFallback(root, lang);
return loadedPreprocessorPath[lang] = resolved;
} catch (e2) {
if (e2.code === "MODULE_NOT_FOUND") {
const installCommand = getPackageManagerCommand("install");
throw new Error(
`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`
);
} else {
const message = new Error(
`Preprocessor dependency "${lang}" failed to load:
${e2.message}`
);
message.stack = e2.stack + "\n" + message.stack;
throw message;
}
}
}
var cachedSss;
function loadSss(root) {
if (cachedSss) return cachedSss;
const sssPath = loadPreprocessorPath("sugarss", root);
cachedSss = (0, import_node_module.createRequire)(import.meta.url)(sssPath);
return cachedSss;
}
function cleanScssBugUrl(url2) {
if (
// check bug via `window` and `location` global
typeof window !== "undefined" && typeof location !== "undefined" && typeof (location == null ? void 0 : location.href) === "string"
) {
const prefix = location.href.replace(/\/$/, "");
return url2.replace(prefix, "");
} else {
return url2;
}
}
function fixScssBugImportValue(data) {
if (
// check bug via `window` and `location` global
typeof window !== "undefined" && typeof location !== "undefined" && data && "file" in data && (!("contents" in data) || data.contents == null)
) {
data.contents = import_node_fs2.default.readFileSync(data.file, "utf-8");
}
return data;
}
var makeScssWorker = (resolvers, alias2, maxWorkers) => {
const internalImporter = async (url2, importer, filename) => {
importer = cleanScssBugUrl(importer);
const resolved = await resolvers.sass(url2, importer);
if (resolved) {
try {
const data = await rebaseUrls(
resolved,
filename,
alias2,
"$",
resolvers.sass
);
return fixScssBugImportValue(data);
} catch (data) {
return data;
}
} else {
return null;
}
};
const worker = new WorkerWithFallback(
() => async (sassPath, data, options2) => {
const sass = require2(sassPath);
const path22 = require2("node:path");
const _internalImporter = (url2, importer2, done) => {
internalImporter(url2, importer2, options2.filename).then(
(data2) => done == null ? void 0 : done(data2)
);
};
const importer = [_internalImporter];
if (options2.importer) {
Array.isArray(options2.importer) ? importer.unshift(...options2.importer) : importer.unshift(options2.importer);
}
const finalOptions = {
...options2,
data,
file: options2.filename,
outFile: options2.filename,
importer,
...options2.enableSourcemap ? {
sourceMap: true,
omitSourceMapUrl: true,
sourceMapRoot: path22.dirname(options2.filename)
} : {}
};
return new Promise((resolve3, reject) => {
sass.render(finalOptions, (err2, res) => {
var _a4;
if (err2) {
reject(err2);
} else {
resolve3({
css: res.css.toString(),
map: (_a4 = res.map) == null ? void 0 : _a4.toString(),
stats: res.stats
});
}
});
});
},
{
parentFunctions: { internalImporter },
shouldUseFake(_sassPath, _data, options2) {
return !!(options2.functions && Object.keys(options2.functions).length > 0 || options2.importer && (!Array.isArray(options2.importer) || options2.importer.length > 0));
},
max: maxWorkers
}
);
return worker;
};
var scssProcessor = (maxWorkers) => {
const workerMap = /* @__PURE__ */ new Map();
return {
close() {
for (const worker of workerMap.values()) {
worker.stop();
}
},
async process(source, root, options2, resolvers) {
const sassPath = loadPreprocessorPath("sass", root);
if (!workerMap.has(options2.alias)) {
workerMap.set(
options2.alias,
makeScssWorker(resolvers, options2.alias, maxWorkers)
);
}
const worker = workerMap.get(options2.alias);
const { content: data, map: additionalMap } = await getSource(
source,
options2.filename,
options2.additionalData,
options2.enableSourcemap
);
const optionsWithoutAdditionalData = {
...options2,
additionalData: void 0
};
try {
const result = await worker.run(
sassPath,
data,
optionsWithoutAdditionalData
);
const deps = result.stats.includedFiles.map((f2) => cleanScssBugUrl(f2));
const map2 = result.map ? JSON.parse(result.map.toString()) : void 0;
return {
code: result.css.toString(),
map: map2,
additionalMap,
deps
};
} catch (e2) {
e2.message = `[sass] ${e2.message}`;
e2.id = e2.file;
e2.frame = e2.formatted;
return { code: "", error: e2, deps: [] };
}
}
};
};
async function rebaseUrls(file, rootFile, alias2, variablePrefix, resolver) {
file = import_node_path3.default.resolve(file);
const fileDir = import_node_path3.default.dirname(file);
const rootDir = import_node_path3.default.dirname(rootFile);
if (fileDir === rootDir) {
return { file };
}
const content = await import_promises.default.readFile(file, "utf-8");
const hasUrls = cssUrlRE.test(content);
const hasDataUris = cssDataUriRE.test(content);
const hasImportCss = importCssRE.test(content);
if (!hasUrls && !hasDataUris && !hasImportCss) {
return { file };
}
let rebased;
const rebaseFn = async (url2) => {
if (url2[0] === "/") return url2;
if (url2.startsWith(variablePrefix)) return url2;
for (const { find: find2 } of alias2) {
const matches2 = typeof find2 === "string" ? url2.startsWith(find2) : find2.test(url2);
if (matches2) {
return url2;
}
}
const absolute = await resolver(url2, file) || import_node_path3.default.resolve(fileDir, url2);
const relative2 = import_node_path3.default.relative(rootDir, absolute);
return normalizePath$3(relative2);
};
if (hasImportCss) {
rebased = await rewriteImportCss(content, rebaseFn);
}
if (hasUrls) {
rebased = await rewriteCssUrls(rebased || content, rebaseFn);
}
if (hasDataUris) {
rebased = await rewriteCssDataUris(rebased || content, rebaseFn);
}
return {
file,
contents: rebased
};
}
var makeLessWorker = (resolvers, alias2, maxWorkers) => {
const viteLessResolve = async (filename, dir, rootFile) => {
const resolved = await resolvers.less(filename, import_node_path3.default.join(dir, "*"));
if (!resolved) return void 0;
const result = await rebaseUrls(
resolved,
rootFile,
alias2,
"@",
resolvers.less
);
if (result) {
return {
resolved,
contents: "contents" in result ? result.contents : void 0
};
}
return result;
};
const worker = new WorkerWithFallback(
() => {
const fsp2 = require2("node:fs/promises");
const path22 = require2("node:path");
let ViteLessManager;
const createViteLessPlugin = (less, rootFile) => {
const { FileManager } = less;
ViteLessManager ?? (ViteLessManager = class ViteManager extends FileManager {
constructor(rootFile2) {
super();
__publicField(this, "rootFile");
this.rootFile = rootFile2;
}
supports(filename) {
return !/^(?:https?:)?\/\//.test(filename);
}
supportsSync() {
return false;
}
async loadFile(filename, dir, opts, env2) {
const result = await viteLessResolve(filename, dir, this.rootFile);
if (result) {
return {
filename: path22.resolve(result.resolved),
contents: result.contents ?? await fsp2.readFile(result.resolved, "utf-8")
};
} else {
return super.loadFile(filename, dir, opts, env2);
}
}
});
return {
install(_, pluginManager) {
pluginManager.addFileManager(new ViteLessManager(rootFile));
},
minVersion: [3, 0, 0]
};
};
return async (lessPath, content, options2) => {
const nodeLess = require2(lessPath);
const viteResolverPlugin = createViteLessPlugin(
nodeLess,
options2.filename
);
const result = await nodeLess.render(content, {
...options2,
plugins: [viteResolverPlugin, ...options2.plugins || []],
...options2.enableSourcemap ? {
sourceMap: {
outputSourceFiles: true,
sourceMapFileInline: false
}
} : {}
});
return result;
};
},
{
parentFunctions: { viteLessResolve },
shouldUseFake(_lessPath, _content, options2) {
var _a4;
return ((_a4 = options2.plugins) == null ? void 0 : _a4.length) > 0;
},
max: maxWorkers
}
);
return worker;
};
var lessProcessor = (maxWorkers) => {
const workerMap = /* @__PURE__ */ new Map();
return {
close() {
for (const worker of workerMap.values()) {
worker.stop();
}
},
async process(source, root, options2, resolvers) {
const lessPath = loadPreprocessorPath("less", root);
if (!workerMap.has(options2.alias)) {
workerMap.set(
options2.alias,
makeLessWorker(resolvers, options2.alias, maxWorkers)
);
}
const worker = workerMap.get(options2.alias);
const { content, map: additionalMap } = await getSource(
source,
options2.filename,
options2.additionalData,
options2.enableSourcemap
);
let result;
const optionsWithoutAdditionalData = {
...options2,
additionalData: void 0
};
try {
result = await worker.run(
lessPath,
content,
optionsWithoutAdditionalData
);
} catch (e2) {
const error2 = e2;
const normalizedError = new Error(
`[less] ${error2.message || error2.type}`
);
normalizedError.loc = {
file: error2.filename || options2.filename,
line: error2.line,
column: error2.column
};
return { code: "", error: normalizedError, deps: [] };
}
const map2 = result.map && JSON.parse(result.map);
if (map2) {
delete map2.sourcesContent;
}
return {
code: result.css.toString(),
map: map2,
additionalMap,
deps: result.imports
};
}
};
};
var makeStylWorker = (maxWorkers) => {
const worker = new WorkerWithFallback(
() => {
return async (stylusPath, content, root, options2) => {
const nodeStylus = require2(stylusPath);
const ref = nodeStylus(content, options2);
if (options2.define) {
for (const key in options2.define) {
ref.define(key, options2.define[key]);
}
}
if (options2.enableSourcemap) {
ref.set("sourcemap", {
comment: false,
inline: false,
basePath: root
});
}
return {
code: ref.render(),
// @ts-expect-error sourcemap exists
map: ref.sourcemap,
deps: ref.deps()
};
};
},
{
shouldUseFake(_stylusPath, _content, _root2, options2) {
return !!(options2.define && Object.values(options2.define).some((d) => typeof d === "function"));
},
max: maxWorkers
}
);
return worker;
};
var stylProcessor = (maxWorkers) => {
const workerMap = /* @__PURE__ */ new Map();
return {
close() {
for (const worker of workerMap.values()) {
worker.stop();
}
},
async process(source, root, options2, resolvers) {
const stylusPath = loadPreprocessorPath("stylus", root);
if (!workerMap.has(options2.alias)) {
workerMap.set(options2.alias, makeStylWorker(maxWorkers));
}
const worker = workerMap.get(options2.alias);
const { content, map: additionalMap } = await getSource(
source,
options2.filename,
options2.additionalData,
options2.enableSourcemap,
"\n"
);
const importsDeps = (options2.imports ?? []).map(
(dep) => import_node_path3.default.resolve(dep)
);
const optionsWithoutAdditionalData = {
...options2,
additionalData: void 0
};
try {
const { code, map: map2, deps } = await worker.run(
stylusPath,
content,
root,
optionsWithoutAdditionalData
);
return {
code,
map: formatStylusSourceMap(map2, root),
additionalMap,
// Concat imports deps with computed deps
deps: [...deps, ...importsDeps]
};
} catch (e2) {
const wrapped = new Error(`[stylus] ${e2.message}`);
wrapped.name = e2.name;
wrapped.stack = e2.stack;
return { code: "", error: wrapped, deps: [] };
}
}
};
};
function formatStylusSourceMap(mapBefore, root) {
if (!mapBefore) return void 0;
const map2 = { ...mapBefore };
const resolveFromRoot = (p) => normalizePath$3(import_node_path3.default.resolve(root, p));
if (map2.file) {
map2.file = resolveFromRoot(map2.file);
}
map2.sources = map2.sources.map(resolveFromRoot);
return map2;
}
async function getSource(source, filename, additionalData, enableSourcemap, sep2 = "") {
if (!additionalData) return { content: source };
if (typeof additionalData === "function") {
const newContent = await additionalData(source, filename);
if (typeof newContent === "string") {
return { content: newContent };
}
return newContent;
}
if (!enableSourcemap) {
return { content: additionalData + sep2 + source };
}
const ms2 = new MagicString(source);
ms2.appendLeft(0, sep2);
ms2.appendLeft(0, additionalData);
const map2 = ms2.generateMap({ hires: "boundary" });
map2.file = filename;
map2.sources = [filename];
return {
content: ms2.toString(),
map: map2
};
}
var createPreprocessorWorkerController = (maxWorkers) => {
const scss = scssProcessor(maxWorkers);
const less = lessProcessor(maxWorkers);
const styl = stylProcessor(maxWorkers);
const sassProcess = (source, root, options2, resolvers) => {
return scss.process(
source,
root,
{ ...options2, indentedSyntax: true },
resolvers
);
};
const close2 = () => {
less.close();
scss.close();
styl.close();
};
return {
[
"less"
/* less */
]: less.process,
[
"scss"
/* scss */
]: scss.process,
[
"sass"
/* sass */
]: sassProcess,
[
"styl"
/* styl */
]: styl.process,
[
"stylus"
/* stylus */
]: styl.process,
close: close2
};
};
var normalizeMaxWorkers = (maxWorker) => {
if (maxWorker === void 0) return 0;
if (maxWorker === true) return void 0;
return maxWorker;
};
var preprocessorSet = /* @__PURE__ */ new Set([
"less",
"sass",
"scss",
"styl",
"stylus"
/* stylus */
]);
function isPreProcessor(lang) {
return lang && preprocessorSet.has(lang);
}
var importLightningCSS = createCachedImport(() => import("./__vite-optional-peer-dep_lightningcss_vite-LUUMBJI5.js"));
async function compileLightningCSS(id, src2, config2, urlReplacer) {
var _a4, _b3, _c2, _d2, _e2, _f2, _g2;
const deps = /* @__PURE__ */ new Set();
const filename = cleanUrl(import_node_path3.default.relative(config2.root, id));
const toAbsolute = (filePath) => import_node_path3.default.isAbsolute(filePath) ? filePath : import_node_path3.default.join(config2.root, filePath);
const res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
filename,
code: Buffer.from(src2),
targets: (_b3 = (_a4 = config2.css) == null ? void 0 : _a4.lightningcss) == null ? void 0 : _b3.targets,
minify: config2.isProduction && !!config2.build.cssMinify,
analyzeDependencies: true
}) : await (await importLightningCSS()).bundleAsync({
...(_c2 = config2.css) == null ? void 0 : _c2.lightningcss,
filename,
resolver: {
read(filePath) {
if (filePath === filename) {
return src2;
}
if (!filePath.endsWith(".css")) {
return src2;
}
return import_node_fs2.default.readFileSync(toAbsolute(filePath), "utf-8");
},
async resolve(id2, from) {
const publicFile = checkPublicFile(id2, config2);
if (publicFile) {
return publicFile;
}
const resolved = await getAtImportResolvers(config2).css(
id2,
toAbsolute(from)
);
if (resolved) {
deps.add(resolved);
return resolved;
}
return id2;
}
},
minify: config2.isProduction && !!config2.build.cssMinify,
sourceMap: config2.command === "build" ? !!config2.build.sourcemap : (_d2 = config2.css) == null ? void 0 : _d2.devSourcemap,
analyzeDependencies: true,
cssModules: cssModuleRE.test(id) ? ((_f2 = (_e2 = config2.css) == null ? void 0 : _e2.lightningcss) == null ? void 0 : _f2.cssModules) ?? true : void 0
});
let css = decoder.decode(res.code);
for (const dep of res.dependencies) {
switch (dep.type) {
case "url":
if (skipUrlReplacer(dep.url)) {
css = css.replace(dep.placeholder, () => dep.url);
break;
}
deps.add(dep.url);
if (urlReplacer) {
const replaceUrl = await urlReplacer(dep.url, id);
css = css.replace(dep.placeholder, () => replaceUrl);
} else {
css = css.replace(dep.placeholder, () => dep.url);
}
break;
default:
throw new Error(`Unsupported dependency type: ${dep.type}`);
}
}
let modules;
if ("exports" in res && res.exports) {
modules = {};
const sortedEntries = Object.entries(res.exports).sort(
(a, b) => a[0].localeCompare(b[0])
);
for (const [key, value2] of sortedEntries) {
modules[key] = value2.name;
for (const c of value2.composes) {
modules[key] += " " + c.name;
}
}
}
return {
code: css,
map: "map" in res ? (_g2 = res.map) == null ? void 0 : _g2.toString() : void 0,
deps,
modules
};
}
var map = {
chrome: "chrome",
edge: "edge",
firefox: "firefox",
hermes: false,
ie: "ie",
ios: "ios_saf",
node: false,
opera: "opera",
rhino: false,
safari: "safari"
};
var esMap = {
// https://caniuse.com/?search=es2015
2015: ["chrome49", "edge13", "safari10", "firefox44", "opera36"],
// https://caniuse.com/?search=es2016
2016: ["chrome50", "edge13", "safari10", "firefox43", "opera37"],
// https://caniuse.com/?search=es2017
2017: ["chrome58", "edge15", "safari11", "firefox52", "opera45"],
// https://caniuse.com/?search=es2018
2018: ["chrome63", "edge79", "safari12", "firefox58", "opera50"],
// https://caniuse.com/?search=es2019
2019: ["chrome73", "edge79", "safari12.1", "firefox64", "opera60"],
// https://caniuse.com/?search=es2020
2020: ["chrome80", "edge80", "safari14.1", "firefox80", "opera67"],
// https://caniuse.com/?search=es2021
2021: ["chrome85", "edge85", "safari14.1", "firefox80", "opera71"],
// https://caniuse.com/?search=es2022
2022: ["chrome94", "edge94", "safari16.4", "firefox93", "opera80"]
};
var esRE = /es(\d{4})/;
var versionRE = /\d/;
var convertTargetsCache = /* @__PURE__ */ new Map();
var convertTargets = (esbuildTarget) => {
if (!esbuildTarget) return {};
const cached = convertTargetsCache.get(esbuildTarget);
if (cached) return cached;
const targets = {};
const entriesWithoutES = arraify(esbuildTarget).flatMap((e2) => {
const match2 = e2.match(esRE);
if (!match2) return e2;
const year = Number(match2[1]);
if (!esMap[year]) throw new Error(`Unsupported target "${e2}"`);
return esMap[year];
});
for (const entry2 of entriesWithoutES) {
if (entry2 === "esnext") continue;
const index = entry2.search(versionRE);
if (index >= 0) {
const browser2 = map[entry2.slice(0, index)];
if (browser2 === false) continue;
if (browser2) {
const [major, minor = 0] = entry2.slice(index).split(".").map((v) => parseInt(v, 10));
if (!isNaN(major) && !isNaN(minor)) {
const version3 = major << 16 | minor << 8;
if (!targets[browser2] || version3 < targets[browser2]) {
targets[browser2] = version3;
}
continue;
}
}
}
throw new Error(`Unsupported target "${entry2}"`);
}
convertTargetsCache.set(esbuildTarget, targets);
return targets;
};
var HASH_RE = /#/g;
var AMPERSAND_RE = /&/g;
var SLASH_RE = /\//g;
var EQUAL_RE = /=/g;
var PLUS_RE = /\+/g;
var ENC_CARET_RE = /%5e/gi;
var ENC_BACKTICK_RE = /%60/gi;
var ENC_PIPE_RE = /%7c/gi;
var ENC_SPACE_RE = /%20/gi;
function encode(text) {
return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
}
function encodeQueryValue(input) {
return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
}
function encodeQueryKey(text) {
return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
}
function encodeQueryItem(key, value2) {
if (typeof value2 === "number" || typeof value2 === "boolean") {
value2 = String(value2);
}
if (!value2) {
return encodeQueryKey(key);
}
if (Array.isArray(value2)) {
return value2.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
}
return `${encodeQueryKey(key)}=${encodeQueryValue(value2)}`;
}
function stringifyQuery(query) {
return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
}
new Set(import_node_module.builtinModules);
function clearImports(imports) {
return (imports || "").replace(/(\/\/[^\n]*\n|\/\*.*\*\/)/g, "").replace(/\s+/g, " ");
}
function getImportNames(cleanedImports) {
var _a4, _b3;
const topLevelImports = cleanedImports.replace(/{([^}]*)}/, "");
const namespacedImport = (_a4 = topLevelImports.match(/\* as \s*(\S*)/)) == null ? void 0 : _a4[1];
const defaultImport = ((_b3 = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))) == null ? void 0 : _b3.trim()) || void 0;
return {
namespacedImport,
defaultImport
};
}
var own$1 = {}.hasOwnProperty;
var classRegExp = /^([A-Z][a-z\d]*)+$/;
var kTypes = /* @__PURE__ */ new Set([
"string",
"function",
"number",
"object",
// Accept 'Function' and 'Object' as alternative to the lower cased version.
"Function",
"Object",
"boolean",
"bigint",
"symbol"
]);
function formatList(array2, type = "and") {
return array2.length < 3 ? array2.join(` ${type} `) : `${array2.slice(0, -1).join(", ")}, ${type} ${array2[array2.length - 1]}`;
}
var messages = /* @__PURE__ */ new Map();
var nodeInternalPrefix = "__node_internal_";
var userStackTraceLimit;
createError(
"ERR_INVALID_ARG_TYPE",
/**
* @param {string} name
* @param {Array<string> | string} expected
* @param {unknown} actual
*/
(name2, expected, actual) => {
(0, import_node_assert.default)(typeof name2 === "string", "'name' must be a string");
if (!Array.isArray(expected)) {
expected = [expected];
}
let message = "The ";
if (name2.endsWith(" argument")) {
message += `${name2} `;
} else {
const type = name2.includes(".") ? "property" : "argument";
message += `"${name2}" ${type} `;
}
message += "must be ";
const types2 = [];
const instances = [];
const other = [];
for (const value2 of expected) {
(0, import_node_assert.default)(
typeof value2 === "string",
"All expected entries have to be of type string"
);
if (kTypes.has(value2)) {
types2.push(value2.toLowerCase());
} else if (classRegExp.exec(value2) === null) {
(0, import_node_assert.default)(
value2 !== "object",
'The value "object" should be written as "Object"'
);
other.push(value2);
} else {
instances.push(value2);
}
}
if (instances.length > 0) {
const pos = types2.indexOf("object");
if (pos !== -1) {
types2.slice(pos, 1);
instances.push("Object");
}
}
if (types2.length > 0) {
message += `${types2.length > 1 ? "one of type" : "of type"} ${formatList(
types2,
"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
);
createError(
"ERR_INVALID_MODULE_SPECIFIER",
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request, reason, base = void 0) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
},
TypeError
);
createError(
"ERR_INVALID_PACKAGE_CONFIG",
/**
* @param {string} path
* @param {string} [base]
* @param {string} [message]
*/
(path3, base, message) => {
return `Invalid package config ${path3}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
},
Error
);
createError(
"ERR_INVALID_PACKAGE_TARGET",
/**
* @param {string} packagePath
* @param {string} key
* @param {unknown} target
* @param {boolean} [isImport=false]
* @param {string} [base]
*/
(packagePath, key, target, isImport = false, base = void 0) => {
const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
if (key === ".") {
(0, import_node_assert.default)(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} 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
)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
},
Error
);
createError(
"ERR_MODULE_NOT_FOUND",
/**
* @param {string} path
* @param {string} base
* @param {boolean} [exactUrl]
*/
(path3, base, exactUrl = false) => {
return `Cannot find ${exactUrl ? "module" : "package"} '${path3}' imported from ${base}`;
},
Error
);
createError(
"ERR_NETWORK_IMPORT_DISALLOWED",
"import of '%s' by %s is not supported: %s",
Error
);
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
);
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
);
createError(
"ERR_UNSUPPORTED_DIR_IMPORT",
"Directory import '%s' is not supported resolving ES modules imported from %s",
Error
);
createError(
"ERR_UNSUPPORTED_RESOLVE_REQUEST",
'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
TypeError
);
createError(
"ERR_UNKNOWN_FILE_EXTENSION",
/**
* @param {string} extension
* @param {string} path
*/
(extension2, path3) => {
return `Unknown file extension "${extension2}" for ${path3}`;
},
TypeError
);
createError(
"ERR_INVALID_ARG_VALUE",
/**
* @param {string} name
* @param {unknown} value
* @param {string} [reason='is invalid']
*/
(name2, value2, reason = "is invalid") => {
let inspected = (0, import_node_util.inspect)(value2);
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`;
}
const type = name2.includes(".") ? "property" : "argument";
return `The ${type} '${name2}' ${reason}. Received ${inspected}`;
},
TypeError
// Note: extra classes have been shaken out.
// , RangeError
);
function createError(sym, value2, constructor) {
messages.set(sym, value2);
return makeNodeErrorWithCode(constructor, sym);
}
function makeNodeErrorWithCode(Base, key) {
return NodeError;
function NodeError(...parameters) {
const limit = Error.stackTraceLimit;
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
const error2 = new Base();
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
const message = getMessage(key, parameters, error2);
Object.defineProperties(error2, {
// Note: no need to implement `kIsNodeError` symbol, would be hard,
// probably.
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
/** @this {Error} */
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
}
});
captureLargerStackTrace(error2);
error2.code = key;
return error2;
}
}
function isErrorStackTraceLimitWritable() {
try {
if (import_node_v8.default.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;
}
function hideStackFrames(wrappedFunction) {
const hidden = nodeInternalPrefix + wrappedFunction.name;
Object.defineProperty(wrappedFunction, "name", { value: hidden });
return wrappedFunction;
}
var captureLargerStackTrace = hideStackFrames(
/**
* @param {Error} error
* @returns {Error}
*/
// @ts-expect-error: fine
function(error2) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error2);
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
return error2;
}
);
function getMessage(key, parameters, self2) {
const message = messages.get(key);
(0, import_node_assert.default)(message !== void 0, "expected `message` to be found");
if (typeof message === "function") {
(0, import_node_assert.default)(
message.length <= parameters.length,
// Default options do not count.
`Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
);
return Reflect.apply(message, self2, parameters);
}
const regex2 = /%[dfijoOs]/g;
let expectedLength = 0;
while (regex2.exec(message) !== null) expectedLength++;
(0, import_node_assert.default)(
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(import_node_util.format, null, parameters);
}
function determineSpecificType(value2) {
if (value2 === null || value2 === void 0) {
return String(value2);
}
if (typeof value2 === "function" && value2.name) {
return `function ${value2.name}`;
}
if (typeof value2 === "object") {
if (value2.constructor && value2.constructor.name) {
return `an instance of ${value2.constructor.name}`;
}
return `${(0, import_node_util.inspect)(value2, { depth: -1 })}`;
}
let inspected = (0, import_node_util.inspect)(value2, { colors: false });
if (inspected.length > 28) {
inspected = `${inspected.slice(0, 25)}...`;
}
return `type ${typeof value2} (${inspected})`;
}
var ESM_STATIC_IMPORT_RE = new RegExp(`(?<=\\s|^|;|\\})import\\s*([\\s"']*(?<imports>[\\p{L}\\p{M}\\w\\t\\n\\r $*,/{}@.]+)from\\s*)?["']\\s*(?<specifier>(?<="\\s*)[^"]*[^\\s"](?=\\s*")|(?<='\\s*)[^']*[^\\s'](?=\\s*'))\\s*["'][\\s;]*`, "gmu");
var TYPE_RE = /^\s*?type\s/;
function parseStaticImport(matched) {
var _a4, _b3;
const cleanedImports = clearImports(matched.imports);
const namedImports = {};
const _matches = ((_b3 = (_a4 = cleanedImports.match(/{([^}]*)}/)) == null ? void 0 : _a4[1]) == null ? void 0 : _b3.split(",")) || [];
for (const namedImport of _matches) {
const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
const source = (_match == null ? void 0 : _match[1]) || namedImport.trim();
const importName = (_match == null ? void 0 : _match[2]) || source;
if (source && !TYPE_RE.test(source)) {
namedImports[source] = importName;
}
}
const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
return {
...matched,
defaultImport,
namespacedImport,
namedImports
};
}
var ESM_RE = /([\s;]|^)(import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
var COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
function hasESMSyntax(code, opts = {}) {
if (opts.stripComments) {
code = code.replace(COMMENT_RE, "");
}
return ESM_RE.test(code);
}
var { isMatch: isMatch$1, scan } = micromatch$2;
function getAffectedGlobModules(file, server2) {
const modules = [];
for (const [id, allGlobs] of server2._importGlobMap) {
if (allGlobs.some(
({ affirmed, negated }) => (!affirmed.length || affirmed.some((glob2) => isMatch$1(file, glob2))) && (!negated.length || negated.every((glob2) => isMatch$1(file, glob2)))
)) {
const mod = server2.moduleGraph.getModuleById(id);
if (mod) modules.push(mod);
}
}
modules.forEach((i) => {
if (i == null ? void 0 : i.file) server2.moduleGraph.onFileChange(i.file);
});
return modules;
}
function importGlobPlugin(config2) {
let server2;
return {
name: "vite:import-glob",
configureServer(_server) {
server2 = _server;
server2._importGlobMap.clear();
},
async transform(code, id) {
if (!code.includes("import.meta.glob")) return;
const result = await transformGlobImport(
code,
id,
config2.root,
(im, _, options2) => this.resolve(im, id, options2).then((i) => (i == null ? void 0 : i.id) || im),
config2.experimental.importGlobRestoreExtension,
config2.logger
);
if (result) {
if (server2) {
const allGlobs = result.matches.map((i) => i.globsResolved);
server2._importGlobMap.set(
id,
allGlobs.map((globs) => {
const affirmed = [];
const negated = [];
for (const glob2 of globs) {
(glob2[0] === "!" ? negated : affirmed).push(glob2);
}
return { affirmed, negated };
})
);
}
return transformStableResult(result.s, id, config2);
}
}
};
}
var importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
var knownOptions = {
as: ["string"],
eager: ["boolean"],
import: ["string"],
exhaustive: ["boolean"],
query: ["object", "string"]
};
var forceDefaultAs = ["raw", "url"];
function err$1(e2, pos) {
const error2 = new Error(e2);
error2.pos = pos;
return error2;
}
function parseGlobOptions(rawOpts, optsStartIndex, logger) {
let opts = {};
try {
opts = evalValue(rawOpts);
} catch {
throw err$1(
"Vite is unable to parse the glob options as the value is not static",
optsStartIndex
);
}
if (opts == null) {
return {};
}
for (const key in opts) {
if (!(key in knownOptions)) {
throw err$1(`Unknown glob option "${key}"`, optsStartIndex);
}
const allowedTypes = knownOptions[key];
const valueType = typeof opts[key];
if (!allowedTypes.includes(valueType)) {
throw err$1(
`Expected glob option "${key}" to be of type ${allowedTypes.join(
" or "
)}, but got ${valueType}`,
optsStartIndex
);
}
}
if (typeof opts.query === "object") {
for (const key in opts.query) {
const value2 = opts.query[key];
if (!["string", "number", "boolean"].includes(typeof value2)) {
throw err$1(
`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value2}`,
optsStartIndex
);
}
}
opts.query = stringifyQuery(opts.query);
}
if (opts.as && logger) {
const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
logger.warn(
colors$1.yellow(
`The glob option "as" has been deprecated in favour of "query". Please update \`as: '${opts.as}'\` to \`query: '?${opts.as}'${importSuggestion}\`.`
)
);
}
if (opts.as && forceDefaultAs.includes(opts.as)) {
if (opts.import && opts.import !== "default" && opts.import !== "*")
throw err$1(
`Option "import" can only be "default" or "*" when "as" is "${opts.as}", but got "${opts.import}"`,
optsStartIndex
);
opts.import = opts.import || "default";
}
if (opts.as && opts.query)
throw err$1(
'Options "as" and "query" cannot be used together',
optsStartIndex
);
if (opts.as) opts.query = opts.as;
if (opts.query && opts.query[0] !== "?") opts.query = `?${opts.query}`;
return opts;
}
async function parseImportGlob(code, importer, root, resolveId, logger) {
let cleanCode;
try {
cleanCode = stripLiteral(code);
} catch (e2) {
return [];
}
const matches2 = Array.from(cleanCode.matchAll(importGlobRE));
const tasks2 = matches2.map(async (match2, index) => {
const start = match2.index;
const err2 = (msg) => {
const e2 = new Error(`Invalid glob import syntax: ${msg}`);
e2.pos = start;
return e2;
};
const end = findCorrespondingCloseParenthesisPosition(
cleanCode,
start + match2[0].length
) + 1;
if (end <= 0) {
throw err2("Close parenthesis not found");
}
const statementCode = code.slice(start, end);
const rootAst = (await parseAstAsync(statementCode)).body[0];
if (rootAst.type !== "ExpressionStatement") {
throw err2(`Expect CallExpression, got ${rootAst.type}`);
}
const ast = rootAst.expression;
if (ast.type !== "CallExpression") {
throw err2(`Expect CallExpression, got ${ast.type}`);
}
if (ast.arguments.length < 1 || ast.arguments.length > 2)
throw err2(`Expected 1-2 arguments, but got ${ast.arguments.length}`);
const arg1 = ast.arguments[0];
const arg2 = ast.arguments[1];
const globs = [];
const validateLiteral = (element) => {
if (!element) return;
if (element.type === "Literal") {
if (typeof element.value !== "string")
throw err2(
`Expected glob to be a string, but got "${typeof element.value}"`
);
globs.push(element.value);
} else if (element.type === "TemplateLiteral") {
if (element.expressions.length !== 0) {
throw err2(
`Expected glob to be a string, but got dynamic template literal`
);
}
globs.push(element.quasis[0].value.raw);
} else {
throw err2("Could only use literals");
}
};
if (arg1.type === "ArrayExpression") {
for (const element of arg1.elements) {
validateLiteral(element);
}
} else {
validateLiteral(arg1);
}
let options2 = {};
if (arg2) {
if (arg2.type !== "ObjectExpression")
throw err2(
`Expected the second argument to be an object literal, but got "${arg2.type}"`
);
options2 = parseGlobOptions(
code.slice(start + arg2.start, start + arg2.end),
start + arg2.start,
logger
);
}
const globsResolved = await Promise.all(
globs.map((glob2) => toAbsoluteGlob(glob2, root, importer, resolveId))
);
const isRelative2 = globs.every((i) => ".!".includes(i[0]));
return {
index,
globs,
globsResolved,
isRelative: isRelative2,
options: options2,
start,
end
};
});
return (await Promise.all(tasks2)).filter(Boolean);
}
function findCorrespondingCloseParenthesisPosition(cleanCode, openPos) {
const closePos = cleanCode.indexOf(")", openPos);
if (closePos < 0) return -1;
if (!cleanCode.slice(openPos, closePos).includes("(")) return closePos;
let remainingParenthesisCount = 0;
const cleanCodeLen = cleanCode.length;
for (let pos = openPos; pos < cleanCodeLen; pos++) {
switch (cleanCode[pos]) {
case "(": {
remainingParenthesisCount++;
break;
}
case ")": {
remainingParenthesisCount--;
if (remainingParenthesisCount <= 0) {
return pos;
}
}
}
}
return -1;
}
var importPrefix = "__vite_glob_";
var { basename, dirname, relative, join } = import_node_path3.posix;
async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
id = slash$1(id);
root = slash$1(root);
const isVirtual = isVirtualModule(id);
const dir = isVirtual ? void 0 : dirname(id);
const matches2 = await parseImportGlob(
code,
isVirtual ? void 0 : id,
root,
resolveId,
logger
);
const matchedFiles = /* @__PURE__ */ new Set();
if (!matches2.length) return null;
const s = new MagicString(code);
const staticImports = (await Promise.all(
matches2.map(
async ({ globsResolved, isRelative: isRelative2, options: options2, index, start, end }) => {
var _a4;
const cwd = getCommonBase(globsResolved) ?? root;
const files = (await glob(globsResolved, {
cwd,
absolute: true,
dot: !!options2.exhaustive,
ignore: options2.exhaustive ? [] : [join(cwd, "**/node_modules/**")]
})).filter((file) => file !== id).sort();
const objectProps = [];
const staticImports2 = [];
const resolvePaths = (file) => {
if (!dir) {
if (isRelative2)
throw new Error(
"In virtual modules, all globs must start with '/'"
);
const filePath2 = `/${relative(root, file)}`;
return { filePath: filePath2, importPath: filePath2 };
}
let importPath = relative(dir, file);
if (importPath[0] !== ".") importPath = `./${importPath}`;
let filePath;
if (isRelative2) {
filePath = importPath;
} else {
filePath = relative(root, file);
if (filePath[0] !== ".") filePath = `/${filePath}`;
}
return { filePath, importPath };
};
files.forEach((file, i) => {
const paths = resolvePaths(file);
const filePath = paths.filePath;
let importPath = paths.importPath;
let importQuery = options2.query ?? "";
if (importQuery && importQuery !== "?raw") {
const fileExtension = basename(file).split(".").slice(-1)[0];
if (fileExtension && restoreQueryExtension)
importQuery = `${importQuery}&lang.${fileExtension}`;
}
importPath = `${importPath}${importQuery}`;
const importKey = options2.import && options2.import !== "*" ? options2.import : void 0;
if (options2.eager) {
const variableName = `${importPrefix}${index}_${i}`;
const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
staticImports2.push(
`import ${expression} from ${JSON.stringify(importPath)}`
);
objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`);
} else {
let importStatement = `import(${JSON.stringify(importPath)})`;
if (importKey)
importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
objectProps.push(
`${JSON.stringify(filePath)}: () => ${importStatement}`
);
}
});
files.forEach((i) => matchedFiles.add(i));
const originalLineBreakCount = ((_a4 = code.slice(start, end).match(/\n/g)) == null ? void 0 : _a4.length) ?? 0;
const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
const replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(
","
)}${lineBreaks}})`;
s.overwrite(start, end, replacement);
return staticImports2;
}
)
)).flat();
if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
return {
s,
matches: matches2,
files: matchedFiles
};
}
function globSafePath(path3) {
return glob.escapePath(normalizePath$3(path3));
}
function lastNthChar(str, n2) {
return str.charAt(str.length - 1 - n2);
}
function globSafeResolvedPath(resolved, glob2) {
let numEqual = 0;
const maxEqual = Math.min(resolved.length, glob2.length);
while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob2, numEqual)) {
numEqual += 1;
}
const staticPartEnd = resolved.length - numEqual;
const staticPart = resolved.slice(0, staticPartEnd);
const dynamicPart = resolved.slice(staticPartEnd);
return globSafePath(staticPart) + dynamicPart;
}
async function toAbsoluteGlob(glob2, root, importer, resolveId) {
let pre = "";
if (glob2[0] === "!") {
pre = "!";
glob2 = glob2.slice(1);
}
root = globSafePath(root);
const dir = importer ? globSafePath(dirname(importer)) : root;
if (glob2[0] === "/") return pre + import_node_path3.posix.join(root, glob2.slice(1));
if (glob2.startsWith("./")) return pre + import_node_path3.posix.join(dir, glob2.slice(2));
if (glob2.startsWith("../")) return pre + import_node_path3.posix.join(dir, glob2);
if (glob2.startsWith("**")) return pre + glob2;
const isSubImportsPattern = glob2[0] === "#" && glob2.includes("*");
const resolved = normalizePath$3(
await resolveId(glob2, importer, {
custom: { "vite:import-glob": { isSubImportsPattern } }
}) || glob2
);
if ((0, import_node_path3.isAbsolute)(resolved)) {
return pre + globSafeResolvedPath(resolved, glob2);
}
throw new Error(
`Invalid glob: "${glob2}" (resolved: "${resolved}"). It must start with '/' or './'`
);
}
function getCommonBase(globsResolved) {
const bases = globsResolved.filter((g) => g[0] !== "!").map((glob2) => {
let { base } = scan(glob2);
if (import_node_path3.posix.basename(base).includes(".")) base = import_node_path3.posix.dirname(base);
return base;
});
if (!bases.length) return null;
let commonAncestor = "";
const dirS = bases[0].split("/");
for (let i = 0; i < dirS.length; i++) {
const candidate = dirS.slice(0, i + 1).join("/");
if (bases.every((base) => base.startsWith(candidate)))
commonAncestor = candidate;
else break;
}
if (!commonAncestor) commonAncestor = "/";
return commonAncestor;
}
function isVirtualModule(id) {
return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
}
var src = { exports: {} };
var browser = { exports: {} };
var debug$f = { exports: {} };
var ms;
var hasRequiredMs;
function requireMs() {
if (hasRequiredMs) return ms;
hasRequiredMs = 1;
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
ms = function(val, options2) {
options2 = options2 || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse4(val);
} else if (type === "number" && isNaN(val) === false) {
return options2.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse4(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match2 = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match2) {
return;
}
var n2 = parseFloat(match2[1]);
var type = (match2[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n2 * y;
case "days":
case "day":
case "d":
return n2 * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n2 * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n2 * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n2 * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n2;
default:
return void 0;
}
}
function fmtShort(ms2) {
if (ms2 >= d) {
return Math.round(ms2 / d) + "d";
}
if (ms2 >= h) {
return Math.round(ms2 / h) + "h";
}
if (ms2 >= m) {
return Math.round(ms2 / m) + "m";
}
if (ms2 >= s) {
return Math.round(ms2 / s) + "s";
}
return ms2 + "ms";
}
function fmtLong(ms2) {
return plural(ms2, d, "day") || plural(ms2, h, "hour") || plural(ms2, m, "minute") || plural(ms2, s, "second") || ms2 + " ms";
}
function plural(ms2, n2, name2) {
if (ms2 < n2) {
return;
}
if (ms2 < n2 * 1.5) {
return Math.floor(ms2 / n2) + " " + name2;
}
return Math.ceil(ms2 / n2) + " " + name2 + "s";
}
return ms;
}
var hasRequiredDebug;
function requireDebug() {
if (hasRequiredDebug) return debug$f.exports;
hasRequiredDebug = 1;
(function(module, exports2) {
exports2 = module.exports = createDebug.debug = createDebug["default"] = createDebug;
exports2.coerce = coerce;
exports2.disable = disable;
exports2.enable = enable;
exports2.enabled = enabled;
exports2.humanize = requireMs();
exports2.names = [];
exports2.skips = [];
exports2.formatters = {};
var prevTime;
function selectColor(namespace) {
var hash2 = 0, i;
for (i in namespace) {
hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
hash2 |= 0;
}
return exports2.colors[Math.abs(hash2) % exports2.colors.length];
}
function createDebug(namespace) {
function debug2() {
if (!debug2.enabled) return;
var self2 = debug2;
var curr = +/* @__PURE__ */ new Date();
var ms2 = curr - (prevTime || curr);
self2.diff = ms2;
self2.prev = prevTime;
self2.curr = curr;
prevTime = curr;
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports2.coerce(args[0]);
if ("string" !== typeof args[0]) {
args.unshift("%O");
}
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match2, format2) {
if (match2 === "%%") return match2;
index++;
var formatter2 = exports2.formatters[format2];
if ("function" === typeof formatter2) {
var val = args[index];
match2 = formatter2.call(self2, val);
args.splice(index, 1);
index--;
}
return match2;
});
exports2.formatArgs.call(self2, args);
var logFn = debug2.log || exports2.log || console.log.bind(console);
logFn.apply(self2, args);
}
debug2.namespace = namespace;
debug2.enabled = exports2.enabled(namespace);
debug2.useColors = exports2.useColors();
debug2.color = selectColor(namespace);
if ("function" === typeof exports2.init) {
exports2.init(debug2);
}
return debug2;
}
function enable(namespaces) {
exports2.save(namespaces);
exports2.names = [];
exports2.skips = [];
var split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue;
namespaces = split[i].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
exports2.skips.push(new RegExp("^" + namespaces.substr(1) + "$"));
} else {
exports2.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
exports2.enable("");
}
function enabled(name2) {
var i, len;
for (i = 0, len = exports2.skips.length; i < len; i++) {
if (exports2.skips[i].test(name2)) {
return false;
}
}
for (i = 0, len = exports2.names.length; i < len; i++) {
if (exports2.names[i].test(name2)) {
return true;
}
}
return false;
}
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
})(debug$f, debug$f.exports);
return debug$f.exports;
}
var hasRequiredBrowser;
function requireBrowser() {
if (hasRequiredBrowser) return browser.exports;
hasRequiredBrowser = 1;
(function(module, exports2) {
exports2 = module.exports = requireDebug();
exports2.log = log;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load2;
exports2.useColors = useColors;
exports2.storage = "undefined" != typeof chrome && "undefined" != typeof chrome.storage ? chrome.storage.local : localstorage();
exports2.colors = [
"lightseagreen",
"forestgreen",
"goldenrod",
"dodgerblue",
"darkorchid",
"crimson"
];
function useColors() {
if (typeof window !== "undefined" && window.process && window.process.type === "renderer") {
return true;
}
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
exports2.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err2) {
return "[UnexpectedJSONParseError]: " + err2.message;
}
};
function formatArgs(args) {
var useColors2 = this.useColors;
args[0] = (useColors2 ? "%c" : "") + this.namespace + (useColors2 ? " %c" : " ") + args[0] + (useColors2 ? "%c " : " ") + "+" + exports2.humanize(this.diff);
if (!useColors2) return;
var c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match2) {
if ("%%" === match2) return;
index++;
if ("%c" === match2) {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
function log() {
return "object" === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments);
}
function save(namespaces) {
try {
if (null == namespaces) {
exports2.storage.removeItem("debug");
} else {
exports2.storage.debug = namespaces;
}
} catch (e2) {
}
}
function load2() {
var r2;
try {
r2 = exports2.storage.debug;
} catch (e2) {
}
if (!r2 && typeof process !== "undefined" && "env" in process) {
r2 = process.env.DEBUG;
}
return r2;
}
exports2.enable(load2());
function localstorage() {
try {
return window.localStorage;
} catch (e2) {
}
}
})(browser, browser.exports);
return browser.exports;
}
var node = { exports: {} };
var hasRequiredNode;
function requireNode() {
if (hasRequiredNode) return node.exports;
hasRequiredNode = 1;
(function(module, exports2) {
var tty = import_tty.default;
var util2 = import_util.default;
exports2 = module.exports = requireDebug();
exports2.init = init2;
exports2.log = log;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load2;
exports2.useColors = useColors;
exports2.colors = [6, 2, 3, 4, 5, 1];
exports2.inspectOpts = Object.keys(process.env).filter(function(key) {
return /^debug_/i.test(key);
}).reduce(function(obj, key) {
var prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, function(_, k) {
return k.toUpperCase();
});
var val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === "null") val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
if (1 !== fd && 2 !== fd) {
util2.deprecate(function() {
}, "except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();
}
var stream4 = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd);
function useColors() {
return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(fd);
}
exports2.formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts).split("\n").map(function(str) {
return str.trim();
}).join(" ");
};
exports2.formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util2.inspect(v, this.inspectOpts);
};
function formatArgs(args) {
var name2 = this.namespace;
var useColors2 = this.useColors;
if (useColors2) {
var c = this.color;
var prefix = " \x1B[3" + c + ";1m" + name2 + " \x1B[0m";
args[0] = prefix + args[0].split("\n").join("\n" + prefix);
args.push("\x1B[3" + c + "m+" + exports2.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = (/* @__PURE__ */ new Date()).toUTCString() + " " + name2 + " " + args[0];
}
}
function log() {
return stream4.write(util2.format.apply(util2, arguments) + "\n");
}
function save(namespaces) {
if (null == namespaces) {
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
function load2() {
return process.env.DEBUG;
}
function createWritableStdioStream(fd2) {
var stream5;
var tty_wrap = process.binding("tty_wrap");
switch (tty_wrap.guessHandleType(fd2)) {
case "TTY":
stream5 = new tty.WriteStream(fd2);
stream5._type = "tty";
if (stream5._handle && stream5._handle.unref) {
stream5._handle.unref();
}
break;
case "FILE":
var fs2 = import_fs.default;
stream5 = new fs2.SyncWriteStream(fd2, { autoClose: false });
stream5._type = "fs";
break;
case "PIPE":
case "TCP":
var net2 = import_net.default;
stream5 = new net2.Socket({
fd: fd2,
readable: false,
writable: true
});
stream5.readable = false;
stream5.read = null;
stream5._type = "pipe";
if (stream5._handle && stream5._handle.unref) {
stream5._handle.unref();
}
break;
default:
throw new Error("Implement me. Unknown stream file type!");
}
stream5.fd = fd2;
stream5._isStdio = true;
return stream5;
}
function init2(debug2) {
debug2.inspectOpts = {};
var keys = Object.keys(exports2.inspectOpts);
for (var i = 0; i < keys.length; i++) {
debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
}
}
exports2.enable(load2());
})(node, node.exports);
return node.exports;
}
if (typeof process !== "undefined" && process.type === "renderer") {
src.exports = requireBrowser();
} else {
src.exports = requireNode();
}
var srcExports = src.exports;
var encodeurl = encodeUrl$1;
var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g;
var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1<>$2";
function encodeUrl$1(url2) {
return String(url2).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
}
var matchHtmlRegExp = /["'&<>]/;
var escapeHtml_1 = escapeHtml$1;
function escapeHtml$1(string2) {
var str = "" + string2;
var match2 = matchHtmlRegExp.exec(str);
if (!match2) {
return str;
}
var escape2;
var html = "";
var index = 0;
var lastIndex = 0;
for (index = match2.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
escape2 = "&quot;";
break;
case 38:
escape2 = "&amp;";
break;
case 39:
escape2 = "&#39;";
break;
case 60:
escape2 = "&lt;";
break;
case 62:
escape2 = "&gt;";
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape2;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
var escapeHtml$2 = getDefaultExportFromCjs(escapeHtml_1);
var onFinished$2 = { exports: {} };
var eeFirst = first$1;
function first$1(stuff, done) {
if (!Array.isArray(stuff))
throw new TypeError("arg must be an array of [ee, events...] arrays");
var cleanups = [];
for (var i = 0; i < stuff.length; i++) {
var arr = stuff[i];
if (!Array.isArray(arr) || arr.length < 2)
throw new TypeError("each array member must be [ee, events...]");
var ee = arr[0];
for (var j = 1; j < arr.length; j++) {
var event = arr[j];
var fn = listener(event, callback);
ee.on(event, fn);
cleanups.push({
ee,
event,
fn
});
}
}
function callback() {
cleanup();
done.apply(null, arguments);
}
function cleanup() {
var x;
for (var i2 = 0; i2 < cleanups.length; i2++) {
x = cleanups[i2];
x.ee.removeListener(x.event, x.fn);
}
}
function thunk(fn2) {
done = fn2;
}
thunk.cancel = cleanup;
return thunk;
}
function listener(event, done) {
return function onevent(arg1) {
var args = new Array(arguments.length);
var ee = this;
var err2 = event === "error" ? arg1 : null;
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
done(err2, ee, event, args);
};
}
onFinished$2.exports = onFinished$1;
onFinished$2.exports.isFinished = isFinished$1;
var first = eeFirst;
var defer$2 = typeof setImmediate === "function" ? setImmediate : function(fn) {
process.nextTick(fn.bind.apply(fn, arguments));
};
function onFinished$1(msg, listener2) {
if (isFinished$1(msg) !== false) {
defer$2(listener2, null, msg);
return msg;
}
attachListener(msg, listener2);
return msg;
}
function isFinished$1(msg) {
var socket = msg.socket;
if (typeof msg.finished === "boolean") {
return Boolean(msg.finished || socket && !socket.writable);
}
if (typeof msg.complete === "boolean") {
return Boolean(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable);
}
return void 0;
}
function attachFinishedListener(msg, callback) {
var eeMsg;
var eeSocket;
var finished = false;
function onFinish(error2) {
eeMsg.cancel();
eeSocket.cancel();
finished = true;
callback(error2);
}
eeMsg = eeSocket = first([[msg, "end", "finish"]], onFinish);
function onSocket(socket) {
msg.removeListener("socket", onSocket);
if (finished) return;
if (eeMsg !== eeSocket) return;
eeSocket = first([[socket, "error", "close"]], onFinish);
}
if (msg.socket) {
onSocket(msg.socket);
return;
}
msg.on("socket", onSocket);
if (msg.socket === void 0) {
patchAssignSocket(msg, onSocket);
}
}
function attachListener(msg, listener2) {
var attached = msg.__onFinished;
if (!attached || !attached.queue) {
attached = msg.__onFinished = createListener(msg);
attachFinishedListener(msg, attached);
}
attached.queue.push(listener2);
}
function createListener(msg) {
function listener2(err2) {
if (msg.__onFinished === listener2) msg.__onFinished = null;
if (!listener2.queue) return;
var queue2 = listener2.queue;
listener2.queue = null;
for (var i = 0; i < queue2.length; i++) {
queue2[i](err2, msg);
}
}
listener2.queue = [];
return listener2;
}
function patchAssignSocket(res, callback) {
var assignSocket = res.assignSocket;
if (typeof assignSocket !== "function") return;
res.assignSocket = function _assignSocket(socket) {
assignSocket.call(this, socket);
callback(socket);
};
}
var onFinishedExports = onFinished$2.exports;
var parseurl$1 = { exports: {} };
var url$3 = import_url.default;
var parse$8 = url$3.parse;
var Url = url$3.Url;
parseurl$1.exports = parseurl;
parseurl$1.exports.original = originalurl;
function parseurl(req2) {
var url2 = req2.url;
if (url2 === void 0) {
return void 0;
}
var parsed = req2._parsedUrl;
if (fresh(url2, parsed)) {
return parsed;
}
parsed = fastparse(url2);
parsed._raw = url2;
return req2._parsedUrl = parsed;
}
function originalurl(req2) {
var url2 = req2.originalUrl;
if (typeof url2 !== "string") {
return parseurl(req2);
}
var parsed = req2._parsedOriginalUrl;
if (fresh(url2, parsed)) {
return parsed;
}
parsed = fastparse(url2);
parsed._raw = url2;
return req2._parsedOriginalUrl = parsed;
}
function fastparse(str) {
if (typeof str !== "string" || str.charCodeAt(0) !== 47) {
return parse$8(str);
}
var pathname = str;
var query = null;
var search = null;
for (var i = 1; i < str.length; i++) {
switch (str.charCodeAt(i)) {
case 63:
if (search === null) {
pathname = str.substring(0, i);
query = str.substring(i + 1);
search = str.substring(i);
}
break;
case 9:
case 10:
case 12:
case 13:
case 32:
case 35:
case 160:
case 65279:
return parse$8(str);
}
}
var url2 = Url !== void 0 ? new Url() : {};
url2.path = str;
url2.href = str;
url2.pathname = pathname;
if (search !== null) {
url2.query = query;
url2.search = search;
}
return url2;
}
function fresh(url2, parsedUrl) {
return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url2;
}
var parseurlExports = parseurl$1.exports;
var require$$0$1 = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"103": "Early Hints",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"306": "(Unused)",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Unordered Collection",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"451": "Unavailable For Legal Reasons",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"509": "Bandwidth Limit Exceeded",
"510": "Not Extended",
"511": "Network Authentication Required"
};
var codes = require$$0$1;
var statuses$1 = status;
status.STATUS_CODES = codes;
status.codes = populateStatusesMap(status, codes);
status.redirect = {
300: true,
301: true,
302: true,
303: true,
305: true,
307: true,
308: true
};
status.empty = {
204: true,
205: true,
304: true
};
status.retry = {
502: true,
503: true,
504: true
};
function populateStatusesMap(statuses2, codes2) {
var arr = [];
Object.keys(codes2).forEach(function forEachCode(code) {
var message = codes2[code];
var status2 = Number(code);
statuses2[status2] = message;
statuses2[message] = status2;
statuses2[message.toLowerCase()] = status2;
arr.push(status2);
});
return arr;
}
function status(code) {
if (typeof code === "number") {
if (!status[code]) throw new Error("invalid status code: " + code);
return code;
}
if (typeof code !== "string") {
throw new TypeError("code must be a number or string");
}
var n2 = parseInt(code, 10);
if (!isNaN(n2)) {
if (!status[n2]) throw new Error("invalid status code: " + n2);
return n2;
}
n2 = status[code.toLowerCase()];
if (!n2) throw new Error('invalid status message: "' + code + '"');
return n2;
}
var unpipe_1 = unpipe$1;
function hasPipeDataListeners(stream4) {
var listeners = stream4.listeners("data");
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].name === "ondata") {
return true;
}
}
return false;
}
function unpipe$1(stream4) {
if (!stream4) {
throw new TypeError("argument stream is required");
}
if (typeof stream4.unpipe === "function") {
stream4.unpipe();
return;
}
if (!hasPipeDataListeners(stream4)) {
return;
}
var listener2;
var listeners = stream4.listeners("close");
for (var i = 0; i < listeners.length; i++) {
listener2 = listeners[i];
if (listener2.name !== "cleanup" && listener2.name !== "onclose") {
continue;
}
listener2.call(stream4);
}
}
var debug$e = srcExports("finalhandler");
var encodeUrl = encodeurl;
var escapeHtml = escapeHtml_1;
var onFinished = onFinishedExports;
var parseUrl$2 = parseurlExports;
var statuses = statuses$1;
var unpipe = unpipe_1;
var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
var NEWLINE_REGEXP = /\n/g;
var defer$1 = typeof setImmediate === "function" ? setImmediate : function(fn) {
process.nextTick(fn.bind.apply(fn, arguments));
};
var isFinished = onFinished.isFinished;
function createHtmlDocument(message) {
var body = escapeHtml(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;");
return '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>' + body + "</pre>\n</body>\n</html>\n";
}
var finalhandler_1 = finalhandler$1;
function finalhandler$1(req2, res, options2) {
var opts = options2 || {};
var env2 = opts.env || "development";
var onerror = opts.onerror;
return function(err2) {
var headers;
var msg;
var status2;
if (!err2 && headersSent(res)) {
debug$e("cannot 404 after headers sent");
return;
}
if (err2) {
status2 = getErrorStatusCode(err2);
if (status2 === void 0) {
status2 = getResponseStatusCode(res);
} else {
headers = getErrorHeaders(err2);
}
msg = getErrorMessage(err2, status2, env2);
} else {
status2 = 404;
msg = "Cannot " + req2.method + " " + encodeUrl(getResourceName(req2));
}
debug$e("default %s", status2);
if (err2 && onerror) {
defer$1(onerror, err2, req2, res);
}
if (headersSent(res)) {
debug$e("cannot %d after headers sent", status2);
req2.socket.destroy();
return;
}
send$2(req2, res, status2, headers, msg);
};
}
function getErrorHeaders(err2) {
if (!err2.headers || typeof err2.headers !== "object") {
return void 0;
}
var headers = /* @__PURE__ */ Object.create(null);
var keys = Object.keys(err2.headers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
headers[key] = err2.headers[key];
}
return headers;
}
function getErrorMessage(err2, status2, env2) {
var msg;
if (env2 !== "production") {
msg = err2.stack;
if (!msg && typeof err2.toString === "function") {
msg = err2.toString();
}
}
return msg || statuses[status2];
}
function getErrorStatusCode(err2) {
if (typeof err2.status === "number" && err2.status >= 400 && err2.status < 600) {
return err2.status;
}
if (typeof err2.statusCode === "number" && err2.statusCode >= 400 && err2.statusCode < 600) {
return err2.statusCode;
}
return void 0;
}
function getResourceName(req2) {
try {
return parseUrl$2.original(req2).pathname;
} catch (e2) {
return "resource";
}
}
function getResponseStatusCode(res) {
var status2 = res.statusCode;
if (typeof status2 !== "number" || status2 < 400 || status2 > 599) {
status2 = 500;
}
return status2;
}
function headersSent(res) {
return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
}
function send$2(req2, res, status2, headers, message) {
function write() {
var body = createHtmlDocument(message);
res.statusCode = status2;
res.statusMessage = statuses[status2];
setHeaders(res, headers);
res.setHeader("Content-Security-Policy", "default-src 'none'");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"));
if (req2.method === "HEAD") {
res.end();
return;
}
res.end(body, "utf8");
}
if (isFinished(req2)) {
write();
return;
}
unpipe(req2);
onFinished(req2, write);
req2.resume();
}
function setHeaders(res, headers) {
if (!headers) {
return;
}
var keys = Object.keys(headers);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
res.setHeader(key, headers[key]);
}
}
var utilsMerge = { exports: {} };
(function(module, exports2) {
module.exports = function(a, b) {
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
})(utilsMerge);
var utilsMergeExports = utilsMerge.exports;
var debug$d = srcExports("connect:dispatcher");
var EventEmitter$3 = import_events.default.EventEmitter;
var finalhandler = finalhandler_1;
var http$4 = import_http.default;
var merge = utilsMergeExports;
var parseUrl$1 = parseurlExports;
var connect = createServer$1;
var env = "development";
var proto = {};
var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
process.nextTick(fn.bind.apply(fn, arguments));
};
function createServer$1() {
function app(req2, res, next) {
app.handle(req2, res, next);
}
merge(app, proto);
merge(app, EventEmitter$3.prototype);
app.route = "/";
app.stack = [];
return app;
}
proto.use = function use(route, fn) {
var handle2 = fn;
var path3 = route;
if (typeof route !== "string") {
handle2 = route;
path3 = "/";
}
if (typeof handle2.handle === "function") {
var server2 = handle2;
server2.route = path3;
handle2 = function(req2, res, next) {
server2.handle(req2, res, next);
};
}
if (handle2 instanceof http$4.Server) {
handle2 = handle2.listeners("request")[0];
}
if (path3[path3.length - 1] === "/") {
path3 = path3.slice(0, -1);
}
debug$d("use %s %s", path3 || "/", handle2.name || "anonymous");
this.stack.push({ route: path3, handle: handle2 });
return this;
};
proto.handle = function handle(req2, res, out2) {
var index = 0;
var protohost = getProtohost(req2.url) || "";
var removed = "";
var slashAdded = false;
var stack = this.stack;
var done = out2 || finalhandler(req2, res, {
env,
onerror: logerror
});
req2.originalUrl = req2.originalUrl || req2.url;
function next(err2) {
if (slashAdded) {
req2.url = req2.url.substr(1);
slashAdded = false;
}
if (removed.length !== 0) {
req2.url = protohost + removed + req2.url.substr(protohost.length);
removed = "";
}
var layer = stack[index++];
if (!layer) {
defer(done, err2);
return;
}
var path3 = parseUrl$1(req2).pathname || "/";
var route = layer.route;
if (path3.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
return next(err2);
}
var c = path3.length > route.length && path3[route.length];
if (c && c !== "/" && c !== ".") {
return next(err2);
}
if (route.length !== 0 && route !== "/") {
removed = route;
req2.url = protohost + req2.url.substr(protohost.length + removed.length);
if (!protohost && req2.url[0] !== "/") {
req2.url = "/" + req2.url;
slashAdded = true;
}
}
call(layer.handle, route, err2, req2, res, next);
}
next();
};
proto.listen = function listen() {
var server2 = http$4.createServer(this);
return server2.listen.apply(server2, arguments);
};
function call(handle2, route, err2, req2, res, next) {
var arity = handle2.length;
var error2 = err2;
var hasError = Boolean(err2);
debug$d("%s %s : %s", handle2.name || "<anonymous>", route, req2.originalUrl);
try {
if (hasError && arity === 4) {
handle2(err2, req2, res, next);
return;
} else if (!hasError && arity < 4) {
handle2(req2, res, next);
return;
}
} catch (e2) {
error2 = e2;
}
next(error2);
}
function logerror(err2) {
if (env !== "test") console.error(err2.stack || err2.toString());
}
function getProtohost(url2) {
if (url2.length === 0 || url2[0] === "/") {
return void 0;
}
var fqdnIndex = url2.indexOf("://");
return fqdnIndex !== -1 && url2.lastIndexOf("?", fqdnIndex) === -1 ? url2.substr(0, url2.indexOf("/", 3 + fqdnIndex)) : void 0;
}
var connect$1 = getDefaultExportFromCjs(connect);
var lib = { exports: {} };
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === void 0) {
throw new TypeError("Object.assign cannot be called with null or undefined");
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
var test1 = new String("abc");
test1[5] = "de";
if (Object.getOwnPropertyNames(test1)[0] === "5") {
return false;
}
var test2 = {};
for (var i = 0; i < 10; i++) {
test2["_" + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
return test2[n2];
});
if (order2.join("") !== "0123456789") {
return false;
}
var test3 = {};
"abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
return false;
}
return true;
} catch (err2) {
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function(target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
var vary$1 = { exports: {} };
vary$1.exports = vary;
vary$1.exports.append = append;
var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
function append(header, field) {
if (typeof header !== "string") {
throw new TypeError("header argument is required");
}
if (!field) {
throw new TypeError("field argument is required");
}
var fields = !Array.isArray(field) ? parse$7(String(field)) : field;
for (var j = 0; j < fields.length; j++) {
if (!FIELD_NAME_REGEXP.test(fields[j])) {
throw new TypeError("field argument contains an invalid header name");
}
}
if (header === "*") {
return header;
}
var val = header;
var vals = parse$7(header.toLowerCase());
if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) {
return "*";
}
for (var i = 0; i < fields.length; i++) {
var fld = fields[i].toLowerCase();
if (vals.indexOf(fld) === -1) {
vals.push(fld);
val = val ? val + ", " + fields[i] : fields[i];
}
}
return val;
}
function parse$7(header) {
var end = 0;
var list = [];
var start = 0;
for (var i = 0, len = header.length; i < len; i++) {
switch (header.charCodeAt(i)) {
case 32:
if (start === end) {
start = end = i + 1;
}
break;
case 44:
list.push(header.substring(start, end));
start = end = i + 1;
break;
default:
end = i + 1;
break;
}
}
list.push(header.substring(start, end));
return list;
}
function vary(res, field) {
if (!res || !res.getHeader || !res.setHeader) {
throw new TypeError("res argument is required");
}
var val = res.getHeader("Vary") || "";
var header = Array.isArray(val) ? val.join(", ") : String(val);
if (val = append(header, field)) {
res.setHeader("Vary", val);
}
}
var varyExports = vary$1.exports;
(function() {
var assign = objectAssign;
var vary2 = varyExports;
var defaults2 = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204
};
function isString2(s) {
return typeof s === "string" || s instanceof String;
}
function isOriginAllowed(origin, allowedOrigin) {
if (Array.isArray(allowedOrigin)) {
for (var i = 0; i < allowedOrigin.length; ++i) {
if (isOriginAllowed(origin, allowedOrigin[i])) {
return true;
}
}
return false;
} else if (isString2(allowedOrigin)) {
return origin === allowedOrigin;
} else if (allowedOrigin instanceof RegExp) {
return allowedOrigin.test(origin);
} else {
return !!allowedOrigin;
}
}
function configureOrigin(options2, req2) {
var requestOrigin = req2.headers.origin, headers = [], isAllowed;
if (!options2.origin || options2.origin === "*") {
headers.push([{
key: "Access-Control-Allow-Origin",
value: "*"
}]);
} else if (isString2(options2.origin)) {
headers.push([{
key: "Access-Control-Allow-Origin",
value: options2.origin
}]);
headers.push([{
key: "Vary",
value: "Origin"
}]);
} else {
isAllowed = isOriginAllowed(requestOrigin, options2.origin);
headers.push([{
key: "Access-Control-Allow-Origin",
value: isAllowed ? requestOrigin : false
}]);
headers.push([{
key: "Vary",
value: "Origin"
}]);
}
return headers;
}
function configureMethods(options2) {
var methods = options2.methods;
if (methods.join) {
methods = options2.methods.join(",");
}
return {
key: "Access-Control-Allow-Methods",
value: methods
};
}
function configureCredentials(options2) {
if (options2.credentials === true) {
return {
key: "Access-Control-Allow-Credentials",
value: "true"
};
}
return null;
}
function configureAllowedHeaders(options2, req2) {
var allowedHeaders = options2.allowedHeaders || options2.headers;
var headers = [];
if (!allowedHeaders) {
allowedHeaders = req2.headers["access-control-request-headers"];
headers.push([{
key: "Vary",
value: "Access-Control-Request-Headers"
}]);
} else if (allowedHeaders.join) {
allowedHeaders = allowedHeaders.join(",");
}
if (allowedHeaders && allowedHeaders.length) {
headers.push([{
key: "Access-Control-Allow-Headers",
value: allowedHeaders
}]);
}
return headers;
}
function configureExposedHeaders(options2) {
var headers = options2.exposedHeaders;
if (!headers) {
return null;
} else if (headers.join) {
headers = headers.join(",");
}
if (headers && headers.length) {
return {
key: "Access-Control-Expose-Headers",
value: headers
};
}
return null;
}
function configureMaxAge(options2) {
var maxAge = (typeof options2.maxAge === "number" || options2.maxAge) && options2.maxAge.toString();
if (maxAge && maxAge.length) {
return {
key: "Access-Control-Max-Age",
value: maxAge
};
}
return null;
}
function applyHeaders(headers, res) {
for (var i = 0, n2 = headers.length; i < n2; i++) {
var header = headers[i];
if (header) {
if (Array.isArray(header)) {
applyHeaders(header, res);
} else if (header.key === "Vary" && header.value) {
vary2(res, header.value);
} else if (header.value) {
res.setHeader(header.key, header.value);
}
}
}
}
function cors(options2, req2, res, next) {
var headers = [], method = req2.method && req2.method.toUpperCase && req2.method.toUpperCase();
if (method === "OPTIONS") {
headers.push(configureOrigin(options2, req2));
headers.push(configureCredentials(options2));
headers.push(configureMethods(options2));
headers.push(configureAllowedHeaders(options2, req2));
headers.push(configureMaxAge(options2));
headers.push(configureExposedHeaders(options2));
applyHeaders(headers, res);
if (options2.preflightContinue) {
next();
} else {
res.statusCode = options2.optionsSuccessStatus;
res.setHeader("Content-Length", "0");
res.end();
}
} else {
headers.push(configureOrigin(options2, req2));
headers.push(configureCredentials(options2));
headers.push(configureExposedHeaders(options2));
applyHeaders(headers, res);
next();
}
}
function middlewareWrapper(o2) {
var optionsCallback = null;
if (typeof o2 === "function") {
optionsCallback = o2;
} else {
optionsCallback = function(req2, cb) {
cb(null, o2);
};
}
return function corsMiddleware2(req2, res, next) {
optionsCallback(req2, function(err2, options2) {
if (err2) {
next(err2);
} else {
var corsOptions = assign({}, defaults2, options2);
var originCallback = null;
if (corsOptions.origin && typeof corsOptions.origin === "function") {
originCallback = corsOptions.origin;
} else if (corsOptions.origin) {
originCallback = function(origin, cb) {
cb(null, corsOptions.origin);
};
}
if (originCallback) {
originCallback(req2.headers.origin, function(err22, origin) {
if (err22 || !origin) {
next(err22);
} else {
corsOptions.origin = origin;
cors(corsOptions, req2, res, next);
}
});
} else {
next();
}
}
});
};
}
lib.exports = middlewareWrapper;
})();
var libExports = lib.exports;
var corsMiddleware = getDefaultExportFromCjs(libExports);
var chokidar = {};
var fs$8 = import_fs.default;
var { Readable } = import_stream.default;
var sysPath$3 = import_path.default;
var { promisify: promisify$3 } = import_util.default;
var picomatch$1 = picomatch$3;
var readdir$1 = promisify$3(fs$8.readdir);
var stat$3 = promisify$3(fs$8.stat);
var lstat$2 = promisify$3(fs$8.lstat);
var realpath$1 = promisify$3(fs$8.realpath);
var BANG$2 = "!";
var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
var FILE_TYPE = "files";
var DIR_TYPE = "directories";
var FILE_DIR_TYPE = "files_directories";
var EVERYTHING_TYPE = "all";
var ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
var isNormalFlowError = (error2) => NORMAL_FLOW_ERRORS.has(error2.code);
var [maj, min] = process.versions.node.split(".").slice(0, 2).map((n2) => Number.parseInt(n2, 10));
var wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5);
var normalizeFilter = (filter2) => {
if (filter2 === void 0) return;
if (typeof filter2 === "function") return filter2;
if (typeof filter2 === "string") {
const glob2 = picomatch$1(filter2.trim());
return (entry2) => glob2(entry2.basename);
}
if (Array.isArray(filter2)) {
const positive = [];
const negative = [];
for (const item of filter2) {
const trimmed = item.trim();
if (trimmed.charAt(0) === BANG$2) {
negative.push(picomatch$1(trimmed.slice(1)));
} else {
positive.push(picomatch$1(trimmed));
}
}
if (negative.length > 0) {
if (positive.length > 0) {
return (entry2) => positive.some((f2) => f2(entry2.basename)) && !negative.some((f2) => f2(entry2.basename));
}
return (entry2) => !negative.some((f2) => f2(entry2.basename));
}
return (entry2) => positive.some((f2) => f2(entry2.basename));
}
};
var ReaddirpStream = class _ReaddirpStream extends Readable {
static get defaultOptions() {
return {
root: ".",
/* eslint-disable no-unused-vars */
fileFilter: (path3) => true,
directoryFilter: (path3) => true,
/* eslint-enable no-unused-vars */
type: FILE_TYPE,
lstat: false,
depth: 2147483648,
alwaysStat: false
};
}
constructor(options2 = {}) {
super({
objectMode: true,
autoDestroy: true,
highWaterMark: options2.highWaterMark || 4096
});
const opts = { ..._ReaddirpStream.defaultOptions, ...options2 };
const { root, type } = opts;
this._fileFilter = normalizeFilter(opts.fileFilter);
this._directoryFilter = normalizeFilter(opts.directoryFilter);
const statMethod = opts.lstat ? lstat$2 : stat$3;
if (wantBigintFsStats) {
this._stat = (path3) => statMethod(path3, { bigint: true });
} else {
this._stat = statMethod;
}
this._maxDepth = opts.depth;
this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
this._wantsEverything = type === EVERYTHING_TYPE;
this._root = sysPath$3.resolve(root);
this._isDirent = "Dirent" in fs$8 && !opts.alwaysStat;
this._statsProp = this._isDirent ? "dirent" : "stats";
this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
this.parents = [this._exploreDir(root, 1)];
this.reading = false;
this.parent = void 0;
}
async _read(batch) {
if (this.reading) return;
this.reading = true;
try {
while (!this.destroyed && batch > 0) {
const { path: path3, depth: depth2, files = [] } = this.parent || {};
if (files.length > 0) {
const slice2 = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path3));
for (const entry2 of await Promise.all(slice2)) {
if (this.destroyed) return;
const entryType = await this._getEntryType(entry2);
if (entryType === "directory" && this._directoryFilter(entry2)) {
if (depth2 <= this._maxDepth) {
this.parents.push(this._exploreDir(entry2.fullPath, depth2 + 1));
}
if (this._wantsDir) {
this.push(entry2);
batch--;
}
} else if ((entryType === "file" || this._includeAsFile(entry2)) && this._fileFilter(entry2)) {
if (this._wantsFile) {
this.push(entry2);
batch--;
}
}
}
} else {
const parent = this.parents.pop();
if (!parent) {
this.push(null);
break;
}
this.parent = await parent;
if (this.destroyed) return;
}
}
} catch (error2) {
this.destroy(error2);
} finally {
this.reading = false;
}
}
async _exploreDir(path3, depth2) {
let files;
try {
files = await readdir$1(path3, this._rdOptions);
} catch (error2) {
this._onError(error2);
}
return { files, depth: depth2, path: path3 };
}
async _formatEntry(dirent, path3) {
let entry2;
try {
const basename2 = this._isDirent ? dirent.name : dirent;
const fullPath = sysPath$3.resolve(sysPath$3.join(path3, basename2));
entry2 = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename: basename2 };
entry2[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
} catch (err2) {
this._onError(err2);
}
return entry2;
}
_onError(err2) {
if (isNormalFlowError(err2) && !this.destroyed) {
this.emit("warn", err2);
} else {
this.destroy(err2);
}
}
async _getEntryType(entry2) {
const stats = entry2 && entry2[this._statsProp];
if (!stats) {
return;
}
if (stats.isFile()) {
return "file";
}
if (stats.isDirectory()) {
return "directory";
}
if (stats && stats.isSymbolicLink()) {
const full = entry2.fullPath;
try {
const entryRealPath = await realpath$1(full);
const entryRealPathStats = await lstat$2(entryRealPath);
if (entryRealPathStats.isFile()) {
return "file";
}
if (entryRealPathStats.isDirectory()) {
const len = entryRealPath.length;
if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
const recursiveError = new Error(
`Circular symlink detected: "${full}" points to "${entryRealPath}"`
);
recursiveError.code = RECURSIVE_ERROR_CODE;
return this._onError(recursiveError);
}
return "directory";
}
} catch (error2) {
this._onError(error2);
}
}
}
_includeAsFile(entry2) {
const stats = entry2 && entry2[this._statsProp];
return stats && this._wantsEverything && !stats.isDirectory();
}
};
var readdirp$1 = (root, options2 = {}) => {
let type = options2.entryType || options2.type;
if (type === "both") type = FILE_DIR_TYPE;
if (type) options2.type = type;
if (!root) {
throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
} else if (typeof root !== "string") {
throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
} else if (type && !ALL_TYPES.includes(type)) {
throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
}
options2.root = root;
return new ReaddirpStream(options2);
};
var readdirpPromise = (root, options2 = {}) => {
return new Promise((resolve3, reject) => {
const files = [];
readdirp$1(root, options2).on("data", (entry2) => files.push(entry2)).on("end", () => resolve3(files)).on("error", (error2) => reject(error2));
});
};
readdirp$1.promise = readdirpPromise;
readdirp$1.ReaddirpStream = ReaddirpStream;
readdirp$1.default = readdirp$1;
var readdirp_1 = readdirp$1;
var anymatch$2 = { exports: {} };
var normalizePath$2 = function(path3, stripTrailing) {
if (typeof path3 !== "string") {
throw new TypeError("expected path to be a string");
}
if (path3 === "\\" || path3 === "/") return "/";
var len = path3.length;
if (len <= 1) return path3;
var prefix = "";
if (len > 4 && path3[3] === "\\") {
var ch = path3[2];
if ((ch === "?" || ch === ".") && path3.slice(0, 2) === "\\\\") {
path3 = path3.slice(2);
prefix = "//";
}
}
var segs = path3.split(/[/\\]+/);
if (stripTrailing !== false && segs[segs.length - 1] === "") {
segs.pop();
}
return prefix + segs.join("/");
};
var anymatch_1 = anymatch$2.exports;
Object.defineProperty(anymatch_1, "__esModule", { value: true });
var picomatch = picomatch$3;
var normalizePath$1 = normalizePath$2;
var BANG$1 = "!";
var DEFAULT_OPTIONS = { returnIndex: false };
var arrify$1 = (item) => Array.isArray(item) ? item : [item];
var createPattern = (matcher2, options2) => {
if (typeof matcher2 === "function") {
return matcher2;
}
if (typeof matcher2 === "string") {
const glob2 = picomatch(matcher2, options2);
return (string2) => matcher2 === string2 || glob2(string2);
}
if (matcher2 instanceof RegExp) {
return (string2) => matcher2.test(string2);
}
return (string2) => false;
};
var matchPatterns = (patterns, negPatterns, args, returnIndex) => {
const isList = Array.isArray(args);
const _path = isList ? args[0] : args;
if (!isList && typeof _path !== "string") {
throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path));
}
const path3 = normalizePath$1(_path);
for (let index = 0; index < negPatterns.length; index++) {
const nglob = negPatterns[index];
if (nglob(path3)) {
return returnIndex ? -1 : false;
}
}
const applied = isList && [path3].concat(args.slice(1));
for (let index = 0; index < patterns.length; index++) {
const pattern2 = patterns[index];
if (isList ? pattern2(...applied) : pattern2(path3)) {
return returnIndex ? index : true;
}
}
return returnIndex ? -1 : false;
};
var anymatch$1 = (matchers, testString, options2 = DEFAULT_OPTIONS) => {
if (matchers == null) {
throw new TypeError("anymatch: specify first argument");
}
const opts = typeof options2 === "boolean" ? { returnIndex: options2 } : options2;
const returnIndex = opts.returnIndex || false;
const mtchers = arrify$1(matchers);
const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG$1).map((item) => item.slice(1)).map((item) => picomatch(item, opts));
const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG$1).map((matcher2) => createPattern(matcher2, opts));
if (testString == null) {
return (testString2, ri = false) => {
const returnIndex2 = typeof ri === "boolean" ? ri : false;
return matchPatterns(patterns, negatedGlobs, testString2, returnIndex2);
};
}
return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
};
anymatch$1.default = anymatch$1;
anymatch$2.exports = anymatch$1;
var anymatchExports = anymatch$2.exports;
var require$$0 = [
"3dm",
"3ds",
"3g2",
"3gp",
"7z",
"a",
"aac",
"adp",
"ai",
"aif",
"aiff",
"alz",
"ape",
"apk",
"appimage",
"ar",
"arj",
"asf",
"au",
"avi",
"bak",
"baml",
"bh",
"bin",
"bk",
"bmp",
"btif",
"bz2",
"bzip2",
"cab",
"caf",
"cgm",
"class",
"cmx",
"cpio",
"cr2",
"cur",
"dat",
"dcm",
"deb",
"dex",
"djvu",
"dll",
"dmg",
"dng",
"doc",
"docm",
"docx",
"dot",
"dotm",
"dra",
"DS_Store",
"dsk",
"dts",
"dtshd",
"dvb",
"dwg",
"dxf",
"ecelp4800",
"ecelp7470",
"ecelp9600",
"egg",
"eol",
"eot",
"epub",
"exe",
"f4v",
"fbs",
"fh",
"fla",
"flac",
"flatpak",
"fli",
"flv",
"fpx",
"fst",
"fvt",
"g3",
"gh",
"gif",
"graffle",
"gz",
"gzip",
"h261",
"h263",
"h264",
"icns",
"ico",
"ief",
"img",
"ipa",
"iso",
"jar",
"jpeg",
"jpg",
"jpgv",
"jpm",
"jxr",
"key",
"ktx",
"lha",
"lib",
"lvp",
"lz",
"lzh",
"lzma",
"lzo",
"m3u",
"m4a",
"m4v",
"mar",
"mdi",
"mht",
"mid",
"midi",
"mj2",
"mka",
"mkv",
"mmr",
"mng",
"mobi",
"mov",
"movie",
"mp3",
"mp4",
"mp4a",
"mpeg",
"mpg",
"mpga",
"mxu",
"nef",
"npx",
"numbers",
"nupkg",
"o",
"odp",
"ods",
"odt",
"oga",
"ogg",
"ogv",
"otf",
"ott",
"pages",
"pbm",
"pcx",
"pdb",
"pdf",
"pea",
"pgm",
"pic",
"png",
"pnm",
"pot",
"potm",
"potx",
"ppa",
"ppam",
"ppm",
"pps",
"ppsm",
"ppsx",
"ppt",
"pptm",
"pptx",
"psd",
"pya",
"pyc",
"pyo",
"pyv",
"qt",
"rar",
"ras",
"raw",
"resources",
"rgb",
"rip",
"rlc",
"rmf",
"rmvb",
"rpm",
"rtf",
"rz",
"s3m",
"s7z",
"scpt",
"sgi",
"shar",
"snap",
"sil",
"sketch",
"slk",
"smv",
"snk",
"so",
"stl",
"suo",
"sub",
"swf",
"tar",
"tbz",
"tbz2",
"tga",
"tgz",
"thmx",
"tif",
"tiff",
"tlz",
"ttc",
"ttf",
"txz",
"udf",
"uvh",
"uvi",
"uvm",
"uvp",
"uvs",
"uvu",
"viv",
"vob",
"war",
"wav",
"wax",
"wbmp",
"wdp",
"weba",
"webm",
"webp",
"whl",
"wim",
"wm",
"wma",
"wmv",
"wmx",
"woff",
"woff2",
"wrm",
"wvx",
"xbm",
"xif",
"xla",
"xlam",
"xls",
"xlsb",
"xlsm",
"xlsx",
"xlt",
"xltm",
"xltx",
"xm",
"xmind",
"xpi",
"xpm",
"xwd",
"xz",
"z",
"zip",
"zipx"
];
var binaryExtensions$1 = require$$0;
var path$8 = import_path.default;
var binaryExtensions = binaryExtensions$1;
var extensions = new Set(binaryExtensions);
var isBinaryPath$1 = (filePath) => extensions.has(path$8.extname(filePath).slice(1).toLowerCase());
var constants$1 = {};
(function(exports2) {
const { sep: sep2 } = import_path.default;
const { platform: platform2 } = process;
const os2 = import_os.default;
exports2.EV_ALL = "all";
exports2.EV_READY = "ready";
exports2.EV_ADD = "add";
exports2.EV_CHANGE = "change";
exports2.EV_ADD_DIR = "addDir";
exports2.EV_UNLINK = "unlink";
exports2.EV_UNLINK_DIR = "unlinkDir";
exports2.EV_RAW = "raw";
exports2.EV_ERROR = "error";
exports2.STR_DATA = "data";
exports2.STR_END = "end";
exports2.STR_CLOSE = "close";
exports2.FSEVENT_CREATED = "created";
exports2.FSEVENT_MODIFIED = "modified";
exports2.FSEVENT_DELETED = "deleted";
exports2.FSEVENT_MOVED = "moved";
exports2.FSEVENT_CLONED = "cloned";
exports2.FSEVENT_UNKNOWN = "unknown";
exports2.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
exports2.FSEVENT_TYPE_FILE = "file";
exports2.FSEVENT_TYPE_DIRECTORY = "directory";
exports2.FSEVENT_TYPE_SYMLINK = "symlink";
exports2.KEY_LISTENERS = "listeners";
exports2.KEY_ERR = "errHandlers";
exports2.KEY_RAW = "rawEmitters";
exports2.HANDLER_KEYS = [exports2.KEY_LISTENERS, exports2.KEY_ERR, exports2.KEY_RAW];
exports2.DOT_SLASH = `.${sep2}`;
exports2.BACK_SLASH_RE = /\\/g;
exports2.DOUBLE_SLASH_RE = /\/\//;
exports2.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
exports2.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
exports2.REPLACER_RE = /^\.[/\\]/;
exports2.SLASH = "/";
exports2.SLASH_SLASH = "//";
exports2.BRACE_START = "{";
exports2.BANG = "!";
exports2.ONE_DOT = ".";
exports2.TWO_DOTS = "..";
exports2.STAR = "*";
exports2.GLOBSTAR = "**";
exports2.ROOT_GLOBSTAR = "/**/*";
exports2.SLASH_GLOBSTAR = "/**";
exports2.DIR_SUFFIX = "Dir";
exports2.ANYMATCH_OPTS = { dot: true };
exports2.STRING_TYPE = "string";
exports2.FUNCTION_TYPE = "function";
exports2.EMPTY_STR = "";
exports2.EMPTY_FN = () => {
};
exports2.IDENTITY_FN = (val) => val;
exports2.isWindows = platform2 === "win32";
exports2.isMacos = platform2 === "darwin";
exports2.isLinux = platform2 === "linux";
exports2.isIBMi = os2.type() === "OS400";
})(constants$1);
var fs$7 = import_fs.default;
var sysPath$2 = import_path.default;
var { promisify: promisify$2 } = import_util.default;
var isBinaryPath = isBinaryPath$1;
var {
isWindows: isWindows$2,
isLinux,
EMPTY_FN: EMPTY_FN$2,
EMPTY_STR: EMPTY_STR$1,
KEY_LISTENERS,
KEY_ERR,
KEY_RAW,
HANDLER_KEYS,
EV_CHANGE: EV_CHANGE$2,
EV_ADD: EV_ADD$2,
EV_ADD_DIR: EV_ADD_DIR$2,
EV_ERROR: EV_ERROR$2,
STR_DATA: STR_DATA$1,
STR_END: STR_END$2,
BRACE_START: BRACE_START$1,
STAR
} = constants$1;
var THROTTLE_MODE_WATCH = "watch";
var open$2 = promisify$2(fs$7.open);
var stat$2 = promisify$2(fs$7.stat);
var lstat$1 = promisify$2(fs$7.lstat);
var close = promisify$2(fs$7.close);
var fsrealpath = promisify$2(fs$7.realpath);
var statMethods$1 = { lstat: lstat$1, stat: stat$2 };
var foreach = (val, fn) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
};
var addAndConvert = (main2, prop, item) => {
let container = main2[prop];
if (!(container instanceof Set)) {
main2[prop] = container = /* @__PURE__ */ new Set([container]);
}
container.add(item);
};
var clearItem = (cont) => (key) => {
const set2 = cont[key];
if (set2 instanceof Set) {
set2.clear();
} else {
delete cont[key];
}
};
var delFromSet = (main2, prop, item) => {
const container = main2[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main2[prop];
}
};
var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
var FsWatchInstances = /* @__PURE__ */ new Map();
function createFsWatchInstance(path3, options2, listener2, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener2(path3);
emitRaw(rawEvent, evPath, { watchedPath: path3 });
if (evPath && path3 !== evPath) {
fsWatchBroadcast(
sysPath$2.resolve(path3, evPath),
KEY_LISTENERS,
sysPath$2.join(path3, evPath)
);
}
};
try {
return fs$7.watch(path3, options2, handleEvent);
} catch (error2) {
errHandler(error2);
}
}
var fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[type], (listener2) => {
listener2(val1, val2, val3);
});
};
var setFsWatchListener = (path3, fullPath, options2, handlers) => {
const { listener: listener2, errHandler, rawEmitter } = handlers;
let cont = FsWatchInstances.get(fullPath);
let watcher;
if (!options2.persistent) {
watcher = createFsWatchInstance(
path3,
options2,
listener2,
errHandler,
rawEmitter
);
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener2);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(
path3,
options2,
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
errHandler,
// no need to use broadcast here
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
);
if (!watcher) return;
watcher.on(EV_ERROR$2, async (error2) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
cont.watcherUnusable = true;
if (isWindows$2 && error2.code === "EPERM") {
try {
const fd = await open$2(path3, "r");
await close(fd);
broadcastErr(error2);
} catch (err2) {
}
} else {
broadcastErr(error2);
}
});
cont = {
listeners: listener2,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener2);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
cont.watcher.close();
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = void 0;
Object.freeze(cont);
}
};
};
var FsWatchFileInstances = /* @__PURE__ */ new Map();
var setFsWatchFileListener = (path3, fullPath, options2, handlers) => {
const { listener: listener2, rawEmitter } = handlers;
let cont = FsWatchFileInstances.get(fullPath);
const copts = cont && cont.options;
if (copts && (copts.persistent < options2.persistent || copts.interval > options2.interval)) {
fs$7.unwatchFile(fullPath);
cont = void 0;
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener2);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
cont = {
listeners: listener2,
rawEmitters: rawEmitter,
options: options2,
watcher: fs$7.watchFile(fullPath, options2, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter2) => {
rawEmitter2(EV_CHANGE$2, fullPath, { curr, prev });
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener3) => listener3(path3, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
return () => {
delFromSet(cont, KEY_LISTENERS, listener2);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
fs$7.unwatchFile(fullPath);
cont.options = cont.watcher = void 0;
Object.freeze(cont);
}
};
};
var NodeFsHandler$1 = class NodeFsHandler {
/**
* @param {import("../index").FSWatcher} fsW
*/
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error2) => fsW._handleError(error2);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param {String} path to file or dir
* @param {Function} listener on fs change
* @returns {Function} closer for the watcher instance
*/
_watchWithNodeFs(path3, listener2) {
const opts = this.fsw.options;
const directory = sysPath$2.dirname(path3);
const basename2 = sysPath$2.basename(path3);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename2);
const absolutePath = sysPath$2.resolve(path3);
const options2 = { persistent: opts.persistent };
if (!listener2) listener2 = EMPTY_FN$2;
let closer;
if (opts.usePolling) {
options2.interval = opts.enableBinaryInterval && isBinaryPath(basename2) ? opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path3, absolutePath, options2, {
listener: listener2,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path3, absolutePath, options2, {
listener: listener2,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @param {Path} file Path
* @param {fs.Stats} stats result of fs_stat
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @returns {Function} closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname2 = sysPath$2.dirname(file);
const basename2 = sysPath$2.basename(file);
const parent = this.fsw._getWatchedDir(dirname2);
let prevStats = stats;
if (parent.has(basename2)) return;
const listener2 = async (path3, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats2 = await stat$2(file);
if (this.fsw.closed) return;
const at = newStats2.atimeMs;
const mt = newStats2.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE$2, file, newStats2);
}
if (isLinux && prevStats.ino !== newStats2.ino) {
this.fsw._closeFile(path3);
prevStats = newStats2;
this.fsw._addPathCloser(path3, this._watchWithNodeFs(file, listener2));
} else {
prevStats = newStats2;
}
} catch (error2) {
this.fsw._remove(dirname2, basename2);
}
} else if (parent.has(basename2)) {
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE$2, file, newStats);
}
prevStats = newStats;
}
};
const closer = this._watchWithNodeFs(file, listener2);
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
this.fsw._emit(EV_ADD$2, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param {Object} entry returned by readdirp
* @param {String} directory path of dir being read
* @param {String} path of this item
* @param {String} item basename of this item
* @returns {Promise<Boolean>} true if no more processing is needed for this entry.
*/
async _handleSymlink(entry2, directory, path3, item) {
if (this.fsw.closed) {
return;
}
const full = entry2.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path3);
} catch (e2) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_CHANGE$2, path3, entry2.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_ADD$2, path3, entry2.stats);
}
this.fsw._emitReady();
return true;
}
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth2, throttler) {
directory = sysPath$2.join(directory, EMPTY_STR$1);
if (!wh.hasGlob) {
throttler = this.fsw._throttle("readdir", directory, 1e3);
if (!throttler) return;
}
const previous = this.fsw._getWatchedDir(wh.path);
const current = /* @__PURE__ */ new Set();
let stream4 = this.fsw._readdirp(directory, {
fileFilter: (entry2) => wh.filterPath(entry2),
directoryFilter: (entry2) => wh.filterDir(entry2),
depth: 0
}).on(STR_DATA$1, async (entry2) => {
if (this.fsw.closed) {
stream4 = void 0;
return;
}
const item = entry2.path;
let path3 = sysPath$2.join(directory, item);
current.add(item);
if (entry2.stats.isSymbolicLink() && await this._handleSymlink(entry2, directory, path3, item)) {
return;
}
if (this.fsw.closed) {
stream4 = void 0;
return;
}
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
path3 = sysPath$2.join(dir, sysPath$2.relative(dir, path3));
this._addToNodeFs(path3, initialAdd, wh, depth2 + 1);
}
}).on(EV_ERROR$2, this._boundHandleError);
return new Promise(
(resolve3) => stream4.once(STR_END$2, () => {
if (this.fsw.closed) {
stream4 = void 0;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve3();
previous.getChildren().filter((item) => {
return item !== directory && !current.has(item) && // in case of intersecting globs;
// a path may have been filtered out of this readdir, but
// shouldn't be removed because it matches a different glob
(!wh.hasGlob || wh.filterPath({
fullPath: sysPath$2.resolve(directory, item)
}));
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream4 = void 0;
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth2, throttler);
})
);
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param {String} dir fs path
* @param {fs.Stats} stats
* @param {Boolean} initialAdd
* @param {Number} depth relative to user-supplied path
* @param {String} target child path targeted for watch
* @param {Object} wh Common watch helpers for this path
* @param {String} realpath
* @returns {Promise<Function>} closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth2, target, wh, realpath2) {
const parentDir2 = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
const tracked = parentDir2.has(sysPath$2.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
}
parentDir2.add(sysPath$2.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth2 <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth2, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
if (stats2 && stats2.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth2, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param {String} path to file or ir
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @param {Object} priorWh depth relative to user-supplied path
* @param {Number} depth Child path actually targeted for watch
* @param {String=} target Child path actually targeted for watch
* @returns {Promise}
*/
async _addToNodeFs(path3, initialAdd, priorWh, depth2, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path3) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path3, depth2);
if (!wh.hasGlob && priorWh) {
wh.hasGlob = priorWh.hasGlob;
wh.globFilter = priorWh.globFilter;
wh.filterPath = (entry2) => priorWh.filterPath(entry2);
wh.filterDir = (entry2) => priorWh.filterDir(entry2);
}
try {
const stats = await statMethods$1[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks && !path3.includes(STAR) && !path3.includes(BRACE_START$1);
let closer;
if (stats.isDirectory()) {
const absPath = sysPath$2.resolve(path3);
const targetPath = follow ? await fsrealpath(path3) : path3;
if (this.fsw.closed) return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth2, target, wh, targetPath);
if (this.fsw.closed) return;
if (absPath !== targetPath && targetPath !== void 0) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path3) : path3;
if (this.fsw.closed) return;
const parent = sysPath$2.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth2, path3, wh, targetPath);
if (this.fsw.closed) return;
if (targetPath !== void 0) {
this.fsw._symlinkPaths.set(sysPath$2.resolve(path3), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
this.fsw._addPathCloser(path3, closer);
return false;
} catch (error2) {
if (this.fsw._handleError(error2)) {
ready();
return path3;
}
}
}
};
var nodefsHandler = NodeFsHandler$1;
var fseventsHandler = { exports: {} };
var fs$6 = import_fs.default;
var sysPath$1 = import_path.default;
var { promisify: promisify$1 } = import_util.default;
var fsevents;
try {
fsevents = __require2("fsevents");
} catch (error2) {
if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error2);
}
if (fsevents) {
const mtch = process.version.match(/v(\d+)\.(\d+)/);
if (mtch && mtch[1] && mtch[2]) {
const maj2 = Number.parseInt(mtch[1], 10);
const min2 = Number.parseInt(mtch[2], 10);
if (maj2 === 8 && min2 < 16) {
fsevents = void 0;
}
}
}
var {
EV_ADD: EV_ADD$1,
EV_CHANGE: EV_CHANGE$1,
EV_ADD_DIR: EV_ADD_DIR$1,
EV_UNLINK: EV_UNLINK$1,
EV_ERROR: EV_ERROR$1,
STR_DATA,
STR_END: STR_END$1,
FSEVENT_CREATED,
FSEVENT_MODIFIED,
FSEVENT_DELETED,
FSEVENT_MOVED,
// FSEVENT_CLONED,
FSEVENT_UNKNOWN,
FSEVENT_FLAG_MUST_SCAN_SUBDIRS,
FSEVENT_TYPE_FILE,
FSEVENT_TYPE_DIRECTORY,
FSEVENT_TYPE_SYMLINK,
ROOT_GLOBSTAR,
DIR_SUFFIX,
DOT_SLASH,
FUNCTION_TYPE: FUNCTION_TYPE$1,
EMPTY_FN: EMPTY_FN$1,
IDENTITY_FN
} = constants$1;
var Depth = (value2) => isNaN(value2) ? {} : { depth: value2 };
var stat$1 = promisify$1(fs$6.stat);
var lstat = promisify$1(fs$6.lstat);
var realpath = promisify$1(fs$6.realpath);
var statMethods = { stat: stat$1, lstat };
var FSEventsWatchers = /* @__PURE__ */ new Map();
var consolidateThreshhold = 10;
var wrongEventFlags = /* @__PURE__ */ new Set([
69888,
70400,
71424,
72704,
73472,
131328,
131840,
262912
]);
var createFSEventsInstance = (path3, callback) => {
const stop = fsevents.watch(path3, callback);
return { stop };
};
function setFSEventsListener(path3, realPath, listener2, rawEmitter) {
let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
const parentPath = sysPath$1.dirname(watchPath);
let cont = FSEventsWatchers.get(watchPath);
if (couldConsolidate(parentPath)) {
watchPath = parentPath;
}
const resolvedPath = sysPath$1.resolve(path3);
const hasSymlink = resolvedPath !== realPath;
const filteredListener = (fullPath, flags, info) => {
if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
if (fullPath === resolvedPath || !fullPath.indexOf(resolvedPath + sysPath$1.sep)) listener2(fullPath, flags, info);
};
let watchedParent = false;
for (const watchedPath of FSEventsWatchers.keys()) {
if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
watchPath = watchedPath;
cont = FSEventsWatchers.get(watchPath);
watchedParent = true;
break;
}
}
if (cont || watchedParent) {
cont.listeners.add(filteredListener);
} else {
cont = {
listeners: /* @__PURE__ */ new Set([filteredListener]),
rawEmitter,
watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
if (!cont.listeners.size) return;
if (flags & FSEVENT_FLAG_MUST_SCAN_SUBDIRS) return;
const info = fsevents.getInfo(fullPath, flags);
cont.listeners.forEach((list) => {
list(fullPath, flags, info);
});
cont.rawEmitter(info.event, fullPath, info);
})
};
FSEventsWatchers.set(watchPath, cont);
}
return () => {
const lst = cont.listeners;
lst.delete(filteredListener);
if (!lst.size) {
FSEventsWatchers.delete(watchPath);
if (cont.watcher) return cont.watcher.stop().then(() => {
cont.rawEmitter = cont.watcher = void 0;
Object.freeze(cont);
});
}
};
}
var couldConsolidate = (path3) => {
let count = 0;
for (const watchPath of FSEventsWatchers.keys()) {
if (watchPath.indexOf(path3) === 0) {
count++;
if (count >= consolidateThreshhold) {
return true;
}
}
}
return false;
};
var canUse = () => fsevents && FSEventsWatchers.size < 128;
var calcDepth = (path3, root) => {
let i = 0;
while (!path3.indexOf(root) && (path3 = sysPath$1.dirname(path3)) !== root) i++;
return i;
};
var sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile();
var FsEventsHandler$1 = class FsEventsHandler {
/**
* @param {import('../index').FSWatcher} fsw
*/
constructor(fsw) {
this.fsw = fsw;
}
checkIgnored(path3, stats) {
const ipaths = this.fsw._ignoredPaths;
if (this.fsw._isIgnored(path3, stats)) {
ipaths.add(path3);
if (stats && stats.isDirectory()) {
ipaths.add(path3 + ROOT_GLOBSTAR);
}
return true;
}
ipaths.delete(path3);
ipaths.delete(path3 + ROOT_GLOBSTAR);
}
addOrChange(path3, fullPath, realPath, parent, watchedDir, item, info, opts) {
const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
this.handleEvent(event, path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
async checkExists(path3, fullPath, realPath, parent, watchedDir, item, info, opts) {
try {
const stats = await stat$1(path3);
if (this.fsw.closed) return;
if (sameTypes(info, stats)) {
this.addOrChange(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK$1, path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} catch (error2) {
if (error2.code === "EACCES") {
this.addOrChange(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK$1, path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
}
}
handleEvent(event, path3, fullPath, realPath, parent, watchedDir, item, info, opts) {
if (this.fsw.closed || this.checkIgnored(path3)) return;
if (event === EV_UNLINK$1) {
const isDirectory2 = info.type === FSEVENT_TYPE_DIRECTORY;
if (isDirectory2 || watchedDir.has(item)) {
this.fsw._remove(parent, item, isDirectory2);
}
} else {
if (event === EV_ADD$1) {
if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path3);
if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1;
return this._addToFsEvents(path3, false, true, curDepth);
}
this.fsw._getWatchedDir(parent).add(item);
}
const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
this.fsw._emit(eventName, path3);
if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path3, false, true);
}
}
/**
* Handle symlinks encountered during directory scan
* @param {String} watchPath - file/dir path to be watched with fsevents
* @param {String} realPath - real path (in case of symlinks)
* @param {Function} transform - path transformer
* @param {Function} globFilter - path filter in case a glob pattern was provided
* @returns {Function} closer for the watcher instance
*/
_watchWithFsEvents(watchPath, realPath, transform2, globFilter) {
if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
const opts = this.fsw.options;
const watchCallback = async (fullPath, flags, info) => {
if (this.fsw.closed || this.fsw._isIgnored(fullPath)) return;
if (opts.depth !== void 0 && calcDepth(fullPath, realPath) > opts.depth) return;
const path3 = transform2(sysPath$1.join(
watchPath,
sysPath$1.relative(watchPath, fullPath)
));
if (globFilter && !globFilter(path3)) return;
const parent = sysPath$1.dirname(path3);
const item = sysPath$1.basename(path3);
const watchedDir = this.fsw._getWatchedDir(
info.type === FSEVENT_TYPE_DIRECTORY ? path3 : parent
);
if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
if (typeof opts.ignored === FUNCTION_TYPE$1) {
let stats;
try {
stats = await stat$1(path3);
} catch (error2) {
}
if (this.fsw.closed) return;
if (this.checkIgnored(path3, stats)) return;
if (sameTypes(info, stats)) {
this.addOrChange(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
} else {
this.handleEvent(EV_UNLINK$1, path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} else {
this.checkExists(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
} else {
switch (info.event) {
case FSEVENT_CREATED:
case FSEVENT_MODIFIED:
return this.addOrChange(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
case FSEVENT_DELETED:
case FSEVENT_MOVED:
return this.checkExists(path3, fullPath, realPath, parent, watchedDir, item, info, opts);
}
}
};
const closer = setFSEventsListener(
watchPath,
realPath,
watchCallback,
this.fsw._emitRaw
);
this.fsw._emitReady();
return closer;
}
/**
* Handle symlinks encountered during directory scan
* @param {String} linkPath path to symlink
* @param {String} fullPath absolute path to the symlink
* @param {Function} transform pre-existing path transformer
* @param {Number} curDepth level of subdirectories traversed to where symlink is
* @returns {Promise<void>}
*/
async _handleFsEventsSymlink(linkPath, fullPath, transform2, curDepth) {
if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
this.fsw._symlinkPaths.set(fullPath, true);
this.fsw._incrReadyCount();
try {
const linkTarget = await realpath(linkPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(linkTarget)) {
return this.fsw._emitReady();
}
this.fsw._incrReadyCount();
this._addToFsEvents(linkTarget || linkPath, (path3) => {
let aliasedPath = linkPath;
if (linkTarget && linkTarget !== DOT_SLASH) {
aliasedPath = path3.replace(linkTarget, linkPath);
} else if (path3 !== DOT_SLASH) {
aliasedPath = sysPath$1.join(linkPath, path3);
}
return transform2(aliasedPath);
}, false, curDepth);
} catch (error2) {
if (this.fsw._handleError(error2)) {
return this.fsw._emitReady();
}
}
}
/**
*
* @param {Path} newPath
* @param {fs.Stats} stats
*/
emitAdd(newPath, stats, processPath, opts, forceAdd) {
const pp = processPath(newPath);
const isDir = stats.isDirectory();
const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
const base = sysPath$1.basename(pp);
if (isDir) this.fsw._getWatchedDir(pp);
if (dirObj.has(base)) return;
dirObj.add(base);
if (!opts.ignoreInitial || forceAdd === true) {
this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
}
}
initWatch(realPath, path3, wh, processPath) {
if (this.fsw.closed) return;
const closer = this._watchWithFsEvents(
wh.watchPath,
sysPath$1.resolve(realPath || wh.watchPath),
processPath,
wh.globFilter
);
this.fsw._addPathCloser(path3, closer);
}
/**
* Handle added path with fsevents
* @param {String} path file/dir path or glob pattern
* @param {Function|Boolean=} transform converts working path to what the user expects
* @param {Boolean=} forceAdd ensure add is emitted
* @param {Number=} priorDepth Level of subdirectories already traversed.
* @returns {Promise<void>}
*/
async _addToFsEvents(path3, transform2, forceAdd, priorDepth) {
if (this.fsw.closed) {
return;
}
const opts = this.fsw.options;
const processPath = typeof transform2 === FUNCTION_TYPE$1 ? transform2 : IDENTITY_FN;
const wh = this.fsw._getWatchHelpers(path3);
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
throw null;
}
if (stats.isDirectory()) {
if (!wh.globFilter) this.emitAdd(processPath(path3), stats, processPath, opts, forceAdd);
if (priorDepth && priorDepth > opts.depth) return;
this.fsw._readdirp(wh.watchPath, {
fileFilter: (entry2) => wh.filterPath(entry2),
directoryFilter: (entry2) => wh.filterDir(entry2),
...Depth(opts.depth - (priorDepth || 0))
}).on(STR_DATA, (entry2) => {
if (this.fsw.closed) {
return;
}
if (entry2.stats.isDirectory() && !wh.filterPath(entry2)) return;
const joinedPath = sysPath$1.join(wh.watchPath, entry2.path);
const { fullPath } = entry2;
if (wh.followSymlinks && entry2.stats.isSymbolicLink()) {
const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
} else {
this.emitAdd(joinedPath, entry2.stats, processPath, opts, forceAdd);
}
}).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
this.fsw._emitReady();
});
} else {
this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
this.fsw._emitReady();
}
} catch (error2) {
if (!error2 || this.fsw._handleError(error2)) {
this.fsw._emitReady();
this.fsw._emitReady();
}
}
if (opts.persistent && forceAdd !== true) {
if (typeof transform2 === FUNCTION_TYPE$1) {
this.initWatch(void 0, path3, wh, processPath);
} else {
let realPath;
try {
realPath = await realpath(wh.watchPath);
} catch (e2) {
}
this.initWatch(realPath, path3, wh, processPath);
}
}
}
};
fseventsHandler.exports = FsEventsHandler$1;
fseventsHandler.exports.canUse = canUse;
var fseventsHandlerExports = fseventsHandler.exports;
var { EventEmitter: EventEmitter$2 } = import_events.default;
var fs$5 = import_fs.default;
var sysPath = import_path.default;
var { promisify } = import_util.default;
var readdirp = readdirp_1;
var anymatch = anymatchExports.default;
var globParent2 = globParent$2;
var isGlob2 = isGlob$2;
var braces = braces_1;
var normalizePath2 = normalizePath$2;
var NodeFsHandler2 = nodefsHandler;
var FsEventsHandler2 = fseventsHandlerExports;
var {
EV_ALL,
EV_READY,
EV_ADD,
EV_CHANGE,
EV_UNLINK,
EV_ADD_DIR,
EV_UNLINK_DIR,
EV_RAW,
EV_ERROR,
STR_CLOSE,
STR_END,
BACK_SLASH_RE,
DOUBLE_SLASH_RE,
SLASH_OR_BACK_SLASH_RE,
DOT_RE,
REPLACER_RE,
SLASH,
SLASH_SLASH,
BRACE_START,
BANG,
ONE_DOT,
TWO_DOTS,
GLOBSTAR,
SLASH_GLOBSTAR,
ANYMATCH_OPTS,
STRING_TYPE,
FUNCTION_TYPE,
EMPTY_STR,
EMPTY_FN,
isWindows: isWindows$1,
isMacos,
isIBMi
} = constants$1;
var stat = promisify(fs$5.stat);
var readdir = promisify(fs$5.readdir);
var arrify = (value2 = []) => Array.isArray(value2) ? value2 : [value2];
var flatten = (list, result = []) => {
list.forEach((item) => {
if (Array.isArray(item)) {
flatten(item, result);
} else {
result.push(item);
}
});
return result;
};
var unifyPaths = (paths_) => {
const paths = flatten(arrify(paths_));
if (!paths.every((p) => typeof p === STRING_TYPE)) {
throw new TypeError(`Non-string provided as watch path: ${paths}`);
}
return paths.map(normalizePathToUnix);
};
var toUnix = (string2) => {
let str = string2.replace(BACK_SLASH_RE, SLASH);
let prepend = false;
if (str.startsWith(SLASH_SLASH)) {
prepend = true;
}
while (str.match(DOUBLE_SLASH_RE)) {
str = str.replace(DOUBLE_SLASH_RE, SLASH);
}
if (prepend) {
str = SLASH + str;
}
return str;
};
var normalizePathToUnix = (path3) => toUnix(sysPath.normalize(toUnix(path3)));
var normalizeIgnored = (cwd = EMPTY_STR) => (path3) => {
if (typeof path3 !== STRING_TYPE) return path3;
return normalizePathToUnix(sysPath.isAbsolute(path3) ? path3 : sysPath.join(cwd, path3));
};
var getAbsolutePath = (path3, cwd) => {
if (sysPath.isAbsolute(path3)) {
return path3;
}
if (path3.startsWith(BANG)) {
return BANG + sysPath.join(cwd, path3.slice(1));
}
return sysPath.join(cwd, path3);
};
var undef = (opts, key) => opts[key] === void 0;
var DirEntry = class {
/**
* @param {Path} dir
* @param {Function} removeWatcher
*/
constructor(dir, removeWatcher) {
this.path = dir;
this._removeWatcher = removeWatcher;
this.items = /* @__PURE__ */ new Set();
}
add(item) {
const { items } = this;
if (!items) return;
if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
}
async remove(item) {
const { items } = this;
if (!items) return;
items.delete(item);
if (items.size > 0) return;
const dir = this.path;
try {
await readdir(dir);
} catch (err2) {
if (this._removeWatcher) {
this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
}
}
}
has(item) {
const { items } = this;
if (!items) return;
return items.has(item);
}
/**
* @returns {Array<String>}
*/
getChildren() {
const { items } = this;
if (!items) return;
return [...items.values()];
}
dispose() {
this.items.clear();
delete this.path;
delete this._removeWatcher;
delete this.items;
Object.freeze(this);
}
};
var STAT_METHOD_F = "stat";
var STAT_METHOD_L = "lstat";
var WatchHelper = class {
constructor(path3, watchPath, follow, fsw) {
this.fsw = fsw;
this.path = path3 = path3.replace(REPLACER_RE, EMPTY_STR);
this.watchPath = watchPath;
this.fullWatchPath = sysPath.resolve(watchPath);
this.hasGlob = watchPath !== path3;
if (path3 === EMPTY_STR) this.hasGlob = false;
this.globSymlink = this.hasGlob && follow ? void 0 : false;
this.globFilter = this.hasGlob ? anymatch(path3, void 0, ANYMATCH_OPTS) : false;
this.dirParts = this.getDirParts(path3);
this.dirParts.forEach((parts) => {
if (parts.length > 1) parts.pop();
});
this.followSymlinks = follow;
this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
}
checkGlobSymlink(entry2) {
if (this.globSymlink === void 0) {
this.globSymlink = entry2.fullParentDir === this.fullWatchPath ? false : { realPath: entry2.fullParentDir, linkPath: this.fullWatchPath };
}
if (this.globSymlink) {
return entry2.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
}
return entry2.fullPath;
}
entryPath(entry2) {
return sysPath.join(
this.watchPath,
sysPath.relative(this.watchPath, this.checkGlobSymlink(entry2))
);
}
filterPath(entry2) {
const { stats } = entry2;
if (stats && stats.isSymbolicLink()) return this.filterDir(entry2);
const resolvedPath = this.entryPath(entry2);
const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true;
return matchesGlob && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
}
getDirParts(path3) {
if (!this.hasGlob) return [];
const parts = [];
const expandedPath = path3.includes(BRACE_START) ? braces.expand(path3) : [path3];
expandedPath.forEach((path4) => {
parts.push(sysPath.relative(this.watchPath, path4).split(SLASH_OR_BACK_SLASH_RE));
});
return parts;
}
filterDir(entry2) {
if (this.hasGlob) {
const entryParts = this.getDirParts(this.checkGlobSymlink(entry2));
let globstar = false;
this.unmatchedGlob = !this.dirParts.some((parts) => {
return parts.every((part, i) => {
if (part === GLOBSTAR) globstar = true;
return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
});
});
}
return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry2), entry2.stats);
}
};
var FSWatcher = class extends EventEmitter$2 {
// Not indenting methods for history sake; for now.
constructor(_opts) {
super();
const opts = {};
if (_opts) Object.assign(opts, _opts);
this._watched = /* @__PURE__ */ new Map();
this._closers = /* @__PURE__ */ new Map();
this._ignoredPaths = /* @__PURE__ */ new Set();
this._throttled = /* @__PURE__ */ new Map();
this._symlinkPaths = /* @__PURE__ */ new Map();
this._streams = /* @__PURE__ */ new Set();
this.closed = false;
if (undef(opts, "persistent")) opts.persistent = true;
if (undef(opts, "ignoreInitial")) opts.ignoreInitial = false;
if (undef(opts, "ignorePermissionErrors")) opts.ignorePermissionErrors = false;
if (undef(opts, "interval")) opts.interval = 100;
if (undef(opts, "binaryInterval")) opts.binaryInterval = 300;
if (undef(opts, "disableGlobbing")) opts.disableGlobbing = false;
opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
if (undef(opts, "useFsEvents")) opts.useFsEvents = !opts.usePolling;
const canUseFsEvents = FsEventsHandler2.canUse();
if (!canUseFsEvents) opts.useFsEvents = false;
if (undef(opts, "usePolling") && !opts.useFsEvents) {
opts.usePolling = isMacos;
}
if (isIBMi) {
opts.usePolling = true;
}
const envPoll = process.env.CHOKIDAR_USEPOLLING;
if (envPoll !== void 0) {
const envLower = envPoll.toLowerCase();
if (envLower === "false" || envLower === "0") {
opts.usePolling = false;
} else if (envLower === "true" || envLower === "1") {
opts.usePolling = true;
} else {
opts.usePolling = !!envLower;
}
}
const envInterval = process.env.CHOKIDAR_INTERVAL;
if (envInterval) {
opts.interval = Number.parseInt(envInterval, 10);
}
if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents;
if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map();
if (undef(opts, "followSymlinks")) opts.followSymlinks = true;
if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false;
if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
const awf = opts.awaitWriteFinish;
if (awf) {
if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3;
if (!awf.pollInterval) awf.pollInterval = 100;
this._pendingWrites = /* @__PURE__ */ new Map();
}
if (opts.ignored) opts.ignored = arrify(opts.ignored);
let readyCalls = 0;
this._emitReady = () => {
readyCalls++;
if (readyCalls >= this._readyCount) {
this._emitReady = EMPTY_FN;
this._readyEmitted = true;
process.nextTick(() => this.emit(EV_READY));
}
};
this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
this._readyEmitted = false;
this.options = opts;
if (opts.useFsEvents) {
this._fsEventsHandler = new FsEventsHandler2(this);
} else {
this._nodeFsHandler = new NodeFsHandler2(this);
}
Object.freeze(opts);
}
// Public methods
/**
* Adds paths to be watched on an existing FSWatcher instance
* @param {Path|Array<Path>} paths_
* @param {String=} _origAdd private; for handling non-existent paths to be watched
* @param {Boolean=} _internal private; indicates a non-user add
* @returns {FSWatcher} for chaining
*/
add(paths_, _origAdd, _internal) {
const { cwd, disableGlobbing } = this.options;
this.closed = false;
let paths = unifyPaths(paths_);
if (cwd) {
paths = paths.map((path3) => {
const absPath = getAbsolutePath(path3, cwd);
if (disableGlobbing || !isGlob2(path3)) {
return absPath;
}
return normalizePath2(absPath);
});
}
paths = paths.filter((path3) => {
if (path3.startsWith(BANG)) {
this._ignoredPaths.add(path3.slice(1));
return false;
}
this._ignoredPaths.delete(path3);
this._ignoredPaths.delete(path3 + SLASH_GLOBSTAR);
this._userIgnored = void 0;
return true;
});
if (this.options.useFsEvents && this._fsEventsHandler) {
if (!this._readyCount) this._readyCount = paths.length;
if (this.options.persistent) this._readyCount += paths.length;
paths.forEach((path3) => this._fsEventsHandler._addToFsEvents(path3));
} else {
if (!this._readyCount) this._readyCount = 0;
this._readyCount += paths.length;
Promise.all(
paths.map(async (path3) => {
const res = await this._nodeFsHandler._addToNodeFs(path3, !_internal, 0, 0, _origAdd);
if (res) this._emitReady();
return res;
})
).then((results) => {
if (this.closed) return;
results.filter((item) => item).forEach((item) => {
this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
});
});
}
return this;
}
/**
* Close watchers or start ignoring events from specified paths.
* @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
* @returns {FSWatcher} for chaining
*/
unwatch(paths_) {
if (this.closed) return this;
const paths = unifyPaths(paths_);
const { cwd } = this.options;
paths.forEach((path3) => {
if (!sysPath.isAbsolute(path3) && !this._closers.has(path3)) {
if (cwd) path3 = sysPath.join(cwd, path3);
path3 = sysPath.resolve(path3);
}
this._closePath(path3);
this._ignoredPaths.add(path3);
if (this._watched.has(path3)) {
this._ignoredPaths.add(path3 + SLASH_GLOBSTAR);
}
this._userIgnored = void 0;
});
return this;
}
/**
* Close watchers and remove all listeners from watched paths.
* @returns {Promise<void>}.
*/
close() {
if (this.closed) return this._closePromise;
this.closed = true;
this.removeAllListeners();
const closers = [];
this._closers.forEach((closerList) => closerList.forEach((closer) => {
const promise2 = closer();
if (promise2 instanceof Promise) closers.push(promise2);
}));
this._streams.forEach((stream4) => stream4.destroy());
this._userIgnored = void 0;
this._readyCount = 0;
this._readyEmitted = false;
this._watched.forEach((dirent) => dirent.dispose());
["closers", "watched", "streams", "symlinkPaths", "throttled"].forEach((key) => {
this[`_${key}`].clear();
});
this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
return this._closePromise;
}
/**
* Expose list of watched paths
* @returns {Object} for chaining
*/
getWatched() {
const watchList = {};
this._watched.forEach((entry2, dir) => {
const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
watchList[key || ONE_DOT] = entry2.getChildren().sort();
});
return watchList;
}
emitWithAll(event, args) {
this.emit(...args);
if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
}
// Common helpers
// --------------
/**
* Normalize and emit events.
* Calling _emit DOES NOT MEAN emit() would be called!
* @param {EventName} event Type of event
* @param {Path} path File or directory path
* @param {*=} val1 arguments to be passed with event
* @param {*=} val2
* @param {*=} val3
* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
async _emit(event, path3, val1, val2, val3) {
if (this.closed) return;
const opts = this.options;
if (isWindows$1) path3 = sysPath.normalize(path3);
if (opts.cwd) path3 = sysPath.relative(opts.cwd, path3);
const args = [event, path3];
if (val3 !== void 0) args.push(val1, val2, val3);
else if (val2 !== void 0) args.push(val1, val2);
else if (val1 !== void 0) args.push(val1);
const awf = opts.awaitWriteFinish;
let pw;
if (awf && (pw = this._pendingWrites.get(path3))) {
pw.lastChange = /* @__PURE__ */ new Date();
return this;
}
if (opts.atomic) {
if (event === EV_UNLINK) {
this._pendingUnlinks.set(path3, args);
setTimeout(() => {
this._pendingUnlinks.forEach((entry2, path4) => {
this.emit(...entry2);
this.emit(EV_ALL, ...entry2);
this._pendingUnlinks.delete(path4);
});
}, typeof opts.atomic === "number" ? opts.atomic : 100);
return this;
}
if (event === EV_ADD && this._pendingUnlinks.has(path3)) {
event = args[0] = EV_CHANGE;
this._pendingUnlinks.delete(path3);
}
}
if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
const awfEmit = (err2, stats) => {
if (err2) {
event = args[0] = EV_ERROR;
args[1] = err2;
this.emitWithAll(event, args);
} else if (stats) {
if (args.length > 2) {
args[2] = stats;
} else {
args.push(stats);
}
this.emitWithAll(event, args);
}
};
this._awaitWriteFinish(path3, awf.stabilityThreshold, event, awfEmit);
return this;
}
if (event === EV_CHANGE) {
const isThrottled = !this._throttle(EV_CHANGE, path3, 50);
if (isThrottled) return this;
}
if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) {
const fullPath = opts.cwd ? sysPath.join(opts.cwd, path3) : path3;
let stats;
try {
stats = await stat(fullPath);
} catch (err2) {
}
if (!stats || this.closed) return;
args.push(stats);
}
this.emitWithAll(event, args);
return this;
}
/**
* Common handler for errors
* @param {Error} error
* @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
*/
_handleError(error2) {
const code = error2 && error2.code;
if (error2 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
this.emit(EV_ERROR, error2);
}
return error2 || this.closed;
}
/**
* Helper utility for throttling
* @param {ThrottleType} actionType type being throttled
* @param {Path} path being acted upon
* @param {Number} timeout duration of time to suppress duplicate actions
* @returns {Object|false} tracking object or false if action should be suppressed
*/
_throttle(actionType, path3, timeout2) {
if (!this._throttled.has(actionType)) {
this._throttled.set(actionType, /* @__PURE__ */ new Map());
}
const action = this._throttled.get(actionType);
const actionPath = action.get(path3);
if (actionPath) {
actionPath.count++;
return false;
}
let timeoutObject;
const clear = () => {
const item = action.get(path3);
const count = item ? item.count : 0;
action.delete(path3);
clearTimeout(timeoutObject);
if (item) clearTimeout(item.timeoutObject);
return count;
};
timeoutObject = setTimeout(clear, timeout2);
const thr = { timeoutObject, clear, count: 0 };
action.set(path3, thr);
return thr;
}
_incrReadyCount() {
return this._readyCount++;
}
/**
* Awaits write operation to finish.
* Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
* @param {Path} path being acted upon
* @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
* @param {EventName} event
* @param {Function} awfEmit Callback to be called when ready for event to be emitted.
*/
_awaitWriteFinish(path3, threshold, event, awfEmit) {
let timeoutHandler;
let fullPath = path3;
if (this.options.cwd && !sysPath.isAbsolute(path3)) {
fullPath = sysPath.join(this.options.cwd, path3);
}
const now = /* @__PURE__ */ new Date();
const awaitWriteFinish = (prevStat) => {
fs$5.stat(fullPath, (err2, curStat) => {
if (err2 || !this._pendingWrites.has(path3)) {
if (err2 && err2.code !== "ENOENT") awfEmit(err2);
return;
}
const now2 = Number(/* @__PURE__ */ new Date());
if (prevStat && curStat.size !== prevStat.size) {
this._pendingWrites.get(path3).lastChange = now2;
}
const pw = this._pendingWrites.get(path3);
const df = now2 - pw.lastChange;
if (df >= threshold) {
this._pendingWrites.delete(path3);
awfEmit(void 0, curStat);
} else {
timeoutHandler = setTimeout(
awaitWriteFinish,
this.options.awaitWriteFinish.pollInterval,
curStat
);
}
});
};
if (!this._pendingWrites.has(path3)) {
this._pendingWrites.set(path3, {
lastChange: now,
cancelWait: () => {
this._pendingWrites.delete(path3);
clearTimeout(timeoutHandler);
return event;
}
});
timeoutHandler = setTimeout(
awaitWriteFinish,
this.options.awaitWriteFinish.pollInterval
);
}
}
_getGlobIgnored() {
return [...this._ignoredPaths.values()];
}
/**
* Determines whether user has asked to ignore this path.
* @param {Path} path filepath or dir
* @param {fs.Stats=} stats result of fs.stat
* @returns {Boolean}
*/
_isIgnored(path3, stats) {
if (this.options.atomic && DOT_RE.test(path3)) return true;
if (!this._userIgnored) {
const { cwd } = this.options;
const ign = this.options.ignored;
const ignored = ign && ign.map(normalizeIgnored(cwd));
const paths = arrify(ignored).filter((path4) => typeof path4 === STRING_TYPE && !isGlob2(path4)).map((path4) => path4 + SLASH_GLOBSTAR);
const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
this._userIgnored = anymatch(list, void 0, ANYMATCH_OPTS);
}
return this._userIgnored([path3, stats]);
}
_isntIgnored(path3, stat2) {
return !this._isIgnored(path3, stat2);
}
/**
* Provides a set of common helpers and properties relating to symlink and glob handling.
* @param {Path} path file, directory, or glob pattern being watched
* @param {Number=} depth at any depth > 0, this isn't a glob
* @returns {WatchHelper} object containing helpers for this path
*/
_getWatchHelpers(path3, depth2) {
const watchPath = depth2 || this.options.disableGlobbing || !isGlob2(path3) ? path3 : globParent2(path3);
const follow = this.options.followSymlinks;
return new WatchHelper(path3, watchPath, follow, this);
}
// Directory helpers
// -----------------
/**
* Provides directory tracking objects
* @param {String} directory path of the directory
* @returns {DirEntry} the directory's tracking object
*/
_getWatchedDir(directory) {
if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
const dir = sysPath.resolve(directory);
if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
return this._watched.get(dir);
}
// File helpers
// ------------
/**
* Check for read permissions.
* Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
* @param {fs.Stats} stats - object, result of fs_stat
* @returns {Boolean} indicates whether the file can be read
*/
_hasReadPermissions(stats) {
if (this.options.ignorePermissionErrors) return true;
const md = stats && Number.parseInt(stats.mode, 10);
const st = md & 511;
const it = Number.parseInt(st.toString(8)[0], 10);
return Boolean(4 & it);
}
/**
* Handles emitting unlink events for
* files and directories, and via recursion, for
* files and directories within directories that are unlinked
* @param {String} directory within which the following item is located
* @param {String} item base path of item/directory
* @returns {void}
*/
_remove(directory, item, isDirectory2) {
const path3 = sysPath.join(directory, item);
const fullPath = sysPath.resolve(path3);
isDirectory2 = isDirectory2 != null ? isDirectory2 : this._watched.has(path3) || this._watched.has(fullPath);
if (!this._throttle("remove", path3, 100)) return;
if (!isDirectory2 && !this.options.useFsEvents && this._watched.size === 1) {
this.add(directory, item, true);
}
const wp = this._getWatchedDir(path3);
const nestedDirectoryChildren = wp.getChildren();
nestedDirectoryChildren.forEach((nested) => this._remove(path3, nested));
const parent = this._getWatchedDir(directory);
const wasTracked = parent.has(item);
parent.remove(item);
if (this._symlinkPaths.has(fullPath)) {
this._symlinkPaths.delete(fullPath);
}
let relPath = path3;
if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path3);
if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
const event = this._pendingWrites.get(relPath).cancelWait();
if (event === EV_ADD) return;
}
this._watched.delete(path3);
this._watched.delete(fullPath);
const eventName = isDirectory2 ? EV_UNLINK_DIR : EV_UNLINK;
if (wasTracked && !this._isIgnored(path3)) this._emit(eventName, path3);
if (!this.options.useFsEvents) {
this._closePath(path3);
}
}
/**
* Closes all watchers for a path
* @param {Path} path
*/
_closePath(path3) {
this._closeFile(path3);
const dir = sysPath.dirname(path3);
this._getWatchedDir(dir).remove(sysPath.basename(path3));
}
/**
* Closes only file-specific watchers
* @param {Path} path
*/
_closeFile(path3) {
const closers = this._closers.get(path3);
if (!closers) return;
closers.forEach((closer) => closer());
this._closers.delete(path3);
}
/**
*
* @param {Path} path
* @param {Function} closer
*/
_addPathCloser(path3, closer) {
if (!closer) return;
let list = this._closers.get(path3);
if (!list) {
list = [];
this._closers.set(path3, list);
}
list.push(closer);
}
_readdirp(root, opts) {
if (this.closed) return;
const options2 = { type: EV_ALL, alwaysStat: true, lstat: true, ...opts };
let stream4 = readdirp(root, options2);
this._streams.add(stream4);
stream4.once(STR_CLOSE, () => {
stream4 = void 0;
});
stream4.once(STR_END, () => {
if (stream4) {
this._streams.delete(stream4);
stream4 = void 0;
}
});
return stream4;
}
};
chokidar.FSWatcher = FSWatcher;
var watch = (paths, options2) => {
const watcher = new FSWatcher(options2);
watcher.add(paths);
return watcher;
};
chokidar.watch = watch;
var shellQuote$1 = {};
var quote = function quote2(xs) {
return xs.map(function(s) {
if (s && typeof s === "object") {
return s.op.replace(/(.)/g, "\\$1");
}
if (/["\s]/.test(s) && !/'/.test(s)) {
return "'" + s.replace(/(['\\])/g, "\\$1") + "'";
}
if (/["'\s]/.test(s)) {
return '"' + s.replace(/(["\\$`!])/g, "\\$1") + '"';
}
return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, "$1\\$2");
}).join(" ");
};
var CONTROL = "(?:" + [
"\\|\\|",
"\\&\\&",
";;",
"\\|\\&",
"\\<\\(",
"\\<\\<\\<",
">>",
">\\&",
"<\\&",
"[&;()|<>]"
].join("|") + ")";
var controlRE = new RegExp("^" + CONTROL + "$");
var META = "|&;()<> \\t";
var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"';
var DOUBLE_QUOTE = "'((\\\\'|[^'])*?)'";
var hash = /^#$/;
var SQ = "'";
var DQ = '"';
var DS = "$";
var TOKEN = "";
var mult = 4294967296;
for (i = 0; i < 4; i++) {
TOKEN += (mult * Math.random()).toString(16);
}
var i;
var startsWithToken = new RegExp("^" + TOKEN);
function matchAll(s, r2) {
var origIndex = r2.lastIndex;
var matches2 = [];
var matchObj;
while (matchObj = r2.exec(s)) {
matches2.push(matchObj);
if (r2.lastIndex === matchObj.index) {
r2.lastIndex += 1;
}
}
r2.lastIndex = origIndex;
return matches2;
}
function getVar(env2, pre, key) {
var r2 = typeof env2 === "function" ? env2(key) : env2[key];
if (typeof r2 === "undefined" && key != "") {
r2 = "";
} else if (typeof r2 === "undefined") {
r2 = "$";
}
if (typeof r2 === "object") {
return pre + TOKEN + JSON.stringify(r2) + TOKEN;
}
return pre + r2;
}
function parseInternal(string2, env2, opts) {
if (!opts) {
opts = {};
}
var BS = opts.escape || "\\";
var BAREWORD = "(\\" + BS + `['"` + META + `]|[^\\s'"` + META + "])+";
var chunker = new RegExp([
"(" + CONTROL + ")",
// control chars
"(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"
].join("|"), "g");
var matches2 = matchAll(string2, chunker);
if (matches2.length === 0) {
return [];
}
if (!env2) {
env2 = {};
}
var commented = false;
return matches2.map(function(match2) {
var s = match2[0];
if (!s || commented) {
return void 0;
}
if (controlRE.test(s)) {
return { op: s };
}
var quote3 = false;
var esc = false;
var out2 = "";
var isGlob3 = false;
var i;
function parseEnvVar() {
i += 1;
var varend;
var varname;
var char = s.charAt(i);
if (char === "{") {
i += 1;
if (s.charAt(i) === "}") {
throw new Error("Bad substitution: " + s.slice(i - 2, i + 1));
}
varend = s.indexOf("}", i);
if (varend < 0) {
throw new Error("Bad substitution: " + s.slice(i));
}
varname = s.slice(i, varend);
i = varend;
} else if (/[*@#?$!_-]/.test(char)) {
varname = char;
i += 1;
} else {
var slicedFromI = s.slice(i);
varend = slicedFromI.match(/[^\w\d_]/);
if (!varend) {
varname = slicedFromI;
i = s.length;
} else {
varname = slicedFromI.slice(0, varend.index);
i += varend.index - 1;
}
}
return getVar(env2, "", varname);
}
for (i = 0; i < s.length; i++) {
var c = s.charAt(i);
isGlob3 = isGlob3 || !quote3 && (c === "*" || c === "?");
if (esc) {
out2 += c;
esc = false;
} else if (quote3) {
if (c === quote3) {
quote3 = false;
} else if (quote3 == SQ) {
out2 += c;
} else {
if (c === BS) {
i += 1;
c = s.charAt(i);
if (c === DQ || c === BS || c === DS) {
out2 += c;
} else {
out2 += BS + c;
}
} else if (c === DS) {
out2 += parseEnvVar();
} else {
out2 += c;
}
}
} else if (c === DQ || c === SQ) {
quote3 = c;
} else if (controlRE.test(c)) {
return { op: s };
} else if (hash.test(c)) {
commented = true;
var commentObj = { comment: string2.slice(match2.index + i + 1) };
if (out2.length) {
return [out2, commentObj];
}
return [commentObj];
} else if (c === BS) {
esc = true;
} else if (c === DS) {
out2 += parseEnvVar();
} else {
out2 += c;
}
}
if (isGlob3) {
return { op: "glob", pattern: out2 };
}
return out2;
}).reduce(function(prev, arg) {
return typeof arg === "undefined" ? prev : prev.concat(arg);
}, []);
}
var parse$6 = function parse2(s, env2, opts) {
var mapped = parseInternal(s, env2, opts);
if (typeof env2 !== "function") {
return mapped;
}
return mapped.reduce(function(acc, s2) {
if (typeof s2 === "object") {
return acc.concat(s2);
}
var xs = s2.split(RegExp("(" + TOKEN + ".*?" + TOKEN + ")", "g"));
if (xs.length === 1) {
return acc.concat(xs[0]);
}
return acc.concat(xs.filter(Boolean).map(function(x) {
if (startsWithToken.test(x)) {
return JSON.parse(x.split(TOKEN)[1]);
}
return x;
}));
}, []);
};
shellQuote$1.quote = quote;
shellQuote$1.parse = parse$6;
var macos = {
"/Applications/Atom.app/Contents/MacOS/Atom": "atom",
"/Applications/Atom Beta.app/Contents/MacOS/Atom Beta": "/Applications/Atom Beta.app/Contents/MacOS/Atom Beta",
"/Applications/Brackets.app/Contents/MacOS/Brackets": "brackets",
"/Applications/Sublime Text.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
"/Applications/Sublime Text.app/Contents/MacOS/sublime_text": "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl",
"/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2": "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
"/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text": "/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl",
"/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
"/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron": "code-insiders",
"/Applications/VSCodium.app/Contents/MacOS/Electron": "codium",
"/Applications/Cursor.app/Contents/MacOS/Cursor": "cursor",
"/Applications/AppCode.app/Contents/MacOS/appcode": "/Applications/AppCode.app/Contents/MacOS/appcode",
"/Applications/CLion.app/Contents/MacOS/clion": "/Applications/CLion.app/Contents/MacOS/clion",
"/Applications/IntelliJ IDEA.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea",
"/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Ultimate.app/Contents/MacOS/idea",
"/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea": "/Applications/IntelliJ IDEA Community Edition.app/Contents/MacOS/idea",
"/Applications/PhpStorm.app/Contents/MacOS/phpstorm": "/Applications/PhpStorm.app/Contents/MacOS/phpstorm",
"/Applications/PyCharm.app/Contents/MacOS/pycharm": "/Applications/PyCharm.app/Contents/MacOS/pycharm",
"/Applications/PyCharm CE.app/Contents/MacOS/pycharm": "/Applications/PyCharm CE.app/Contents/MacOS/pycharm",
"/Applications/RubyMine.app/Contents/MacOS/rubymine": "/Applications/RubyMine.app/Contents/MacOS/rubymine",
"/Applications/WebStorm.app/Contents/MacOS/webstorm": "/Applications/WebStorm.app/Contents/MacOS/webstorm",
"/Applications/MacVim.app/Contents/MacOS/MacVim": "mvim",
"/Applications/GoLand.app/Contents/MacOS/goland": "/Applications/GoLand.app/Contents/MacOS/goland",
"/Applications/Rider.app/Contents/MacOS/rider": "/Applications/Rider.app/Contents/MacOS/rider",
"/Applications/Zed.app/Contents/MacOS/zed": "zed"
};
var linux = {
atom: "atom",
Brackets: "brackets",
"code-insiders": "code-insiders",
code: "code",
vscodium: "vscodium",
codium: "codium",
emacs: "emacs",
gvim: "gvim",
"idea.sh": "idea",
"phpstorm.sh": "phpstorm",
"pycharm.sh": "pycharm",
"rubymine.sh": "rubymine",
sublime_text: "subl",
vim: "vim",
"webstorm.sh": "webstorm",
"goland.sh": "goland",
"rider.sh": "rider"
};
var windows$1 = [
"Brackets.exe",
"Code.exe",
"Code - Insiders.exe",
"VSCodium.exe",
"atom.exe",
"sublime_text.exe",
"notepad++.exe",
"clion.exe",
"clion64.exe",
"idea.exe",
"idea64.exe",
"phpstorm.exe",
"phpstorm64.exe",
"pycharm.exe",
"pycharm64.exe",
"rubymine.exe",
"rubymine64.exe",
"webstorm.exe",
"webstorm64.exe",
"goland.exe",
"goland64.exe",
"rider.exe",
"rider64.exe"
];
var path$7 = import_path.default;
var shellQuote = shellQuote$1;
var childProcess$2 = import_child_process.default;
var COMMON_EDITORS_MACOS = macos;
var COMMON_EDITORS_LINUX = linux;
var COMMON_EDITORS_WIN = windows$1;
var guess = function guessEditor(specifiedEditor) {
if (specifiedEditor) {
return shellQuote.parse(specifiedEditor);
}
if (process.env.LAUNCH_EDITOR) {
return [process.env.LAUNCH_EDITOR];
}
if (process.versions.webcontainer) {
return [process.env.EDITOR || "code"];
}
try {
if (process.platform === "darwin") {
const output = childProcess$2.execSync("ps x -o comm=", {
stdio: ["pipe", "pipe", "ignore"]
}).toString();
const processNames = Object.keys(COMMON_EDITORS_MACOS);
const processList = output.split("\n");
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (processList.includes(processName)) {
return [COMMON_EDITORS_MACOS[processName]];
}
const processNameWithoutApplications = processName.replace("/Applications", "");
if (output.indexOf(processNameWithoutApplications) !== -1) {
if (processName !== COMMON_EDITORS_MACOS[processName]) {
return [COMMON_EDITORS_MACOS[processName]];
}
const runningProcess = processList.find((procName) => procName.endsWith(processNameWithoutApplications));
if (runningProcess !== void 0) {
return [runningProcess];
}
}
}
} else if (process.platform === "win32") {
const output = childProcess$2.execSync(
'powershell -NoProfile -Command "Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }"',
{
stdio: ["pipe", "pipe", "ignore"]
}
).toString();
const runningProcesses = output.split("\r\n");
for (let i = 0; i < runningProcesses.length; i++) {
const fullProcessPath = runningProcesses[i].trim();
const shortProcessName = path$7.basename(fullProcessPath);
if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
return [fullProcessPath];
}
}
} else if (process.platform === "linux") {
const output = childProcess$2.execSync("ps x --no-heading -o comm --sort=comm", {
stdio: ["pipe", "pipe", "ignore"]
}).toString();
const processNames = Object.keys(COMMON_EDITORS_LINUX);
for (let i = 0; i < processNames.length; i++) {
const processName = processNames[i];
if (output.indexOf(processName) !== -1) {
return [COMMON_EDITORS_LINUX[processName]];
}
}
}
} catch (ignoreError) {
}
if (process.env.VISUAL) {
return [process.env.VISUAL];
} else if (process.env.EDITOR) {
return [process.env.EDITOR];
}
return [null];
};
var path$6 = import_path.default;
var getArgs = function getArgumentsForPosition(editor, fileName, lineNumber, columnNumber = 1) {
const editorBasename = path$6.basename(editor).replace(/\.(exe|cmd|bat)$/i, "");
switch (editorBasename) {
case "atom":
case "Atom":
case "Atom Beta":
case "subl":
case "sublime":
case "sublime_text":
case "wstorm":
case "charm":
case "zed":
return [`${fileName}:${lineNumber}:${columnNumber}`];
case "notepad++":
return ["-n" + lineNumber, "-c" + columnNumber, fileName];
case "vim":
case "mvim":
return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName];
case "joe":
case "gvim":
return [`+${lineNumber}`, fileName];
case "emacs":
case "emacsclient":
return [`+${lineNumber}:${columnNumber}`, fileName];
case "rmate":
case "mate":
case "mine":
return ["--line", lineNumber, fileName];
case "code":
case "Code":
case "code-insiders":
case "Code - Insiders":
case "codium":
case "cursor":
case "vscodium":
case "VSCodium":
return ["-r", "-g", `${fileName}:${lineNumber}:${columnNumber}`];
case "appcode":
case "clion":
case "clion64":
case "idea":
case "idea64":
case "phpstorm":
case "phpstorm64":
case "pycharm":
case "pycharm64":
case "rubymine":
case "rubymine64":
case "webstorm":
case "webstorm64":
case "goland":
case "goland64":
case "rider":
case "rider64":
return ["--line", lineNumber, "--column", columnNumber, fileName];
}
if (process.env.LAUNCH_EDITOR) {
return [fileName, lineNumber, columnNumber];
}
return [fileName];
};
var fs$4 = import_fs.default;
var os$1 = import_os.default;
var path$5 = import_path.default;
var colors = picocolorsExports;
var childProcess$1 = import_child_process.default;
var guessEditor2 = guess;
var getArgumentsForPosition2 = getArgs;
function wrapErrorCallback(cb) {
return (fileName, errorMessage) => {
console.log();
console.log(
colors.red("Could not open " + path$5.basename(fileName) + " in the editor.")
);
if (errorMessage) {
if (errorMessage[errorMessage.length - 1] !== ".") {
errorMessage += ".";
}
console.log(
colors.red("The editor process exited with an error: " + errorMessage)
);
}
console.log();
if (cb) cb(fileName, errorMessage);
};
}
function isTerminalEditor(editor) {
switch (editor) {
case "vim":
case "emacs":
case "nano":
return true;
}
return false;
}
var positionRE = /:(\d+)(:(\d+))?$/;
function parseFile(file) {
const fileName = file.replace(positionRE, "");
const match2 = file.match(positionRE);
const lineNumber = match2 && match2[1];
const columnNumber = match2 && match2[3];
return {
fileName,
lineNumber,
columnNumber
};
}
var _childProcess = null;
function launchEditor(file, specifiedEditor, onErrorCallback) {
const parsed = parseFile(file);
let { fileName } = parsed;
const { lineNumber, columnNumber } = parsed;
if (!fs$4.existsSync(fileName)) {
return;
}
if (typeof specifiedEditor === "function") {
onErrorCallback = specifiedEditor;
specifiedEditor = void 0;
}
onErrorCallback = wrapErrorCallback(onErrorCallback);
const [editor, ...args] = guessEditor2(specifiedEditor);
if (!editor) {
onErrorCallback(fileName, null);
return;
}
if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os$1.release())) {
fileName = path$5.relative("", fileName);
}
const WINDOWS_CMD_SAFE_FILE_NAME_PATTERN = /^([A-Za-z]:[/\\])?[\p{L}0-9/.\-_\\]+$/u;
if (process.platform === "win32" && !WINDOWS_CMD_SAFE_FILE_NAME_PATTERN.test(fileName.trim())) {
console.log();
console.log(
colors.red("Could not open " + path$5.basename(fileName) + " in the editor.")
);
console.log();
console.log(
"When running on Windows, file names are checked against a safe file name pattern to protect against remote code execution attacks. File names may consist only of alphanumeric characters (all languages), periods, dashes, slashes, and underscores."
);
console.log();
return;
}
if (lineNumber) {
const extraArgs = getArgumentsForPosition2(editor, fileName, lineNumber, columnNumber);
args.push.apply(args, extraArgs);
} else {
args.push(fileName);
}
if (_childProcess && isTerminalEditor(editor)) {
_childProcess.kill("SIGKILL");
}
if (process.platform === "win32") {
_childProcess = childProcess$1.spawn(
"cmd.exe",
["/C", editor].concat(args),
{ stdio: "inherit" }
);
} else {
_childProcess = childProcess$1.spawn(editor, args, { stdio: "inherit" });
}
_childProcess.on("exit", function(errorCode) {
_childProcess = null;
if (errorCode) {
onErrorCallback(fileName, "(code " + errorCode + ")");
}
});
_childProcess.on("error", function(error2) {
let { code, message } = error2;
if ("ENOENT" === code) {
message = `${message} ('${editor}' command does not exist in 'PATH')`;
}
onErrorCallback(fileName, message);
});
}
var launchEditor_1 = launchEditor;
var url$2 = import_url.default;
var path$4 = import_path.default;
var launch = launchEditor_1;
var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => {
if (typeof specifiedEditor === "function") {
onErrorCallback = specifiedEditor;
specifiedEditor = void 0;
}
if (typeof srcRoot === "function") {
onErrorCallback = srcRoot;
srcRoot = void 0;
}
srcRoot = srcRoot || process.cwd();
return function launchEditorMiddleware2(req2, res) {
const { file } = url$2.parse(req2.url, true).query || {};
if (!file) {
res.statusCode = 500;
res.end(`launch-editor-middleware: required query param "file" is missing.`);
} else {
launch(path$4.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
res.end();
}
};
};
var launchEditorMiddleware$1 = getDefaultExportFromCjs(launchEditorMiddleware);
async function resolveHttpServer({ proxy }, app, httpsOptions) {
if (!httpsOptions) {
const { createServer: createServer2 } = await import("./node_http-PVJAKJLZ.js");
return createServer2(app);
}
if (proxy) {
const { createServer: createServer2 } = await import("./node_https-MF5UXHZ4.js");
return createServer2(httpsOptions, app);
} else {
const { createSecureServer } = await import("./node_http2-LSZGSR42.js");
return createSecureServer(
{
// Manually increase the session memory to prevent 502 ENHANCE_YOUR_CALM
// errors on large numbers of requests
maxSessionMemory: 1e3,
...httpsOptions,
allowHTTP1: true
},
// @ts-expect-error TODO: is this correct?
app
);
}
}
async function resolveHttpsConfig(https2) {
if (!https2) return void 0;
const [ca, cert, key, pfx] = await Promise.all([
readFileIfExists(https2.ca),
readFileIfExists(https2.cert),
readFileIfExists(https2.key),
readFileIfExists(https2.pfx)
]);
return { ...https2, ca, cert, key, pfx };
}
async function readFileIfExists(value2) {
if (typeof value2 === "string") {
return import_promises.default.readFile(import_node_path3.default.resolve(value2)).catch(() => value2);
}
return value2;
}
async function httpServerStart(httpServer, serverOptions) {
let { port, strictPort, host, logger } = serverOptions;
return new Promise((resolve3, reject) => {
const onError2 = (e2) => {
if (e2.code === "EADDRINUSE") {
if (strictPort) {
httpServer.removeListener("error", onError2);
reject(new Error(`Port ${port} is already in use`));
} else {
logger.info(`Port ${port} is in use, trying another one...`);
httpServer.listen(++port, host);
}
} else {
httpServer.removeListener("error", onError2);
reject(e2);
}
};
httpServer.on("error", onError2);
httpServer.listen(port, host, () => {
httpServer.removeListener("error", onError2);
resolve3(port);
});
});
}
function setClientErrorHandler(server2, logger) {
server2.on("clientError", (err2, socket) => {
let msg = "400 Bad Request";
if (err2.code === "HPE_HEADER_OVERFLOW") {
msg = "431 Request Header Fields Too Large";
logger.warn(
colors$1.yellow(
"Server responded with status code 431. See https://vitejs.dev/guide/troubleshooting.html#_431-request-header-fields-too-large."
)
);
}
if (err2.code === "ECONNRESET" || !socket.writable) {
return;
}
socket.end(`HTTP/1.1 ${msg}\r
\r
`);
});
}
var commonFsUtils = {
existsSync: import_node_fs2.default.existsSync,
isDirectory,
tryResolveRealFile,
tryResolveRealFileWithExtensions,
tryResolveRealFileOrType
};
var cachedFsUtilsMap = /* @__PURE__ */ new WeakMap();
function getFsUtils(config2) {
var _a4;
let fsUtils = cachedFsUtilsMap.get(config2);
if (!fsUtils) {
if (config2.command !== "serve" || config2.server.fs.cachedChecks === false || ((_a4 = config2.server.watch) == null ? void 0 : _a4.ignored) || process.versions.pnp) {
fsUtils = commonFsUtils;
} else if (!config2.resolve.preserveSymlinks && config2.root !== getRealPath(config2.root)) {
fsUtils = commonFsUtils;
} else {
fsUtils = createCachedFsUtils(config2);
}
cachedFsUtilsMap.set(config2, fsUtils);
}
return fsUtils;
}
function readDirCacheSync(file) {
let dirents;
try {
dirents = import_node_fs2.default.readdirSync(file, { withFileTypes: true });
} catch {
return;
}
return direntsToDirentMap(dirents);
}
function direntsToDirentMap(fsDirents) {
const dirents = /* @__PURE__ */ new Map();
for (const dirent of fsDirents) {
const type = dirent.isDirectory() ? "directory" : dirent.isSymbolicLink() ? "symlink" : dirent.isFile() ? "file" : void 0;
if (type) {
dirents.set(dirent.name, { type });
}
}
return dirents;
}
function ensureFileMaybeSymlinkIsResolved(direntCache, filePath) {
var _a4;
if (direntCache.type !== "file_maybe_symlink") return;
const isSymlink = (_a4 = import_node_fs2.default.lstatSync(filePath, { throwIfNoEntry: false })) == null ? void 0 : _a4.isSymbolicLink();
direntCache.type = isSymlink === void 0 ? "error" : isSymlink ? "symlink" : "file";
}
function pathUntilPart(root, parts, i) {
let p = root;
for (let k = 0; k < i; k++) p += "/" + parts[k];
return p;
}
function createCachedFsUtils(config2) {
const root = config2.root;
const rootDirPath = `${root}/`;
const rootCache = { type: "directory" };
const getDirentCacheSync = (parts) => {
var _a4;
let direntCache = rootCache;
for (let i = 0; i < parts.length; i++) {
if (direntCache.type === "directory") {
let dirPath;
if (!direntCache.dirents) {
dirPath = pathUntilPart(root, parts, i);
const dirents = readDirCacheSync(dirPath);
if (!dirents) {
direntCache.type = "error";
return;
}
direntCache.dirents = dirents;
}
const nextDirentCache = direntCache.dirents.get(parts[i]);
if (!nextDirentCache) {
return;
}
if (nextDirentCache.type === "directory_maybe_symlink") {
dirPath ?? (dirPath = pathUntilPart(root, parts, i + 1));
const isSymlink = (_a4 = import_node_fs2.default.lstatSync(dirPath, { throwIfNoEntry: false })) == null ? void 0 : _a4.isSymbolicLink();
nextDirentCache.type = isSymlink ? "symlink" : "directory";
}
direntCache = nextDirentCache;
} else if (direntCache.type === "symlink") {
return direntCache;
} else if (direntCache.type === "error") {
return direntCache;
} else {
if (i !== parts.length - 1) {
return;
}
if (direntCache.type === "file_maybe_symlink") {
ensureFileMaybeSymlinkIsResolved(
direntCache,
pathUntilPart(root, parts, i)
);
return direntCache;
} else if (direntCache.type === "file") {
return direntCache;
} else {
return;
}
}
}
return direntCache;
};
function getDirentCacheFromPath(normalizedFile) {
if (normalizedFile[normalizedFile.length - 1] === "/") {
normalizedFile = normalizedFile.slice(0, -1);
}
if (normalizedFile === root) {
return rootCache;
}
if (!normalizedFile.startsWith(rootDirPath)) {
return void 0;
}
const pathFromRoot = normalizedFile.slice(rootDirPath.length);
const parts = pathFromRoot.split("/");
const direntCache = getDirentCacheSync(parts);
if (!direntCache || direntCache.type === "error") {
return false;
}
return direntCache;
}
function onPathAdd(file, type) {
const direntCache = getDirentCacheFromPath(
normalizePath$3(import_node_path3.default.dirname(file))
);
if (direntCache && direntCache.type === "directory" && direntCache.dirents) {
direntCache.dirents.set(import_node_path3.default.basename(file), { type });
}
}
function onPathUnlink(file) {
const direntCache = getDirentCacheFromPath(
normalizePath$3(import_node_path3.default.dirname(file))
);
if (direntCache && direntCache.type === "directory" && direntCache.dirents) {
direntCache.dirents.delete(import_node_path3.default.basename(file));
}
}
return {
existsSync(file) {
if (isInNodeModules$1(file)) {
return import_node_fs2.default.existsSync(file);
}
const normalizedFile = normalizePath$3(file);
const direntCache = getDirentCacheFromPath(normalizedFile);
if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
return import_node_fs2.default.existsSync(file);
}
return !!direntCache;
},
tryResolveRealFile(file, preserveSymlinks) {
if (isInNodeModules$1(file)) {
return tryResolveRealFile(file, preserveSymlinks);
}
const normalizedFile = normalizePath$3(file);
const direntCache = getDirentCacheFromPath(normalizedFile);
if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
return tryResolveRealFile(file, preserveSymlinks);
}
if (!direntCache || direntCache.type === "directory") {
return;
}
return normalizedFile;
},
tryResolveRealFileWithExtensions(file, extensions2, preserveSymlinks) {
if (isInNodeModules$1(file)) {
return tryResolveRealFileWithExtensions(
file,
extensions2,
preserveSymlinks
);
}
const normalizedFile = normalizePath$3(file);
const dirPath = import_node_path3.default.posix.dirname(normalizedFile);
const direntCache = getDirentCacheFromPath(dirPath);
if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
return tryResolveRealFileWithExtensions(
file,
extensions2,
preserveSymlinks
);
}
if (!direntCache || direntCache.type !== "directory") {
return;
}
if (!direntCache.dirents) {
const dirents = readDirCacheSync(dirPath);
if (!dirents) {
direntCache.type = "error";
return;
}
direntCache.dirents = dirents;
}
const base = import_node_path3.default.posix.basename(normalizedFile);
for (const ext2 of extensions2) {
const fileName = base + ext2;
const fileDirentCache = direntCache.dirents.get(fileName);
if (fileDirentCache) {
const filePath = dirPath + "/" + fileName;
ensureFileMaybeSymlinkIsResolved(fileDirentCache, filePath);
if (fileDirentCache.type === "symlink") {
return tryResolveRealFile(filePath, preserveSymlinks);
}
if (fileDirentCache.type === "file") {
return filePath;
}
}
}
},
tryResolveRealFileOrType(file, preserveSymlinks) {
if (isInNodeModules$1(file)) {
return tryResolveRealFileOrType(file, preserveSymlinks);
}
const normalizedFile = normalizePath$3(file);
const direntCache = getDirentCacheFromPath(normalizedFile);
if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
return tryResolveRealFileOrType(file, preserveSymlinks);
}
if (!direntCache) {
return;
}
if (direntCache.type === "directory") {
return { type: "directory" };
}
return { path: normalizedFile, type: "file" };
},
isDirectory(dirPath) {
if (isInNodeModules$1(dirPath)) {
return isDirectory(dirPath);
}
const direntCache = getDirentCacheFromPath(normalizePath$3(dirPath));
if (direntCache === void 0 || direntCache && direntCache.type === "symlink") {
return isDirectory(dirPath);
}
return direntCache && direntCache.type === "directory";
},
initWatcher(watcher) {
watcher.on("add", (file) => {
onPathAdd(file, "file_maybe_symlink");
});
watcher.on("addDir", (dir) => {
onPathAdd(dir, "directory_maybe_symlink");
});
watcher.on("unlink", onPathUnlink);
watcher.on("unlinkDir", onPathUnlink);
}
};
}
function tryResolveRealFile(file, preserveSymlinks) {
const stat2 = tryStatSync(file);
if (stat2 == null ? void 0 : stat2.isFile()) return getRealPath(file, preserveSymlinks);
}
function tryResolveRealFileWithExtensions(filePath, extensions2, preserveSymlinks) {
for (const ext2 of extensions2) {
const res = tryResolveRealFile(filePath + ext2, preserveSymlinks);
if (res) return res;
}
}
function tryResolveRealFileOrType(file, preserveSymlinks) {
const fileStat = tryStatSync(file);
if (fileStat == null ? void 0 : fileStat.isFile()) {
return { path: getRealPath(file, preserveSymlinks), type: "file" };
}
if (fileStat == null ? void 0 : fileStat.isDirectory()) {
return { type: "directory" };
}
return;
}
function getRealPath(resolved, preserveSymlinks) {
if (!preserveSymlinks) {
resolved = safeRealpathSync(resolved);
}
return normalizePath$3(resolved);
}
function isDirectory(path22) {
const stat2 = tryStatSync(path22);
return (stat2 == null ? void 0 : stat2.isDirectory()) ?? false;
}
var etag_1 = etag;
var crypto = import_crypto.default;
var Stats = import_fs.default.Stats;
var toString = Object.prototype.toString;
function entitytag(entity) {
if (entity.length === 0) {
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';
}
var hash2 = crypto.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length;
return '"' + len.toString(16) + "-" + hash2 + '"';
}
function etag(entity, options2) {
if (entity == null) {
throw new TypeError("argument entity is required");
}
var isStats = isstats(entity);
var weak = options2 && typeof options2.weak === "boolean" ? options2.weak : isStats;
if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) {
throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
}
var tag = isStats ? stattag(entity) : entitytag(entity);
return weak ? "W/" + tag : tag;
}
function isstats(obj) {
if (typeof Stats === "function" && obj instanceof Stats) {
return true;
}
return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
}
function stattag(stat2) {
var mtime = stat2.mtime.getTime().toString(16);
var size = stat2.size.toString(16);
return '"' + size + "-" + mtime + '"';
}
var getEtag = getDefaultExportFromCjs(etag_1);
function e(e2, n2, r2) {
throw new Error(r2 ? `No known conditions for "${n2}" specifier in "${e2}" package` : `Missing "${n2}" specifier in "${e2}" package`);
}
function n(n2, i, o2, f2) {
let s, u, l = r(n2, o2), c = function(e2) {
let n3 = /* @__PURE__ */ new Set(["default", ...e2.conditions || []]);
return e2.unsafe || n3.add(e2.require ? "require" : "import"), e2.unsafe || n3.add(e2.browser ? "browser" : "node"), n3;
}(f2 || {}), a = i[l];
if (void 0 === a) {
let e2, n3, r2, t2;
for (t2 in i) n3 && t2.length < n3.length || ("/" === t2[t2.length - 1] && l.startsWith(t2) ? (u = l.substring(t2.length), n3 = t2) : t2.length > 1 && (r2 = t2.indexOf("*", 1), ~r2 && (e2 = RegExp("^" + t2.substring(0, r2) + "(.*)" + t2.substring(1 + r2)).exec(l), e2 && e2[1] && (u = e2[1], n3 = t2))));
a = i[n3];
}
return a || e(n2, l), s = t(a, c), s || e(n2, l, 1), u && function(e2, n3) {
let r2, t2 = 0, i2 = e2.length, o3 = /[*]/g, f3 = /[/]$/;
for (; t2 < i2; t2++) e2[t2] = o3.test(r2 = e2[t2]) ? r2.replace(o3, n3) : f3.test(r2) ? r2 + n3 : r2;
}(s, u), s;
}
function r(e2, n2, r2) {
if (e2 === n2 || "." === n2) return ".";
let t2 = e2 + "/", i = t2.length, o2 = n2.slice(0, i) === t2, f2 = o2 ? n2.slice(i) : n2;
return "#" === f2[0] ? f2 : o2 || !r2 ? "./" === f2.slice(0, 2) ? f2 : "./" + f2 : f2;
}
function t(e2, n2, r2) {
if (e2) {
if ("string" == typeof e2) return r2 && r2.add(e2), [e2];
let i, o2;
if (Array.isArray(e2)) {
for (o2 = r2 || /* @__PURE__ */ new Set(), i = 0; i < e2.length; i++) t(e2[i], n2, o2);
if (!r2 && o2.size) return [...o2];
} else for (i in e2) if (n2.has(i)) return t(e2[i], n2, r2);
}
}
function o(e2, r2, t2) {
let i, o2 = e2.exports;
if (o2) {
if ("string" == typeof o2) o2 = { ".": o2 };
else for (i in o2) {
"." !== i[0] && (o2 = { ".": o2 });
break;
}
return n(e2.name, o2, r2 || ".", t2);
}
}
function f(e2, r2, t2) {
if (e2.imports) return n(e2.name, e2.imports, r2, t2);
}
var normalizedClientEntry$1 = normalizePath$3(CLIENT_ENTRY);
var normalizedEnvEntry$1 = normalizePath$3(ENV_ENTRY);
var ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
var browserExternalId = "__vite-browser-external";
var optionalPeerDepId = "__vite-optional-peer-dep";
var subpathImportsPrefix = "#";
var startsWithWordCharRE = /^\w/;
var debug$c = createDebugger("vite:resolve-details", {
onlyWhenFocused: true
});
function resolvePlugin(resolveOptions) {
var _a4;
const {
root,
isProduction,
asSrc,
ssrConfig,
preferRelative = false
} = resolveOptions;
const {
target: ssrTarget,
noExternal: ssrNoExternal,
external: ssrExternal
} = ssrConfig ?? {};
const rootInRoot = ((_a4 = tryStatSync(import_node_path3.default.join(root, root))) == null ? void 0 : _a4.isDirectory()) ?? false;
return {
name: "vite:resolve",
async resolveId(id, importer, resolveOpts) {
var _a5, _b3, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2;
if (id[0] === "\0" || id.startsWith("virtual:") || // When injected directly in html/client code
id.startsWith("/virtual:")) {
return;
}
const ssr = (resolveOpts == null ? void 0 : resolveOpts.ssr) === true;
const depsOptimizer = (_a5 = resolveOptions.getDepsOptimizer) == null ? void 0 : _a5.call(resolveOptions, ssr);
if (id.startsWith(browserExternalId)) {
return id;
}
const targetWeb = !ssr || ssrTarget === "webworker";
const isRequire2 = ((_c2 = (_b3 = resolveOpts == null ? void 0 : resolveOpts.custom) == null ? void 0 : _b3["node-resolve"]) == null ? void 0 : _c2.isRequire) ?? false;
const ssrConditions = ((_e2 = (_d2 = resolveOptions.ssrConfig) == null ? void 0 : _d2.resolve) == null ? void 0 : _e2.conditions) || resolveOptions.conditions;
const options2 = {
isRequire: isRequire2,
...resolveOptions,
scan: (resolveOpts == null ? void 0 : resolveOpts.scan) ?? resolveOptions.scan,
conditions: ssr ? ssrConditions : resolveOptions.conditions
};
const resolvedImports = resolveSubpathImports(
id,
importer,
options2,
targetWeb
);
if (resolvedImports) {
id = resolvedImports;
if ((_g2 = (_f2 = resolveOpts.custom) == null ? void 0 : _f2["vite:import-glob"]) == null ? void 0 : _g2.isSubImportsPattern) {
return normalizePath$3(import_node_path3.default.join(root, id));
}
}
if (importer) {
if (isTsRequest(importer) || ((_j2 = (_i2 = (_h2 = resolveOpts.custom) == null ? void 0 : _h2.depScan) == null ? void 0 : _i2.loader) == null ? void 0 : _j2.startsWith("ts"))) {
options2.isFromTsImporter = true;
} else {
const moduleLang = (_m2 = (_l2 = (_k2 = this.getModuleInfo(importer)) == null ? void 0 : _k2.meta) == null ? void 0 : _l2.vite) == null ? void 0 : _m2.lang;
options2.isFromTsImporter = moduleLang && isTsRequest(`.${moduleLang}`);
}
}
let res;
if (asSrc && (depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepUrl(id))) {
const optimizedPath = id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath$3(import_node_path3.default.resolve(root, id.slice(1)));
return optimizedPath;
}
if (asSrc && id.startsWith(FS_PREFIX)) {
res = fsPathFromId(id);
debug$c == null ? void 0 : debug$c(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
return ensureVersionQuery(res, id, options2, depsOptimizer);
}
if (asSrc && id[0] === "/" && (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
const fsPath = import_node_path3.default.resolve(root, id.slice(1));
if (res = tryFsResolve(fsPath, options2)) {
debug$c == null ? void 0 : debug$c(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
return ensureVersionQuery(res, id, options2, depsOptimizer);
}
}
if (id[0] === "." || (preferRelative || (importer == null ? void 0 : importer.endsWith(".html"))) && startsWithWordCharRE.test(id)) {
const basedir = importer ? import_node_path3.default.dirname(importer) : process.cwd();
const fsPath = import_node_path3.default.resolve(basedir, id);
const normalizedFsPath = normalizePath$3(fsPath);
if (depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepFile(normalizedFsPath)) {
if (!resolveOptions.isBuild && !DEP_VERSION_RE.test(normalizedFsPath)) {
const browserHash = (_n2 = optimizedDepInfoFromFile(
depsOptimizer.metadata,
normalizedFsPath
)) == null ? void 0 : _n2.browserHash;
if (browserHash) {
return injectQuery(normalizedFsPath, `v=${browserHash}`);
}
}
return normalizedFsPath;
}
if (targetWeb && options2.mainFields.includes("browser") && (res = tryResolveBrowserMapping(fsPath, importer, options2, true))) {
return res;
}
if (res = tryFsResolve(fsPath, options2)) {
res = ensureVersionQuery(res, id, options2, depsOptimizer);
debug$c == null ? void 0 : debug$c(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
if (!options2.idOnly && !options2.scan && options2.isBuild && !(importer == null ? void 0 : importer.endsWith(".html"))) {
const resPkg = findNearestPackageData(
import_node_path3.default.dirname(res),
options2.packageCache
);
if (resPkg) {
return {
id: res,
moduleSideEffects: resPkg.hasSideEffects(res)
};
}
}
return res;
}
}
if (isWindows$3 && id[0] === "/") {
const basedir = importer ? import_node_path3.default.dirname(importer) : process.cwd();
const fsPath = import_node_path3.default.resolve(basedir, id);
if (res = tryFsResolve(fsPath, options2)) {
debug$c == null ? void 0 : debug$c(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
return ensureVersionQuery(res, id, options2, depsOptimizer);
}
}
if (isNonDriveRelativeAbsolutePath(id) && (res = tryFsResolve(id, options2))) {
debug$c == null ? void 0 : debug$c(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
return ensureVersionQuery(res, id, options2, depsOptimizer);
}
if (isExternalUrl(id)) {
return options2.idOnly ? id : { id, external: true };
}
if (isDataUrl(id)) {
return null;
}
if (bareImportRE.test(id)) {
const external = (_o2 = options2.shouldExternalize) == null ? void 0 : _o2.call(options2, id, importer);
if (!external && asSrc && depsOptimizer && !options2.scan && (res = await tryOptimizedResolve(
depsOptimizer,
id,
importer,
options2.preserveSymlinks,
options2.packageCache
))) {
return res;
}
if (targetWeb && options2.mainFields.includes("browser") && (res = tryResolveBrowserMapping(
id,
importer,
options2,
false,
external
))) {
return res;
}
if (res = tryNodeResolve(
id,
importer,
options2,
targetWeb,
depsOptimizer,
ssr,
external
)) {
return res;
}
if (isBuiltin(id)) {
if (ssr) {
if (targetWeb && ssrNoExternal === true && // if both noExternal and external are true, noExternal will take the higher priority and bundle it.
// only if the id is explicitly listed in external, we will externalize it and skip this error.
(ssrExternal === true || !(ssrExternal == null ? void 0 : ssrExternal.includes(id)))) {
let message = `Cannot bundle Node.js built-in "${id}"`;
if (importer) {
message += ` imported from "${import_node_path3.default.relative(
process.cwd(),
importer
)}"`;
}
message += `. Consider disabling ssr.noExternal or remove the built-in dependency.`;
this.error(message);
}
return options2.idOnly ? id : { id, external: true, moduleSideEffects: false };
} else {
if (!asSrc) {
debug$c == null ? void 0 : debug$c(
`externalized node built-in "${id}" to empty module. (imported by: ${colors$1.white(colors$1.dim(importer))})`
);
} else if (isProduction) {
this.warn(
`Module "${id}" has been externalized for browser compatibility, imported by "${importer}". See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`
);
}
return isProduction ? browserExternalId : `${browserExternalId}:${id}`;
}
}
}
debug$c == null ? void 0 : debug$c(`[fallthrough] ${colors$1.dim(id)}`);
},
load(id) {
if (id.startsWith(browserExternalId)) {
if (isProduction) {
return `export default {}`;
} else {
id = id.slice(browserExternalId.length + 1);
return `export default new Proxy({}, {
get(_, key) {
throw new Error(\`Module "${id}" has been externalized for browser compatibility. Cannot access "${id}.\${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
}
})`;
}
}
if (id.startsWith(optionalPeerDepId)) {
if (isProduction) {
return `export default {}`;
} else {
const [, peerDep, parentDep] = id.split(":");
return `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`;
}
}
}
};
}
function resolveSubpathImports(id, importer, options2, targetWeb) {
if (!importer || !id.startsWith(subpathImportsPrefix)) return;
const basedir = import_node_path3.default.dirname(importer);
const pkgData = findNearestPackageData(basedir, options2.packageCache);
if (!pkgData) return;
let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
idWithoutPostfix = "#" + idWithoutPostfix;
let importsPath = resolveExportsOrImports(
pkgData.data,
idWithoutPostfix,
options2,
targetWeb,
"imports"
);
if ((importsPath == null ? void 0 : importsPath[0]) === ".") {
importsPath = import_node_path3.default.relative(basedir, import_node_path3.default.join(pkgData.dir, importsPath));
if (importsPath[0] !== ".") {
importsPath = `./${importsPath}`;
}
}
return importsPath + postfix;
}
function ensureVersionQuery(resolved, id, options2, depsOptimizer) {
if (!options2.isBuild && !options2.scan && depsOptimizer && !(resolved === normalizedClientEntry$1 || resolved === normalizedEnvEntry$1)) {
const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved);
if (isNodeModule && !DEP_VERSION_RE.test(resolved)) {
const versionHash = depsOptimizer.metadata.browserHash;
if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
resolved = injectQuery(resolved, `v=${versionHash}`);
}
}
}
return resolved;
}
function splitFileAndPostfix(path22) {
const file = cleanUrl(path22);
return { file, postfix: path22.slice(file.length) };
}
function tryFsResolve(fsPath, options2, tryIndex = true, targetWeb = true, skipPackageJson = false) {
const hashIndex = fsPath.indexOf("#");
if (hashIndex >= 0 && isInNodeModules$1(fsPath)) {
const queryIndex = fsPath.indexOf("?");
if (queryIndex < 0 || queryIndex > hashIndex) {
const file2 = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
const res2 = tryCleanFsResolve(
file2,
options2,
tryIndex,
targetWeb,
skipPackageJson
);
if (res2) return res2 + fsPath.slice(file2.length);
}
}
const { file, postfix } = splitFileAndPostfix(fsPath);
const res = tryCleanFsResolve(
file,
options2,
tryIndex,
targetWeb,
skipPackageJson
);
if (res) return res + postfix;
}
var knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
var isPossibleTsOutput = (url2) => knownTsOutputRE.test(url2);
function tryCleanFsResolve(file, options2, tryIndex = true, targetWeb = true, skipPackageJson = false) {
const { tryPrefix, extensions: extensions2, preserveSymlinks } = options2;
const fsUtils = options2.fsUtils ?? commonFsUtils;
const fileResult = fsUtils.tryResolveRealFileOrType(
file,
options2.preserveSymlinks
);
if (fileResult == null ? void 0 : fileResult.path) return fileResult.path;
let res;
const possibleJsToTs = options2.isFromTsImporter && isPossibleTsOutput(file);
if (possibleJsToTs || options2.extensions.length || tryPrefix) {
const dirPath = import_node_path3.default.dirname(file);
if (fsUtils.isDirectory(dirPath)) {
if (possibleJsToTs) {
const fileExt = import_node_path3.default.extname(file);
const fileName = file.slice(0, -fileExt.length);
if (res = fsUtils.tryResolveRealFile(
fileName + fileExt.replace("js", "ts"),
preserveSymlinks
))
return res;
if (fileExt === ".js" && (res = fsUtils.tryResolveRealFile(
fileName + ".tsx",
preserveSymlinks
)))
return res;
}
if (res = fsUtils.tryResolveRealFileWithExtensions(
file,
extensions2,
preserveSymlinks
))
return res;
if (tryPrefix) {
const prefixed = `${dirPath}/${options2.tryPrefix}${import_node_path3.default.basename(file)}`;
if (res = fsUtils.tryResolveRealFile(prefixed, preserveSymlinks))
return res;
if (res = fsUtils.tryResolveRealFileWithExtensions(
prefixed,
extensions2,
preserveSymlinks
))
return res;
}
}
}
if (tryIndex && (fileResult == null ? void 0 : fileResult.type) === "directory") {
const dirPath = file;
if (!skipPackageJson) {
let pkgPath = `${dirPath}/package.json`;
try {
if (fsUtils.existsSync(pkgPath)) {
if (!options2.preserveSymlinks) {
pkgPath = safeRealpathSync(pkgPath);
}
const pkg = loadPackageData(pkgPath);
return resolvePackageEntry(dirPath, pkg, targetWeb, options2);
}
} catch (e2) {
if (e2.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e2.code !== "ENOENT")
throw e2;
}
}
if (res = fsUtils.tryResolveRealFileWithExtensions(
`${dirPath}/index`,
extensions2,
preserveSymlinks
))
return res;
if (tryPrefix) {
if (res = fsUtils.tryResolveRealFileWithExtensions(
`${dirPath}/${options2.tryPrefix}index`,
extensions2,
preserveSymlinks
))
return res;
}
}
}
function tryNodeResolve(id, importer, options2, targetWeb, depsOptimizer, ssr = false, externalize, allowLinkedExternal = true) {
var _a4, _b3, _c2, _d2, _e2, _f2, _g2, _h2;
const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options2;
const deepMatch = id.match(deepImportRE);
const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
let basedir;
if (dedupe == null ? void 0 : dedupe.includes(pkgId)) {
basedir = root;
} else if (importer && import_node_path3.default.isAbsolute(importer) && // css processing appends `*` for importer
(importer[importer.length - 1] === "*" || import_node_fs2.default.existsSync(cleanUrl(importer)))) {
basedir = import_node_path3.default.dirname(importer);
} else {
basedir = root;
}
let selfPkg = null;
if (!isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
const selfPackageData = findNearestPackageData(basedir, packageCache);
selfPkg = (selfPackageData == null ? void 0 : selfPackageData.data.exports) && (selfPackageData == null ? void 0 : selfPackageData.data.name) === pkgId ? selfPackageData : null;
}
const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
if (!pkg) {
if (basedir !== root && // root has no peer dep
!isBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
const mainPkg = (_a4 = findNearestMainPackageData(basedir, packageCache)) == null ? void 0 : _a4.data;
if (mainPkg) {
const pkgName = getNpmPackageName(id);
if (pkgName != null && ((_b3 = mainPkg.peerDependencies) == null ? void 0 : _b3[pkgName]) && ((_d2 = (_c2 = mainPkg.peerDependenciesMeta) == null ? void 0 : _c2[pkgName]) == null ? void 0 : _d2.optional)) {
return {
id: `${optionalPeerDepId}:${id}:${mainPkg.name}`
};
}
}
}
return;
}
const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
const unresolvedId = deepMatch ? "." + id.slice(pkgId.length) : id;
let resolved;
try {
resolved = resolveId(unresolvedId, pkg, targetWeb, options2);
} catch (err2) {
if (!options2.tryEsmOnly) {
throw err2;
}
}
if (!resolved && options2.tryEsmOnly) {
resolved = resolveId(unresolvedId, pkg, targetWeb, {
...options2,
isRequire: false,
mainFields: DEFAULT_MAIN_FIELDS,
extensions: DEFAULT_EXTENSIONS
});
}
if (!resolved) {
return;
}
const processResult2 = (resolved2) => {
if (!externalize) {
return resolved2;
}
if (!allowLinkedExternal && !isInNodeModules$1(resolved2.id)) {
return resolved2;
}
const resolvedExt = import_node_path3.default.extname(resolved2.id);
if (resolvedExt && resolvedExt !== ".js" && resolvedExt !== ".mjs" && resolvedExt !== ".cjs") {
return resolved2;
}
let resolvedId = id;
if (deepMatch && !(pkg == null ? void 0 : pkg.data.exports) && import_node_path3.default.extname(id) !== resolvedExt) {
const index = resolved2.id.indexOf(id);
if (index > -1) {
resolvedId = resolved2.id.slice(index);
debug$c == null ? void 0 : debug$c(
`[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`
);
}
}
return { ...resolved2, id: resolvedId, external: true };
};
if (!options2.idOnly && (!options2.scan && isBuild && !depsOptimizer || externalize)) {
return processResult2({
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved)
});
}
if (!options2.ssrOptimizeCheck && (!isInNodeModules$1(resolved) || // linked
!depsOptimizer || // resolving before listening to the server
options2.scan)) {
return { id: resolved };
}
const isJsType = depsOptimizer ? isOptimizable(resolved, depsOptimizer.options) : OPTIMIZABLE_ENTRY_RE.test(resolved);
let exclude = depsOptimizer == null ? void 0 : depsOptimizer.options.exclude;
let include = depsOptimizer == null ? void 0 : depsOptimizer.options.include;
if (options2.ssrOptimizeCheck) {
exclude = (_f2 = (_e2 = options2.ssrConfig) == null ? void 0 : _e2.optimizeDeps) == null ? void 0 : _f2.exclude;
include = (_h2 = (_g2 = options2.ssrConfig) == null ? void 0 : _g2.optimizeDeps) == null ? void 0 : _h2.include;
}
const skipOptimization = !options2.ssrOptimizeCheck && (depsOptimizer == null ? void 0 : depsOptimizer.options.noDiscovery) || !isJsType || importer && isInNodeModules$1(importer) || (exclude == null ? void 0 : exclude.includes(pkgId)) || (exclude == null ? void 0 : exclude.includes(id)) || SPECIAL_QUERY_RE.test(resolved) || // During dev SSR, we don't have a way to reload the module graph if
// a non-optimized dep is found. So we need to skip optimization here.
// The only optimized deps are the ones explicitly listed in the config.
!options2.ssrOptimizeCheck && !isBuild && ssr || // Only optimize non-external CJS deps during SSR by default
ssr && isFilePathESM(resolved, options2.packageCache) && !((include == null ? void 0 : include.includes(pkgId)) || (include == null ? void 0 : include.includes(id)));
if (options2.ssrOptimizeCheck) {
return {
id: skipOptimization ? injectQuery(resolved, `__vite_skip_optimization`) : resolved
};
}
if (skipOptimization) {
if (!isBuild) {
const versionHash = depsOptimizer.metadata.browserHash;
if (versionHash && isJsType) {
resolved = injectQuery(resolved, `v=${versionHash}`);
}
}
} else {
const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
}
if (!options2.idOnly && !options2.scan && isBuild) {
return {
id: resolved,
moduleSideEffects: pkg.hasSideEffects(resolved)
};
} else {
return { id: resolved };
}
}
async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
var _a4;
await depsOptimizer.scanProcessing;
const metadata = depsOptimizer.metadata;
const depInfo = optimizedDepInfoFromId(metadata, id);
if (depInfo) {
return depsOptimizer.getOptimizedDepId(depInfo);
}
if (!importer) return;
let idPkgDir;
const nestedIdMatch = `> ${id}`;
for (const optimizedData of metadata.depInfoList) {
if (!optimizedData.src) continue;
if (!optimizedData.id.endsWith(nestedIdMatch)) continue;
if (idPkgDir == null) {
const pkgName = getNpmPackageName(id);
if (!pkgName) break;
idPkgDir = (_a4 = resolvePackageData(
pkgName,
importer,
preserveSymlinks,
packageCache
)) == null ? void 0 : _a4.dir;
if (idPkgDir == null) break;
idPkgDir = normalizePath$3(idPkgDir);
}
if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
return depsOptimizer.getOptimizedDepId(optimizedData);
}
}
}
function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, targetWeb, options2) {
const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
const cached = getResolvedCache(".", targetWeb);
if (cached) {
return cached + postfix;
}
try {
let entryPoint;
if (data.exports) {
entryPoint = resolveExportsOrImports(
data,
".",
options2,
targetWeb,
"exports"
);
}
if (!entryPoint) {
for (const field of options2.mainFields) {
if (field === "browser") {
if (targetWeb) {
entryPoint = tryResolveBrowserEntry(dir, data, options2);
if (entryPoint) {
break;
}
}
} else if (typeof data[field] === "string") {
entryPoint = data[field];
break;
}
}
}
entryPoint || (entryPoint = data.main);
const entryPoints = entryPoint ? [entryPoint] : ["index.js", "index.json", "index.node"];
for (let entry2 of entryPoints) {
let skipPackageJson = false;
if (options2.mainFields[0] === "sass" && !options2.extensions.includes(import_node_path3.default.extname(entry2))) {
entry2 = "";
skipPackageJson = true;
} else {
const { browser: browserField } = data;
if (targetWeb && options2.mainFields.includes("browser") && isObject$1(browserField)) {
entry2 = mapWithBrowserField(entry2, browserField) || entry2;
}
}
const entryPointPath = import_node_path3.default.join(dir, entry2);
const resolvedEntryPoint = tryFsResolve(
entryPointPath,
options2,
true,
true,
skipPackageJson
);
if (resolvedEntryPoint) {
debug$c == null ? void 0 : debug$c(
`[package entry] ${colors$1.cyan(idWithoutPostfix)} -> ${colors$1.dim(
resolvedEntryPoint
)}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`
);
setResolvedCache(".", resolvedEntryPoint, targetWeb);
return resolvedEntryPoint + postfix;
}
}
} catch (e2) {
packageEntryFailure(id, e2.message);
}
packageEntryFailure(id);
}
function packageEntryFailure(id, details) {
const err2 = new Error(
`Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : ".")
);
err2.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
throw err2;
}
function resolveExportsOrImports(pkg, key, options2, targetWeb, type) {
const additionalConditions = new Set(
options2.overrideConditions || [
"production",
"development",
"module",
...options2.conditions
]
);
const conditions = [...additionalConditions].filter((condition) => {
switch (condition) {
case "production":
return options2.isProduction;
case "development":
return !options2.isProduction;
}
return true;
});
const fn = type === "imports" ? f : o;
const result = fn(pkg, key, {
browser: targetWeb && !additionalConditions.has("node"),
require: options2.isRequire && !additionalConditions.has("import"),
conditions
});
return result ? result[0] : void 0;
}
function resolveDeepImport(id, {
webResolvedImports,
setResolvedCache,
getResolvedCache,
dir,
data
}, targetWeb, options2) {
const cache = getResolvedCache(id, targetWeb);
if (cache) {
return cache;
}
let relativeId = id;
const { exports: exportsField, browser: browserField } = data;
if (exportsField) {
if (isObject$1(exportsField) && !Array.isArray(exportsField)) {
const { file, postfix } = splitFileAndPostfix(relativeId);
const exportsId = resolveExportsOrImports(
data,
file,
options2,
targetWeb,
"exports"
);
if (exportsId !== void 0) {
relativeId = exportsId + postfix;
} else {
relativeId = void 0;
}
} else {
relativeId = void 0;
}
if (!relativeId) {
throw new Error(
`Package subpath '${relativeId}' is not defined by "exports" in ${import_node_path3.default.join(dir, "package.json")}.`
);
}
} else if (targetWeb && options2.mainFields.includes("browser") && isObject$1(browserField)) {
const { file, postfix } = splitFileAndPostfix(relativeId);
const mapped = mapWithBrowserField(file, browserField);
if (mapped) {
relativeId = mapped + postfix;
} else if (mapped === false) {
return webResolvedImports[id] = browserExternalId;
}
}
if (relativeId) {
const resolved = tryFsResolve(
import_node_path3.default.join(dir, relativeId),
options2,
!exportsField,
// try index only if no exports field
targetWeb
);
if (resolved) {
debug$c == null ? void 0 : debug$c(
`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`
);
setResolvedCache(id, resolved, targetWeb);
return resolved;
}
}
}
function tryResolveBrowserMapping(id, importer, options2, isFilePath, externalize) {
var _a4;
let res;
const pkg = importer && findNearestPackageData(import_node_path3.default.dirname(importer), options2.packageCache);
if (pkg && isObject$1(pkg.data.browser)) {
const mapId = isFilePath ? "./" + slash$1(import_node_path3.default.relative(pkg.dir, id)) : id;
const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser);
if (browserMappedPath) {
if (res = bareImportRE.test(browserMappedPath) ? (_a4 = tryNodeResolve(browserMappedPath, importer, options2, true)) == null ? void 0 : _a4.id : tryFsResolve(import_node_path3.default.join(pkg.dir, browserMappedPath), options2)) {
debug$c == null ? void 0 : debug$c(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
let result = { id: res };
if (options2.idOnly) {
return result;
}
if (!options2.scan && options2.isBuild) {
const resPkg = findNearestPackageData(
import_node_path3.default.dirname(res),
options2.packageCache
);
if (resPkg) {
result = {
id: res,
moduleSideEffects: resPkg.hasSideEffects(res)
};
}
}
return externalize ? { ...result, external: true } : result;
}
} else if (browserMappedPath === false) {
return browserExternalId;
}
}
}
function tryResolveBrowserEntry(dir, data, options2) {
const browserEntry = typeof data.browser === "string" ? data.browser : isObject$1(data.browser) && data.browser["."];
if (browserEntry) {
if (!options2.isRequire && options2.mainFields.includes("module") && typeof data.module === "string" && data.module !== browserEntry) {
const resolvedBrowserEntry = tryFsResolve(
import_node_path3.default.join(dir, browserEntry),
options2
);
if (resolvedBrowserEntry) {
const content = import_node_fs2.default.readFileSync(resolvedBrowserEntry, "utf-8");
if (hasESMSyntax(content)) {
return browserEntry;
} else {
return data.module;
}
}
} else {
return browserEntry;
}
}
}
function mapWithBrowserField(relativePathInPkgDir, map2) {
const normalizedPath = import_node_path3.default.posix.normalize(relativePathInPkgDir);
for (const key in map2) {
const normalizedKey = import_node_path3.default.posix.normalize(key);
if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) {
return map2[key];
}
}
}
function equalWithoutSuffix(path22, key, suffix) {
return key.endsWith(suffix) && key.slice(0, -suffix.length) === path22;
}
var externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
var convertedExternalPrefix = "vite-dep-pre-bundle-external:";
var cjsExternalFacadeNamespace = "vite:cjs-external-facade";
var nonFacadePrefix = "vite-cjs-external-facade:";
var externalTypes = [
"css",
// supported pre-processor types
"less",
"sass",
"scss",
"styl",
"stylus",
"pcss",
"postcss",
// wasm
"wasm",
// known SFC types
"vue",
"svelte",
"marko",
"astro",
"imba",
// JSX/TSX may be configured to be compiled differently from how esbuild
// handles it by default, so exclude them as well
"jsx",
"tsx",
...KNOWN_ASSET_TYPES
];
function esbuildDepPlugin(qualified, external, config2, ssr) {
const { extensions: extensions2 } = getDepOptimizationConfig(config2, ssr);
const allExternalTypes = extensions2 ? externalTypes.filter((type) => !(extensions2 == null ? void 0 : extensions2.includes("." + type))) : externalTypes;
const esmPackageCache = /* @__PURE__ */ new Map();
const cjsPackageCache = /* @__PURE__ */ new Map();
const _resolve = config2.createResolver({
asSrc: false,
scan: true,
packageCache: esmPackageCache
});
const _resolveRequire = config2.createResolver({
asSrc: false,
isRequire: true,
scan: true,
packageCache: cjsPackageCache
});
const resolve3 = (id, importer, kind, resolveDir) => {
let _importer;
{
_importer = importer in qualified ? qualified[importer] : importer;
}
const resolver = kind.startsWith("require") ? _resolveRequire : _resolve;
return resolver(id, _importer, void 0, ssr);
};
const resolveResult = (id, resolved) => {
if (resolved.startsWith(browserExternalId)) {
return {
path: id,
namespace: "browser-external"
};
}
if (resolved.startsWith(optionalPeerDepId)) {
return {
path: resolved,
namespace: "optional-peer-dep"
};
}
if (ssr && isBuiltin(resolved)) {
return;
}
if (isExternalUrl(resolved)) {
return {
path: resolved,
external: true
};
}
return {
path: import_node_path3.default.resolve(resolved)
};
};
return {
name: "vite:dep-pre-bundle",
setup(build2) {
build2.onEnd(() => {
esmPackageCache.clear();
cjsPackageCache.clear();
});
build2.onResolve(
{
filter: new RegExp(
`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`
)
},
async ({ path: id, importer, kind }) => {
if (id.startsWith(convertedExternalPrefix)) {
return {
path: id.slice(convertedExternalPrefix.length),
external: true
};
}
const resolved = await resolve3(id, importer, kind);
if (resolved) {
if (kind === "require-call") {
if (resolved.endsWith(".js")) {
return {
path: resolved,
external: false
};
}
return {
path: resolved,
namespace: externalWithConversionNamespace
};
}
return {
path: resolved,
external: true
};
}
}
);
build2.onLoad(
{ filter: /./, namespace: externalWithConversionNamespace },
(args) => {
const modulePath = `"${convertedExternalPrefix}${args.path}"`;
return {
contents: isCSSRequest(args.path) && !isModuleCSSRequest(args.path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};`,
loader: "js"
};
}
);
function resolveEntry(id) {
const flatId = flattenId(id);
if (flatId in qualified) {
return {
path: qualified[flatId]
};
}
}
build2.onResolve(
{ filter: /^[\w@][^:]/ },
async ({ path: id, importer, kind }) => {
if (moduleListContains(external, id)) {
return {
path: id,
external: true
};
}
let entry2;
if (!importer) {
if (entry2 = resolveEntry(id)) return entry2;
const aliased = await _resolve(id, void 0, true);
if (aliased && (entry2 = resolveEntry(aliased))) {
return entry2;
}
}
const resolved = await resolve3(id, importer, kind);
if (resolved) {
return resolveResult(id, resolved);
}
}
);
build2.onLoad(
{ filter: /.*/, namespace: "browser-external" },
({ path: path22 }) => {
if (config2.isProduction) {
return {
contents: "module.exports = {}"
};
} else {
return {
// Return in CJS to intercept named imports. Use `Object.create` to
// create the Proxy in the prototype to workaround esbuild issue. Why?
//
// In short, esbuild cjs->esm flow:
// 1. Create empty object using `Object.create(Object.getPrototypeOf(module.exports))`.
// 2. Assign props of `module.exports` to the object.
// 3. Return object for ESM use.
//
// If we do `module.exports = new Proxy({}, {})`, step 1 returns empty object,
// step 2 does nothing as there's no props for `module.exports`. The final object
// is just an empty object.
//
// Creating the Proxy in the prototype satisfies step 1 immediately, which means
// the returned object is a Proxy that we can intercept.
//
// Note: Skip keys that are accessed by esbuild and browser devtools.
contents: `module.exports = Object.create(new Proxy({}, {
get(_, key) {
if (
key !== '__esModule' &&
key !== '__proto__' &&
key !== 'constructor' &&
key !== 'splice'
) {
console.warn(\`Module "${path22}" has been externalized for browser compatibility. Cannot access "${path22}.\${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
}
}
}))`
};
}
}
);
build2.onLoad(
{ filter: /.*/, namespace: "optional-peer-dep" },
({ path: path22 }) => {
if (config2.isProduction) {
return {
contents: "module.exports = {}"
};
} else {
const [, peerDep, parentDep] = path22.split(":");
return {
contents: `throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)`
};
}
}
);
}
};
}
var matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
function esbuildCjsExternalPlugin(externals, platform2) {
return {
name: "cjs-external",
setup(build2) {
const filter2 = new RegExp(externals.map(matchesEntireLine).join("|"));
build2.onResolve({ filter: new RegExp(`^${nonFacadePrefix}`) }, (args) => {
return {
path: args.path.slice(nonFacadePrefix.length),
external: true
};
});
build2.onResolve({ filter: filter2 }, (args) => {
if (args.kind === "require-call" && platform2 !== "node") {
return {
path: args.path,
namespace: cjsExternalFacadeNamespace
};
}
return {
path: args.path,
external: true
};
});
build2.onLoad(
{ filter: /.*/, namespace: cjsExternalFacadeNamespace },
(args) => ({
contents: `import * as m from ${JSON.stringify(
nonFacadePrefix + args.path
)};module.exports = m;`
})
);
}
};
}
var debug$b = createDebugger("vite:ssr-external");
var isSsrExternalCache = /* @__PURE__ */ new WeakMap();
function shouldExternalizeForSSR(id, importer, config2) {
let isSsrExternal = isSsrExternalCache.get(config2);
if (!isSsrExternal) {
isSsrExternal = createIsSsrExternal(config2);
isSsrExternalCache.set(config2, isSsrExternal);
}
return isSsrExternal(id, importer);
}
function createIsConfiguredAsSsrExternal(config2) {
var _a4;
const { ssr, root } = config2;
const noExternal = ssr == null ? void 0 : ssr.noExternal;
const noExternalFilter = noExternal !== "undefined" && typeof noExternal !== "boolean" && createFilter2(void 0, noExternal, { resolve: false });
const targetConditions = ((_a4 = config2.ssr.resolve) == null ? void 0 : _a4.externalConditions) || [];
const resolveOptions = {
...config2.resolve,
root,
isProduction: false,
isBuild: true,
conditions: targetConditions
};
const isExternalizable = (id, importer, configuredAsExternal) => {
var _a5;
if (!bareImportRE.test(id) || id.includes("\0")) {
return false;
}
try {
return !!((_a5 = tryNodeResolve(
id,
// Skip passing importer in build to avoid externalizing non-hoisted dependencies
// unresolvable from root (which would be unresolvable from output bundles also)
config2.command === "build" ? void 0 : importer,
resolveOptions,
(ssr == null ? void 0 : ssr.target) === "webworker",
void 0,
true,
// try to externalize, will return undefined or an object without
// a external flag if it isn't externalizable
true,
// Allow linked packages to be externalized if they are explicitly
// configured as external
!!configuredAsExternal
)) == null ? void 0 : _a5.external);
} catch (e2) {
debug$b == null ? void 0 : debug$b(
`Failed to node resolve "${id}". Skipping externalizing it by default.`
);
return false;
}
};
return (id, importer) => {
var _a5, _b3;
if (
// If this id is defined as external, force it as external
// Note that individual package entries are allowed in ssr.external
ssr.external !== true && ((_a5 = ssr.external) == null ? void 0 : _a5.includes(id))
) {
return true;
}
const pkgName = getNpmPackageName(id);
if (!pkgName) {
return isExternalizable(id, importer);
}
if (
// A package name in ssr.external externalizes every
// externalizable package entry
ssr.external !== true && ((_b3 = ssr.external) == null ? void 0 : _b3.includes(pkgName))
) {
return isExternalizable(id, importer, true);
}
if (typeof noExternal === "boolean") {
return !noExternal;
}
if (noExternalFilter && !noExternalFilter(pkgName)) {
return false;
}
return isExternalizable(id, importer, ssr.external === true);
};
}
function createIsSsrExternal(config2) {
const processedIds = /* @__PURE__ */ new Map();
const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config2);
return (id, importer) => {
if (processedIds.has(id)) {
return processedIds.get(id);
}
let external = false;
if (id[0] !== "." && !import_node_path3.default.isAbsolute(id)) {
external = isBuiltin(id) || isConfiguredAsExternal(id, importer);
}
processedIds.set(id, external);
return external;
};
}
var jsonExtRE = /\.json(?:$|\?)(?!commonjs-(?:proxy|external))/;
var jsonLangs = `\\.(?:json|json5)(?:$|\\?)`;
var jsonLangRE = new RegExp(jsonLangs);
var isJSONRequest = (request) => jsonLangRE.test(request);
function jsonPlugin(options2 = {}, isBuild) {
return {
name: "vite:json",
transform(json, id) {
if (!jsonExtRE.test(id)) return null;
if (SPECIAL_QUERY_RE.test(id)) return null;
json = stripBomTag(json);
try {
if (options2.stringify) {
if (isBuild) {
return {
// during build, parse then double-stringify to remove all
// unnecessary whitespaces to reduce bundle size.
code: `export default JSON.parse(${JSON.stringify(
JSON.stringify(JSON.parse(json))
)})`,
map: { mappings: "" }
};
} else {
return `export default JSON.parse(${JSON.stringify(json)})`;
}
}
const parsed = JSON.parse(json);
return {
code: dataToEsm(parsed, {
preferConst: true,
namedExports: options2.namedExports
}),
map: { mappings: "" }
};
} catch (e2) {
const position = extractJsonErrorPosition(e2.message, json.length);
const msg = position ? `, invalid JSON syntax found at position ${position}` : `.`;
this.error(`Failed to parse JSON file` + msg, position);
}
}
};
}
function extractJsonErrorPosition(errorMessage, inputLength) {
if (errorMessage.startsWith("Unexpected end of JSON input")) {
return inputLength - 1;
}
const errorMessageList = /at position (\d+)/.exec(errorMessage);
return errorMessageList ? Math.max(parseInt(errorMessageList[1], 10) - 1, 0) : void 0;
}
var ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR";
var ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP";
var ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR";
var debug$a = createDebugger("vite:optimize-deps");
function optimizedDepsPlugin(config2) {
return {
name: "vite:optimized-deps",
resolveId(id, source, { ssr }) {
var _a4;
if ((_a4 = getDepsOptimizer(config2, ssr)) == null ? void 0 : _a4.isOptimizedDepFile(id)) {
return id;
}
},
// this.load({ id }) isn't implemented in PluginContainer
// The logic to register an id to wait until it is processed
// is in importAnalysis, see call to delayDepsOptimizerUntil
async load(id, options2) {
const ssr = (options2 == null ? void 0 : options2.ssr) === true;
const depsOptimizer = getDepsOptimizer(config2, ssr);
if (depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepFile(id)) {
const metadata = depsOptimizer.metadata;
const file = cleanUrl(id);
const versionMatch = id.match(DEP_VERSION_RE);
const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
const info = optimizedDepInfoFromFile(metadata, file);
if (info) {
if (browserHash && info.browserHash !== browserHash) {
throwOutdatedRequest(id);
}
try {
await info.processing;
} catch {
throwProcessingError(id);
}
const newMetadata = depsOptimizer.metadata;
if (metadata !== newMetadata) {
const currentInfo = optimizedDepInfoFromFile(newMetadata, file);
if (info.browserHash !== (currentInfo == null ? void 0 : currentInfo.browserHash)) {
throwOutdatedRequest(id);
}
}
}
debug$a == null ? void 0 : debug$a(`load ${colors$1.cyan(file)}`);
try {
return await import_promises.default.readFile(file, "utf-8");
} catch (e2) {
const newMetadata = depsOptimizer.metadata;
if (optimizedDepInfoFromFile(newMetadata, file)) {
throwOutdatedRequest(id);
}
throwFileNotFoundInOptimizedDep(id);
}
}
}
};
}
function throwProcessingError(id) {
const err2 = new Error(
`Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`
);
err2.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
throw err2;
}
function throwOutdatedRequest(id) {
const err2 = new Error(
`There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.`
);
err2.code = ERR_OUTDATED_OPTIMIZED_DEP;
throw err2;
}
function throwFileNotFoundInOptimizedDep(id) {
const err2 = new Error(
`The file does not exist at "${id}" which is in the optimize deps directory. The dependency might be incompatible with the dep optimizer. Try adding it to \`optimizeDeps.exclude\`.`
);
err2.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
throw err2;
}
var nonJsRe = /\.json(?:$|\?)/;
var isNonJsRequest = (request) => nonJsRe.test(request);
function definePlugin(config2) {
const isBuild = config2.command === "build";
const isBuildLib = isBuild && config2.build.lib;
const processEnv = {};
if (!isBuildLib) {
const nodeEnv = "development";
Object.assign(processEnv, {
"process.env": `{}`,
"global.process.env": `{}`,
"globalThis.process.env": `{}`,
"process.env.NODE_ENV": JSON.stringify(nodeEnv),
"global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
"globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
});
}
const importMetaKeys = {};
const importMetaEnvKeys = {};
const importMetaFallbackKeys = {};
if (isBuild) {
importMetaKeys["import.meta.hot"] = `undefined`;
for (const key in config2.env) {
const val = JSON.stringify(config2.env[key]);
importMetaKeys[`import.meta.env.${key}`] = val;
importMetaEnvKeys[key] = val;
}
importMetaKeys["import.meta.env.SSR"] = `undefined`;
importMetaFallbackKeys["import.meta.env"] = `undefined`;
}
const userDefine = {};
const userDefineEnv = {};
for (const key in config2.define) {
userDefine[key] = handleDefineValue(config2.define[key]);
if (isBuild && key.startsWith("import.meta.env.")) {
userDefineEnv[key.slice(16)] = config2.define[key];
}
}
function generatePattern(ssr) {
var _a4;
const replaceProcessEnv = !ssr || ((_a4 = config2.ssr) == null ? void 0 : _a4.target) === "webworker";
const define = {
...replaceProcessEnv ? processEnv : {},
...importMetaKeys,
...userDefine,
...importMetaFallbackKeys
};
if ("import.meta.env.SSR" in define) {
define["import.meta.env.SSR"] = ssr + "";
}
if ("import.meta.env" in define) {
define["import.meta.env"] = serializeDefine({
...importMetaEnvKeys,
SSR: ssr + "",
...userDefineEnv
});
}
const patternKeys = Object.keys(userDefine);
if (replaceProcessEnv && Object.keys(processEnv).length) {
patternKeys.push("process.env");
}
if (Object.keys(importMetaKeys).length) {
patternKeys.push("import.meta.env", "import.meta.hot");
}
const pattern2 = patternKeys.length ? new RegExp(patternKeys.map(escapeRegex).join("|")) : null;
return [define, pattern2];
}
const defaultPattern = generatePattern(false);
const ssrPattern = generatePattern(true);
return {
name: "vite:define",
async transform(code, id, options2) {
const ssr = (options2 == null ? void 0 : options2.ssr) === true;
if (!ssr && !isBuild) {
return;
}
if (
// exclude html, css and static assets for performance
isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config2.assetsInclude(id)
) {
return;
}
const [define, pattern2] = ssr ? ssrPattern : defaultPattern;
if (!pattern2) return;
pattern2.lastIndex = 0;
if (!pattern2.test(code)) return;
return await replaceDefine(code, id, define, config2);
}
};
}
async function replaceDefine(code, id, define, config2) {
const replacementMarkers = {};
const env2 = define["import.meta.env"];
if (env2 && !canJsonParse(env2)) {
const marker = `_${getHash(env2, env2.length - 2)}_`;
replacementMarkers[marker] = env2;
define = { ...define, "import.meta.env": marker };
}
const esbuildOptions = config2.esbuild || {};
const result = await (0, import_esbuild.transform)(code, {
loader: "js",
charset: esbuildOptions.charset ?? "utf8",
platform: "neutral",
define,
sourcefile: id,
sourcemap: config2.command === "build" ? !!config2.build.sourcemap : true
});
if (result.map.includes("<define:")) {
const originalMap = new TraceMap(result.map);
if (originalMap.sources.length >= 2) {
const sourceIndex = originalMap.sources.indexOf(id);
const decoded = decodedMap(originalMap);
decoded.sources = [id];
decoded.mappings = decoded.mappings.map(
(segments) => segments.filter((segment) => {
const index = segment[1];
segment[1] = 0;
return index === sourceIndex;
})
);
result.map = JSON.stringify(encodedMap(new TraceMap(decoded)));
}
}
for (const marker in replacementMarkers) {
result.code = result.code.replaceAll(marker, replacementMarkers[marker]);
}
return {
code: result.code,
map: result.map || null
};
}
function serializeDefine(define) {
let res = `{`;
const keys = Object.keys(define).sort();
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const val = define[key];
res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
if (i !== keys.length - 1) {
res += `, `;
}
}
return res + `}`;
}
function handleDefineValue(value2) {
if (typeof value2 === "undefined") return "undefined";
if (typeof value2 === "string") return value2;
return JSON.stringify(value2);
}
function canJsonParse(value2) {
try {
JSON.parse(value2);
return true;
} catch {
return false;
}
}
var normalizedClientEntry = normalizePath$3(CLIENT_ENTRY);
var normalizedEnvEntry = normalizePath$3(ENV_ENTRY);
function clientInjectionsPlugin(config2) {
let injectConfigValues;
return {
name: "vite:client-inject",
async buildStart() {
const resolvedServerHostname = (await resolveHostname(config2.server.host)).name;
const resolvedServerPort = config2.server.port;
const devBase = config2.base;
const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
let hmrConfig = config2.server.hmr;
hmrConfig = isObject$1(hmrConfig) ? hmrConfig : void 0;
const host = (hmrConfig == null ? void 0 : hmrConfig.host) || null;
const protocol = (hmrConfig == null ? void 0 : hmrConfig.protocol) || null;
const timeout2 = (hmrConfig == null ? void 0 : hmrConfig.timeout) || 3e4;
const overlay = (hmrConfig == null ? void 0 : hmrConfig.overlay) !== false;
const isHmrServerSpecified = !!(hmrConfig == null ? void 0 : hmrConfig.server);
const hmrConfigName = import_node_path3.default.basename(config2.configFile || "vite.config.js");
let port = (hmrConfig == null ? void 0 : hmrConfig.clientPort) || (hmrConfig == null ? void 0 : hmrConfig.port) || null;
if (config2.server.middlewareMode && !isHmrServerSpecified) {
port || (port = 24678);
}
let directTarget = (hmrConfig == null ? void 0 : hmrConfig.host) || resolvedServerHostname;
directTarget += `:${(hmrConfig == null ? void 0 : hmrConfig.port) || resolvedServerPort}`;
directTarget += devBase;
let hmrBase = devBase;
if (hmrConfig == null ? void 0 : hmrConfig.path) {
hmrBase = import_node_path3.default.posix.join(hmrBase, hmrConfig.path);
}
const userDefine = {};
for (const key in config2.define) {
if (!key.startsWith("import.meta.env.")) {
userDefine[key] = config2.define[key];
}
}
const serializedDefines = serializeDefine(userDefine);
const modeReplacement = escapeReplacement(config2.mode);
const baseReplacement = escapeReplacement(devBase);
const definesReplacement = () => serializedDefines;
const serverHostReplacement = escapeReplacement(serverHost);
const hmrProtocolReplacement = escapeReplacement(protocol);
const hmrHostnameReplacement = escapeReplacement(host);
const hmrPortReplacement = escapeReplacement(port);
const hmrDirectTargetReplacement = escapeReplacement(directTarget);
const hmrBaseReplacement = escapeReplacement(hmrBase);
const hmrTimeoutReplacement = escapeReplacement(timeout2);
const hmrEnableOverlayReplacement = escapeReplacement(overlay);
const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
injectConfigValues = (code) => {
return code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).replace(`__DEFINES__`, definesReplacement).replace(`__SERVER_HOST__`, serverHostReplacement).replace(`__HMR_PROTOCOL__`, hmrProtocolReplacement).replace(`__HMR_HOSTNAME__`, hmrHostnameReplacement).replace(`__HMR_PORT__`, hmrPortReplacement).replace(`__HMR_DIRECT_TARGET__`, hmrDirectTargetReplacement).replace(`__HMR_BASE__`, hmrBaseReplacement).replace(`__HMR_TIMEOUT__`, hmrTimeoutReplacement).replace(`__HMR_ENABLE_OVERLAY__`, hmrEnableOverlayReplacement).replace(`__HMR_CONFIG_NAME__`, hmrConfigNameReplacement);
};
},
async transform(code, id, options2) {
var _a4;
if (id === normalizedClientEntry || id === normalizedEnvEntry) {
return injectConfigValues(code);
} else if (!(options2 == null ? void 0 : options2.ssr) && code.includes("process.env.NODE_ENV")) {
const nodeEnv = ((_a4 = config2.define) == null ? void 0 : _a4["process.env.NODE_ENV"]) || JSON.stringify("development");
return await replaceDefine(
code,
id,
{
"process.env.NODE_ENV": nodeEnv,
"global.process.env.NODE_ENV": nodeEnv,
"globalThis.process.env.NODE_ENV": nodeEnv
},
config2
);
}
}
};
}
function escapeReplacement(value2) {
const jsonValue = JSON.stringify(value2);
return () => jsonValue;
}
var wasmHelperId = "\0vite/wasm-helper.js";
var wasmHelper = async (opts = {}, url2) => {
let result;
if (url2.startsWith("data:")) {
const urlContent = url2.replace(/^data:.*?base64,/, "");
let bytes;
if (typeof Buffer === "function" && typeof Buffer.from === "function") {
bytes = Buffer.from(urlContent, "base64");
} else if (typeof atob === "function") {
const binaryString = atob(urlContent);
bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
} else {
throw new Error(
"Failed to decode base64-encoded data URL, Buffer and atob are not supported"
);
}
result = await WebAssembly.instantiate(bytes, opts);
} else {
const response = await fetch(url2);
const contentType = response.headers.get("Content-Type") || "";
if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) {
result = await WebAssembly.instantiateStreaming(response, opts);
} else {
const buffer = await response.arrayBuffer();
result = await WebAssembly.instantiate(buffer, opts);
}
}
return result.instance;
};
var wasmHelperCode = wasmHelper.toString();
var wasmHelperPlugin = (config2) => {
return {
name: "vite:wasm-helper",
resolveId(id) {
if (id === wasmHelperId) {
return id;
}
},
async load(id) {
if (id === wasmHelperId) {
return `export default ${wasmHelperCode}`;
}
if (!id.endsWith(".wasm?init")) {
return;
}
const url2 = await fileToUrl$1(id, config2, this);
return `
import initWasm from "${wasmHelperId}"
export default opts => initWasm(opts, ${JSON.stringify(url2)})
`;
}
};
};
var wasmFallbackPlugin = () => {
return {
name: "vite:wasm-fallback",
async load(id) {
if (!id.endsWith(".wasm")) {
return;
}
throw new Error(
'"ESM integration proposal for Wasm" is not supported currently. Use vite-plugin-wasm or other community plugins to handle this. Alternatively, you can use `.wasm?init` or `.wasm?url`. See https://vitejs.dev/guide/features.html#webassembly for more details.'
);
}
};
};
var workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
var workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
var inlineRE = /[?&]inline\b/;
var WORKER_FILE_ID = "worker_file";
var workerCache = /* @__PURE__ */ new WeakMap();
function saveEmitWorkerAsset(config2, asset) {
const workerMap = workerCache.get(config2.mainConfig || config2);
workerMap.assets.set(asset.fileName, asset);
}
async function bundleWorkerEntry(config2, id) {
const input = cleanUrl(id);
const newBundleChain = [...config2.bundleChain, input];
if (config2.bundleChain.includes(input)) {
throw new Error(
`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.map((id2) => prettifyUrl(id2, config2.root)).join(" -> ")}`
);
}
const { rollup } = await import("./rollup-CIAQV775.js");
const { plugins: plugins2, rollupOptions, format: format2 } = config2.worker;
const bundle = await rollup({
...rollupOptions,
input,
plugins: await plugins2(newBundleChain),
onwarn(warning, warn2) {
onRollupWarning(warning, warn2, config2);
},
preserveEntrySignatures: false
});
let chunk;
try {
const workerOutputConfig = config2.worker.rollupOptions.output;
const workerConfig = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
const {
output: [outputChunk, ...outputChunks]
} = await bundle.generate({
entryFileNames: import_node_path3.default.posix.join(
config2.build.assetsDir,
"[name]-[hash].js"
),
chunkFileNames: import_node_path3.default.posix.join(
config2.build.assetsDir,
"[name]-[hash].js"
),
assetFileNames: import_node_path3.default.posix.join(
config2.build.assetsDir,
"[name]-[hash].[ext]"
),
...workerConfig,
format: format2,
sourcemap: config2.build.sourcemap
});
chunk = outputChunk;
outputChunks.forEach((outputChunk2) => {
if (outputChunk2.type === "asset") {
saveEmitWorkerAsset(config2, outputChunk2);
} else if (outputChunk2.type === "chunk") {
saveEmitWorkerAsset(config2, {
fileName: outputChunk2.fileName,
source: outputChunk2.code
});
}
});
} finally {
await bundle.close();
}
return emitSourcemapForWorkerEntry(config2, chunk);
}
function emitSourcemapForWorkerEntry(config2, chunk) {
const { map: sourcemap } = chunk;
if (sourcemap) {
if (config2.build.sourcemap === "hidden" || config2.build.sourcemap === true) {
const data = sourcemap.toString();
const mapFileName = chunk.fileName + ".map";
saveEmitWorkerAsset(config2, {
fileName: mapFileName,
source: data
});
}
}
return chunk;
}
var workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
function encodeWorkerAssetFileName(fileName, workerCache2) {
const { fileNameHash } = workerCache2;
const hash2 = getHash(fileName);
if (!fileNameHash.get(hash2)) {
fileNameHash.set(hash2, fileName);
}
return `__VITE_WORKER_ASSET__${hash2}__`;
}
async function workerFileToUrl(config2, id) {
const workerMap = workerCache.get(config2.mainConfig || config2);
let fileName = workerMap.bundle.get(id);
if (!fileName) {
const outputChunk = await bundleWorkerEntry(config2, id);
fileName = outputChunk.fileName;
saveEmitWorkerAsset(config2, {
fileName,
source: outputChunk.code
});
workerMap.bundle.set(id, fileName);
}
return encodeWorkerAssetFileName(fileName, workerMap);
}
function webWorkerPostPlugin() {
return {
name: "vite:worker-post",
resolveImportMeta(property, { format: format2 }) {
if (format2 === "iife") {
if (!property) {
return `{
url: self.location.href
}`;
}
if (property === "url") {
return "self.location.href";
}
}
return null;
}
};
}
function webWorkerPlugin(config2) {
const isBuild = config2.command === "build";
let server2;
const isWorker = config2.isWorker;
return {
name: "vite:worker",
configureServer(_server) {
server2 = _server;
},
buildStart() {
if (isWorker) {
return;
}
workerCache.set(config2, {
assets: /* @__PURE__ */ new Map(),
bundle: /* @__PURE__ */ new Map(),
fileNameHash: /* @__PURE__ */ new Map()
});
},
load(id) {
if (isBuild && workerOrSharedWorkerRE.test(id)) {
return "";
}
},
shouldTransformCachedModule({ id }) {
if (isBuild && config2.build.watch && workerOrSharedWorkerRE.test(id)) {
return true;
}
},
async transform(raw, id) {
var _a4, _b3;
const workerFileMatch = workerFileRE.exec(id);
if (workerFileMatch) {
const workerType2 = workerFileMatch[1];
let injectEnv = "";
const scriptPath = JSON.stringify(
import_node_path3.default.posix.join(config2.base, ENV_PUBLIC_PATH)
);
if (workerType2 === "classic") {
injectEnv = `importScripts(${scriptPath})
`;
} else if (workerType2 === "module") {
injectEnv = `import ${scriptPath}
`;
} else if (workerType2 === "ignore") {
if (isBuild) {
injectEnv = "";
} else if (server2) {
const { moduleGraph } = server2;
const module = moduleGraph.getModuleById(ENV_ENTRY);
injectEnv = ((_a4 = module == null ? void 0 : module.transformResult) == null ? void 0 : _a4.code) || "";
}
}
if (injectEnv) {
const s = new MagicString(raw);
s.prepend(injectEnv);
return {
code: s.toString(),
map: s.generateMap({ hires: "boundary" })
};
}
return;
}
const workerMatch = workerOrSharedWorkerRE.exec(id);
if (!workerMatch) return;
const { format: format2 } = config2.worker;
const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
const workerType = isBuild ? format2 === "es" ? "module" : "classic" : "module";
const workerTypeOption = `{
${workerType === "module" ? `type: "module",` : ""}
name: options?.name
}`;
let urlCode;
if (isBuild) {
if (isWorker && ((_b3 = this.getModuleInfo(cleanUrl(id))) == null ? void 0 : _b3.isEntry)) {
urlCode = "self.location.href";
} else if (inlineRE.test(id)) {
const chunk = await bundleWorkerEntry(config2, id);
const encodedJs = `const encodedJs = "${Buffer.from(
chunk.code
).toString("base64")}";`;
const code = (
// Using blob URL for SharedWorker results in multiple instances of a same worker
workerConstructor === "Worker" ? `${encodedJs}
const decodeBase64 = (base64) => Uint8Array.from(atob(base64), c => c.charCodeAt(0));
const blob = typeof self !== "undefined" && self.Blob && new Blob([${workerType === "classic" ? "" : (
// `URL` is always available, in `Worker[type="module"]`
`'URL.revokeObjectURL(import.meta.url);',`
)}decodeBase64(encodedJs)], { type: "text/javascript;charset=utf-8" });
export default function WorkerWrapper(options) {
let objURL;
try {
objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
if (!objURL) throw ''
const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
worker.addEventListener("error", () => {
(self.URL || self.webkitURL).revokeObjectURL(objURL);
});
return worker;
} catch(e) {
return new ${workerConstructor}(
"data:text/javascript;base64," + encodedJs,
${workerTypeOption}
);
}${// For module workers, we should not revoke the URL until the worker runs,
// otherwise the worker fails to run
workerType === "classic" ? ` finally {
objURL && (self.URL || self.webkitURL).revokeObjectURL(objURL);
}` : ""}
}` : `${encodedJs}
export default function WorkerWrapper(options) {
return new ${workerConstructor}(
"data:text/javascript;base64," + encodedJs,
${workerTypeOption}
);
}
`
);
return {
code,
// Empty sourcemap to suppress Rollup warning
map: { mappings: "" }
};
} else {
urlCode = JSON.stringify(await workerFileToUrl(config2, id));
}
} else {
let url2 = await fileToUrl$1(cleanUrl(id), config2, this);
url2 = injectQuery(url2, `${WORKER_FILE_ID}&type=${workerType}`);
urlCode = JSON.stringify(url2);
}
if (urlRE.test(id)) {
return {
code: `export default ${urlCode}`,
map: { mappings: "" }
// Empty sourcemap to suppress Rollup warning
};
}
return {
code: `export default function WorkerWrapper(options) {
return new ${workerConstructor}(
${urlCode},
${workerTypeOption}
);
}`,
map: { mappings: "" }
// Empty sourcemap to suppress Rollup warning
};
},
renderChunk(code, chunk, outputOptions) {
let s;
const result = () => {
return s && {
code: s.toString(),
map: config2.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
};
};
workerAssetUrlRE.lastIndex = 0;
if (workerAssetUrlRE.test(code)) {
const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
outputOptions.format,
config2.isWorker
);
let match2;
s = new MagicString(code);
workerAssetUrlRE.lastIndex = 0;
const workerMap = workerCache.get(config2.mainConfig || config2);
const { fileNameHash } = workerMap;
while (match2 = workerAssetUrlRE.exec(code)) {
const [full, hash2] = match2;
const filename = fileNameHash.get(hash2);
const replacement = toOutputFilePathInJS(
filename,
"asset",
chunk.fileName,
"js",
config2,
toRelativeRuntime
);
const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
s.update(match2.index, match2.index + full.length, replacementString);
}
}
return result();
},
generateBundle(opts, bundle) {
if (opts.__vite_skip_asset_emit__ || isWorker) {
return;
}
const workerMap = workerCache.get(config2);
workerMap.assets.forEach((asset) => {
const duplicateAsset = bundle[asset.fileName];
if (duplicateAsset) {
const content = duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code;
if (isSameContent(content, asset.source)) {
return;
}
}
this.emitFile({
type: "asset",
fileName: asset.fileName,
source: asset.source
});
});
workerMap.assets.clear();
}
};
}
function isSameContent(a, b) {
if (typeof a === "string") {
if (typeof b === "string") {
return a === b;
}
return Buffer.from(a).equals(b);
}
return Buffer.from(b).equals(a);
}
function preAliasPlugin(config2) {
const findPatterns = getAliasPatterns(config2.resolve.alias);
const isConfiguredAsExternal = createIsConfiguredAsSsrExternal(config2);
const isBuild = config2.command === "build";
const fsUtils = getFsUtils(config2);
return {
name: "vite:pre-alias",
async resolveId(id, importer, options2) {
var _a4;
const ssr = (options2 == null ? void 0 : options2.ssr) === true;
const depsOptimizer = !isBuild && getDepsOptimizer(config2, ssr);
if (importer && depsOptimizer && bareImportRE.test(id) && !(options2 == null ? void 0 : options2.scan) && id !== "@vite/client" && id !== "@vite/env") {
if (findPatterns.find((pattern2) => matches(pattern2, id))) {
const optimizedId = await tryOptimizedResolve(
depsOptimizer,
id,
importer,
config2.resolve.preserveSymlinks,
config2.packageCache
);
if (optimizedId) {
return optimizedId;
}
if (depsOptimizer.options.noDiscovery) {
return;
}
const resolved = await this.resolve(id, importer, {
...options2,
custom: { ...options2.custom, "vite:pre-alias": true }
});
if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
const optimizeDeps2 = depsOptimizer.options;
const resolvedId = cleanUrl(resolved.id);
const isVirtual = resolvedId === id || resolvedId.includes("\0");
if (!isVirtual && fsUtils.existsSync(resolvedId) && !moduleListContains(optimizeDeps2.exclude, id) && import_node_path3.default.isAbsolute(resolvedId) && (isInNodeModules$1(resolvedId) || ((_a4 = optimizeDeps2.include) == null ? void 0 : _a4.includes(id))) && isOptimizable(resolvedId, optimizeDeps2) && !(isBuild && ssr && isConfiguredAsExternal(id, importer)) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps2))) {
const optimizedInfo = depsOptimizer.registerMissingImport(
id,
resolvedId
);
return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
}
}
return resolved;
}
}
}
};
}
function optimizeAliasReplacementForSSR(id, optimizeDeps2) {
var _a4;
if ((_a4 = optimizeDeps2.include) == null ? void 0 : _a4.includes(id)) {
return true;
}
return false;
}
function matches(pattern2, importee) {
if (pattern2 instanceof RegExp) {
return pattern2.test(importee);
}
if (importee.length < pattern2.length) {
return false;
}
if (importee === pattern2) {
return true;
}
return importee.startsWith(withTrailingSlash(pattern2));
}
function getAliasPatterns(entries) {
if (!entries) {
return [];
}
if (Array.isArray(entries)) {
return entries.map((entry2) => entry2.find);
}
return Object.entries(entries).map(([find2]) => find2);
}
function getAliasPatternMatcher(entries) {
const patterns = getAliasPatterns(entries);
return (importee) => patterns.some((pattern2) => matches(pattern2, importee));
}
function err(e2, pos) {
const error2 = new Error(e2);
error2.pos = pos;
return error2;
}
function parseWorkerOptions(rawOpts, optsStartIndex) {
let opts = {};
try {
opts = evalValue(rawOpts);
} catch {
throw err(
"Vite is unable to parse the worker options as the value is not static.To ignore this error, please use /* @vite-ignore */ in the worker options.",
optsStartIndex
);
}
if (opts == null) {
return {};
}
if (typeof opts !== "object") {
throw err(
`Expected worker options to be an object, got ${typeof opts}`,
optsStartIndex
);
}
return opts;
}
function getWorkerType(raw, clean, i) {
const commaIndex = clean.indexOf(",", i);
if (commaIndex === -1) {
return "classic";
}
const endIndex = clean.indexOf(")", i);
if (commaIndex > endIndex) {
return "classic";
}
const workerOptString = raw.substring(commaIndex + 1, endIndex).replace(/\}[\s\S]*,/g, "}");
const hasViteIgnore = hasViteIgnoreRE.test(workerOptString);
if (hasViteIgnore) {
return "ignore";
}
const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex).trim();
if (!cleanWorkerOptString.length) {
return "classic";
}
const workerOpts = parseWorkerOptions(workerOptString, commaIndex + 1);
if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) {
return workerOpts.type;
}
return "classic";
}
function isIncludeWorkerImportMetaUrl(code) {
if ((code.includes("new Worker") || code.includes("new SharedWorker")) && code.includes("new URL") && code.includes(`import.meta.url`)) {
return true;
}
return false;
}
function workerImportMetaUrlPlugin(config2) {
const isBuild = config2.command === "build";
let workerResolver;
const fsResolveOptions = {
...config2.resolve,
root: config2.root,
isProduction: config2.isProduction,
isBuild: config2.command === "build",
packageCache: config2.packageCache,
ssrConfig: config2.ssr,
asSrc: true
};
return {
name: "vite:worker-import-meta-url",
shouldTransformCachedModule({ code }) {
if (isBuild && config2.build.watch && isIncludeWorkerImportMetaUrl(code)) {
return true;
}
},
async transform(code, id, options2) {
var _a4;
if (!(options2 == null ? void 0 : options2.ssr) && isIncludeWorkerImportMetaUrl(code)) {
let s;
const cleanString = stripLiteral(code);
const workerImportMetaUrlRE = new RegExp("\\bnew\\s+(?:Worker|SharedWorker)\\s*\\(\\s*(new\\s+URL\\s*\\(\\s*('[^']+'|\"[^\"]+\"|`[^`]+`)\\s*,\\s*import\\.meta\\.url\\s*\\))", "dg");
let match2;
while (match2 = workerImportMetaUrlRE.exec(cleanString)) {
const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match2.indices;
const rawUrl = code.slice(urlStart, urlEnd);
if (rawUrl[0] === "`" && rawUrl.includes("${")) {
this.error(
`\`new URL(url, import.meta.url)\` is not supported in dynamic template string.`,
expStart
);
}
s || (s = new MagicString(code));
const workerType = getWorkerType(code, cleanString, endIndex);
const url2 = rawUrl.slice(1, -1);
let file;
if (url2[0] === ".") {
file = import_node_path3.default.resolve(import_node_path3.default.dirname(id), url2);
file = tryFsResolve(file, fsResolveOptions) ?? file;
} else {
workerResolver ?? (workerResolver = config2.createResolver({
extensions: [],
tryIndex: false,
preferRelative: true
}));
file = await workerResolver(url2, id);
file ?? (file = url2[0] === "/" ? slash$1(import_node_path3.default.join(config2.publicDir, url2)) : slash$1(import_node_path3.default.resolve(import_node_path3.default.dirname(id), url2)));
}
if (isBuild && config2.isWorker && ((_a4 = this.getModuleInfo(cleanUrl(file))) == null ? void 0 : _a4.isEntry)) {
s.update(expStart, expEnd, "self.location.href");
} else {
let builtUrl;
if (isBuild) {
builtUrl = await workerFileToUrl(config2, file);
} else {
builtUrl = await fileToUrl$1(cleanUrl(file), config2, this);
builtUrl = injectQuery(
builtUrl,
`${WORKER_FILE_ID}&type=${workerType}`
);
}
s.update(
expStart,
expEnd,
`new URL(/* @vite-ignore */ ${JSON.stringify(builtUrl)}, import.meta.url)`
);
}
}
if (s) {
return transformStableResult(s, id, config2);
}
return null;
}
}
};
}
function assetImportMetaUrlPlugin(config2) {
const { publicDir } = config2;
let assetResolver;
const fsResolveOptions = {
...config2.resolve,
root: config2.root,
isProduction: config2.isProduction,
isBuild: config2.command === "build",
packageCache: config2.packageCache,
ssrConfig: config2.ssr,
asSrc: true
};
return {
name: "vite:asset-import-meta-url",
async transform(code, id, options2) {
if (!(options2 == null ? void 0 : options2.ssr) && id !== preloadHelperId && id !== CLIENT_ENTRY && code.includes("new URL") && code.includes(`import.meta.url`)) {
let s;
const assetImportMetaUrlRE = new RegExp("\\bnew\\s+URL\\s*\\(\\s*('[^']+'|\"[^\"]+\"|`[^`]+`)\\s*,\\s*import\\.meta\\.url\\s*(?:,\\s*)?\\)", "dg");
const cleanString = stripLiteral(code);
let match2;
while (match2 = assetImportMetaUrlRE.exec(cleanString)) {
const [[startIndex, endIndex], [urlStart, urlEnd]] = match2.indices;
if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
const rawUrl = code.slice(urlStart, urlEnd);
if (!s) s = new MagicString(code);
if (rawUrl[0] === "`" && rawUrl.includes("${")) {
const queryDelimiterIndex = getQueryDelimiterIndex(rawUrl);
const hasQueryDelimiter = queryDelimiterIndex !== -1;
const pureUrl = hasQueryDelimiter ? rawUrl.slice(0, queryDelimiterIndex) + "`" : rawUrl;
const queryString = hasQueryDelimiter ? rawUrl.slice(queryDelimiterIndex, -1) : "";
const ast = this.parse(pureUrl);
const templateLiteral = ast.body[0].expression;
if (templateLiteral.expressions.length) {
const pattern2 = buildGlobPattern(templateLiteral);
if (pattern2.startsWith("**")) {
continue;
}
const globOptions = {
eager: true,
import: "default",
// A hack to allow 'as' & 'query' exist at the same time
query: injectQuery(queryString, "url")
};
s.update(
startIndex,
endIndex,
`new URL((import.meta.glob(${JSON.stringify(
pattern2
)}, ${JSON.stringify(
globOptions
)}))[${pureUrl}], import.meta.url)`
);
continue;
}
}
const url2 = rawUrl.slice(1, -1);
let file;
if (url2[0] === ".") {
file = slash$1(import_node_path3.default.resolve(import_node_path3.default.dirname(id), url2));
file = tryFsResolve(file, fsResolveOptions) ?? file;
} else {
assetResolver ?? (assetResolver = config2.createResolver({
extensions: [],
mainFields: [],
tryIndex: false,
preferRelative: true
}));
file = await assetResolver(url2, id);
file ?? (file = url2[0] === "/" ? slash$1(import_node_path3.default.join(publicDir, url2)) : slash$1(import_node_path3.default.resolve(import_node_path3.default.dirname(id), url2)));
}
let builtUrl;
if (file) {
try {
if (publicDir && isParentDirectory(publicDir, file)) {
const publicPath = "/" + import_node_path3.default.posix.relative(publicDir, file);
builtUrl = await fileToUrl$1(publicPath, config2, this);
} else {
builtUrl = await fileToUrl$1(file, config2, this);
}
} catch {
}
}
if (!builtUrl) {
const rawExp = code.slice(startIndex, endIndex);
config2.logger.warnOnce(
`
${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime. If this is intended, you can use the /* @vite-ignore */ comment to suppress this warning.`
);
builtUrl = url2;
}
s.update(
startIndex,
endIndex,
`new URL(${JSON.stringify(builtUrl)}, import.meta.url)`
);
}
if (s) {
return transformStableResult(s, id, config2);
}
}
return null;
}
};
}
function buildGlobPattern(ast) {
let pattern2 = "";
let lastElementIndex = -1;
for (const exp of ast.expressions) {
for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
const el = ast.quasis[i];
if (el.end < exp.start) {
pattern2 += el.value.raw;
lastElementIndex = i;
}
}
pattern2 += "**";
}
for (let i = lastElementIndex + 1; i < ast.quasis.length; i++) {
pattern2 += ast.quasis[i].value.raw;
}
return pattern2;
}
function getQueryDelimiterIndex(rawUrl) {
let bracketsStack = 0;
for (let i = 0; i < rawUrl.length; i++) {
if (rawUrl[i] === "{") {
bracketsStack++;
} else if (rawUrl[i] === "}") {
bracketsStack--;
} else if (rawUrl[i] === "?" && bracketsStack === 0) {
return i;
}
}
return -1;
}
function metadataPlugin() {
return {
name: "vite:build-metadata",
async renderChunk(_code, chunk) {
chunk.viteMetadata = {
importedAssets: /* @__PURE__ */ new Set(),
importedCss: /* @__PURE__ */ new Set()
};
return null;
}
};
}
if (!String.prototype.repeat) {
throw new Error(
"String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation"
);
}
if (!String.prototype.endsWith) {
throw new Error(
"String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation"
);
}
var VariableDynamicImportError = class extends Error {
};
var example = "For example: import(`./foo/${bar}.js`).";
function sanitizeString(str) {
if (str === "") return str;
if (str.includes("*")) {
throw new VariableDynamicImportError("A dynamic import cannot contain * characters.");
}
return glob.escapePath(str);
}
function templateLiteralToGlob(node2) {
let glob2 = "";
for (let i = 0; i < node2.quasis.length; i += 1) {
glob2 += sanitizeString(node2.quasis[i].value.raw);
if (node2.expressions[i]) {
glob2 += expressionToGlob(node2.expressions[i]);
}
}
return glob2;
}
function callExpressionToGlob(node2) {
const { callee } = node2;
if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") {
return `${expressionToGlob(callee.object)}${node2.arguments.map(expressionToGlob).join("")}`;
}
return "*";
}
function binaryExpressionToGlob(node2) {
if (node2.operator !== "+") {
throw new VariableDynamicImportError(`${node2.operator} operator is not supported.`);
}
return `${expressionToGlob(node2.left)}${expressionToGlob(node2.right)}`;
}
function expressionToGlob(node2) {
switch (node2.type) {
case "TemplateLiteral":
return templateLiteralToGlob(node2);
case "CallExpression":
return callExpressionToGlob(node2);
case "BinaryExpression":
return binaryExpressionToGlob(node2);
case "Literal": {
return sanitizeString(node2.value);
}
default:
return "*";
}
}
var defaultProtocol = "file:";
var ignoredProtocols = ["data:", "http:", "https:"];
function shouldIgnore(glob2) {
const containsAsterisk = glob2.includes("*");
const globURL = new URL(glob2, defaultProtocol);
const containsIgnoredProtocol = ignoredProtocols.some(
(ignoredProtocol) => ignoredProtocol === globURL.protocol
);
return !containsAsterisk || containsIgnoredProtocol;
}
function dynamicImportToGlob(node2, sourceString) {
let glob2 = expressionToGlob(node2);
if (shouldIgnore(glob2)) {
return null;
}
glob2 = glob2.replace(/\*\*/g, "*");
if (glob2.startsWith("*")) {
throw new VariableDynamicImportError(
`invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}`
);
}
if (glob2.startsWith("/")) {
throw new VariableDynamicImportError(
`invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}`
);
}
if (!glob2.startsWith("./") && !glob2.startsWith("../")) {
throw new VariableDynamicImportError(
`invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}`
);
}
const ownDirectoryStarExtension = /^\.\/\*\.[\w]+$/;
if (ownDirectoryStarExtension.test(glob2)) {
throw new VariableDynamicImportError(
`${`invalid import "${sourceString}". Variable imports cannot import their own directory, place imports in a separate directory or make the import filename more specific. `}${example}`
);
}
if (import_path.default.extname(glob2) === "") {
throw new VariableDynamicImportError(
`invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`
);
}
return glob2;
}
var dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
var relativePathRE = /^\.{1,2}\//;
var hasDynamicImportRE = /\bimport\s*[(/]/;
var dynamicImportHelper = (glob2, path3, segs) => {
const v = glob2[path3];
if (v) {
return typeof v === "function" ? v() : Promise.resolve(v);
}
return new Promise((_, reject) => {
(typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(
reject.bind(
null,
new Error(
"Unknown variable dynamic import: " + path3 + (path3.split("/").length !== segs ? ". Note that variables only represent file names one level deep." : "")
)
)
);
});
};
function parseDynamicImportPattern(strings) {
const filename = strings.slice(1, -1);
const ast = parseAst(strings).body[0].expression;
const userPatternQuery = dynamicImportToGlob(ast, filename);
if (!userPatternQuery) {
return null;
}
const [userPattern] = userPatternQuery.split(
// ? is escaped on posix OS
requestQueryMaybeEscapedSplitRE,
2
);
let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
let globParams = null;
if (search) {
search = "?" + search;
if (workerOrSharedWorkerRE.test(search) || urlRE.test(search) || rawRE.test(search)) {
globParams = {
query: search,
import: "*"
};
} else {
globParams = {
query: search
};
}
}
return {
globParams,
userPattern,
rawPattern
};
}
async function transformDynamicImport(importSource, importer, resolve3, root) {
if (importSource[1] !== "." && importSource[1] !== "/") {
const resolvedFileName = await resolve3(importSource.slice(1, -1), importer);
if (!resolvedFileName) {
return null;
}
const relativeFileName = normalizePath$3(
import_node_path3.posix.relative(
import_node_path3.posix.dirname(normalizePath$3(importer)),
normalizePath$3(resolvedFileName)
)
);
importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
}
const dynamicImportPattern = parseDynamicImportPattern(importSource);
if (!dynamicImportPattern) {
return null;
}
const { globParams, rawPattern, userPattern } = dynamicImportPattern;
const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
let newRawPattern = import_node_path3.posix.relative(
import_node_path3.posix.dirname(importer),
await toAbsoluteGlob(rawPattern, root, importer, resolve3)
);
if (!relativePathRE.test(newRawPattern)) {
newRawPattern = `./${newRawPattern}`;
}
const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
return {
rawPattern: newRawPattern,
pattern: userPattern,
glob: exp
};
}
function dynamicImportVarsPlugin(config2) {
const resolve3 = config2.createResolver({
preferRelative: true,
tryIndex: false,
extensions: []
});
const { include, exclude, warnOnError } = config2.build.dynamicImportVarsOptions;
const filter2 = createFilter2(include, exclude);
return {
name: "vite:dynamic-import-vars",
resolveId(id) {
if (id === dynamicImportHelperId) {
return id;
}
},
load(id) {
if (id === dynamicImportHelperId) {
return "export default " + dynamicImportHelper.toString();
}
},
async transform(source, importer) {
if (!filter2(importer) || importer === CLIENT_ENTRY || !hasDynamicImportRE.test(source)) {
return;
}
await init;
let imports = [];
try {
imports = parse$d(source)[0];
} catch (e2) {
return null;
}
if (!imports.length) {
return null;
}
let s;
let needDynamicImportHelper = false;
for (let index = 0; index < imports.length; index++) {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex
} = imports[index];
if (dynamicIndex === -1 || source[start] !== "`") {
continue;
}
if (hasViteIgnoreRE.test(source.slice(expStart, expEnd))) {
continue;
}
s || (s = new MagicString(source));
let result;
try {
result = await transformDynamicImport(
source.slice(start, end),
importer,
resolve3,
config2.root
);
} catch (error2) {
if (warnOnError) {
this.warn(error2);
} else {
this.error(error2);
}
}
if (!result) {
continue;
}
const { rawPattern, glob: glob2 } = result;
needDynamicImportHelper = true;
s.overwrite(
expStart,
expEnd,
`__variableDynamicImportRuntimeHelper(${glob2}, \`${rawPattern}\`, ${rawPattern.split("/").length})`
);
}
if (s) {
if (needDynamicImportHelper) {
s.prepend(
`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`
);
}
return transformStableResult(s, importer, config2);
}
}
};
}
async function resolvePlugins(config2, prePlugins, normalPlugins, postPlugins) {
const isBuild = config2.command === "build";
const isWorker = config2.isWorker;
const buildPlugins = isBuild ? await (await Promise.resolve().then(function() {
return build$1;
})).resolveBuildPlugins(config2) : { pre: [], post: [] };
const { modulePreload } = config2.build;
const depsOptimizerEnabled = !isBuild && (isDepsOptimizerEnabled(config2, false) || isDepsOptimizerEnabled(config2, true));
return [
depsOptimizerEnabled ? optimizedDepsPlugin(config2) : null,
isBuild ? metadataPlugin() : null,
!isWorker ? watchPackageDataPlugin(config2.packageCache) : null,
preAliasPlugin(config2),
alias$1({
entries: config2.resolve.alias,
customResolver: viteAliasCustomResolver
}),
...prePlugins,
modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin(config2) : null,
resolvePlugin({
...config2.resolve,
root: config2.root,
isProduction: config2.isProduction,
isBuild,
packageCache: config2.packageCache,
ssrConfig: config2.ssr,
asSrc: true,
fsUtils: getFsUtils(config2),
getDepsOptimizer: isBuild ? void 0 : (ssr) => getDepsOptimizer(config2, ssr),
shouldExternalize: isBuild && config2.build.ssr ? (id, importer) => shouldExternalizeForSSR(id, importer, config2) : void 0
}),
htmlInlineProxyPlugin(config2),
cssPlugin(config2),
config2.esbuild !== false ? esbuildPlugin(config2) : null,
jsonPlugin(
{
namedExports: true,
...config2.json
},
isBuild
),
wasmHelperPlugin(config2),
webWorkerPlugin(config2),
assetPlugin(config2),
...normalPlugins,
wasmFallbackPlugin(),
definePlugin(config2),
cssPostPlugin(config2),
isBuild && buildHtmlPlugin(config2),
workerImportMetaUrlPlugin(config2),
assetImportMetaUrlPlugin(config2),
...buildPlugins.pre,
dynamicImportVarsPlugin(config2),
importGlobPlugin(config2),
...postPlugins,
...buildPlugins.post,
// internal server-only plugins are always applied after everything else
...isBuild ? [] : [
clientInjectionsPlugin(config2),
cssAnalysisPlugin(config2),
importAnalysisPlugin(config2)
]
].filter(Boolean);
}
function createPluginHookUtils(plugins2) {
const sortedPluginsCache = /* @__PURE__ */ new Map();
function getSortedPlugins(hookName) {
if (sortedPluginsCache.has(hookName))
return sortedPluginsCache.get(hookName);
const sorted = getSortedPluginsByHook(hookName, plugins2);
sortedPluginsCache.set(hookName, sorted);
return sorted;
}
function getSortedPluginHooks(hookName) {
const plugins22 = getSortedPlugins(hookName);
return plugins22.map((p) => getHookHandler(p[hookName])).filter(Boolean);
}
return {
getSortedPlugins,
getSortedPluginHooks
};
}
function getSortedPluginsByHook(hookName, plugins2) {
const sortedPlugins = [];
let pre = 0, normal = 0, post = 0;
for (const plugin of plugins2) {
const hook = plugin[hookName];
if (hook) {
if (typeof hook === "object") {
if (hook.order === "pre") {
sortedPlugins.splice(pre++, 0, plugin);
continue;
}
if (hook.order === "post") {
sortedPlugins.splice(pre + normal + post++, 0, plugin);
continue;
}
}
sortedPlugins.splice(pre + normal++, 0, plugin);
}
}
return sortedPlugins;
}
function getHookHandler(hook) {
return typeof hook === "object" ? hook.handler : hook;
}
var viteAliasCustomResolver = async function(id, importer, options2) {
const resolved = await this.resolve(id, importer, options2);
return resolved || { id, meta: { "vite:alias": { noResolved: true } } };
};
function ansiRegex({ onlyFirst = false } = {}) {
const pattern2 = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
].join("|");
return new RegExp(pattern2, onlyFirst ? void 0 : "g");
}
var regex = ansiRegex();
function stripAnsi(string2) {
if (typeof string2 !== "string") {
throw new TypeError(`Expected a \`string\`, got \`${typeof string2}\``);
}
return string2.replace(regex, "");
}
function prepareError(err2) {
var _a4;
return {
message: stripAnsi(err2.message),
stack: stripAnsi(cleanStack(err2.stack || "")),
id: err2.id,
frame: stripAnsi(err2.frame || ""),
plugin: err2.plugin,
pluginCode: (_a4 = err2.pluginCode) == null ? void 0 : _a4.toString(),
loc: err2.loc
};
}
function buildErrorMessage(err2, args = [], includeStack = true) {
if (err2.plugin) args.push(` Plugin: ${colors$1.magenta(err2.plugin)}`);
const loc = err2.loc ? `:${err2.loc.line}:${err2.loc.column}` : "";
if (err2.id) args.push(` File: ${colors$1.cyan(err2.id)}${loc}`);
if (err2.frame) args.push(colors$1.yellow(pad$1(err2.frame)));
if (includeStack && err2.stack) args.push(pad$1(cleanStack(err2.stack)));
return args.join("\n");
}
function cleanStack(stack) {
return stack.split(/\n/g).filter((l) => /^\s*at/.test(l)).join("\n");
}
function logError(server2, err2) {
const msg = buildErrorMessage(err2, [
colors$1.red(`Internal server error: ${err2.message}`)
]);
server2.config.logger.error(msg, {
clear: true,
timestamp: true,
error: err2
});
server2.hot.send({
type: "error",
err: prepareError(err2)
});
}
function errorMiddleware(server2, allowNext = false) {
return function viteErrorMiddleware(err2, _req, res, next) {
logError(server2, err2);
if (allowNext) {
next();
} else {
res.statusCode = 500;
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Error</title>
<script type="module">
const error = ${JSON.stringify(prepareError(err2)).replace(
/</g,
"\\u003c"
)}
try {
const { ErrorOverlay } = await import(${JSON.stringify(import_node_path3.default.posix.join(server2.config.base, CLIENT_PUBLIC_PATH))})
document.body.appendChild(new ErrorOverlay(error))
} catch {
const h = (tag, text) => {
const el = document.createElement(tag)
el.textContent = text
return el
}
document.body.appendChild(h('h1', 'Internal Server Error'))
document.body.appendChild(h('h2', error.message))
document.body.appendChild(h('pre', error.stack))
document.body.appendChild(h('p', '(Error overlay failed to load)'))
}
<\/script>
</head>
<body>
</body>
</html>
`);
}
};
}
var noop$3 = () => {
};
var EMPTY_OBJECT = Object.freeze({});
var debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
var debugSourcemapCombine = createDebugger("vite:sourcemap-combine", {
onlyWhenFocused: true
});
var debugResolve = createDebugger("vite:resolve");
var debugPluginResolve = createDebugger("vite:plugin-resolve", {
onlyWhenFocused: "vite:plugin"
});
var debugPluginTransform = createDebugger("vite:plugin-transform", {
onlyWhenFocused: "vite:plugin"
});
var ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
function throwClosedServerError() {
const err2 = new Error(
"The server is being restarted or closed. Request is outdated"
);
err2.code = ERR_CLOSED_SERVER;
throw err2;
}
async function createPluginContainer(config2, moduleGraph, watcher) {
const container = new PluginContainer(config2, moduleGraph, watcher);
await container.resolveRollupOptions();
return container;
}
var PluginContainer = class {
/**
* @internal use `createPluginContainer` instead
*/
constructor(config2, moduleGraph, watcher, plugins2 = config2.plugins) {
__publicField(this, "_pluginContextMap", /* @__PURE__ */ new Map());
__publicField(this, "_pluginContextMapSsr", /* @__PURE__ */ new Map());
__publicField(this, "_resolvedRollupOptions");
__publicField(this, "_processesing", /* @__PURE__ */ new Set());
__publicField(this, "_seenResolves", {});
__publicField(this, "_closed", false);
// _addedFiles from the `load()` hook gets saved here so it can be reused in the `transform()` hook
__publicField(this, "_moduleNodeToLoadAddedImports", /* @__PURE__ */ new WeakMap());
__publicField(this, "getSortedPluginHooks");
__publicField(this, "getSortedPlugins");
__publicField(this, "watchFiles", /* @__PURE__ */ new Set());
__publicField(this, "minimalContext");
this.config = config2;
this.moduleGraph = moduleGraph;
this.watcher = watcher;
this.plugins = plugins2;
this.minimalContext = {
meta: {
rollupVersion,
watchMode: true
},
debug: noop$3,
info: noop$3,
warn: noop$3,
// @ts-expect-error noop
error: noop$3
};
const utils2 = createPluginHookUtils(plugins2);
this.getSortedPlugins = utils2.getSortedPlugins;
this.getSortedPluginHooks = utils2.getSortedPluginHooks;
}
_updateModuleLoadAddedImports(id, addedImports) {
var _a4;
const module = (_a4 = this.moduleGraph) == null ? void 0 : _a4.getModuleById(id);
if (module) {
this._moduleNodeToLoadAddedImports.set(module, addedImports);
}
}
_getAddedImports(id) {
var _a4;
const module = (_a4 = this.moduleGraph) == null ? void 0 : _a4.getModuleById(id);
return module ? this._moduleNodeToLoadAddedImports.get(module) || null : null;
}
getModuleInfo(id) {
var _a4;
const module = (_a4 = this.moduleGraph) == null ? void 0 : _a4.getModuleById(id);
if (!module) {
return null;
}
if (!module.info) {
module.info = new Proxy(
{ id, meta: module.meta || EMPTY_OBJECT },
// throw when an unsupported ModuleInfo property is accessed,
// so that incompatible plugins fail in a non-cryptic way.
{
get(info, key) {
if (key in info) {
return info[key];
}
if (key === "then") {
return void 0;
}
throw Error(
`[vite] The "${key}" property of ModuleInfo is not supported.`
);
}
}
);
}
return module.info ?? null;
}
// keeps track of hook promises so that we can wait for them all to finish upon closing the server
handleHookPromise(maybePromise) {
if (!(maybePromise == null ? void 0 : maybePromise.then)) {
return maybePromise;
}
const promise2 = maybePromise;
this._processesing.add(promise2);
return promise2.finally(() => this._processesing.delete(promise2));
}
get options() {
return this._resolvedRollupOptions;
}
async resolveRollupOptions() {
if (!this._resolvedRollupOptions) {
let options2 = this.config.build.rollupOptions;
for (const optionsHook of this.getSortedPluginHooks("options")) {
if (this._closed) {
throwClosedServerError();
}
options2 = await this.handleHookPromise(
optionsHook.call(this.minimalContext, options2)
) || options2;
}
this._resolvedRollupOptions = options2;
}
return this._resolvedRollupOptions;
}
_getPluginContext(plugin, ssr) {
const map2 = ssr ? this._pluginContextMapSsr : this._pluginContextMap;
if (!map2.has(plugin)) {
const ctx = new PluginContext(plugin, this, ssr);
map2.set(plugin, ctx);
}
return map2.get(plugin);
}
// parallel, ignores returns
async hookParallel(hookName, context, args) {
const parallelPromises = [];
for (const plugin of this.getSortedPlugins(hookName)) {
const hook = plugin[hookName];
if (!hook) continue;
const handler = getHookHandler(hook);
if (hook.sequential) {
await Promise.all(parallelPromises);
parallelPromises.length = 0;
await handler.apply(context(plugin), args(plugin));
} else {
parallelPromises.push(handler.apply(context(plugin), args(plugin)));
}
}
await Promise.all(parallelPromises);
}
async buildStart(_options2) {
await this.handleHookPromise(
this.hookParallel(
"buildStart",
(plugin) => this._getPluginContext(plugin, false),
() => [this.options]
)
);
}
async resolveId(rawId, importer = (0, import_node_path3.join)(this.config.root, "index.html"), options2) {
const skip = options2 == null ? void 0 : options2.skip;
const ssr = options2 == null ? void 0 : options2.ssr;
const scan2 = !!(options2 == null ? void 0 : options2.scan);
const ctx = new ResolveIdContext(this, !!ssr, skip, scan2);
const resolveStart = debugResolve ? import_node_perf_hooks.performance.now() : 0;
let id = null;
const partial2 = {};
for (const plugin of this.getSortedPlugins("resolveId")) {
if (this._closed && !ssr) throwClosedServerError();
if (!plugin.resolveId) continue;
if (skip == null ? void 0 : skip.has(plugin)) continue;
ctx._plugin = plugin;
const pluginResolveStart = debugPluginResolve ? import_node_perf_hooks.performance.now() : 0;
const handler = getHookHandler(plugin.resolveId);
const result = await this.handleHookPromise(
handler.call(ctx, rawId, importer, {
attributes: (options2 == null ? void 0 : options2.attributes) ?? {},
custom: options2 == null ? void 0 : options2.custom,
isEntry: !!(options2 == null ? void 0 : options2.isEntry),
ssr,
scan: scan2
})
);
if (!result) continue;
if (typeof result === "string") {
id = result;
} else {
id = result.id;
Object.assign(partial2, result);
}
debugPluginResolve == null ? void 0 : debugPluginResolve(
timeFrom(pluginResolveStart),
plugin.name,
prettifyUrl(id, this.config.root)
);
break;
}
if (debugResolve && rawId !== id && !rawId.startsWith(FS_PREFIX)) {
const key = rawId + id;
if (!this._seenResolves[key]) {
this._seenResolves[key] = true;
debugResolve(
`${timeFrom(resolveStart)} ${colors$1.cyan(rawId)} -> ${colors$1.dim(
id
)}`
);
}
}
if (id) {
partial2.id = isExternalUrl(id) ? id : normalizePath$3(id);
return partial2;
} else {
return null;
}
}
async load(id, options2) {
const ssr = options2 == null ? void 0 : options2.ssr;
const ctx = new LoadPluginContext(this, !!ssr);
for (const plugin of this.getSortedPlugins("load")) {
if (this._closed && !ssr) throwClosedServerError();
if (!plugin.load) continue;
ctx._plugin = plugin;
const handler = getHookHandler(plugin.load);
const result = await this.handleHookPromise(
handler.call(ctx, id, { ssr })
);
if (result != null) {
if (isObject$1(result)) {
ctx._updateModuleInfo(id, result);
}
this._updateModuleLoadAddedImports(id, ctx._addedImports);
return result;
}
}
this._updateModuleLoadAddedImports(id, ctx._addedImports);
return null;
}
async transform(code, id, options2) {
const inMap = options2 == null ? void 0 : options2.inMap;
const ssr = options2 == null ? void 0 : options2.ssr;
const ctx = new TransformPluginContext(
this,
id,
code,
inMap,
!!ssr
);
ctx._addedImports = this._getAddedImports(id);
for (const plugin of this.getSortedPlugins("transform")) {
if (this._closed && !ssr) throwClosedServerError();
if (!plugin.transform) continue;
ctx._updateActiveInfo(plugin, id, code);
const start = debugPluginTransform ? import_node_perf_hooks.performance.now() : 0;
let result;
const handler = getHookHandler(plugin.transform);
try {
result = await this.handleHookPromise(
handler.call(ctx, code, id, { ssr })
);
} catch (e2) {
ctx.error(e2);
}
if (!result) continue;
debugPluginTransform == null ? void 0 : debugPluginTransform(
timeFrom(start),
plugin.name,
prettifyUrl(id, this.config.root)
);
if (isObject$1(result)) {
if (result.code !== void 0) {
code = result.code;
if (result.map) {
if (debugSourcemapCombine) {
result.map.name = plugin.name;
}
ctx.sourcemapChain.push(result.map);
}
}
ctx._updateModuleInfo(id, result);
} else {
code = result;
}
}
return {
code,
map: ctx._getCombinedSourcemap()
};
}
async watchChange(id, change) {
await this.hookParallel(
"watchChange",
(plugin) => this._getPluginContext(plugin, false),
() => [id, change]
);
}
async close() {
if (this._closed) return;
this._closed = true;
await Promise.allSettled(Array.from(this._processesing));
await this.hookParallel(
"buildEnd",
(plugin) => this._getPluginContext(plugin, false),
() => []
);
await this.hookParallel(
"closeBundle",
(plugin) => this._getPluginContext(plugin, false),
() => []
);
}
};
var PluginContext = class {
constructor(_plugin, _container, ssr) {
__publicField(this, "_scan", false);
__publicField(this, "_resolveSkips");
__publicField(this, "_activeId", null);
__publicField(this, "_activeCode", null);
__publicField(this, "meta");
__publicField(this, "debug", noop$3);
__publicField(this, "info", noop$3);
this._plugin = _plugin;
this._container = _container;
this.ssr = ssr;
this.meta = this._container.minimalContext.meta;
}
parse(code, opts) {
return parseAst(code, opts);
}
getModuleInfo(id) {
return this._container.getModuleInfo(id);
}
async resolve(id, importer, options2) {
let skip;
if ((options2 == null ? void 0 : options2.skipSelf) !== false && this._plugin) {
skip = new Set(this._resolveSkips);
skip.add(this._plugin);
}
let out2 = await this._container.resolveId(id, importer, {
attributes: options2 == null ? void 0 : options2.attributes,
custom: options2 == null ? void 0 : options2.custom,
isEntry: !!(options2 == null ? void 0 : options2.isEntry),
skip,
ssr: this.ssr,
scan: this._scan
});
if (typeof out2 === "string") out2 = { id: out2 };
return out2;
}
async load(options2) {
var _a4;
await ((_a4 = this._container.moduleGraph) == null ? void 0 : _a4.ensureEntryFromUrl(
unwrapId$1(options2.id),
this.ssr
));
this._updateModuleInfo(options2.id, options2);
const loadResult = await this._container.load(options2.id, {
ssr: this.ssr
});
const code = typeof loadResult === "object" ? loadResult == null ? void 0 : loadResult.code : loadResult;
if (code != null) {
await this._container.transform(code, options2.id, { ssr: this.ssr });
}
const moduleInfo = this.getModuleInfo(options2.id);
if (!moduleInfo) throw Error(`Failed to load module with id ${options2.id}`);
return moduleInfo;
}
_updateModuleInfo(id, { meta }) {
if (meta) {
const moduleInfo = this.getModuleInfo(id);
if (moduleInfo) {
moduleInfo.meta = { ...moduleInfo.meta, ...meta };
}
}
}
getModuleIds() {
return this._container.moduleGraph ? this._container.moduleGraph.idToModuleMap.keys() : Array.prototype[Symbol.iterator]();
}
addWatchFile(id) {
this._container.watchFiles.add(id);
if (this._container.watcher)
ensureWatchedFile(
this._container.watcher,
id,
this._container.config.root
);
}
getWatchFiles() {
return [...this._container.watchFiles];
}
emitFile(assetOrFile) {
this._warnIncompatibleMethod(`emitFile`);
return "";
}
setAssetSource() {
this._warnIncompatibleMethod(`setAssetSource`);
}
getFileName() {
this._warnIncompatibleMethod(`getFileName`);
return "";
}
warn(e2, position) {
const err2 = this._formatError(typeof e2 === "function" ? e2() : e2, position);
const msg = buildErrorMessage(
err2,
[colors$1.yellow(`warning: ${err2.message}`)],
false
);
this._container.config.logger.warn(msg, {
clear: true,
timestamp: true
});
}
error(e2, position) {
throw this._formatError(e2, position);
}
_formatError(e2, position) {
var _a4, _b3, _c2, _d2, _e2;
const err2 = typeof e2 === "string" ? new Error(e2) : e2;
if (err2.pluginCode) {
return err2;
}
if (this._plugin) err2.plugin = this._plugin.name;
if (this._activeId && !err2.id) err2.id = this._activeId;
if (this._activeCode) {
err2.pluginCode = this._activeCode;
const pos = position ?? err2.pos ?? err2.position;
if (pos != null) {
let errLocation;
try {
errLocation = numberToPos(this._activeCode, pos);
} catch (err22) {
this._container.config.logger.error(
colors$1.red(
`Error in error handler:
${err22.stack || err22.message}
`
),
// print extra newline to separate the two errors
{ error: err22 }
);
throw err2;
}
err2.loc = err2.loc || {
file: err2.id,
...errLocation
};
err2.frame = err2.frame || generateCodeFrame(this._activeCode, pos);
} else if (err2.loc) {
if (!err2.frame) {
let code = this._activeCode;
if (err2.loc.file) {
err2.id = normalizePath$3(err2.loc.file);
try {
code = import_node_fs2.default.readFileSync(err2.loc.file, "utf-8");
} catch {
}
}
err2.frame = generateCodeFrame(code, err2.loc);
}
} else if (err2.line && err2.column) {
err2.loc = {
file: err2.id,
line: err2.line,
column: err2.column
};
err2.frame = err2.frame || generateCodeFrame(this._activeCode, err2.loc);
}
if (this instanceof TransformPluginContext && typeof ((_a4 = err2.loc) == null ? void 0 : _a4.line) === "number" && typeof ((_b3 = err2.loc) == null ? void 0 : _b3.column) === "number") {
const rawSourceMap = this._getCombinedSourcemap();
if (rawSourceMap && "version" in rawSourceMap) {
const traced = new TraceMap(rawSourceMap);
const { source, line, column } = originalPositionFor$1(traced, {
line: Number(err2.loc.line),
column: Number(err2.loc.column)
});
if (source && line != null && column != null) {
err2.loc = { file: source, line, column };
}
}
}
} else if (err2.loc) {
if (!err2.frame) {
let code = err2.pluginCode;
if (err2.loc.file) {
err2.id = normalizePath$3(err2.loc.file);
if (!code) {
try {
code = import_node_fs2.default.readFileSync(err2.loc.file, "utf-8");
} catch {
}
}
}
if (code) {
err2.frame = generateCodeFrame(`${code}`, err2.loc);
}
}
}
if (typeof ((_c2 = err2.loc) == null ? void 0 : _c2.column) !== "number" && typeof ((_d2 = err2.loc) == null ? void 0 : _d2.line) !== "number" && !((_e2 = err2.loc) == null ? void 0 : _e2.file)) {
delete err2.loc;
}
return err2;
}
_warnIncompatibleMethod(method) {
this._container.config.logger.warn(
colors$1.cyan(`[plugin:${this._plugin.name}] `) + colors$1.yellow(
`context method ${colors$1.bold(
`${method}()`
)} is not supported in serve mode. This plugin is likely not vite-compatible.`
)
);
}
};
var ResolveIdContext = class extends PluginContext {
constructor(container, ssr, skip, scan2) {
super(null, container, ssr);
this._resolveSkips = skip;
this._scan = scan2;
}
};
var LoadPluginContext = class extends PluginContext {
constructor(container, ssr) {
super(null, container, ssr);
__publicField(this, "_addedImports", null);
}
addWatchFile(id) {
if (!this._addedImports) {
this._addedImports = /* @__PURE__ */ new Set();
}
this._addedImports.add(id);
super.addWatchFile(id);
}
};
var TransformPluginContext = class extends LoadPluginContext {
constructor(container, id, code, inMap, ssr) {
super(container, ssr);
__publicField(this, "filename");
__publicField(this, "originalCode");
__publicField(this, "originalSourcemap", null);
__publicField(this, "sourcemapChain", []);
__publicField(this, "combinedMap", null);
this.filename = id;
this.originalCode = code;
if (inMap) {
if (debugSourcemapCombine) {
inMap.name = "$inMap";
}
this.sourcemapChain.push(inMap);
}
}
_getCombinedSourcemap() {
if (debugSourcemapCombine && debugSourcemapCombineFilter && this.filename.includes(debugSourcemapCombineFilter)) {
debugSourcemapCombine("----------", this.filename);
debugSourcemapCombine(this.combinedMap);
debugSourcemapCombine(this.sourcemapChain);
debugSourcemapCombine("----------");
}
let combinedMap = this.combinedMap;
if (combinedMap && !("version" in combinedMap) && combinedMap.mappings === "") {
this.sourcemapChain.length = 0;
return combinedMap;
}
for (let m of this.sourcemapChain) {
if (typeof m === "string") m = JSON.parse(m);
if (!("version" in m)) {
if (m.mappings === "") {
combinedMap = { mappings: "" };
break;
}
combinedMap = null;
break;
}
if (!combinedMap) {
const sm = m;
if (sm.sources.length === 1 && !sm.sources[0]) {
combinedMap = {
...sm,
sources: [this.filename],
sourcesContent: [this.originalCode]
};
} else {
combinedMap = sm;
}
} else {
combinedMap = combineSourcemaps(cleanUrl(this.filename), [
m,
combinedMap
]);
}
}
if (combinedMap !== this.combinedMap) {
this.combinedMap = combinedMap;
this.sourcemapChain.length = 0;
}
return this.combinedMap;
}
getCombinedSourcemap() {
const map2 = this._getCombinedSourcemap();
if (!map2 || !("version" in map2) && map2.mappings === "") {
return new MagicString(this.originalCode).generateMap({
includeContent: true,
hires: "boundary",
source: cleanUrl(this.filename)
});
}
return map2;
}
_updateActiveInfo(plugin, id, code) {
this._plugin = plugin;
this._activeId = id;
this._activeCode = code;
}
};
var debug$9 = createDebugger("vite:deps");
var htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
var importsRE = new RegExp(`(?<!\\/\\/.*)(?<=^|;|\\*\\/)\\s*import(?!\\s+type)(?:[\\w*{}\\n\\r\\t, ]+from)?\\s*("[^"]+"|'[^']+')\\s*(?=$|;|\\/\\/|\\/\\*)`, "gm");
function scanImports(config2) {
const start = import_node_perf_hooks.performance.now();
const deps = {};
const missing = {};
let entries;
const scanContext = { cancelled: false };
const esbuildContext = computeEntries(
config2
).then((computedEntries) => {
entries = computedEntries;
if (!entries.length) {
if (!config2.optimizeDeps.entries && !config2.optimizeDeps.include) {
config2.logger.warn(
colors$1.yellow(
"(!) Could not auto-determine entry point from rollupOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."
)
);
}
return;
}
if (scanContext.cancelled) return;
debug$9 == null ? void 0 : debug$9(
`Crawling dependencies using entries: ${entries.map((entry2) => `
${colors$1.dim(entry2)}`).join("")}`
);
return prepareEsbuildScanner(config2, entries, deps, missing, scanContext);
});
const result = esbuildContext.then((context) => {
function disposeContext() {
return context == null ? void 0 : context.dispose().catch((e2) => {
config2.logger.error("Failed to dispose esbuild context", { error: e2 });
});
}
if (!context || (scanContext == null ? void 0 : scanContext.cancelled)) {
disposeContext();
return { deps: {}, missing: {} };
}
return context.rebuild().then(() => {
return {
// Ensure a fixed order so hashes are stable and improve logs
deps: orderedDependencies(deps),
missing
};
}).finally(() => {
return disposeContext();
});
}).catch(async (e2) => {
if (e2.errors && e2.message.includes("The build was canceled")) {
return { deps: {}, missing: {} };
}
const prependMessage = colors$1.red(` Failed to scan for dependencies from entries:
${entries.join("\n")}
`);
if (e2.errors) {
const msgs = await (0, import_esbuild.formatMessages)(e2.errors, {
kind: "error",
color: true
});
e2.message = prependMessage + msgs.join("\n");
} else {
e2.message = prependMessage + e2.message;
}
throw e2;
}).finally(() => {
if (debug$9) {
const duration = (import_node_perf_hooks.performance.now() - start).toFixed(2);
const depsStr = Object.keys(orderedDependencies(deps)).sort().map((id) => `
${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`).join("") || colors$1.dim("no dependencies found");
debug$9(`Scan completed in ${duration}ms: ${depsStr}`);
}
});
return {
cancel: async () => {
scanContext.cancelled = true;
return esbuildContext.then((context) => context == null ? void 0 : context.cancel());
},
result
};
}
async function computeEntries(config2) {
var _a4;
let entries = [];
const explicitEntryPatterns = config2.optimizeDeps.entries;
const buildInput = (_a4 = config2.build.rollupOptions) == null ? void 0 : _a4.input;
if (explicitEntryPatterns) {
entries = await globEntries(explicitEntryPatterns, config2);
} else if (buildInput) {
const resolvePath = (p) => import_node_path3.default.resolve(config2.root, p);
if (typeof buildInput === "string") {
entries = [resolvePath(buildInput)];
} else if (Array.isArray(buildInput)) {
entries = buildInput.map(resolvePath);
} else if (isObject$1(buildInput)) {
entries = Object.values(buildInput).map(resolvePath);
} else {
throw new Error("invalid rollupOptions.input value.");
}
} else {
entries = await globEntries("**/*.html", config2);
}
entries = entries.filter(
(entry2) => isScannable(entry2, config2.optimizeDeps.extensions) && import_node_fs2.default.existsSync(entry2)
);
return entries;
}
async function prepareEsbuildScanner(config2, entries, deps, missing, scanContext) {
var _a4, _b3;
const container = await createPluginContainer(config2);
if (scanContext == null ? void 0 : scanContext.cancelled) return;
const plugin = esbuildScanPlugin(config2, container, deps, missing, entries);
const { plugins: plugins2 = [], ...esbuildOptions } = ((_a4 = config2.optimizeDeps) == null ? void 0 : _a4.esbuildOptions) ?? {};
let tsconfigRaw = esbuildOptions.tsconfigRaw;
if (!tsconfigRaw && !esbuildOptions.tsconfig) {
const tsconfigResult = await loadTsconfigJsonForFile(
import_node_path3.default.join(config2.root, "_dummy.js")
);
if ((_b3 = tsconfigResult.compilerOptions) == null ? void 0 : _b3.experimentalDecorators) {
tsconfigRaw = { compilerOptions: { experimentalDecorators: true } };
}
}
return await import_esbuild.default.context({
absWorkingDir: process.cwd(),
write: false,
stdin: {
contents: entries.map((e2) => `import ${JSON.stringify(e2)}`).join("\n"),
loader: "js"
},
bundle: true,
format: "esm",
logLevel: "silent",
plugins: [...plugins2, plugin],
...esbuildOptions,
tsconfigRaw
});
}
function orderedDependencies(deps) {
const depsList = Object.entries(deps);
depsList.sort((a, b) => a[0].localeCompare(b[0]));
return Object.fromEntries(depsList);
}
function globEntries(pattern2, config2) {
const resolvedPatterns = arraify(pattern2);
if (resolvedPatterns.every((str) => !glob.isDynamicPattern(str))) {
return resolvedPatterns.map(
(p) => normalizePath$3(import_node_path3.default.resolve(config2.root, p))
);
}
return glob(pattern2, {
cwd: config2.root,
ignore: [
"**/node_modules/**",
`**/${config2.build.outDir}/**`,
// if there aren't explicit entries, also ignore other common folders
...config2.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]
],
absolute: true,
suppressErrors: true
// suppress EACCES errors
});
}
var scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
var commentRE = /<!--.*?-->/gs;
var srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
var typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
var langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
var contextRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
function esbuildScanPlugin(config2, container, depImports, missing, entries) {
var _a4, _b3;
const seen2 = /* @__PURE__ */ new Map();
const resolve3 = async (id, importer, options2) => {
const key = id + (importer && import_node_path3.default.dirname(importer));
if (seen2.has(key)) {
return seen2.get(key);
}
const resolved = await container.resolveId(
id,
importer && normalizePath$3(importer),
{
...options2,
scan: true
}
);
const res = resolved == null ? void 0 : resolved.id;
seen2.set(key, res);
return res;
};
const include = (_a4 = config2.optimizeDeps) == null ? void 0 : _a4.include;
const exclude = [
...((_b3 = config2.optimizeDeps) == null ? void 0 : _b3.exclude) || [],
"@vite/client",
"@vite/env"
];
const isUnlessEntry = (path22) => !entries.includes(path22);
const externalUnlessEntry = ({ path: path22 }) => ({
path: path22,
external: isUnlessEntry(path22)
});
const doTransformGlobImport = async (contents, id, loader) => {
let transpiledContents;
if (loader !== "js") {
transpiledContents = (await (0, import_esbuild.transform)(contents, { loader })).code;
} else {
transpiledContents = contents;
}
const result = await transformGlobImport(
transpiledContents,
id,
config2.root,
resolve3
);
return (result == null ? void 0 : result.s.toString()) || transpiledContents;
};
return {
name: "vite:dep-scan",
setup(build2) {
const scripts2 = {};
build2.onResolve({ filter: externalRE }, ({ path: path22 }) => ({
path: path22,
external: true
}));
build2.onResolve({ filter: dataUrlRE }, ({ path: path22 }) => ({
path: path22,
external: true
}));
build2.onResolve({ filter: virtualModuleRE }, ({ path: path22 }) => {
return {
// strip prefix to get valid filesystem path so esbuild can resolve imports in the file
path: path22.replace(virtualModulePrefix, ""),
namespace: "script"
};
});
build2.onLoad({ filter: /.*/, namespace: "script" }, ({ path: path22 }) => {
return scripts2[path22];
});
build2.onResolve({ filter: htmlTypesRE }, async ({ path: path22, importer }) => {
const resolved = await resolve3(path22, importer);
if (!resolved) return;
if (isInNodeModules$1(resolved) && isOptimizable(resolved, config2.optimizeDeps))
return;
return {
path: resolved,
namespace: "html"
};
});
const htmlTypeOnLoadCallback = async ({ path: p }) => {
let raw = await import_promises.default.readFile(p, "utf-8");
raw = raw.replace(commentRE, "<!---->");
const isHtml = p.endsWith(".html");
let js = "";
let scriptId = 0;
const matches2 = raw.matchAll(scriptRE);
for (const [, openTag, content] of matches2) {
const typeMatch = openTag.match(typeRE);
const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
const langMatch = openTag.match(langRE);
const lang = langMatch && (langMatch[1] || langMatch[2] || langMatch[3]);
if (isHtml && type !== "module") {
continue;
}
if (type && !(type.includes("javascript") || type.includes("ecmascript") || type === "module")) {
continue;
}
let loader = "js";
if (lang === "ts" || lang === "tsx" || lang === "jsx") {
loader = lang;
} else if (p.endsWith(".astro")) {
loader = "ts";
}
const srcMatch = openTag.match(srcRE);
if (srcMatch) {
const src2 = srcMatch[1] || srcMatch[2] || srcMatch[3];
js += `import ${JSON.stringify(src2)}
`;
} else if (content.trim()) {
const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : "");
const key = `${p}?id=${scriptId++}`;
if (contents.includes("import.meta.glob")) {
scripts2[key] = {
loader: "js",
// since it is transpiled
contents: await doTransformGlobImport(contents, p, loader),
resolveDir: normalizePath$3(import_node_path3.default.dirname(p)),
pluginData: {
htmlType: { loader }
}
};
} else {
scripts2[key] = {
loader,
contents,
resolveDir: normalizePath$3(import_node_path3.default.dirname(p)),
pluginData: {
htmlType: { loader }
}
};
}
const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
const contextMatch = openTag.match(contextRE);
const context = contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3]);
if (p.endsWith(".svelte") && context !== "module") {
js += `import ${virtualModulePath}
`;
} else {
js += `export * from ${virtualModulePath}
`;
}
}
}
if (!p.endsWith(".vue") || !js.includes("export default")) {
js += "\nexport default {}";
}
return {
loader: "js",
contents: js
};
};
build2.onLoad(
{ filter: htmlTypesRE, namespace: "html" },
htmlTypeOnLoadCallback
);
build2.onLoad(
{ filter: htmlTypesRE, namespace: "file" },
htmlTypeOnLoadCallback
);
build2.onResolve(
{
// avoid matching windows volume
filter: /^[\w@][^:]/
},
async ({ path: id, importer, pluginData }) => {
var _a5;
if (moduleListContains(exclude, id)) {
return externalUnlessEntry({ path: id });
}
if (depImports[id]) {
return externalUnlessEntry({ path: id });
}
const resolved = await resolve3(id, importer, {
custom: {
depScan: { loader: (_a5 = pluginData == null ? void 0 : pluginData.htmlType) == null ? void 0 : _a5.loader }
}
});
if (resolved) {
if (shouldExternalizeDep(resolved, id)) {
return externalUnlessEntry({ path: id });
}
if (isInNodeModules$1(resolved) || (include == null ? void 0 : include.includes(id))) {
if (isOptimizable(resolved, config2.optimizeDeps)) {
depImports[id] = resolved;
}
return externalUnlessEntry({ path: id });
} else if (isScannable(resolved, config2.optimizeDeps.extensions)) {
const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
return {
path: import_node_path3.default.resolve(resolved),
namespace
};
} else {
return externalUnlessEntry({ path: id });
}
} else {
missing[id] = normalizePath$3(importer);
}
}
);
const setupExternalize = (filter2, doExternalize) => {
build2.onResolve({ filter: filter2 }, ({ path: path22 }) => {
return {
path: path22,
external: doExternalize(path22)
};
});
};
setupExternalize(CSS_LANGS_RE, isUnlessEntry);
setupExternalize(/\.(json|json5|wasm)$/, isUnlessEntry);
setupExternalize(
new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`),
isUnlessEntry
);
setupExternalize(SPECIAL_QUERY_RE, () => true);
build2.onResolve(
{
filter: /.*/
},
async ({ path: id, importer, pluginData }) => {
var _a5;
const resolved = await resolve3(id, importer, {
custom: {
depScan: { loader: (_a5 = pluginData == null ? void 0 : pluginData.htmlType) == null ? void 0 : _a5.loader }
}
});
if (resolved) {
if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, config2.optimizeDeps.extensions)) {
return externalUnlessEntry({ path: id });
}
const namespace = htmlTypesRE.test(resolved) ? "html" : void 0;
return {
path: import_node_path3.default.resolve(cleanUrl(resolved)),
namespace
};
} else {
return externalUnlessEntry({ path: id });
}
}
);
build2.onLoad({ filter: JS_TYPES_RE }, async ({ path: id }) => {
var _a5, _b4, _c2;
let ext2 = import_node_path3.default.extname(id).slice(1);
if (ext2 === "mjs") ext2 = "js";
let contents = await import_promises.default.readFile(id, "utf-8");
if (ext2.endsWith("x") && config2.esbuild && config2.esbuild.jsxInject) {
contents = config2.esbuild.jsxInject + `
` + contents;
}
const loader = ((_c2 = (_b4 = (_a5 = config2.optimizeDeps) == null ? void 0 : _a5.esbuildOptions) == null ? void 0 : _b4.loader) == null ? void 0 : _c2[`.${ext2}`]) || ext2;
if (contents.includes("import.meta.glob")) {
return {
loader: "js",
// since it is transpiled,
contents: await doTransformGlobImport(contents, id, loader)
};
}
return {
loader,
contents
};
});
build2.onLoad({ filter: /.*/, namespace: "file" }, () => {
return {
loader: "js",
contents: "export default {}"
};
});
}
};
}
function extractImportPaths(code) {
code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
let js = "";
let m;
importsRE.lastIndex = 0;
while ((m = importsRE.exec(code)) != null) {
js += `
import ${m[1]}`;
}
return js;
}
function shouldExternalizeDep(resolvedId, rawId) {
if (!import_node_path3.default.isAbsolute(resolvedId)) {
return true;
}
if (resolvedId === rawId || resolvedId.includes("\0")) {
return true;
}
return false;
}
function isScannable(id, extensions2) {
return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || (extensions2 == null ? void 0 : extensions2.includes(import_node_path3.default.extname(id))) || false;
}
function createOptimizeDepsIncludeResolver(config2, ssr) {
const resolve3 = config2.createResolver({
asSrc: false,
scan: true,
ssrOptimizeCheck: ssr,
ssrConfig: config2.ssr,
packageCache: /* @__PURE__ */ new Map()
});
return async (id) => {
const lastArrowIndex = id.lastIndexOf(">");
if (lastArrowIndex === -1) {
return await resolve3(id, void 0, void 0, ssr);
}
const nestedRoot = id.substring(0, lastArrowIndex).trim();
const nestedPath = id.substring(lastArrowIndex + 1).trim();
const basedir = nestedResolveBasedir(
nestedRoot,
config2.root,
config2.resolve.preserveSymlinks
);
return await resolve3(
nestedPath,
import_node_path3.default.resolve(basedir, "package.json"),
void 0,
ssr
);
};
}
function expandGlobIds(id, config2) {
const pkgName = getNpmPackageName(id);
if (!pkgName) return [];
const pkgData = resolvePackageData(
pkgName,
config2.root,
config2.resolve.preserveSymlinks,
config2.packageCache
);
if (!pkgData) return [];
const pattern2 = "." + id.slice(pkgName.length);
const exports2 = pkgData.data.exports;
if (exports2) {
if (typeof exports2 === "string" || Array.isArray(exports2)) {
return [pkgName];
}
const possibleExportPaths = [];
for (const key in exports2) {
if (key[0] === ".") {
if (key.includes("*")) {
const exportsValue = getFirstExportStringValue(exports2[key]);
if (!exportsValue) continue;
const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
const exportsValueGlobRe = new RegExp(
exportsValue.split("*").map(escapeRegex).join("(.*)")
);
possibleExportPaths.push(
...glob.sync(exportValuePattern, {
cwd: pkgData.dir,
ignore: ["node_modules"]
}).map((filePath) => {
if (exportsValue.startsWith("./") && !filePath.startsWith("./")) {
filePath = "./" + filePath;
}
const matched2 = slash$1(filePath).match(exportsValueGlobRe);
if (matched2) {
let allGlobSame = matched2.length === 2;
if (!allGlobSame) {
allGlobSame = true;
for (let i = 2; i < matched2.length; i++) {
if (matched2[i] !== matched2[i - 1]) {
allGlobSame = false;
break;
}
}
}
if (allGlobSame) {
return key.replace("*", matched2[1]).slice(2);
}
}
return "";
}).filter(Boolean)
);
} else {
possibleExportPaths.push(key.slice(2));
}
}
}
const matched = micromatch$2(possibleExportPaths, pattern2).map(
(match2) => import_node_path3.default.posix.join(pkgName, match2)
);
matched.unshift(pkgName);
return matched;
} else {
const matched = glob.sync(pattern2, { cwd: pkgData.dir, ignore: ["node_modules"] }).map((match2) => import_node_path3.default.posix.join(pkgName, slash$1(match2)));
matched.unshift(pkgName);
return matched;
}
}
function getFirstExportStringValue(obj) {
if (typeof obj === "string") {
return obj;
} else if (Array.isArray(obj)) {
return obj[0];
} else {
for (const key in obj) {
return getFirstExportStringValue(obj[key]);
}
}
}
function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
var _a4;
const pkgs = id.split(">").map((pkg) => pkg.trim());
for (const pkg of pkgs) {
basedir = ((_a4 = resolvePackageData(pkg, basedir, preserveSymlinks)) == null ? void 0 : _a4.dir) || basedir;
}
return basedir;
}
var debug$8 = createDebugger("vite:deps");
var debounceMs = 100;
var depsOptimizerMap = /* @__PURE__ */ new WeakMap();
var devSsrDepsOptimizerMap = /* @__PURE__ */ new WeakMap();
function getDepsOptimizer(config2, ssr) {
return (ssr ? devSsrDepsOptimizerMap : depsOptimizerMap).get(config2);
}
async function initDepsOptimizer(config2, server2) {
if (!getDepsOptimizer(config2, false)) {
await createDepsOptimizer(config2, server2);
}
}
var creatingDevSsrOptimizer;
async function initDevSsrDepsOptimizer(config2, server2) {
if (getDepsOptimizer(config2, true)) {
return;
}
if (creatingDevSsrOptimizer) {
return creatingDevSsrOptimizer;
}
creatingDevSsrOptimizer = async function() {
const ssr = false;
if (!getDepsOptimizer(config2, ssr)) {
await initDepsOptimizer(config2, server2);
}
await getDepsOptimizer(config2, ssr).scanProcessing;
await createDevSsrDepsOptimizer(config2);
creatingDevSsrOptimizer = void 0;
}();
return await creatingDevSsrOptimizer;
}
async function createDepsOptimizer(config2, server2) {
const { logger } = config2;
const ssr = false;
const sessionTimestamp = Date.now().toString();
const cachedMetadata = await loadCachedDepOptimizationMetadata(config2, ssr);
let debounceProcessingHandle;
let closed = false;
let metadata = cachedMetadata || initDepsOptimizerMetadata(config2, ssr, sessionTimestamp);
const options2 = getDepOptimizationConfig(config2, ssr);
const { noDiscovery, holdUntilCrawlEnd } = options2;
const depsOptimizer = {
metadata,
registerMissingImport,
run: () => debouncedProcessing(0),
isOptimizedDepFile: createIsOptimizedDepFile(config2),
isOptimizedDepUrl: createIsOptimizedDepUrl(config2),
getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
close: close2,
options: options2
};
depsOptimizerMap.set(config2, depsOptimizer);
let newDepsDiscovered = false;
let newDepsToLog = [];
let newDepsToLogHandle;
const logNewlyDiscoveredDeps = () => {
if (newDepsToLog.length) {
config2.logger.info(
colors$1.green(
`✨ new dependencies optimized: ${depsLogString(newDepsToLog)}`
),
{
timestamp: true
}
);
newDepsToLog = [];
}
};
let discoveredDepsWhileScanning = [];
const logDiscoveredDepsWhileScanning = () => {
if (discoveredDepsWhileScanning.length) {
config2.logger.info(
colors$1.green(
`✨ discovered while scanning: ${depsLogString(
discoveredDepsWhileScanning
)}`
),
{
timestamp: true
}
);
discoveredDepsWhileScanning = [];
}
};
let depOptimizationProcessing = promiseWithResolvers();
let depOptimizationProcessingQueue = [];
const resolveEnqueuedProcessingPromises = () => {
for (const processing of depOptimizationProcessingQueue) {
processing.resolve();
}
depOptimizationProcessingQueue = [];
};
let enqueuedRerun;
let currentlyProcessing = false;
let firstRunCalled = !!cachedMetadata;
let warnAboutMissedDependencies = false;
let waitingForCrawlEnd = false;
if (!cachedMetadata) {
server2._onCrawlEnd(onCrawlEnd);
waitingForCrawlEnd = true;
}
let optimizationResult;
let discover;
async function close2() {
closed = true;
await Promise.allSettled([
discover == null ? void 0 : discover.cancel(),
depsOptimizer.scanProcessing,
optimizationResult == null ? void 0 : optimizationResult.cancel()
]);
}
if (!cachedMetadata) {
currentlyProcessing = true;
const manuallyIncludedDeps = {};
await addManuallyIncludedOptimizeDeps(manuallyIncludedDeps, config2, ssr);
const manuallyIncludedDepsInfo = toDiscoveredDependencies(
config2,
manuallyIncludedDeps,
ssr,
sessionTimestamp
);
for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
addOptimizedDepInfo(metadata, "discovered", {
...depInfo,
processing: depOptimizationProcessing.promise
});
newDepsDiscovered = true;
}
if (noDiscovery) {
runOptimizer();
} else {
depsOptimizer.scanProcessing = new Promise((resolve3) => {
(async () => {
try {
debug$8 == null ? void 0 : debug$8(colors$1.green(`scanning for dependencies...`));
discover = discoverProjectDependencies(config2);
const deps = await discover.result;
discover = void 0;
const manuallyIncluded = Object.keys(manuallyIncludedDepsInfo);
discoveredDepsWhileScanning.push(
...Object.keys(metadata.discovered).filter(
(dep) => !deps[dep] && !manuallyIncluded.includes(dep)
)
);
for (const id of Object.keys(deps)) {
if (!metadata.discovered[id]) {
addMissingDep(id, deps[id]);
}
}
const knownDeps = prepareKnownDeps();
startNextDiscoveredBatch();
optimizationResult = runOptimizeDeps(config2, knownDeps, ssr);
if (!holdUntilCrawlEnd) {
optimizationResult.result.then((result) => {
if (!waitingForCrawlEnd) return;
optimizationResult = void 0;
runOptimizer(result);
});
}
} catch (e2) {
logger.error(e2.stack || e2.message);
} finally {
resolve3();
depsOptimizer.scanProcessing = void 0;
}
})();
});
}
}
function startNextDiscoveredBatch() {
newDepsDiscovered = false;
depOptimizationProcessingQueue.push(depOptimizationProcessing);
depOptimizationProcessing = promiseWithResolvers();
}
function prepareKnownDeps() {
const knownDeps = {};
for (const dep of Object.keys(metadata.optimized)) {
knownDeps[dep] = { ...metadata.optimized[dep] };
}
for (const dep of Object.keys(metadata.discovered)) {
const { processing, ...info } = metadata.discovered[dep];
knownDeps[dep] = info;
}
return knownDeps;
}
async function runOptimizer(preRunResult) {
const isRerun = firstRunCalled;
firstRunCalled = true;
enqueuedRerun = void 0;
if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
if (closed) {
currentlyProcessing = false;
return;
}
currentlyProcessing = true;
try {
let processingResult;
if (preRunResult) {
processingResult = preRunResult;
} else {
const knownDeps = prepareKnownDeps();
startNextDiscoveredBatch();
optimizationResult = runOptimizeDeps(config2, knownDeps, ssr);
processingResult = await optimizationResult.result;
optimizationResult = void 0;
}
if (closed) {
currentlyProcessing = false;
processingResult.cancel();
resolveEnqueuedProcessingPromises();
return;
}
const newData = processingResult.metadata;
const needsInteropMismatch = findInteropMismatches(
metadata.discovered,
newData.optimized
);
const needsReload = needsInteropMismatch.length > 0 || metadata.hash !== newData.hash || Object.keys(metadata.optimized).some((dep) => {
return metadata.optimized[dep].fileHash !== newData.optimized[dep].fileHash;
});
const commitProcessing = async () => {
await processingResult.commit();
for (const id in metadata.discovered) {
if (!newData.optimized[id]) {
addOptimizedDepInfo(newData, "discovered", metadata.discovered[id]);
}
}
if (!needsReload) {
newData.browserHash = metadata.browserHash;
for (const dep in newData.chunks) {
newData.chunks[dep].browserHash = metadata.browserHash;
}
for (const dep in newData.optimized) {
newData.optimized[dep].browserHash = (metadata.optimized[dep] || metadata.discovered[dep]).browserHash;
}
}
for (const o2 in newData.optimized) {
const discovered = metadata.discovered[o2];
if (discovered) {
const optimized = newData.optimized[o2];
discovered.browserHash = optimized.browserHash;
discovered.fileHash = optimized.fileHash;
discovered.needsInterop = optimized.needsInterop;
discovered.processing = void 0;
}
}
if (isRerun) {
newDepsToLog.push(
...Object.keys(newData.optimized).filter(
(dep) => !metadata.optimized[dep]
)
);
}
metadata = depsOptimizer.metadata = newData;
resolveEnqueuedProcessingPromises();
};
if (!needsReload) {
await commitProcessing();
if (!debug$8) {
if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
newDepsToLogHandle = setTimeout(() => {
newDepsToLogHandle = void 0;
logNewlyDiscoveredDeps();
if (warnAboutMissedDependencies) {
logDiscoveredDepsWhileScanning();
config2.logger.info(
colors$1.magenta(
`❗ add these dependencies to optimizeDeps.include to speed up cold start`
),
{ timestamp: true }
);
warnAboutMissedDependencies = false;
}
}, 2 * debounceMs);
} else {
debug$8(
colors$1.green(
`✨ ${!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`}`
)
);
}
} else {
if (newDepsDiscovered) {
processingResult.cancel();
debug$8 == null ? void 0 : debug$8(
colors$1.green(
`✨ delaying reload as new dependencies have been found...`
)
);
} else {
await commitProcessing();
if (!debug$8) {
if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
newDepsToLogHandle = void 0;
logNewlyDiscoveredDeps();
if (warnAboutMissedDependencies) {
logDiscoveredDepsWhileScanning();
config2.logger.info(
colors$1.magenta(
`❗ add these dependencies to optimizeDeps.include to avoid a full page reload during cold start`
),
{ timestamp: true }
);
warnAboutMissedDependencies = false;
}
}
logger.info(
colors$1.green(`✨ optimized dependencies changed. reloading`),
{
timestamp: true
}
);
if (needsInteropMismatch.length > 0) {
config2.logger.warn(
`Mixed ESM and CJS detected in ${colors$1.yellow(
needsInteropMismatch.join(", ")
)}, add ${needsInteropMismatch.length === 1 ? "it" : "them"} to optimizeDeps.needsInterop to speed up cold start`,
{
timestamp: true
}
);
}
fullReload();
}
}
} catch (e2) {
logger.error(
colors$1.red(`error while updating dependencies:
${e2.stack}`),
{ timestamp: true, error: e2 }
);
resolveEnqueuedProcessingPromises();
metadata.discovered = {};
}
currentlyProcessing = false;
enqueuedRerun == null ? void 0 : enqueuedRerun();
}
function fullReload() {
server2.moduleGraph.invalidateAll();
server2.hot.send({
type: "full-reload",
path: "*"
});
}
async function rerun() {
const deps = Object.keys(metadata.discovered);
const depsString = depsLogString(deps);
debug$8 == null ? void 0 : debug$8(colors$1.green(`new dependencies found: ${depsString}`));
runOptimizer();
}
function getDiscoveredBrowserHash(hash2, deps, missing) {
return getHash(
hash2 + JSON.stringify(deps) + JSON.stringify(missing) + sessionTimestamp
);
}
function registerMissingImport(id, resolved) {
const optimized = metadata.optimized[id];
if (optimized) {
return optimized;
}
const chunk = metadata.chunks[id];
if (chunk) {
return chunk;
}
let missing = metadata.discovered[id];
if (missing) {
return missing;
}
missing = addMissingDep(id, resolved);
if (!waitingForCrawlEnd) {
debouncedProcessing();
}
return missing;
}
function addMissingDep(id, resolved) {
newDepsDiscovered = true;
return addOptimizedDepInfo(metadata, "discovered", {
id,
file: getOptimizedDepPath(id, config2, ssr),
src: resolved,
// Adding a browserHash to this missing dependency that is unique to
// the current state of known + missing deps. If its optimizeDeps run
// doesn't alter the bundled files of previous known dependencies,
// we don't need a full reload and this browserHash will be kept
browserHash: getDiscoveredBrowserHash(
metadata.hash,
depsFromOptimizedDepInfo(metadata.optimized),
depsFromOptimizedDepInfo(metadata.discovered)
),
// loading of this pre-bundled dep needs to await for its processing
// promise to be resolved
processing: depOptimizationProcessing.promise,
exportsData: extractExportsData(resolved, config2, ssr)
});
}
function debouncedProcessing(timeout2 = debounceMs) {
enqueuedRerun = void 0;
if (debounceProcessingHandle) clearTimeout(debounceProcessingHandle);
if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
newDepsToLogHandle = void 0;
debounceProcessingHandle = setTimeout(() => {
debounceProcessingHandle = void 0;
enqueuedRerun = rerun;
if (!currentlyProcessing) {
enqueuedRerun();
}
}, timeout2);
}
async function onCrawlEnd() {
waitingForCrawlEnd = false;
debug$8 == null ? void 0 : debug$8(colors$1.green(`✨ static imports crawl ended`));
if (closed) {
return;
}
await depsOptimizer.scanProcessing;
if (optimizationResult && !config2.optimizeDeps.noDiscovery) {
const afterScanResult = optimizationResult.result;
optimizationResult = void 0;
const result = await afterScanResult;
currentlyProcessing = false;
const crawlDeps = Object.keys(metadata.discovered);
const scanDeps = Object.keys(result.metadata.optimized);
if (scanDeps.length === 0 && crawlDeps.length === 0) {
debug$8 == null ? void 0 : debug$8(
colors$1.green(
`✨ no dependencies found by the scanner or crawling static imports`
)
);
startNextDiscoveredBatch();
runOptimizer(result);
return;
}
const needsInteropMismatch = findInteropMismatches(
metadata.discovered,
result.metadata.optimized
);
const scannerMissedDeps = crawlDeps.some((dep) => !scanDeps.includes(dep));
const outdatedResult = needsInteropMismatch.length > 0 || scannerMissedDeps;
if (outdatedResult) {
result.cancel();
for (const dep of scanDeps) {
if (!crawlDeps.includes(dep)) {
addMissingDep(dep, result.metadata.optimized[dep].src);
}
}
if (scannerMissedDeps) {
debug$8 == null ? void 0 : debug$8(
colors$1.yellow(
`✨ new dependencies were found while crawling that weren't detected by the scanner`
)
);
}
debug$8 == null ? void 0 : debug$8(colors$1.green(`✨ re-running optimizer`));
debouncedProcessing(0);
} else {
debug$8 == null ? void 0 : debug$8(
colors$1.green(
`✨ using post-scan optimizer result, the scanner found every used dependency`
)
);
startNextDiscoveredBatch();
runOptimizer(result);
}
} else if (!holdUntilCrawlEnd) {
if (newDepsDiscovered) {
debug$8 == null ? void 0 : debug$8(
colors$1.green(
`✨ new dependencies were found while crawling static imports, re-running optimizer`
)
);
warnAboutMissedDependencies = true;
debouncedProcessing(0);
}
} else {
const crawlDeps = Object.keys(metadata.discovered);
currentlyProcessing = false;
if (crawlDeps.length === 0) {
debug$8 == null ? void 0 : debug$8(
colors$1.green(
`✨ no dependencies found while crawling the static imports`
)
);
firstRunCalled = true;
}
debouncedProcessing(0);
}
}
}
async function createDevSsrDepsOptimizer(config2) {
const metadata = await optimizeServerSsrDeps(config2);
const depsOptimizer = {
metadata,
isOptimizedDepFile: createIsOptimizedDepFile(config2),
isOptimizedDepUrl: createIsOptimizedDepUrl(config2),
getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
registerMissingImport: () => {
throw new Error(
"Vite Internal Error: registerMissingImport is not supported in dev SSR"
);
},
// noop, there is no scanning during dev SSR
// the optimizer blocks the server start
run: () => {
},
close: async () => {
},
options: config2.ssr.optimizeDeps
};
devSsrDepsOptimizerMap.set(config2, depsOptimizer);
}
function findInteropMismatches(discovered, optimized) {
const needsInteropMismatch = [];
for (const dep in discovered) {
const discoveredDepInfo = discovered[dep];
if (discoveredDepInfo.needsInterop === void 0) continue;
const depInfo = optimized[dep];
if (!depInfo) continue;
if (depInfo.needsInterop !== discoveredDepInfo.needsInterop) {
needsInteropMismatch.push(dep);
debug$8 == null ? void 0 : debug$8(colors$1.cyan(`✨ needsInterop mismatch detected for ${dep}`));
}
}
return needsInteropMismatch;
}
var debug$7 = createDebugger("vite:deps");
var jsExtensionRE = /\.js$/i;
var jsMapExtensionRE = /\.js\.map$/i;
async function optimizeDeps(config2, force = config2.optimizeDeps.force, asCommand = false) {
const log = asCommand ? config2.logger.info : debug$7;
const ssr = false;
const cachedMetadata = await loadCachedDepOptimizationMetadata(
config2,
ssr,
force,
asCommand
);
if (cachedMetadata) {
return cachedMetadata;
}
const deps = await discoverProjectDependencies(config2).result;
await addManuallyIncludedOptimizeDeps(deps, config2, ssr);
const depsString = depsLogString(Object.keys(deps));
log == null ? void 0 : log(colors$1.green(`Optimizing dependencies:
${depsString}`));
const depsInfo = toDiscoveredDependencies(config2, deps, ssr);
const result = await runOptimizeDeps(config2, depsInfo, ssr).result;
await result.commit();
return result.metadata;
}
async function optimizeServerSsrDeps(config2) {
const ssr = true;
const cachedMetadata = await loadCachedDepOptimizationMetadata(
config2,
ssr,
config2.optimizeDeps.force,
false
);
if (cachedMetadata) {
return cachedMetadata;
}
const deps = {};
await addManuallyIncludedOptimizeDeps(deps, config2, ssr);
const depsInfo = toDiscoveredDependencies(config2, deps, ssr);
const result = await runOptimizeDeps(config2, depsInfo, ssr).result;
await result.commit();
return result.metadata;
}
function initDepsOptimizerMetadata(config2, ssr, timestamp2) {
const { lockfileHash, configHash, hash: hash2 } = getDepHash(config2, ssr);
return {
hash: hash2,
lockfileHash,
configHash,
browserHash: getOptimizedBrowserHash(hash2, {}, timestamp2),
optimized: {},
chunks: {},
discovered: {},
depInfoList: []
};
}
function addOptimizedDepInfo(metadata, type, depInfo) {
metadata[type][depInfo.id] = depInfo;
metadata.depInfoList.push(depInfo);
return depInfo;
}
var firstLoadCachedDepOptimizationMetadata = true;
async function loadCachedDepOptimizationMetadata(config2, ssr, force = config2.optimizeDeps.force, asCommand = false) {
const log = asCommand ? config2.logger.info : debug$7;
if (firstLoadCachedDepOptimizationMetadata) {
firstLoadCachedDepOptimizationMetadata = false;
setTimeout(() => cleanupDepsCacheStaleDirs(config2), 0);
}
const depsCacheDir = getDepsCacheDir(config2, ssr);
if (!force) {
let cachedMetadata;
try {
const cachedMetadataPath = import_node_path3.default.join(depsCacheDir, METADATA_FILENAME);
cachedMetadata = parseDepsOptimizerMetadata(
await import_promises.default.readFile(cachedMetadataPath, "utf-8"),
depsCacheDir
);
} catch (e2) {
}
if (cachedMetadata) {
if (cachedMetadata.lockfileHash !== getLockfileHash(config2)) {
config2.logger.info(
"Re-optimizing dependencies because lockfile has changed"
);
} else if (cachedMetadata.configHash !== getConfigHash(config2, ssr)) {
config2.logger.info(
"Re-optimizing dependencies because vite config has changed"
);
} else {
log == null ? void 0 : log("Hash is consistent. Skipping. Use --force to override.");
return cachedMetadata;
}
}
} else {
config2.logger.info("Forced re-optimization of dependencies");
}
debug$7 == null ? void 0 : debug$7(colors$1.green(`removing old cache dir ${depsCacheDir}`));
await import_promises.default.rm(depsCacheDir, { recursive: true, force: true });
}
function discoverProjectDependencies(config2) {
const { cancel, result } = scanImports(config2);
return {
cancel,
result: result.then(({ deps, missing }) => {
const missingIds = Object.keys(missing);
if (missingIds.length) {
throw new Error(
`The following dependencies are imported but could not be resolved:
${missingIds.map(
(id) => `${colors$1.cyan(id)} ${colors$1.white(
colors$1.dim(`(imported by ${missing[id]})`)
)}`
).join(`
`)}
Are they installed?`
);
}
return deps;
})
};
}
function toDiscoveredDependencies(config2, deps, ssr, timestamp2) {
const browserHash = getOptimizedBrowserHash(
getDepHash(config2, ssr).hash,
deps,
timestamp2
);
const discovered = {};
for (const id in deps) {
const src2 = deps[id];
discovered[id] = {
id,
file: getOptimizedDepPath(id, config2, ssr),
src: src2,
browserHash,
exportsData: extractExportsData(src2, config2, ssr)
};
}
return discovered;
}
function depsLogString(qualifiedIds) {
return colors$1.yellow(qualifiedIds.join(`, `));
}
function runOptimizeDeps(resolvedConfig, depsInfo, ssr) {
const optimizerContext = { cancelled: false };
const config2 = {
...resolvedConfig,
command: "build"
};
const depsCacheDir = getDepsCacheDir(resolvedConfig, ssr);
const processingCacheDir = getProcessingDepsCacheDir(resolvedConfig, ssr);
import_node_fs2.default.mkdirSync(processingCacheDir, { recursive: true });
debug$7 == null ? void 0 : debug$7(colors$1.green(`creating package.json in ${processingCacheDir}`));
import_node_fs2.default.writeFileSync(
import_node_path3.default.resolve(processingCacheDir, "package.json"),
`{
"type": "module"
}
`
);
const metadata = initDepsOptimizerMetadata(config2, ssr);
metadata.browserHash = getOptimizedBrowserHash(
metadata.hash,
depsFromOptimizedDepInfo(depsInfo)
);
const qualifiedIds = Object.keys(depsInfo);
let cleaned = false;
let committed = false;
const cleanUp = () => {
if (!cleaned && !committed) {
cleaned = true;
debug$7 == null ? void 0 : debug$7(colors$1.green(`removing cache dir ${processingCacheDir}`));
try {
import_node_fs2.default.rmSync(processingCacheDir, { recursive: true, force: true });
} catch (error2) {
}
}
};
const successfulResult = {
metadata,
cancel: cleanUp,
commit: async () => {
if (cleaned) {
throw new Error(
"Can not commit a Deps Optimization run as it was cancelled"
);
}
committed = true;
const dataPath = import_node_path3.default.join(processingCacheDir, METADATA_FILENAME);
debug$7 == null ? void 0 : debug$7(
colors$1.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`)
);
import_node_fs2.default.writeFileSync(
dataPath,
stringifyDepsOptimizerMetadata(metadata, depsCacheDir)
);
const temporaryPath = depsCacheDir + getTempSuffix();
const depsCacheDirPresent = import_node_fs2.default.existsSync(depsCacheDir);
if (isWindows$3) {
if (depsCacheDirPresent) {
debug$7 == null ? void 0 : debug$7(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
await safeRename(depsCacheDir, temporaryPath);
}
debug$7 == null ? void 0 : debug$7(
colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`)
);
await safeRename(processingCacheDir, depsCacheDir);
} else {
if (depsCacheDirPresent) {
debug$7 == null ? void 0 : debug$7(colors$1.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
import_node_fs2.default.renameSync(depsCacheDir, temporaryPath);
}
debug$7 == null ? void 0 : debug$7(
colors$1.green(`renaming ${processingCacheDir} to ${depsCacheDir}`)
);
import_node_fs2.default.renameSync(processingCacheDir, depsCacheDir);
}
if (depsCacheDirPresent) {
debug$7 == null ? void 0 : debug$7(colors$1.green(`removing cache temp dir ${temporaryPath}`));
import_promises.default.rm(temporaryPath, { recursive: true, force: true });
}
}
};
if (!qualifiedIds.length) {
return {
cancel: async () => cleanUp(),
result: Promise.resolve(successfulResult)
};
}
const cancelledResult = {
metadata,
commit: async () => cleanUp(),
cancel: cleanUp
};
const start = import_node_perf_hooks.performance.now();
const preparedRun = prepareEsbuildOptimizerRun(
resolvedConfig,
depsInfo,
ssr,
processingCacheDir,
optimizerContext
);
const runResult = preparedRun.then(({ context, idToExports }) => {
function disposeContext() {
return context == null ? void 0 : context.dispose().catch((e2) => {
config2.logger.error("Failed to dispose esbuild context", { error: e2 });
});
}
if (!context || optimizerContext.cancelled) {
disposeContext();
return cancelledResult;
}
return context.rebuild().then((result) => {
const meta = result.metafile;
const processingCacheDirOutputPath = import_node_path3.default.relative(
process.cwd(),
processingCacheDir
);
for (const id in depsInfo) {
const output = esbuildOutputFromId(
meta.outputs,
id,
processingCacheDir
);
const { exportsData, ...info } = depsInfo[id];
addOptimizedDepInfo(metadata, "optimized", {
...info,
// We only need to hash the output.imports in to check for stability, but adding the hash
// and file path gives us a unique hash that may be useful for other things in the future
fileHash: getHash(
metadata.hash + depsInfo[id].file + JSON.stringify(output.imports)
),
browserHash: metadata.browserHash,
// After bundling we have more information and can warn the user about legacy packages
// that require manual configuration
needsInterop: needsInterop(
config2,
ssr,
id,
idToExports[id],
output
)
});
}
for (const o2 of Object.keys(meta.outputs)) {
if (!jsMapExtensionRE.test(o2)) {
const id = import_node_path3.default.relative(processingCacheDirOutputPath, o2).replace(jsExtensionRE, "");
const file = getOptimizedDepPath(id, resolvedConfig, ssr);
if (!findOptimizedDepInfoInRecord(
metadata.optimized,
(depInfo) => depInfo.file === file
)) {
addOptimizedDepInfo(metadata, "chunks", {
id,
file,
needsInterop: false,
browserHash: metadata.browserHash
});
}
}
}
debug$7 == null ? void 0 : debug$7(
`Dependencies bundled in ${(import_node_perf_hooks.performance.now() - start).toFixed(2)}ms`
);
return successfulResult;
}).catch((e2) => {
if (e2.errors && e2.message.includes("The build was canceled")) {
return cancelledResult;
}
throw e2;
}).finally(() => {
return disposeContext();
});
});
runResult.catch(() => {
cleanUp();
});
return {
async cancel() {
optimizerContext.cancelled = true;
const { context } = await preparedRun;
await (context == null ? void 0 : context.cancel());
cleanUp();
},
result: runResult
};
}
async function prepareEsbuildOptimizerRun(resolvedConfig, depsInfo, ssr, processingCacheDir, optimizerContext) {
var _a4;
const config2 = {
...resolvedConfig,
command: "build"
};
const flatIdDeps = {};
const idToExports = {};
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
const { plugins: pluginsFromConfig = [], ...esbuildOptions } = (optimizeDeps2 == null ? void 0 : optimizeDeps2.esbuildOptions) ?? {};
await Promise.all(
Object.keys(depsInfo).map(async (id) => {
var _a5;
const src2 = depsInfo[id].src;
const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(src2, config2, ssr));
if (exportsData.jsxLoader && !((_a5 = esbuildOptions.loader) == null ? void 0 : _a5[".js"])) {
esbuildOptions.loader = {
".js": "jsx",
...esbuildOptions.loader
};
}
const flatId = flattenId(id);
flatIdDeps[flatId] = src2;
idToExports[id] = exportsData;
})
);
if (optimizerContext.cancelled) return { context: void 0, idToExports };
const define = {
"process.env.NODE_ENV": JSON.stringify("development")
};
const platform2 = ssr && ((_a4 = config2.ssr) == null ? void 0 : _a4.target) !== "webworker" ? "node" : "browser";
const external = [...(optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) ?? []];
const plugins2 = [...pluginsFromConfig];
if (external.length) {
plugins2.push(esbuildCjsExternalPlugin(external, platform2));
}
plugins2.push(esbuildDepPlugin(flatIdDeps, external, config2, ssr));
const context = await import_esbuild.default.context({
absWorkingDir: process.cwd(),
entryPoints: Object.keys(flatIdDeps),
bundle: true,
// We can't use platform 'neutral', as esbuild has custom handling
// when the platform is 'node' or 'browser' that can't be emulated
// by using mainFields and conditions
platform: platform2,
define,
format: "esm",
// See https://github.com/evanw/esbuild/issues/1921#issuecomment-1152991694
banner: platform2 === "node" ? {
js: `import { createRequire } from 'module';const require = createRequire(import.meta.url);`
} : void 0,
target: ESBUILD_MODULES_TARGET,
external,
logLevel: "error",
splitting: true,
sourcemap: true,
outdir: processingCacheDir,
ignoreAnnotations: true,
metafile: true,
plugins: plugins2,
charset: "utf8",
...esbuildOptions,
supported: {
...defaultEsbuildSupported,
...esbuildOptions.supported
}
});
return { context, idToExports };
}
async function addManuallyIncludedOptimizeDeps(deps, config2, ssr) {
const { logger } = config2;
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
const optimizeDepsInclude = (optimizeDeps2 == null ? void 0 : optimizeDeps2.include) ?? [];
if (optimizeDepsInclude.length) {
const unableToOptimize = (id, msg) => {
if (optimizeDepsInclude.includes(id)) {
logger.warn(
`${msg}: ${colors$1.cyan(id)}, present in '${ssr ? "ssr." : ""}optimizeDeps.include'`
);
}
};
const includes = [...optimizeDepsInclude];
for (let i = 0; i < includes.length; i++) {
const id = includes[i];
if (glob.isDynamicPattern(id)) {
const globIds = expandGlobIds(id, config2);
includes.splice(i, 1, ...globIds);
i += globIds.length - 1;
}
}
const resolve3 = createOptimizeDepsIncludeResolver(config2, ssr);
for (const id of includes) {
const normalizedId = normalizeId(id);
if (!deps[normalizedId]) {
const entry2 = await resolve3(id);
if (entry2) {
if (isOptimizable(entry2, optimizeDeps2)) {
if (!entry2.endsWith("?__vite_skip_optimization")) {
deps[normalizedId] = entry2;
}
} else {
unableToOptimize(id, "Cannot optimize dependency");
}
} else {
unableToOptimize(id, "Failed to resolve dependency");
}
}
}
}
}
function depsFromOptimizedDepInfo(depsInfo) {
const obj = {};
for (const key in depsInfo) {
obj[key] = depsInfo[key].src;
}
return obj;
}
function getOptimizedDepPath(id, config2, ssr) {
return normalizePath$3(
import_node_path3.default.resolve(getDepsCacheDir(config2, ssr), flattenId(id) + ".js")
);
}
function getDepsCacheSuffix(ssr) {
return ssr ? "_ssr" : "";
}
function getDepsCacheDir(config2, ssr) {
return getDepsCacheDirPrefix(config2) + getDepsCacheSuffix(ssr);
}
function getProcessingDepsCacheDir(config2, ssr) {
return getDepsCacheDirPrefix(config2) + getDepsCacheSuffix(ssr) + getTempSuffix();
}
function getTempSuffix() {
return "_temp_" + getHash(
`${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`
);
}
function getDepsCacheDirPrefix(config2) {
return normalizePath$3(import_node_path3.default.resolve(config2.cacheDir, "deps"));
}
function createIsOptimizedDepFile(config2) {
const depsCacheDirPrefix = getDepsCacheDirPrefix(config2);
return (id) => id.startsWith(depsCacheDirPrefix);
}
function createIsOptimizedDepUrl(config2) {
const { root } = config2;
const depsCacheDir = getDepsCacheDirPrefix(config2);
const depsCacheDirRelative = normalizePath$3(import_node_path3.default.relative(root, depsCacheDir));
const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? (
// if the cache directory is outside root, the url prefix would be something
// like '/@fs/absolute/path/to/node_modules/.vite'
`/@fs/${removeLeadingSlash(normalizePath$3(depsCacheDir))}`
) : (
// if the cache directory is inside root, the url prefix would be something
// like '/node_modules/.vite'
`/${depsCacheDirRelative}`
);
return function isOptimizedDepUrl(url2) {
return url2.startsWith(depsCacheDirPrefix);
};
}
function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
const { hash: hash2, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value2) => {
if (key === "file" || key === "src") {
return normalizePath$3(import_node_path3.default.resolve(depsCacheDir, value2));
}
return value2;
});
if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) {
return;
}
const metadata = {
hash: hash2,
lockfileHash,
configHash,
browserHash,
optimized: {},
discovered: {},
chunks: {},
depInfoList: []
};
for (const id of Object.keys(optimized)) {
addOptimizedDepInfo(metadata, "optimized", {
...optimized[id],
id,
browserHash
});
}
for (const id of Object.keys(chunks)) {
addOptimizedDepInfo(metadata, "chunks", {
...chunks[id],
id,
browserHash,
needsInterop: false
});
}
return metadata;
}
function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
const { hash: hash2, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
return JSON.stringify(
{
hash: hash2,
configHash,
lockfileHash,
browserHash,
optimized: Object.fromEntries(
Object.values(optimized).map(
({ id, src: src2, file, fileHash, needsInterop: needsInterop2 }) => [
id,
{
src: src2,
file,
fileHash,
needsInterop: needsInterop2
}
]
)
),
chunks: Object.fromEntries(
Object.values(chunks).map(({ id, file }) => [id, { file }])
)
},
(key, value2) => {
if (key === "file" || key === "src") {
return normalizePath$3(import_node_path3.default.relative(depsCacheDir, value2));
}
return value2;
},
2
);
}
function esbuildOutputFromId(outputs, id, cacheDirOutputPath) {
const cwd = process.cwd();
const flatId = flattenId(id) + ".js";
const normalizedOutputPath = normalizePath$3(
import_node_path3.default.relative(cwd, import_node_path3.default.join(cacheDirOutputPath, flatId))
);
const output = outputs[normalizedOutputPath];
if (output) {
return output;
}
for (const [key, value2] of Object.entries(outputs)) {
if (normalizePath$3(import_node_path3.default.relative(cwd, key)) === normalizedOutputPath) {
return value2;
}
}
}
async function extractExportsData(filePath, config2, ssr) {
var _a4, _b3;
await init;
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
const esbuildOptions = (optimizeDeps2 == null ? void 0 : optimizeDeps2.esbuildOptions) ?? {};
if ((_a4 = optimizeDeps2.extensions) == null ? void 0 : _a4.some((ext2) => filePath.endsWith(ext2))) {
const result = await (0, import_esbuild.build)({
...esbuildOptions,
entryPoints: [filePath],
write: false,
format: "esm"
});
const [, exports22, , hasModuleSyntax2] = parse$d(result.outputFiles[0].text);
return {
hasModuleSyntax: hasModuleSyntax2,
exports: exports22.map((e2) => e2.n)
};
}
let parseResult;
let usedJsxLoader = false;
const entryContent = await import_promises.default.readFile(filePath, "utf-8");
try {
parseResult = parse$d(entryContent);
} catch {
const loader = ((_b3 = esbuildOptions.loader) == null ? void 0 : _b3[import_node_path3.default.extname(filePath)]) || "jsx";
debug$7 == null ? void 0 : debug$7(
`Unable to parse: ${filePath}.
Trying again with a ${loader} transform.`
);
const transformed = await transformWithEsbuild(entryContent, filePath, {
loader
});
parseResult = parse$d(transformed.code);
usedJsxLoader = true;
}
const [, exports2, , hasModuleSyntax] = parseResult;
const exportsData = {
hasModuleSyntax,
exports: exports2.map((e2) => e2.n),
jsxLoader: usedJsxLoader
};
return exportsData;
}
function needsInterop(config2, ssr, id, exportsData, output) {
var _a4, _b3;
if ((_b3 = (_a4 = getDepOptimizationConfig(config2, ssr)) == null ? void 0 : _a4.needsInterop) == null ? void 0 : _b3.includes(id)) {
return true;
}
const { hasModuleSyntax, exports: exports2 } = exportsData;
if (!hasModuleSyntax) {
return true;
}
if (output) {
const generatedExports = output.exports;
if (!generatedExports || isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports2)) {
return true;
}
}
return false;
}
function isSingleDefaultExport(exports2) {
return exports2.length === 1 && exports2[0] === "default";
}
var lockfileFormats = [
{ name: "package-lock.json", checkPatches: true, manager: "npm" },
{ name: "yarn.lock", checkPatches: true, manager: "yarn" },
// Included in lockfile for v2+
{ name: "pnpm-lock.yaml", checkPatches: false, manager: "pnpm" },
// Included in lockfile
{ name: "bun.lockb", checkPatches: true, manager: "bun" }
].sort((_, { manager }) => {
var _a4;
return ((_a4 = process.env.npm_config_user_agent) == null ? void 0 : _a4.startsWith(manager)) ? 1 : -1;
});
var lockfileNames = lockfileFormats.map((l) => l.name);
function getConfigHash(config2, ssr) {
var _a4, _b3;
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
const content = JSON.stringify(
{
mode: "development",
root: config2.root,
resolve: config2.resolve,
assetsInclude: config2.assetsInclude,
plugins: config2.plugins.map((p) => p.name),
optimizeDeps: {
include: (optimizeDeps2 == null ? void 0 : optimizeDeps2.include) ? unique(optimizeDeps2.include).sort() : void 0,
exclude: (optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) ? unique(optimizeDeps2.exclude).sort() : void 0,
esbuildOptions: {
...optimizeDeps2 == null ? void 0 : optimizeDeps2.esbuildOptions,
plugins: (_b3 = (_a4 = optimizeDeps2 == null ? void 0 : optimizeDeps2.esbuildOptions) == null ? void 0 : _a4.plugins) == null ? void 0 : _b3.map((p) => p.name)
}
}
},
(_, value2) => {
if (typeof value2 === "function" || value2 instanceof RegExp) {
return value2.toString();
}
return value2;
}
);
return getHash(content);
}
function getLockfileHash(config2, ssr) {
const lockfilePath = lookupFile(config2.root, lockfileNames);
let content = lockfilePath ? import_node_fs2.default.readFileSync(lockfilePath, "utf-8") : "";
if (lockfilePath) {
const lockfileName = import_node_path3.default.basename(lockfilePath);
const { checkPatches } = lockfileFormats.find(
(f2) => f2.name === lockfileName
);
if (checkPatches) {
const fullPath = import_node_path3.default.join(import_node_path3.default.dirname(lockfilePath), "patches");
const stat2 = tryStatSync(fullPath);
if (stat2 == null ? void 0 : stat2.isDirectory()) {
content += stat2.mtimeMs.toString();
}
}
}
return getHash(content);
}
function getDepHash(config2, ssr) {
const lockfileHash = getLockfileHash(config2);
const configHash = getConfigHash(config2, ssr);
const hash2 = getHash(lockfileHash + configHash);
return {
hash: hash2,
lockfileHash,
configHash
};
}
function getOptimizedBrowserHash(hash2, deps, timestamp2 = "") {
return getHash(hash2 + JSON.stringify(deps) + timestamp2);
}
function optimizedDepInfoFromId(metadata, id) {
return metadata.optimized[id] || metadata.discovered[id] || metadata.chunks[id];
}
function optimizedDepInfoFromFile(metadata, file) {
return metadata.depInfoList.find((depInfo) => depInfo.file === file);
}
function findOptimizedDepInfoInRecord(dependenciesInfo, callbackFn) {
for (const o2 of Object.keys(dependenciesInfo)) {
const info = dependenciesInfo[o2];
if (callbackFn(info, o2)) {
return info;
}
}
}
async function optimizedDepNeedsInterop(metadata, file, config2, ssr) {
const depInfo = optimizedDepInfoFromFile(metadata, file);
if ((depInfo == null ? void 0 : depInfo.src) && depInfo.needsInterop === void 0) {
depInfo.exportsData ?? (depInfo.exportsData = extractExportsData(depInfo.src, config2, ssr));
depInfo.needsInterop = needsInterop(
config2,
ssr,
depInfo.id,
await depInfo.exportsData
);
}
return depInfo == null ? void 0 : depInfo.needsInterop;
}
var MAX_TEMP_DIR_AGE_MS = 24 * 60 * 60 * 1e3;
async function cleanupDepsCacheStaleDirs(config2) {
try {
const cacheDir = import_node_path3.default.resolve(config2.cacheDir);
if (import_node_fs2.default.existsSync(cacheDir)) {
const dirents = await import_promises.default.readdir(cacheDir, { withFileTypes: true });
for (const dirent of dirents) {
if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
const tempDirPath = import_node_path3.default.resolve(config2.cacheDir, dirent.name);
const stats = await import_promises.default.stat(tempDirPath).catch((_) => null);
if ((stats == null ? void 0 : stats.mtime) && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
debug$7 == null ? void 0 : debug$7(`removing stale cache temp dir ${tempDirPath}`);
await import_promises.default.rm(tempDirPath, { recursive: true, force: true });
}
}
}
}
} catch (err2) {
config2.logger.error(err2);
}
}
var GRACEFUL_RENAME_TIMEOUT = 5e3;
var safeRename = (0, import_node_util.promisify)(function gracefulRename(from, to, cb) {
const start = Date.now();
let backoff = 0;
import_node_fs2.default.rename(from, to, function CB(er) {
if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
setTimeout(function() {
import_node_fs2.default.stat(to, function(stater, st) {
if (stater && stater.code === "ENOENT") import_node_fs2.default.rename(from, to, CB);
else CB(er);
});
}, backoff);
if (backoff < 100) backoff += 10;
return;
}
if (cb) cb(er);
});
});
function totalist(dir, callback, pre = "") {
dir = (0, import_path.resolve)(".", dir);
let arr = (0, import_fs.readdirSync)(dir);
let i = 0, abs, stats;
for (; i < arr.length; i++) {
abs = (0, import_path.join)(dir, arr[i]);
stats = (0, import_fs.statSync)(abs);
stats.isDirectory() ? totalist(abs, callback, (0, import_path.join)(pre, arr[i])) : callback((0, import_path.join)(pre, arr[i]), abs, stats);
}
}
function parse$5(req2) {
let raw = req2.url;
if (raw == null) return;
let prev = req2._parsedUrl;
if (prev && prev.raw === raw) return prev;
let pathname = raw, search = "", query;
if (raw.length > 1) {
let idx = raw.indexOf("?", 1);
if (idx !== -1) {
search = raw.substring(idx);
pathname = raw.substring(0, idx);
if (search.length > 1) {
query = qs.parse(search.substring(1));
}
}
}
return req2._parsedUrl = { pathname, search, query, raw };
}
var noop$2 = () => {
};
function isMatch(uri, arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].test(uri)) return true;
}
}
function toAssume(uri, extns) {
let i = 0, x, len = uri.length - 1;
if (uri.charCodeAt(len) === 47) {
uri = uri.substring(0, len);
}
let arr = [], tmp = `${uri}/index`;
for (; i < extns.length; i++) {
x = extns[i] ? `.${extns[i]}` : "";
if (uri) arr.push(uri + x);
arr.push(tmp + x);
}
return arr;
}
function viaCache(cache, uri, extns) {
let i = 0, data, arr = toAssume(uri, extns);
for (; i < arr.length; i++) {
if (data = cache[arr[i]]) return data;
}
}
function viaLocal(dir, isEtag, uri, extns, shouldServe) {
let i = 0, arr = toAssume(uri, extns);
let abs, stats, name2, headers;
for (; i < arr.length; i++) {
abs = (0, import_path.normalize)((0, import_path.join)(dir, name2 = arr[i]));
if (abs.startsWith(dir) && require$$0$2.existsSync(abs)) {
stats = require$$0$2.statSync(abs);
if (stats.isDirectory()) continue;
if (shouldServe && !shouldServe(abs)) continue;
headers = toHeaders(name2, stats, isEtag);
headers["Cache-Control"] = isEtag ? "no-cache" : "no-store";
return { abs, stats, headers };
}
}
}
function is404(req2, res) {
return res.statusCode = 404, res.end();
}
function send$1(req2, res, file, stats, headers) {
let code = 200, tmp, opts = {};
headers = { ...headers };
for (let key in headers) {
tmp = res.getHeader(key);
if (tmp) headers[key] = tmp;
}
if (tmp = res.getHeader("content-type")) {
headers["Content-Type"] = tmp;
}
if (req2.headers.range) {
code = 206;
let [x, y] = req2.headers.range.replace("bytes=", "").split("-");
let end = opts.end = parseInt(y, 10) || stats.size - 1;
let start = opts.start = parseInt(x, 10) || 0;
if (end >= stats.size) {
end = stats.size - 1;
}
if (start >= stats.size) {
res.setHeader("Content-Range", `bytes */${stats.size}`);
res.statusCode = 416;
return res.end();
}
headers["Content-Range"] = `bytes ${start}-${end}/${stats.size}`;
headers["Content-Length"] = end - start + 1;
headers["Accept-Ranges"] = "bytes";
}
res.writeHead(code, headers);
require$$0$2.createReadStream(file, opts).pipe(res);
}
var ENCODING = {
".br": "br",
".gz": "gzip"
};
function toHeaders(name2, stats, isEtag) {
let enc = ENCODING[name2.slice(-3)];
let ctype = lookup(name2.slice(0, enc && -3)) || "";
if (ctype === "text/html") ctype += ";charset=utf-8";
let headers = {
"Content-Length": stats.size,
"Content-Type": ctype,
"Last-Modified": stats.mtime.toUTCString()
};
if (enc) headers["Content-Encoding"] = enc;
if (isEtag) headers["ETag"] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
return headers;
}
function sirv(dir, opts = {}) {
dir = (0, import_path.resolve)(dir || ".");
let isNotFound = opts.onNoMatch || is404;
let setHeaders2 = opts.setHeaders || noop$2;
let extensions2 = opts.extensions || ["html", "htm"];
let gzips = opts.gzip && extensions2.map((x) => `${x}.gz`).concat("gz");
let brots = opts.brotli && extensions2.map((x) => `${x}.br`).concat("br");
const FILES = {};
let fallback = "/";
let isEtag = !!opts.etag;
let isSPA = !!opts.single;
if (typeof opts.single === "string") {
let idx = opts.single.lastIndexOf(".");
fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
}
let ignores = [];
if (opts.ignores !== false) {
ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/);
if (opts.dotfiles) ignores.push(/\/\.\w/);
else ignores.push(/\/\.well-known/);
[].concat(opts.ignores || []).forEach((x) => {
ignores.push(new RegExp(x, "i"));
});
}
let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
if (cc && opts.immutable) cc += ",immutable";
else if (cc && opts.maxAge === 0) cc += ",must-revalidate";
if (!opts.dev) {
totalist(dir, (name2, abs, stats) => {
if (/\.well-known[\\+\/]/.test(name2)) ;
else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name2)) return;
let headers = toHeaders(name2, stats, isEtag);
if (cc) headers["Cache-Control"] = cc;
FILES["/" + name2.normalize().replace(/\\+/g, "/")] = { abs, stats, headers };
});
}
let lookup2 = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
return function(req2, res, next) {
let extns = [""];
let pathname = parse$5(req2).pathname;
let val = req2.headers["accept-encoding"] || "";
if (gzips && val.includes("gzip")) extns.unshift(...gzips);
if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
extns.push(...extensions2);
if (pathname.indexOf("%") !== -1) {
try {
pathname = decodeURI(pathname);
} catch (err2) {
}
}
let data = lookup2(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup2(fallback, extns, opts.shouldServe);
if (!data) return next ? next() : isNotFound(req2, res);
if (isEtag && req2.headers["if-none-match"] === data.headers["ETag"]) {
res.writeHead(304);
return res.end();
}
if (gzips || brots) {
res.setHeader("Vary", "Accept-Encoding");
}
setHeaders2(res, pathname, data.stats);
send$1(req2, res, data.abs, data.stats, data.headers);
};
}
var knownJavascriptExtensionRE = /\.[tj]sx?$/;
var sirvOptions = ({
getHeaders
}) => {
return {
dev: true,
etag: true,
extensions: [],
setHeaders(res, pathname) {
if (knownJavascriptExtensionRE.test(pathname)) {
res.setHeader("Content-Type", "text/javascript");
}
const headers = getHeaders();
if (headers) {
for (const name2 in headers) {
res.setHeader(name2, headers[name2]);
}
}
}
};
};
function servePublicMiddleware(server2, publicFiles) {
const dir = server2.config.publicDir;
const serve = sirv(
dir,
sirvOptions({
getHeaders: () => server2.config.server.headers
})
);
const toFilePath = (url2) => {
let filePath = cleanUrl(url2);
if (filePath.indexOf("%") !== -1) {
try {
filePath = decodeURI(filePath);
} catch (err2) {
}
}
return normalizePath$3(filePath);
};
return function viteServePublicMiddleware(req2, res, next) {
if (publicFiles && !publicFiles.has(toFilePath(req2.url)) || isImportRequest(req2.url) || isInternalRequest(req2.url)) {
return next();
}
serve(req2, res, next);
};
}
function serveStaticMiddleware(server2) {
const dir = server2.config.root;
const serve = sirv(
dir,
sirvOptions({
getHeaders: () => server2.config.server.headers
})
);
return function viteServeStaticMiddleware(req2, res, next) {
const cleanedUrl = cleanUrl(req2.url);
if (cleanedUrl[cleanedUrl.length - 1] === "/" || import_node_path3.default.extname(cleanedUrl) === ".html" || isInternalRequest(req2.url)) {
return next();
}
const url2 = new URL(req2.url.replace(/^\/{2,}/, "/"), "http://example.com");
const pathname = decodeURI(url2.pathname);
let redirectedPathname;
for (const { find: find2, replacement } of server2.config.resolve.alias) {
const matches2 = typeof find2 === "string" ? pathname.startsWith(find2) : find2.test(pathname);
if (matches2) {
redirectedPathname = pathname.replace(find2, replacement);
break;
}
}
if (redirectedPathname) {
if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
redirectedPathname = redirectedPathname.slice(dir.length);
}
}
const resolvedPathname = redirectedPathname || pathname;
let fileUrl = import_node_path3.default.resolve(dir, removeLeadingSlash(resolvedPathname));
if (resolvedPathname[resolvedPathname.length - 1] === "/" && fileUrl[fileUrl.length - 1] !== "/") {
fileUrl = withTrailingSlash(fileUrl);
}
if (!ensureServingAccess(fileUrl, server2, res, next)) {
return;
}
if (redirectedPathname) {
url2.pathname = encodeURI(redirectedPathname);
req2.url = url2.href.slice(url2.origin.length);
}
serve(req2, res, next);
};
}
function serveRawFsMiddleware(server2) {
const serveFromRoot = sirv(
"/",
sirvOptions({ getHeaders: () => server2.config.server.headers })
);
return function viteServeRawFsMiddleware(req2, res, next) {
const url2 = new URL(req2.url.replace(/^\/{2,}/, "/"), "http://example.com");
if (url2.pathname.startsWith(FS_PREFIX)) {
const pathname = decodeURI(url2.pathname);
if (!ensureServingAccess(
slash$1(import_node_path3.default.resolve(fsPathFromId(pathname))),
server2,
res,
next
)) {
return;
}
let newPathname = pathname.slice(FS_PREFIX.length);
if (isWindows$3) newPathname = newPathname.replace(/^[A-Z]:/i, "");
url2.pathname = encodeURI(newPathname);
req2.url = url2.href.slice(url2.origin.length);
serveFromRoot(req2, res, next);
} else {
next();
}
};
}
function isFileServingAllowed(url2, server2) {
if (!server2.config.server.fs.strict) return true;
const file = fsPathFromUrl(url2);
if (server2._fsDenyGlob(file)) return false;
if (server2.moduleGraph.safeModulesPath.has(file)) return true;
if (server2.config.server.fs.allow.some(
(uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file)
))
return true;
return false;
}
function ensureServingAccess(url2, server2, res, next) {
if (isFileServingAllowed(url2, server2)) {
return true;
}
if (isFileReadable(cleanUrl(url2))) {
const urlMessage = `The request url "${url2}" is outside of Vite serving allow list.`;
const hintMessage = `
${server2.config.server.fs.allow.map((i) => `- ${i}`).join("\n")}
Refer to docs https://vitejs.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
server2.config.logger.error(urlMessage);
server2.config.logger.warnOnce(hintMessage + "\n");
res.statusCode = 403;
res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
res.end();
} else {
next();
}
return false;
}
function renderRestrictedErrorHTML(msg) {
const html = String.raw;
return html`
<body>
<h1>403 Restricted</h1>
<p>${escapeHtml$2(msg).replace(/\n/g, "<br/>")}</p>
<style>
body {
padding: 1em 2em;
}
</style>
</body>
`;
}
var ERR_LOAD_URL = "ERR_LOAD_URL";
var ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
var debugLoad = createDebugger("vite:load");
var debugTransform = createDebugger("vite:transform");
var debugCache$1 = createDebugger("vite:cache");
function transformRequest(url2, server2, options2 = {}) {
if (server2._restartPromise && !options2.ssr) throwClosedServerError();
const cacheKey = (options2.ssr ? "ssr:" : options2.html ? "html:" : "") + url2;
const timestamp2 = Date.now();
const pending = server2._pendingRequests.get(cacheKey);
if (pending) {
return server2.moduleGraph.getModuleByUrl(removeTimestampQuery(url2), options2.ssr).then((module) => {
if (!module || pending.timestamp > module.lastInvalidationTimestamp) {
return pending.request;
} else {
pending.abort();
return transformRequest(url2, server2, options2);
}
});
}
const request = doTransform(url2, server2, options2, timestamp2);
let cleared = false;
const clearCache = () => {
if (!cleared) {
server2._pendingRequests.delete(cacheKey);
cleared = true;
}
};
server2._pendingRequests.set(cacheKey, {
request,
timestamp: timestamp2,
abort: clearCache
});
return request.finally(clearCache);
}
async function doTransform(url2, server2, options2, timestamp2) {
url2 = removeTimestampQuery(url2);
const { config: config2, pluginContainer } = server2;
const ssr = !!options2.ssr;
if (ssr && isDepsOptimizerEnabled(config2, true)) {
await initDevSsrDepsOptimizer(config2, server2);
}
let module = await server2.moduleGraph.getModuleByUrl(url2, ssr);
if (module) {
const cached = await getCachedTransformResult(
url2,
module,
server2,
ssr,
timestamp2
);
if (cached) return cached;
}
const resolved = module ? void 0 : await pluginContainer.resolveId(url2, void 0, { ssr }) ?? void 0;
const id = (module == null ? void 0 : module.id) ?? (resolved == null ? void 0 : resolved.id) ?? url2;
module ?? (module = server2.moduleGraph.getModuleById(id));
if (module) {
await server2.moduleGraph._ensureEntryFromUrl(url2, ssr, void 0, resolved);
const cached = await getCachedTransformResult(
url2,
module,
server2,
ssr,
timestamp2
);
if (cached) return cached;
}
const result = loadAndTransform(
id,
url2,
server2,
options2,
timestamp2,
module,
resolved
);
if (!ssr) {
const depsOptimizer = getDepsOptimizer(config2, ssr);
if (!(depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepFile(id))) {
server2._registerRequestProcessing(id, () => result);
}
}
return result;
}
async function getCachedTransformResult(url2, module, server2, ssr, timestamp2) {
const prettyUrl = debugCache$1 ? prettifyUrl(url2, server2.config.root) : "";
const softInvalidatedTransformResult = module && await handleModuleSoftInvalidation(module, ssr, timestamp2, server2);
if (softInvalidatedTransformResult) {
debugCache$1 == null ? void 0 : debugCache$1(`[memory-hmr] ${prettyUrl}`);
return softInvalidatedTransformResult;
}
const cached = module && (ssr ? module.ssrTransformResult : module.transformResult);
if (cached) {
debugCache$1 == null ? void 0 : debugCache$1(`[memory] ${prettyUrl}`);
return cached;
}
}
async function loadAndTransform(id, url2, server2, options2, timestamp2, mod, resolved) {
var _a4;
const { config: config2, pluginContainer, moduleGraph } = server2;
const { logger } = config2;
const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url2, config2.root) : "";
const ssr = !!options2.ssr;
const file = cleanUrl(id);
let code = null;
let map2 = null;
const loadStart = debugLoad ? import_node_perf_hooks.performance.now() : 0;
const loadResult = await pluginContainer.load(id, { ssr });
if (loadResult == null) {
if (options2.html && !id.endsWith(".html")) {
return null;
}
if (options2.ssr || isFileServingAllowed(file, server2)) {
try {
code = await import_promises.default.readFile(file, "utf-8");
debugLoad == null ? void 0 : debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
} catch (e2) {
if (e2.code !== "ENOENT") {
if (e2.code === "EISDIR") {
e2.message = `${e2.message} ${file}`;
}
throw e2;
}
}
if (code != null) {
ensureWatchedFile(server2.watcher, file, config2.root);
}
}
if (code) {
try {
const extracted = await extractSourcemapFromFile(code, file);
if (extracted) {
code = extracted.code;
map2 = extracted.map;
}
} catch (e2) {
logger.warn(`Failed to load source map for ${file}.
${e2}`, {
timestamp: true
});
}
}
} else {
debugLoad == null ? void 0 : debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
if (isObject$1(loadResult)) {
code = loadResult.code;
map2 = loadResult.map;
} else {
code = loadResult;
}
}
if (code == null) {
const isPublicFile = checkPublicFile(url2, config2);
let publicDirName = import_node_path3.default.relative(config2.root, config2.publicDir);
if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName;
const msg = isPublicFile ? `This file is in ${publicDirName} and will be copied as-is during build without going through the plugin transforms, and therefore should not be imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?`;
const importerMod = (_a4 = server2.moduleGraph.idToModuleMap.get(id)) == null ? void 0 : _a4.importers.values().next().value;
const importer = (importerMod == null ? void 0 : importerMod.file) || (importerMod == null ? void 0 : importerMod.url);
const err2 = new Error(
`Failed to load url ${url2} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`
);
err2.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
throw err2;
}
if (server2._restartPromise && !ssr) throwClosedServerError();
mod ?? (mod = await moduleGraph._ensureEntryFromUrl(url2, ssr, void 0, resolved));
const transformStart = debugTransform ? import_node_perf_hooks.performance.now() : 0;
const transformResult = await pluginContainer.transform(code, id, {
inMap: map2,
ssr
});
const originalCode = code;
if (transformResult == null || isObject$1(transformResult) && transformResult.code == null) {
debugTransform == null ? void 0 : debugTransform(
timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`)
);
} else {
debugTransform == null ? void 0 : debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`);
code = transformResult.code;
map2 = transformResult.map;
}
let normalizedMap;
if (typeof map2 === "string") {
normalizedMap = JSON.parse(map2);
} else if (map2) {
normalizedMap = map2;
} else {
normalizedMap = null;
}
if (normalizedMap && "version" in normalizedMap && mod.file) {
if (normalizedMap.mappings) {
await injectSourcesContent(normalizedMap, mod.file, logger);
}
const sourcemapPath = `${mod.file}.map`;
applySourcemapIgnoreList(
normalizedMap,
sourcemapPath,
config2.server.sourcemapIgnoreList,
logger
);
if (import_node_path3.default.isAbsolute(mod.file)) {
let modDirname;
for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
const sourcePath = normalizedMap.sources[sourcesIndex];
if (sourcePath) {
if (import_node_path3.default.isAbsolute(sourcePath)) {
modDirname ?? (modDirname = import_node_path3.default.dirname(mod.file));
normalizedMap.sources[sourcesIndex] = import_node_path3.default.relative(
modDirname,
sourcePath
);
}
}
}
}
}
if (server2._restartPromise && !ssr) throwClosedServerError();
const result = ssr && !server2.config.experimental.skipSsrTransform ? await server2.ssrTransform(code, normalizedMap, url2, originalCode) : {
code,
map: normalizedMap,
etag: getEtag(code, { weak: true })
};
if (timestamp2 > mod.lastInvalidationTimestamp)
moduleGraph.updateModuleTransformResult(mod, result, ssr);
return result;
}
async function handleModuleSoftInvalidation(mod, ssr, timestamp2, server2) {
const transformResult = ssr ? mod.ssrInvalidationState : mod.invalidationState;
if (ssr) mod.ssrInvalidationState = void 0;
else mod.invalidationState = void 0;
if (!transformResult || transformResult === "HARD_INVALIDATED") return;
if (ssr ? mod.ssrTransformResult : mod.transformResult) {
throw new Error(
`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`
);
}
let result;
if (ssr) {
result = transformResult;
} else {
await init;
const source = transformResult.code;
const s = new MagicString(source);
const [imports] = parse$d(source, mod.id || void 0);
for (const imp of imports) {
let rawUrl = source.slice(imp.s, imp.e);
if (rawUrl === "import.meta") continue;
const hasQuotes = rawUrl[0] === '"' || rawUrl[0] === "'";
if (hasQuotes) {
rawUrl = rawUrl.slice(1, -1);
}
const urlWithoutTimestamp = removeTimestampQuery(rawUrl);
const hmrUrl = unwrapId$1(
stripBase(removeImportQuery(urlWithoutTimestamp), server2.config.base)
);
for (const importedMod of mod.clientImportedModules) {
if (importedMod.url !== hmrUrl) continue;
if (importedMod.lastHMRTimestamp > 0) {
const replacedUrl = injectQuery(
urlWithoutTimestamp,
`t=${importedMod.lastHMRTimestamp}`
);
const start = hasQuotes ? imp.s + 1 : imp.s;
const end = hasQuotes ? imp.e - 1 : imp.e;
s.overwrite(start, end, replacedUrl);
}
if (imp.d === -1 && server2.config.server.preTransformRequests) {
server2.warmupRequest(hmrUrl, { ssr });
}
break;
}
}
const code = s.toString();
result = {
...transformResult,
code,
etag: getEtag(code, { weak: true })
};
}
if (timestamp2 > mod.lastInvalidationTimestamp)
server2.moduleGraph.updateModuleTransformResult(mod, result, ssr);
return result;
}
function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
var _a4;
if (metadata == null ? void 0 : metadata.isDynamicImport) return;
if ((_a4 = metadata == null ? void 0 : metadata.importedNames) == null ? void 0 : _a4.length) {
const missingBindings = metadata.importedNames.filter((s) => !(s in mod));
if (missingBindings.length) {
const lastBinding = missingBindings[missingBindings.length - 1];
if (moduleType === "module") {
throw new SyntaxError(
`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
);
} else {
throw new SyntaxError(`[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '${rawId}';
const {${missingBindings.join(", ")}} = pkg;
`);
}
}
}
}
function extract_names(param) {
return extract_identifiers(param).map((node2) => node2.name);
}
function extract_identifiers(param, nodes = []) {
switch (param.type) {
case "Identifier":
nodes.push(param);
break;
case "MemberExpression":
let object = param;
while (object.type === "MemberExpression") {
object = /** @type {any} */
object.object;
}
nodes.push(
/** @type {any} */
object
);
break;
case "ObjectPattern":
for (const prop of param.properties) {
if (prop.type === "RestElement") {
extract_identifiers(prop.argument, nodes);
} else {
extract_identifiers(prop.value, nodes);
}
}
break;
case "ArrayPattern":
for (const element of param.elements) {
if (element) extract_identifiers(element, nodes);
}
break;
case "RestElement":
extract_identifiers(param.argument, nodes);
break;
case "AssignmentPattern":
extract_identifiers(param.left, nodes);
break;
}
return nodes;
}
var WalkerBase2 = class {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node2) => this.replacement = node2
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node2) {
if (parent && prop) {
if (index != null) {
parent[prop][index] = node2;
} else {
parent[prop] = node2;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== void 0) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
var SyncWalker2 = class extends WalkerBase2 {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node2) => this.replacement = node2
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node2, parent, prop, index) {
if (node2) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node2, parent, prop, index);
if (this.replacement) {
node2 = this.replacement;
this.replace(parent, prop, index, node2);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped) return node2;
if (removed) return null;
}
let key;
for (key in node2) {
const value2 = node2[key];
if (value2 && typeof value2 === "object") {
if (Array.isArray(value2)) {
const nodes = (
/** @type {Array<unknown>} */
value2
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node2, key, i)) {
i--;
}
}
}
} else if (isNode(value2)) {
this.visit(value2, node2, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node2, parent, prop, index);
if (this.replacement) {
node2 = this.replacement;
this.replace(parent, prop, index, node2);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed) return null;
}
}
return node2;
}
};
function isNode(value2) {
return value2 !== null && typeof value2 === "object" && "type" in value2 && typeof value2.type === "string";
}
function walk$1(ast, { enter, leave }) {
const instance = new SyncWalker2(enter, leave);
return instance.visit(ast, null);
}
var ssrModuleExportsKey = `__vite_ssr_exports__`;
var ssrImportKey = `__vite_ssr_import__`;
var ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
var ssrExportAllKey = `__vite_ssr_exportAll__`;
var ssrImportMetaKey = `__vite_ssr_import_meta__`;
var hashbangRE = /^#!.*\n/;
async function ssrTransform(code, inMap, url2, originalCode, options2) {
var _a4;
if (((_a4 = options2 == null ? void 0 : options2.json) == null ? void 0 : _a4.stringify) && isJSONRequest(url2)) {
return ssrTransformJSON(code, inMap);
}
return ssrTransformScript(code, inMap, url2, originalCode);
}
async function ssrTransformJSON(code, inMap) {
return {
code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
map: inMap,
deps: [],
dynamicDeps: []
};
}
async function ssrTransformScript(code, inMap, url2, originalCode) {
var _a4;
const s = new MagicString(code);
let ast;
try {
ast = await parseAstAsync(code);
} catch (err2) {
if (!err2.loc || !err2.loc.line) throw err2;
const line = err2.loc.line;
throw new Error(
`Parse failure: ${err2.message}
At file: ${url2}
Contents of line ${line}: ${code.split("\n")[line - 1]}`
);
}
let uid = 0;
const deps = /* @__PURE__ */ new Set();
const dynamicDeps = /* @__PURE__ */ new Set();
const idToImportMap = /* @__PURE__ */ new Map();
const declaredConst = /* @__PURE__ */ new Set();
const hoistIndex = ((_a4 = code.match(hashbangRE)) == null ? void 0 : _a4[0].length) ?? 0;
function defineImport(index, source, metadata) {
deps.add(source);
const importId = `__vite_ssr_import_${uid++}__`;
if (metadata && (metadata.importedNames == null || metadata.importedNames.length === 0)) {
metadata = void 0;
}
const metadataStr = metadata ? `, ${JSON.stringify(metadata)}` : "";
s.appendLeft(
index,
`const ${importId} = await ${ssrImportKey}(${JSON.stringify(
source
)}${metadataStr});
`
);
return importId;
}
function defineExport(position, name2, local = name2) {
s.appendLeft(
position,
`
Object.defineProperty(${ssrModuleExportsKey}, "${name2}", { enumerable: true, configurable: true, get(){ return ${local} }});`
);
}
for (const node2 of ast.body) {
if (node2.type === "ImportDeclaration") {
const importId = defineImport(hoistIndex, node2.source.value, {
importedNames: node2.specifiers.map((s2) => {
if (s2.type === "ImportSpecifier")
return s2.imported.type === "Identifier" ? s2.imported.name : (
// @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet
s2.imported.value
);
else if (s2.type === "ImportDefaultSpecifier") return "default";
}).filter(isDefined)
});
s.remove(node2.start, node2.end);
for (const spec of node2.specifiers) {
if (spec.type === "ImportSpecifier") {
if (spec.imported.type === "Identifier") {
idToImportMap.set(
spec.local.name,
`${importId}.${spec.imported.name}`
);
} else {
idToImportMap.set(
spec.local.name,
`${importId}[${// @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet
JSON.stringify(spec.imported.value)}]`
);
}
} else if (spec.type === "ImportDefaultSpecifier") {
idToImportMap.set(spec.local.name, `${importId}.default`);
} else {
idToImportMap.set(spec.local.name, importId);
}
}
}
}
for (const node2 of ast.body) {
if (node2.type === "ExportNamedDeclaration") {
if (node2.declaration) {
if (node2.declaration.type === "FunctionDeclaration" || node2.declaration.type === "ClassDeclaration") {
defineExport(node2.end, node2.declaration.id.name);
} else {
for (const declaration of node2.declaration.declarations) {
const names = extract_names(declaration.id);
for (const name2 of names) {
defineExport(node2.end, name2);
}
}
}
s.remove(node2.start, node2.declaration.start);
} else {
s.remove(node2.start, node2.end);
if (node2.source) {
const importId = defineImport(
node2.start,
node2.source.value,
{
importedNames: node2.specifiers.map((s2) => s2.local.name)
}
);
for (const spec of node2.specifiers) {
const exportedAs = spec.exported.type === "Identifier" ? spec.exported.name : (
// @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet
spec.exported.value
);
defineExport(
node2.start,
exportedAs,
`${importId}.${spec.local.name}`
);
}
} else {
for (const spec of node2.specifiers) {
const local = spec.local.name;
const binding = idToImportMap.get(local);
const exportedAs = spec.exported.type === "Identifier" ? spec.exported.name : (
// @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet
spec.exported.value
);
defineExport(node2.end, exportedAs, binding || local);
}
}
}
}
if (node2.type === "ExportDefaultDeclaration") {
const expressionTypes = ["FunctionExpression", "ClassExpression"];
if ("id" in node2.declaration && node2.declaration.id && !expressionTypes.includes(node2.declaration.type)) {
const { name: name2 } = node2.declaration.id;
s.remove(
node2.start,
node2.start + 15
/* 'export default '.length */
);
s.append(
`
Object.defineProperty(${ssrModuleExportsKey}, "default", { enumerable: true, configurable: true, value: ${name2} });`
);
} else {
s.update(
node2.start,
node2.start + 14,
`${ssrModuleExportsKey}.default =`
);
}
}
if (node2.type === "ExportAllDeclaration") {
s.remove(node2.start, node2.end);
const importId = defineImport(node2.start, node2.source.value);
if (node2.exported) {
defineExport(node2.start, node2.exported.name, `${importId}`);
} else {
s.appendLeft(node2.start, `${ssrExportAllKey}(${importId});
`);
}
}
}
walk(ast, {
onIdentifier(id, parent, parentStack) {
const grandparent = parentStack[1];
const binding = idToImportMap.get(id.name);
if (!binding) {
return;
}
if (isStaticProperty(parent) && parent.shorthand) {
if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) {
s.appendLeft(id.end, `: ${binding}`);
}
} else if (parent.type === "PropertyDefinition" && (grandparent == null ? void 0 : grandparent.type) === "ClassBody" || parent.type === "ClassDeclaration" && id === parent.superClass) {
if (!declaredConst.has(id.name)) {
declaredConst.add(id.name);
const topNode = parentStack[parentStack.length - 2];
s.prependRight(topNode.start, `const ${id.name} = ${binding};
`);
}
} else if (
// don't transform class name identifier
!(parent.type === "ClassExpression" && id === parent.id)
) {
s.update(id.start, id.end, binding);
}
},
onImportMeta(node2) {
s.update(node2.start, node2.end, ssrImportMetaKey);
},
onDynamicImport(node2) {
s.update(node2.start, node2.start + 6, ssrDynamicImportKey);
if (node2.type === "ImportExpression" && node2.source.type === "Literal") {
dynamicDeps.add(node2.source.value);
}
}
});
let map2 = s.generateMap({ hires: "boundary" });
if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) {
map2 = combineSourcemaps(url2, [
{
...map2,
sources: inMap.sources,
sourcesContent: inMap.sourcesContent
},
inMap
]);
} else {
map2.sources = [import_node_path3.default.basename(url2)];
map2.sourcesContent = [originalCode];
}
return {
code: s.toString(),
map: map2,
deps: [...deps],
dynamicDeps: [...dynamicDeps]
};
}
var isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
var setIsNodeInPattern = (node2) => isNodeInPatternWeakSet.add(node2);
var isNodeInPattern = (node2) => isNodeInPatternWeakSet.has(node2);
function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) {
const parentStack = [];
const varKindStack = [];
const scopeMap = /* @__PURE__ */ new WeakMap();
const identifiers = [];
const setScope = (node2, name2) => {
let scopeIds = scopeMap.get(node2);
if (scopeIds && scopeIds.has(name2)) {
return;
}
if (!scopeIds) {
scopeIds = /* @__PURE__ */ new Set();
scopeMap.set(node2, scopeIds);
}
scopeIds.add(name2);
};
function isInScope(name2, parents) {
return parents.some((node2) => {
var _a4;
return node2 && ((_a4 = scopeMap.get(node2)) == null ? void 0 : _a4.has(name2));
});
}
function handlePattern(p, parentScope) {
if (p.type === "Identifier") {
setScope(parentScope, p.name);
} else if (p.type === "RestElement") {
handlePattern(p.argument, parentScope);
} else if (p.type === "ObjectPattern") {
p.properties.forEach((property) => {
if (property.type === "RestElement") {
setScope(parentScope, property.argument.name);
} else {
handlePattern(property.value, parentScope);
}
});
} else if (p.type === "ArrayPattern") {
p.elements.forEach((element) => {
if (element) {
handlePattern(element, parentScope);
}
});
} else if (p.type === "AssignmentPattern") {
handlePattern(p.left, parentScope);
} else {
setScope(parentScope, p.name);
}
}
walk$1(root, {
enter(node2, parent) {
if (node2.type === "ImportDeclaration") {
return this.skip();
}
if (parent && !(parent.type === "IfStatement" && node2 === parent.alternate)) {
parentStack.unshift(parent);
}
if (node2.type === "VariableDeclaration") {
varKindStack.unshift(node2.kind);
}
if (node2.type === "MetaProperty" && node2.meta.name === "import") {
onImportMeta(node2);
} else if (node2.type === "ImportExpression") {
onDynamicImport(node2);
}
if (node2.type === "Identifier") {
if (!isInScope(node2.name, parentStack) && isRefIdentifier(node2, parent, parentStack)) {
identifiers.push([node2, parentStack.slice(0)]);
}
} else if (isFunction$1(node2)) {
if (node2.type === "FunctionDeclaration") {
const parentScope = findParentScope(parentStack);
if (parentScope) {
setScope(parentScope, node2.id.name);
}
}
if (node2.type === "FunctionExpression" && node2.id) {
setScope(node2, node2.id.name);
}
node2.params.forEach((p) => {
if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
handlePattern(p, node2);
return;
}
walk$1(p.type === "AssignmentPattern" ? p.left : p, {
enter(child, parent2) {
if ((parent2 == null ? void 0 : parent2.type) === "AssignmentPattern" && (parent2 == null ? void 0 : parent2.right) === child) {
return this.skip();
}
if (child.type !== "Identifier") return;
if (isStaticPropertyKey(child, parent2)) return;
if ((parent2 == null ? void 0 : parent2.type) === "TemplateLiteral" && (parent2 == null ? void 0 : parent2.expressions.includes(child)) || (parent2 == null ? void 0 : parent2.type) === "CallExpression" && (parent2 == null ? void 0 : parent2.callee) === child) {
return;
}
setScope(node2, child.name);
}
});
});
} else if (node2.type === "ClassDeclaration") {
const parentScope = findParentScope(parentStack);
if (parentScope) {
setScope(parentScope, node2.id.name);
}
} else if (node2.type === "ClassExpression" && node2.id) {
setScope(node2, node2.id.name);
} else if (node2.type === "Property" && parent.type === "ObjectPattern") {
setIsNodeInPattern(node2);
} else if (node2.type === "VariableDeclarator") {
const parentFunction = findParentScope(
parentStack,
varKindStack[0] === "var"
);
if (parentFunction) {
handlePattern(node2.id, parentFunction);
}
} else if (node2.type === "CatchClause" && node2.param) {
handlePattern(node2.param, node2);
}
},
leave(node2, parent) {
if (parent && !(parent.type === "IfStatement" && node2 === parent.alternate)) {
parentStack.shift();
}
if (node2.type === "VariableDeclaration") {
varKindStack.shift();
}
}
});
identifiers.forEach(([node2, stack]) => {
if (!isInScope(node2.name, stack)) onIdentifier(node2, stack[0], stack);
});
}
function isRefIdentifier(id, parent, parentStack) {
if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) {
return false;
}
if (isFunction$1(parent)) {
if (parent.id === id) {
return false;
}
if (parent.params.includes(id)) {
return false;
}
}
if (parent.type === "MethodDefinition" && !parent.computed) {
return false;
}
if (isStaticPropertyKey(id, parent)) {
return false;
}
if (isNodeInPattern(parent) && parent.value === id) {
return false;
}
if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) {
return false;
}
if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) {
return false;
}
if (parent.type === "ExportSpecifier") {
return false;
}
if (id.name === "arguments") {
return false;
}
return true;
}
var isStaticProperty = (node2) => node2 && node2.type === "Property" && !node2.computed;
var isStaticPropertyKey = (node2, parent) => isStaticProperty(parent) && parent.key === node2;
var functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
function isFunction$1(node2) {
return functionNodeTypeRE.test(node2.type);
}
var blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
function isBlock(node2) {
return blockNodeTypeRE.test(node2.type);
}
function findParentScope(parentStack, isVar = false) {
return parentStack.find(isVar ? isFunction$1 : isBlock);
}
function isInDestructuringAssignment(parent, parentStack) {
if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) {
return parentStack.some((i) => i.type === "AssignmentExpression");
}
return false;
}
var offset;
function calculateOffsetOnce() {
if (offset !== void 0) {
return;
}
try {
new Function("throw new Error(1)")();
} catch (e2) {
const match2 = /:(\d+):\d+\)$/.exec(e2.stack.split("\n")[1]);
offset = match2 ? +match2[1] - 1 : 0;
}
}
function ssrRewriteStacktrace(stack, moduleGraph) {
calculateOffsetOnce();
return stack.split("\n").map((line) => {
return line.replace(
/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/,
(input, varName, id, line2, column) => {
var _a4;
if (!id) return input;
const mod = moduleGraph.idToModuleMap.get(id);
const rawSourceMap = (_a4 = mod == null ? void 0 : mod.ssrTransformResult) == null ? void 0 : _a4.map;
if (!rawSourceMap) {
return input;
}
const traced = new TraceMap(rawSourceMap);
const pos = originalPositionFor$1(traced, {
line: Number(line2) - offset,
// stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed
column: Number(column) - 1
});
if (!pos.source || pos.line == null || pos.column == null) {
return input;
}
const trimmedVarName = varName.trim();
const sourceFile = import_node_path3.default.resolve(import_node_path3.default.dirname(id), pos.source);
const source = `${sourceFile}:${pos.line}:${pos.column + 1}`;
if (!trimmedVarName || trimmedVarName === "eval") {
return ` at ${source}`;
} else {
return ` at ${trimmedVarName} (${source})`;
}
}
);
}).join("\n");
}
function rebindErrorStacktrace(e2, stacktrace) {
const { configurable, writable } = Object.getOwnPropertyDescriptor(
e2,
"stack"
);
if (configurable) {
Object.defineProperty(e2, "stack", {
value: stacktrace,
enumerable: true,
configurable: true,
writable: true
});
} else if (writable) {
e2.stack = stacktrace;
}
}
var rewroteStacktraces = /* @__PURE__ */ new WeakSet();
function ssrFixStacktrace(e2, moduleGraph) {
if (!e2.stack) return;
if (rewroteStacktraces.has(e2)) return;
const stacktrace = ssrRewriteStacktrace(e2.stack, moduleGraph);
rebindErrorStacktrace(e2, stacktrace);
rewroteStacktraces.add(e2);
}
var pendingModules = /* @__PURE__ */ new Map();
var pendingModuleDependencyGraph = /* @__PURE__ */ new Map();
var importErrors = /* @__PURE__ */ new WeakMap();
async function ssrLoadModule(url2, server2, context = { global }, fixStacktrace) {
url2 = unwrapId$1(url2);
const pending = pendingModules.get(url2);
if (pending) {
return pending;
}
const modulePromise = instantiateModule(url2, server2, context, fixStacktrace);
pendingModules.set(url2, modulePromise);
modulePromise.catch(() => {
}).finally(() => {
pendingModules.delete(url2);
});
return modulePromise;
}
async function instantiateModule(url2, server2, context = { global }, fixStacktrace) {
var _a4, _b3;
const { moduleGraph } = server2;
const mod = await moduleGraph.ensureEntryFromUrl(url2, true);
if (mod.ssrError) {
throw mod.ssrError;
}
if (mod.ssrModule) {
return mod.ssrModule;
}
const result = mod.ssrTransformResult || await transformRequest(url2, server2, { ssr: true });
if (!result) {
throw new Error(`failed to load module for ssr: ${url2}`);
}
const ssrModule = {
[Symbol.toStringTag]: "Module"
};
Object.defineProperty(ssrModule, "__esModule", { value: true });
mod.ssrModule = ssrModule;
const osNormalizedFilename = isWindows$3 ? import_node_path3.default.resolve(mod.file) : mod.file;
const ssrImportMeta = {
dirname: import_node_path3.default.dirname(osNormalizedFilename),
filename: osNormalizedFilename,
// The filesystem URL, matching native Node.js modules
url: (0, import_node_url2.pathToFileURL)(mod.file).toString()
};
const {
isProduction,
resolve: { dedupe, preserveSymlinks },
root,
ssr
} = server2.config;
const overrideConditions = ((_a4 = ssr.resolve) == null ? void 0 : _a4.externalConditions) || [];
const resolveOptions = {
mainFields: ["main"],
conditions: [],
overrideConditions: [...overrideConditions, "production", "development"],
extensions: [".js", ".cjs", ".json"],
dedupe,
preserveSymlinks,
isBuild: false,
isProduction,
root,
ssrConfig: ssr,
legacyProxySsrExternalModules: (_b3 = server2.config.legacy) == null ? void 0 : _b3.proxySsrExternalModules,
packageCache: server2.config.packageCache
};
const ssrImport = async (dep, metadata) => {
var _a5;
try {
if (dep[0] !== "." && dep[0] !== "/") {
return await nodeImport(dep, mod.file, resolveOptions, metadata);
}
dep = unwrapId$1(dep);
if (!(metadata == null ? void 0 : metadata.isDynamicImport)) {
addPendingModuleDependency(url2, dep);
if (checkModuleDependencyExists(dep, url2)) {
const depSsrModule = (_a5 = moduleGraph.urlToModuleMap.get(dep)) == null ? void 0 : _a5.ssrModule;
if (!depSsrModule) {
throw new Error(
"[vite] The dependency module is not yet fully initialized due to circular dependency. This is a bug in Vite SSR"
);
}
return depSsrModule;
}
}
return ssrLoadModule(dep, server2, context, fixStacktrace);
} catch (err2) {
importErrors.set(err2, { importee: dep });
throw err2;
}
};
const ssrDynamicImport = (dep) => {
if (dep[0] === ".") {
dep = import_node_path3.default.posix.resolve(import_node_path3.default.dirname(url2), dep);
}
return ssrImport(dep, { isDynamicImport: true });
};
function ssrExportAll(sourceModule) {
for (const key in sourceModule) {
if (key !== "default" && key !== "__esModule") {
Object.defineProperty(ssrModule, key, {
enumerable: true,
configurable: true,
get() {
return sourceModule[key];
}
});
}
}
}
let sourceMapSuffix = "";
if (result.map && "version" in result.map) {
const moduleSourceMap = Object.assign({}, result.map, {
mappings: ";".repeat(asyncFunctionDeclarationPaddingLineCount) + result.map.mappings
});
sourceMapSuffix = `
//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(moduleSourceMap)}`;
}
try {
const initModule = new AsyncFunction(
`global`,
ssrModuleExportsKey,
ssrImportMetaKey,
ssrImportKey,
ssrDynamicImportKey,
ssrExportAllKey,
'"use strict";' + result.code + `
//# sourceURL=${mod.id}${sourceMapSuffix}`
);
await initModule(
context.global,
ssrModule,
ssrImportMeta,
ssrImport,
ssrDynamicImport,
ssrExportAll
);
} catch (e2) {
mod.ssrError = e2;
const errorData = importErrors.get(e2);
if (e2.stack && fixStacktrace) {
ssrFixStacktrace(e2, moduleGraph);
}
server2.config.logger.error(
colors$1.red(
`Error when evaluating SSR module ${url2}:` + ((errorData == null ? void 0 : errorData.importee) ? ` failed to import "${errorData.importee}"` : "") + `
|- ${e2.stack}
`
),
{
timestamp: true,
clear: server2.config.clearScreen,
error: e2
}
);
throw e2;
} finally {
pendingModuleDependencyGraph.delete(url2);
}
return Object.freeze(ssrModule);
}
function addPendingModuleDependency(originUrl, depUrl) {
if (pendingModuleDependencyGraph.has(originUrl)) {
pendingModuleDependencyGraph.get(originUrl).add(depUrl);
} else {
pendingModuleDependencyGraph.set(originUrl, /* @__PURE__ */ new Set([depUrl]));
}
}
function checkModuleDependencyExists(originUrl, targetUrl) {
const visited = /* @__PURE__ */ new Set();
const stack = [originUrl];
while (stack.length) {
const currentUrl = stack.pop();
if (currentUrl === targetUrl) {
return true;
}
if (!visited.has(currentUrl)) {
visited.add(currentUrl);
const dependencies = pendingModuleDependencyGraph.get(currentUrl);
if (dependencies) {
for (const depUrl of dependencies) {
if (!visited.has(depUrl)) {
stack.push(depUrl);
}
}
}
}
}
return false;
}
async function nodeImport(id, importer, resolveOptions, metadata) {
let url2;
let filePath;
if (id.startsWith("data:") || isExternalUrl(id) || isBuiltin(id)) {
url2 = id;
} else {
const resolved = tryNodeResolve(
id,
importer,
{ ...resolveOptions, tryEsmOnly: true },
false,
void 0,
true
);
if (!resolved) {
const err2 = new Error(
`Cannot find module '${id}' imported from '${importer}'`
);
err2.code = "ERR_MODULE_NOT_FOUND";
throw err2;
}
filePath = resolved.id;
url2 = (0, import_node_url2.pathToFileURL)(resolved.id).toString();
}
const mod = await import(url2);
if (resolveOptions.legacyProxySsrExternalModules) {
return proxyESM(mod);
} else if (filePath) {
analyzeImportedModDifference(
mod,
id,
isFilePathESM(filePath, resolveOptions.packageCache) ? "module" : void 0,
metadata
);
return mod;
} else {
return mod;
}
}
function proxyESM(mod) {
if (isPrimitive(mod)) return { default: mod };
let defaultExport = "default" in mod ? mod.default : mod;
if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
mod = defaultExport;
if ("default" in defaultExport) {
defaultExport = defaultExport.default;
}
}
return new Proxy(mod, {
get(mod2, prop) {
if (prop === "default") return defaultExport;
return mod2[prop] ?? (defaultExport == null ? void 0 : defaultExport[prop]);
}
});
}
function isPrimitive(value2) {
return !value2 || typeof value2 !== "object" && typeof value2 !== "function";
}
var isWsl$2 = { exports: {} };
var fs$3 = import_fs.default;
var isDocker$2;
function hasDockerEnv() {
try {
fs$3.statSync("/.dockerenv");
return true;
} catch (_) {
return false;
}
}
function hasDockerCGroup() {
try {
return fs$3.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
} catch (_) {
return false;
}
}
var isDocker_1 = () => {
if (isDocker$2 === void 0) {
isDocker$2 = hasDockerEnv() || hasDockerCGroup();
}
return isDocker$2;
};
var os = import_os.default;
var fs$2 = import_fs.default;
var isDocker$1 = isDocker_1;
var isWsl$1 = () => {
if (process.platform !== "linux") {
return false;
}
if (os.release().toLowerCase().includes("microsoft")) {
if (isDocker$1()) {
return false;
}
return true;
}
try {
return fs$2.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker$1() : false;
} catch (_) {
return false;
}
};
if (process.env.__IS_WSL_TEST__) {
isWsl$2.exports = isWsl$1;
} else {
isWsl$2.exports = isWsl$1();
}
var isWslExports = isWsl$2.exports;
var defineLazyProp = (object, propertyName, fn) => {
const define = (value2) => Object.defineProperty(object, propertyName, { value: value2, enumerable: true, writable: true });
Object.defineProperty(object, propertyName, {
configurable: true,
enumerable: true,
get() {
const result = fn();
define(result);
return result;
},
set(value2) {
define(value2);
}
});
return object;
};
var path$3 = import_path.default;
var childProcess = import_child_process.default;
var { promises: fs$1, constants: fsConstants } = import_fs.default;
var isWsl = isWslExports;
var isDocker = isDocker_1;
var defineLazyProperty = defineLazyProp;
var localXdgOpenPath = path$3.join(__dirname2, "xdg-open");
var { platform, arch } = process;
var hasContainerEnv = () => {
try {
fs$1.statSync("/run/.containerenv");
return true;
} catch {
return false;
}
};
var cachedResult;
function isInsideContainer() {
if (cachedResult === void 0) {
cachedResult = hasContainerEnv() || isDocker();
}
return cachedResult;
}
var getWslDrivesMountPoint = /* @__PURE__ */ (() => {
const defaultMountPoint = "/mnt/";
let mountPoint;
return async function() {
if (mountPoint) {
return mountPoint;
}
const configFilePath = "/etc/wsl.conf";
let isConfigFileExists = false;
try {
await fs$1.access(configFilePath, fsConstants.F_OK);
isConfigFileExists = true;
} catch {
}
if (!isConfigFileExists) {
return defaultMountPoint;
}
const configContent = await fs$1.readFile(configFilePath, { encoding: "utf8" });
const configMountPoint = new RegExp("(?<!#.*)root\\s*=\\s*(?<mountPoint>.*)", "g").exec(configContent);
if (!configMountPoint) {
return defaultMountPoint;
}
mountPoint = configMountPoint.groups.mountPoint.trim();
mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
return mountPoint;
};
})();
var pTryEach = async (array2, mapper) => {
let latestError;
for (const item of array2) {
try {
return await mapper(item);
} catch (error2) {
latestError = error2;
}
}
throw latestError;
};
var baseOpen = async (options2) => {
options2 = {
wait: false,
background: false,
newInstance: false,
allowNonzeroExitCode: false,
...options2
};
if (Array.isArray(options2.app)) {
return pTryEach(options2.app, (singleApp) => baseOpen({
...options2,
app: singleApp
}));
}
let { name: app, arguments: appArguments = [] } = options2.app || {};
appArguments = [...appArguments];
if (Array.isArray(app)) {
return pTryEach(app, (appName) => baseOpen({
...options2,
app: {
name: appName,
arguments: appArguments
}
}));
}
let command;
const cliArguments = [];
const childProcessOptions = {};
if (platform === "darwin") {
command = "open";
if (options2.wait) {
cliArguments.push("--wait-apps");
}
if (options2.background) {
cliArguments.push("--background");
}
if (options2.newInstance) {
cliArguments.push("--new");
}
if (app) {
cliArguments.push("-a", app);
}
} else if (platform === "win32" || isWsl && !isInsideContainer() && !app) {
const mountPoint = await getWslDrivesMountPoint();
command = isWsl ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
cliArguments.push(
"-NoProfile",
"-NonInteractive",
"ExecutionPolicy",
"Bypass",
"-EncodedCommand"
);
if (!isWsl) {
childProcessOptions.windowsVerbatimArguments = true;
}
const encodedArguments = ["Start"];
if (options2.wait) {
encodedArguments.push("-Wait");
}
if (app) {
encodedArguments.push(`"\`"${app}\`""`, "-ArgumentList");
if (options2.target) {
appArguments.unshift(options2.target);
}
} else if (options2.target) {
encodedArguments.push(`"${options2.target}"`);
}
if (appArguments.length > 0) {
appArguments = appArguments.map((arg) => `"\`"${arg}\`""`);
encodedArguments.push(appArguments.join(","));
}
options2.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64");
} else {
if (app) {
command = app;
} else {
const isBundled = !__dirname2 || __dirname2 === "/";
let exeLocalXdgOpen = false;
try {
await fs$1.access(localXdgOpenPath, fsConstants.X_OK);
exeLocalXdgOpen = true;
} catch {
}
const useSystemXdgOpen = process.versions.electron || platform === "android" || isBundled || !exeLocalXdgOpen;
command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
}
if (appArguments.length > 0) {
cliArguments.push(...appArguments);
}
if (!options2.wait) {
childProcessOptions.stdio = "ignore";
childProcessOptions.detached = true;
}
}
if (options2.target) {
cliArguments.push(options2.target);
}
if (platform === "darwin" && appArguments.length > 0) {
cliArguments.push("--args", ...appArguments);
}
const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
if (options2.wait) {
return new Promise((resolve3, reject) => {
subprocess.once("error", reject);
subprocess.once("close", (exitCode) => {
if (!options2.allowNonzeroExitCode && exitCode > 0) {
reject(new Error(`Exited with code ${exitCode}`));
return;
}
resolve3(subprocess);
});
});
}
subprocess.unref();
return subprocess;
};
var open = (target, options2) => {
if (typeof target !== "string") {
throw new TypeError("Expected a `target`");
}
return baseOpen({
...options2,
target
});
};
var openApp = (name2, options2) => {
if (typeof name2 !== "string") {
throw new TypeError("Expected a `name`");
}
const { arguments: appArguments = [] } = options2 || {};
if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
throw new TypeError("Expected `appArguments` as Array type");
}
return baseOpen({
...options2,
app: {
name: name2,
arguments: appArguments
}
});
};
function detectArchBinary(binary2) {
if (typeof binary2 === "string" || Array.isArray(binary2)) {
return binary2;
}
const { [arch]: archBinary } = binary2;
if (!archBinary) {
throw new Error(`${arch} is not supported`);
}
return archBinary;
}
function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
if (wsl && isWsl) {
return detectArchBinary(wsl);
}
if (!platformBinary) {
throw new Error(`${platform} is not supported`);
}
return detectArchBinary(platformBinary);
}
var apps = {};
defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
darwin: "google chrome",
win32: "chrome",
linux: ["google-chrome", "google-chrome-stable", "chromium"]
}, {
wsl: {
ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
}
}));
defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
darwin: "firefox",
win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
linux: "firefox"
}, {
wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
}));
defineLazyProperty(apps, "edge", () => detectPlatformBinary({
darwin: "microsoft edge",
win32: "msedge",
linux: ["microsoft-edge", "microsoft-edge-dev"]
}, {
wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
}));
open.apps = apps;
open.openApp = openApp;
var open_1 = open;
var open$1 = getDefaultExportFromCjs(open_1);
var crossSpawn = { exports: {} };
var windows;
var hasRequiredWindows;
function requireWindows() {
if (hasRequiredWindows) return windows;
hasRequiredWindows = 1;
windows = isexe2;
isexe2.sync = sync2;
var fs2 = import_fs.default;
function checkPathExt(path3, options2) {
var pathext = options2.pathExt !== void 0 ? options2.pathExt : process.env.PATHEXT;
if (!pathext) {
return true;
}
pathext = pathext.split(";");
if (pathext.indexOf("") !== -1) {
return true;
}
for (var i = 0; i < pathext.length; i++) {
var p = pathext[i].toLowerCase();
if (p && path3.substr(-p.length).toLowerCase() === p) {
return true;
}
}
return false;
}
function checkStat(stat2, path3, options2) {
if (!stat2.isSymbolicLink() && !stat2.isFile()) {
return false;
}
return checkPathExt(path3, options2);
}
function isexe2(path3, options2, cb) {
fs2.stat(path3, function(er, stat2) {
cb(er, er ? false : checkStat(stat2, path3, options2));
});
}
function sync2(path3, options2) {
return checkStat(fs2.statSync(path3), path3, options2);
}
return windows;
}
var mode;
var hasRequiredMode;
function requireMode() {
if (hasRequiredMode) return mode;
hasRequiredMode = 1;
mode = isexe2;
isexe2.sync = sync2;
var fs2 = import_fs.default;
function isexe2(path3, options2, cb) {
fs2.stat(path3, function(er, stat2) {
cb(er, er ? false : checkStat(stat2, options2));
});
}
function sync2(path3, options2) {
return checkStat(fs2.statSync(path3), options2);
}
function checkStat(stat2, options2) {
return stat2.isFile() && checkMode(stat2, options2);
}
function checkMode(stat2, options2) {
var mod = stat2.mode;
var uid = stat2.uid;
var gid = stat2.gid;
var myUid = options2.uid !== void 0 ? options2.uid : process.getuid && process.getuid();
var myGid = options2.gid !== void 0 ? options2.gid : process.getgid && process.getgid();
var u = parseInt("100", 8);
var g = parseInt("010", 8);
var o2 = parseInt("001", 8);
var ug = u | g;
var ret = mod & o2 || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
return ret;
}
return mode;
}
var core;
if (process.platform === "win32" || commonjsGlobal.TESTING_WINDOWS) {
core = requireWindows();
} else {
core = requireMode();
}
var isexe_1 = isexe$1;
isexe$1.sync = sync;
function isexe$1(path3, options2, cb) {
if (typeof options2 === "function") {
cb = options2;
options2 = {};
}
if (!cb) {
if (typeof Promise !== "function") {
throw new TypeError("callback not provided");
}
return new Promise(function(resolve3, reject) {
isexe$1(path3, options2 || {}, function(er, is) {
if (er) {
reject(er);
} else {
resolve3(is);
}
});
});
}
core(path3, options2 || {}, function(er, is) {
if (er) {
if (er.code === "EACCES" || options2 && options2.ignoreErrors) {
er = null;
is = false;
}
}
cb(er, is);
});
}
function sync(path3, options2) {
try {
return core.sync(path3, options2 || {});
} catch (er) {
if (options2 && options2.ignoreErrors || er.code === "EACCES") {
return false;
} else {
throw er;
}
}
}
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
var path$2 = import_path.default;
var COLON = isWindows ? ";" : ":";
var isexe = isexe_1;
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
var getPathInfo = (cmd, opt) => {
const colon = opt.colon || COLON;
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [
// windows always checks the cwd first
...isWindows ? [process.cwd()] : [],
...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
"").split(colon)
];
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
if (isWindows) {
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
pathExt.unshift("");
}
return {
pathEnv,
pathExt,
pathExtExe
};
};
var which$1 = (cmd, opt, cb) => {
if (typeof opt === "function") {
cb = opt;
opt = {};
}
if (!opt)
opt = {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found2 = [];
const step = (i) => new Promise((resolve3, reject) => {
if (i === pathEnv.length)
return opt.all && found2.length ? resolve3(found2) : reject(getNotFoundError(cmd));
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path$2.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
resolve3(subStep(p, i, 0));
});
const subStep = (p, i, ii) => new Promise((resolve3, reject) => {
if (ii === pathExt.length)
return resolve3(step(i + 1));
const ext2 = pathExt[ii];
isexe(p + ext2, { pathExt: pathExtExe }, (er, is) => {
if (!er && is) {
if (opt.all)
found2.push(p + ext2);
else
return resolve3(p + ext2);
}
return resolve3(subStep(p, i, ii + 1));
});
});
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
};
var whichSync = (cmd, opt) => {
opt = opt || {};
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
const found2 = [];
for (let i = 0; i < pathEnv.length; i++) {
const ppRaw = pathEnv[i];
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
const pCmd = path$2.join(pathPart, cmd);
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
for (let j = 0; j < pathExt.length; j++) {
const cur = p + pathExt[j];
try {
const is = isexe.sync(cur, { pathExt: pathExtExe });
if (is) {
if (opt.all)
found2.push(cur);
else
return cur;
}
} catch (ex) {
}
}
}
if (opt.all && found2.length)
return found2;
if (opt.nothrow)
return null;
throw getNotFoundError(cmd);
};
var which_1 = which$1;
which$1.sync = whichSync;
var pathKey$1 = { exports: {} };
var pathKey = (options2 = {}) => {
const environment = options2.env || process.env;
const platform2 = options2.platform || process.platform;
if (platform2 !== "win32") {
return "PATH";
}
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
};
pathKey$1.exports = pathKey;
pathKey$1.exports.default = pathKey;
var pathKeyExports = pathKey$1.exports;
var path$1 = import_path.default;
var which = which_1;
var getPathKey = pathKeyExports;
function resolveCommandAttempt(parsed, withoutPathExt) {
const env2 = parsed.options.env || process.env;
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
if (shouldSwitchCwd) {
try {
process.chdir(parsed.options.cwd);
} catch (err2) {
}
}
let resolved;
try {
resolved = which.sync(parsed.command, {
path: env2[getPathKey({ env: env2 })],
pathExt: withoutPathExt ? path$1.delimiter : void 0
});
} catch (e2) {
} finally {
if (shouldSwitchCwd) {
process.chdir(cwd);
}
}
if (resolved) {
resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
}
return resolved;
}
function resolveCommand$1(parsed) {
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}
var resolveCommand_1 = resolveCommand$1;
var _escape = {};
var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
function escapeCommand(arg) {
arg = arg.replace(metaCharsRegExp, "^$1");
return arg;
}
function escapeArgument(arg, doubleEscapeMetaChars) {
arg = `${arg}`;
arg = arg.replace(/(\\*)"/g, '$1$1\\"');
arg = arg.replace(/(\\*)$/, "$1$1");
arg = `"${arg}"`;
arg = arg.replace(metaCharsRegExp, "^$1");
if (doubleEscapeMetaChars) {
arg = arg.replace(metaCharsRegExp, "^$1");
}
return arg;
}
_escape.command = escapeCommand;
_escape.argument = escapeArgument;
var shebangRegex$1 = /^#!(.*)/;
var shebangRegex = shebangRegex$1;
var shebangCommand$1 = (string2 = "") => {
const match2 = string2.match(shebangRegex);
if (!match2) {
return null;
}
const [path3, argument] = match2[0].replace(/#! ?/, "").split(" ");
const binary2 = path3.split("/").pop();
if (binary2 === "env") {
return argument;
}
return argument ? `${binary2} ${argument}` : binary2;
};
var fs = import_fs.default;
var shebangCommand = shebangCommand$1;
function readShebang$1(command) {
const size = 150;
const buffer = Buffer.alloc(size);
let fd;
try {
fd = fs.openSync(command, "r");
fs.readSync(fd, buffer, 0, size, 0);
fs.closeSync(fd);
} catch (e2) {
}
return shebangCommand(buffer.toString());
}
var readShebang_1 = readShebang$1;
var path2 = import_path.default;
var resolveCommand = resolveCommand_1;
var escape$1 = _escape;
var readShebang = readShebang_1;
var isWin$1 = process.platform === "win32";
var isExecutableRegExp = /\.(?:com|exe)$/i;
var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function detectShebang(parsed) {
parsed.file = resolveCommand(parsed);
const shebang = parsed.file && readShebang(parsed.file);
if (shebang) {
parsed.args.unshift(parsed.file);
parsed.command = shebang;
return resolveCommand(parsed);
}
return parsed.file;
}
function parseNonShell(parsed) {
if (!isWin$1) {
return parsed;
}
const commandFile = detectShebang(parsed);
const needsShell = !isExecutableRegExp.test(commandFile);
if (parsed.options.forceShell || needsShell) {
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
parsed.command = path2.normalize(parsed.command);
parsed.command = escape$1.command(parsed.command);
parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars));
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
parsed.command = process.env.comspec || "cmd.exe";
parsed.options.windowsVerbatimArguments = true;
}
return parsed;
}
function parse$4(command, args, options2) {
if (args && !Array.isArray(args)) {
options2 = args;
args = null;
}
args = args ? args.slice(0) : [];
options2 = Object.assign({}, options2);
const parsed = {
command,
args,
options: options2,
file: void 0,
original: {
command,
args
}
};
return options2.shell ? parsed : parseNonShell(parsed);
}
var parse_1 = parse$4;
var isWin = process.platform === "win32";
function notFoundError(original, syscall) {
return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
code: "ENOENT",
errno: "ENOENT",
syscall: `${syscall} ${original.command}`,
path: original.command,
spawnargs: original.args
});
}
function hookChildProcess(cp2, parsed) {
if (!isWin) {
return;
}
const originalEmit = cp2.emit;
cp2.emit = function(name2, arg1) {
if (name2 === "exit") {
const err2 = verifyENOENT(arg1, parsed);
if (err2) {
return originalEmit.call(cp2, "error", err2);
}
}
return originalEmit.apply(cp2, arguments);
};
}
function verifyENOENT(status2, parsed) {
if (isWin && status2 === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawn");
}
return null;
}
function verifyENOENTSync(status2, parsed) {
if (isWin && status2 === 1 && !parsed.file) {
return notFoundError(parsed.original, "spawnSync");
}
return null;
}
var enoent$1 = {
hookChildProcess,
verifyENOENT,
verifyENOENTSync,
notFoundError
};
var cp = import_child_process.default;
var parse$3 = parse_1;
var enoent = enoent$1;
function spawn(command, args, options2) {
const parsed = parse$3(command, args, options2);
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
enoent.hookChildProcess(spawned, parsed);
return spawned;
}
function spawnSync(command, args, options2) {
const parsed = parse$3(command, args, options2);
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
return result;
}
crossSpawn.exports = spawn;
crossSpawn.exports.spawn = spawn;
crossSpawn.exports.sync = spawnSync;
crossSpawn.exports._parse = parse$3;
crossSpawn.exports._enoent = enoent;
var crossSpawnExports = crossSpawn.exports;
var spawn$1 = getDefaultExportFromCjs(crossSpawnExports);
function openBrowser(url2, opt, logger) {
const browser2 = process.env.BROWSER || "";
if (browser2.toLowerCase().endsWith(".js")) {
executeNodeScript(browser2, url2, logger);
} else if (browser2.toLowerCase() !== "none") {
const browserArgs = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [];
startBrowserProcess(browser2, browserArgs, url2, logger);
}
}
function executeNodeScript(scriptPath, url2, logger) {
const extraArgs = process.argv.slice(2);
const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url2], {
stdio: "inherit"
});
child.on("close", (code) => {
if (code !== 0) {
logger.error(
colors$1.red(
`
The script specified as BROWSER environment variable failed.
${colors$1.cyan(
scriptPath
)} exited with code ${code}.`
),
{ error: null }
);
}
});
}
var supportedChromiumBrowsers = [
"Google Chrome Canary",
"Google Chrome Dev",
"Google Chrome Beta",
"Google Chrome",
"Microsoft Edge",
"Brave Browser",
"Vivaldi",
"Chromium"
];
async function startBrowserProcess(browser2, browserArgs, url2, logger) {
const preferredOSXBrowser = browser2 === "google chrome" ? "Google Chrome" : browser2;
const shouldTryOpenChromeWithAppleScript = process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser));
if (shouldTryOpenChromeWithAppleScript) {
try {
const ps = await execAsync("ps cax");
const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b));
if (openedBrowser) {
await execAsync(
`osascript openChrome.applescript "${encodeURI(
url2
)}" "${openedBrowser}"`,
{
cwd: (0, import_node_path3.join)(VITE_PACKAGE_DIR, "bin")
}
);
return true;
}
} catch (err2) {
}
}
if (process.platform === "darwin" && browser2 === "open") {
browser2 = void 0;
}
try {
const options2 = browser2 ? { app: { name: browser2, arguments: browserArgs } } : {};
new Promise((_, reject) => {
open$1(url2, options2).then((subprocess) => {
subprocess.on("error", reject);
}).catch(reject);
}).catch((err2) => {
logger.error(err2.stack || err2.message);
});
return true;
} catch (err2) {
return false;
}
}
function execAsync(command, options2) {
return new Promise((resolve3, reject) => {
(0, import_node_child_process.exec)(command, options2, (error2, stdout) => {
if (error2) {
reject(error2);
} else {
resolve3(stdout.toString());
}
});
});
}
function bindCLIShortcuts(server2, opts) {
if (!server2.httpServer || !process.stdin.isTTY || process.env.CI) {
return;
}
const isDev = isDevServer(server2);
if (isDev) {
server2._shortcutsOptions = opts;
}
if (opts == null ? void 0 : opts.print) {
server2.config.logger.info(
colors$1.dim(colors$1.green(" ➜")) + colors$1.dim(" press ") + colors$1.bold("h + enter") + colors$1.dim(" to show help")
);
}
const shortcuts = ((opts == null ? void 0 : opts.customShortcuts) ?? []).concat(
isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS
);
let actionRunning = false;
const onInput = async (input) => {
if (actionRunning) return;
if (input === "h") {
const loggedKeys = /* @__PURE__ */ new Set();
server2.config.logger.info("\n Shortcuts");
for (const shortcut2 of shortcuts) {
if (loggedKeys.has(shortcut2.key)) continue;
loggedKeys.add(shortcut2.key);
if (shortcut2.action == null) continue;
server2.config.logger.info(
colors$1.dim(" press ") + colors$1.bold(`${shortcut2.key} + enter`) + colors$1.dim(` to ${shortcut2.description}`)
);
}
return;
}
const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input);
if (!shortcut || shortcut.action == null) return;
actionRunning = true;
await shortcut.action(server2);
actionRunning = false;
};
const rl = import_node_readline.default.createInterface({ input: process.stdin });
rl.on("line", onInput);
server2.httpServer.on("close", () => rl.close());
}
var BASE_DEV_SHORTCUTS = [
{
key: "r",
description: "restart the server",
async action(server2) {
await restartServerWithUrls(server2);
}
},
{
key: "u",
description: "show server url",
action(server2) {
server2.config.logger.info("");
server2.printUrls();
}
},
{
key: "o",
description: "open in browser",
action(server2) {
server2.openBrowser();
}
},
{
key: "c",
description: "clear console",
action(server2) {
server2.config.logger.clearScreen("error");
}
},
{
key: "q",
description: "quit",
async action(server2) {
try {
await server2.close();
} finally {
process.exit();
}
}
}
];
var BASE_PREVIEW_SHORTCUTS = [
{
key: "o",
description: "open in browser",
action(server2) {
var _a4, _b3;
const url2 = ((_a4 = server2.resolvedUrls) == null ? void 0 : _a4.local[0]) ?? ((_b3 = server2.resolvedUrls) == null ? void 0 : _b3.network[0]);
if (url2) {
openBrowser(url2, true, server2.config.logger);
} else {
server2.config.logger.warn("No URL available to open in browser");
}
}
},
{
key: "q",
description: "quit",
async action(server2) {
try {
await server2.close();
} finally {
process.exit();
}
}
}
];
function getResolvedOutDirs(root, outDir, outputOptions) {
const resolvedOutDir = import_node_path3.default.resolve(root, outDir);
if (!outputOptions) return /* @__PURE__ */ new Set([resolvedOutDir]);
return new Set(
arraify(outputOptions).map(
({ dir }) => dir ? import_node_path3.default.resolve(root, dir) : resolvedOutDir
)
);
}
function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
if (emptyOutDir != null) return emptyOutDir;
for (const outDir of outDirs) {
if (!normalizePath$3(outDir).startsWith(withTrailingSlash(root))) {
logger == null ? void 0 : logger.warn(
picocolorsExports.yellow(
`
${picocolorsExports.bold(`(!)`)} outDir ${picocolorsExports.white(
picocolorsExports.dim(outDir)
)} is not inside project root and will not be emptied.
Use --emptyOutDir to override.
`
)
);
return false;
}
}
return true;
}
function resolveChokidarOptions(config2, options2, resolvedOutDirs, emptyOutDir) {
const { ignored: ignoredList, ...otherOptions } = options2 ?? {};
const ignored = [
"**/.git/**",
"**/node_modules/**",
"**/test-results/**",
// Playwright
glob.escapePath(config2.cacheDir) + "/**",
...arraify(ignoredList || [])
];
if (emptyOutDir) {
ignored.push(
...[...resolvedOutDirs].map((outDir) => glob.escapePath(outDir) + "/**")
);
}
const resolvedWatchOptions = {
ignored,
ignoreInitial: true,
ignorePermissionErrors: true,
...otherOptions
};
return resolvedWatchOptions;
}
var NoopWatcher = class extends import_node_events.EventEmitter {
constructor(options2) {
super();
this.options = options2;
}
add() {
return this;
}
unwatch() {
return this;
}
getWatched() {
return {};
}
ref() {
return this;
}
unref() {
return this;
}
async close() {
}
};
function createNoopWatcher(options2) {
return new NoopWatcher(options2);
}
async function fetchModule(server2, url2, importer, options2 = {}) {
var _a4;
if (url2.startsWith("data:") || isBuiltin(url2)) {
return { externalize: url2, type: "builtin" };
}
if (isExternalUrl(url2)) {
return { externalize: url2, type: "network" };
}
if (url2[0] !== "." && url2[0] !== "/") {
const {
isProduction,
resolve: { dedupe, preserveSymlinks },
root,
ssr
} = server2.config;
const overrideConditions = ((_a4 = ssr.resolve) == null ? void 0 : _a4.externalConditions) || [];
const resolveOptions = {
mainFields: ["main"],
conditions: [],
overrideConditions: [...overrideConditions, "production", "development"],
extensions: [".js", ".cjs", ".json"],
dedupe,
preserveSymlinks,
isBuild: false,
isProduction,
root,
ssrConfig: ssr,
packageCache: server2.config.packageCache
};
const resolved = tryNodeResolve(
url2,
importer,
{ ...resolveOptions, tryEsmOnly: true },
false,
void 0,
true
);
if (!resolved) {
const err2 = new Error(
`Cannot find module '${url2}' imported from '${importer}'`
);
err2.code = "ERR_MODULE_NOT_FOUND";
throw err2;
}
const file = (0, import_node_url2.pathToFileURL)(resolved.id).toString();
const type = isFilePathESM(resolved.id, server2.config.packageCache) ? "module" : "commonjs";
return { externalize: file, type };
}
url2 = unwrapId$1(url2);
let result = await server2.transformRequest(url2, { ssr: true });
if (!result) {
throw new Error(
`[vite] transform failed for module '${url2}'${importer ? ` imported from '${importer}'` : ""}.`
);
}
const mod = await server2.moduleGraph.getModuleByUrl(url2, true);
if (!mod) {
throw new Error(
`[vite] cannot find module '${url2}' ${importer ? ` imported from '${importer}'` : ""}.`
);
}
if (options2.inlineSourceMap !== false) {
result = inlineSourceMap(mod, result, options2.processSourceMap);
}
if (result.code[0] === "#")
result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
return { code: result.code, file: mod.file };
}
var OTHER_SOURCE_MAP_REGEXP = new RegExp(
`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`,
"gm"
);
function inlineSourceMap(mod, result, processSourceMap) {
const map2 = result.map;
let code = result.code;
if (!map2 || !("version" in map2) || code.includes(VITE_RUNTIME_SOURCEMAPPING_SOURCE))
return result;
OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
if (OTHER_SOURCE_MAP_REGEXP.test(code))
code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
const sourceMap = (processSourceMap == null ? void 0 : processSourceMap(map2)) || map2;
result.code = `${code.trimEnd()}
//# sourceURL=${mod.id}
${VITE_RUNTIME_SOURCEMAPPING_SOURCE}
//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}
`;
return result;
}
function ssrFetchModule(server2, id, importer) {
return fetchModule(server2, id, importer, {
processSourceMap(map2) {
return Object.assign({}, map2, {
mappings: ";".repeat(asyncFunctionDeclarationPaddingLineCount) + map2.mappings
});
}
});
}
var bufferUtil$1 = { exports: {} };
var BINARY_TYPES$2 = ["nodebuffer", "arraybuffer", "fragments"];
var hasBlob$1 = typeof Blob !== "undefined";
if (hasBlob$1) BINARY_TYPES$2.push("blob");
var constants = {
BINARY_TYPES: BINARY_TYPES$2,
EMPTY_BUFFER: Buffer.alloc(0),
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
hasBlob: hasBlob$1,
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
kListener: Symbol("kListener"),
kStatusCode: Symbol("status-code"),
kWebSocket: Symbol("websocket"),
NOOP: () => {
}
};
var { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants;
var FastBuffer$2 = Buffer[Symbol.species];
function concat$1(list, totalLength) {
if (list.length === 0) return EMPTY_BUFFER$3;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength);
let offset2 = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
target.set(buf, offset2);
offset2 += buf.length;
}
if (offset2 < totalLength) {
return new FastBuffer$2(target.buffer, target.byteOffset, offset2);
}
return target;
}
function _mask(source, mask, output, offset2, length) {
for (let i = 0; i < length; i++) {
output[offset2 + i] = source[i] ^ mask[i & 3];
}
}
function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
}
function toArrayBuffer$1(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
function toBuffer$2(data) {
toBuffer$2.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = new FastBuffer$2(data);
} else if (ArrayBuffer.isView(data)) {
buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer$2.readOnly = false;
}
return buf;
}
bufferUtil$1.exports = {
concat: concat$1,
mask: _mask,
toArrayBuffer: toArrayBuffer$1,
toBuffer: toBuffer$2,
unmask: _unmask
};
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil2 = require2("bufferutil");
bufferUtil$1.exports.mask = function(source, mask, output, offset2, length) {
if (length < 48) _mask(source, mask, output, offset2, length);
else bufferUtil2.mask(source, mask, output, offset2, length);
};
bufferUtil$1.exports.unmask = function(buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil2.unmask(buffer, mask);
};
} catch (e2) {
}
}
var bufferUtilExports = bufferUtil$1.exports;
var kDone = Symbol("kDone");
var kRun = Symbol("kRun");
var Limiter$1 = class Limiter {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
};
var limiter = Limiter$1;
var zlib = import_zlib.default;
var bufferUtil = bufferUtilExports;
var Limiter2 = limiter;
var { kStatusCode: kStatusCode$2 } = constants;
var FastBuffer$1 = Buffer[Symbol.species];
var TRAILER = Buffer.from([0, 0, 255, 255]);
var kPerMessageDeflate = Symbol("permessage-deflate");
var kTotalLength = Symbol("total-length");
var kCallback = Symbol("callback");
var kBuffers = Symbol("buffers");
var kError$1 = Symbol("error");
var zlibLimiter;
var PerMessageDeflate$4 = class PerMessageDeflate {
/**
* Creates a PerMessageDeflate instance.
*
* @param {Object} [options] Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
* for, or request, a custom client window size
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
* acknowledge disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
* calls to zlib
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
* disabling of server context takeover
* @param {Number} [options.threshold=1024] Size (in bytes) below which
* messages should not be compressed if context takeover is disabled
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
* deflate
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
* inflate
* @param {Boolean} [isServer=false] Create the instance in either server or
* client mode
* @param {Number} [maxPayload=0] The maximum allowed message length
*/
constructor(options2, isServer, maxPayload) {
this._maxPayload = maxPayload | 0;
this._options = options2 || {};
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
this._isServer = !!isServer;
this._deflate = null;
this._inflate = null;
this.params = null;
if (!zlibLimiter) {
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
zlibLimiter = new Limiter2(concurrency);
}
}
/**
* @type {String}
*/
static get extensionName() {
return "permessage-deflate";
}
/**
* Create an extension negotiation offer.
*
* @return {Object} Extension parameters
* @public
*/
offer() {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept an extension negotiation offer/response.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Object} Accepted configuration
* @public
*/
accept(configurations) {
configurations = this.normalizeParams(configurations);
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
return this.params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup() {
if (this._inflate) {
this._inflate.close();
this._inflate = null;
}
if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
"The deflate stream was closed while data was being processed"
)
);
}
}
}
/**
* Accept an extension negotiation offer.
*
* @param {Array} offers The extension negotiation offers
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer(offers) {
const opts = this._options;
const accepted = offers.find((params) => {
if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
return false;
}
return true;
});
if (!accepted) {
throw new Error("None of the extension offers can be accepted");
}
if (opts.serverNoContextTakeover) {
accepted.server_no_context_takeover = true;
}
if (opts.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (typeof opts.serverMaxWindowBits === "number") {
accepted.server_max_window_bits = opts.serverMaxWindowBits;
}
if (typeof opts.clientMaxWindowBits === "number") {
accepted.client_max_window_bits = opts.clientMaxWindowBits;
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
delete accepted.client_max_window_bits;
}
return accepted;
}
/**
* Accept the extension negotiation response.
*
* @param {Array} response The extension negotiation response
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient(response) {
const params = response[0];
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
throw new Error('Unexpected parameter "client_no_context_takeover"');
}
if (!params.client_max_window_bits) {
if (typeof this._options.clientMaxWindowBits === "number") {
params.client_max_window_bits = this._options.clientMaxWindowBits;
}
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
throw new Error(
'Unexpected or invalid parameter "client_max_window_bits"'
);
}
return params;
}
/**
* Normalize parameters.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Array} The offers/response with normalized parameters
* @private
*/
normalizeParams(configurations) {
configurations.forEach((params) => {
Object.keys(params).forEach((key) => {
let value2 = params[key];
if (value2.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`);
}
value2 = value2[0];
if (key === "client_max_window_bits") {
if (value2 !== true) {
const num = +value2;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
value2 = num;
} else if (!this._isServer) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
} else if (key === "server_max_window_bits") {
const num = +value2;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
value2 = num;
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
if (value2 !== true) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
} else {
throw new Error(`Unknown parameter "${key}"`);
}
params[key] = value2;
});
});
return configurations;
}
/**
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err2, result) => {
done();
callback(err2, result);
});
});
}
/**
* Compress data. Concurrency limited.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress(data, fin, callback) {
zlibLimiter.add((done) => {
this._compress(data, fin, (err2, result) => {
done();
callback(err2, result);
});
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_decompress(data, fin, callback) {
const endpoint = this._isServer ? "client" : "server";
if (!this._inflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._inflate = zlib.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on("error", inflateOnError);
this._inflate.on("data", inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const err2 = this._inflate[kError$1];
if (err2) {
this._inflate.close();
this._inflate = null;
callback(err2);
return;
}
const data2 = bufferUtil.concat(
this._inflate[kBuffers],
this._inflate[kTotalLength]
);
if (this._inflate._readableState.endEmitted) {
this._inflate.close();
this._inflate = null;
} else {
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
}
callback(null, data2);
});
}
/**
* Compress data.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_compress(data, fin, callback) {
const endpoint = this._isServer ? "server" : "client";
if (!this._deflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._deflate = zlib.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on("data", deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
return;
}
let data2 = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data2 = new FastBuffer$1(data2.buffer, data2.byteOffset, data2.length - 4);
}
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data2);
});
}
};
var permessageDeflate = PerMessageDeflate$4;
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
function inflateOnData(chunk) {
this[kTotalLength] += chunk.length;
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
this[kBuffers].push(chunk);
return;
}
this[kError$1] = new RangeError("Max payload size exceeded");
this[kError$1].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
this[kError$1][kStatusCode$2] = 1009;
this.removeListener("data", inflateOnData);
this.reset();
}
function inflateOnError(err2) {
this[kPerMessageDeflate]._inflate = null;
err2[kStatusCode$2] = 1007;
this[kCallback](err2);
}
var validation = { exports: {} };
var { isUtf8 } = import_buffer.default;
var { hasBlob } = constants;
var tokenChars$2 = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 0 - 15
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 16 - 31
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
// 32 - 47
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
// 48 - 63
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 64 - 79
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
// 80 - 95
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 96 - 111
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0
// 112 - 127
];
function isValidStatusCode$2(code) {
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
}
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 128) === 0) {
i++;
} else if ((buf[i] & 224) === 192) {
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
return false;
}
i += 2;
} else if ((buf[i] & 240) === 224) {
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
return false;
}
i += 3;
} else if ((buf[i] & 248) === 240) {
if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
function isBlob$2(value2) {
return hasBlob && typeof value2 === "object" && typeof value2.arrayBuffer === "function" && typeof value2.type === "string" && typeof value2.stream === "function" && (value2[Symbol.toStringTag] === "Blob" || value2[Symbol.toStringTag] === "File");
}
validation.exports = {
isBlob: isBlob$2,
isValidStatusCode: isValidStatusCode$2,
isValidUTF8: _isValidUTF8,
tokenChars: tokenChars$2
};
if (isUtf8) {
validation.exports.isValidUTF8 = function(buf) {
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
};
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF82 = require2("utf-8-validate");
validation.exports.isValidUTF8 = function(buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF82(buf);
};
} catch (e2) {
}
}
var validationExports = validation.exports;
var { Writable: Writable$1 } = import_stream.default;
var PerMessageDeflate$3 = permessageDeflate;
var {
BINARY_TYPES: BINARY_TYPES$1,
EMPTY_BUFFER: EMPTY_BUFFER$2,
kStatusCode: kStatusCode$1,
kWebSocket: kWebSocket$3
} = constants;
var { concat, toArrayBuffer, unmask } = bufferUtilExports;
var { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports;
var FastBuffer = Buffer[Symbol.species];
var GET_INFO = 0;
var GET_PAYLOAD_LENGTH_16 = 1;
var GET_PAYLOAD_LENGTH_64 = 2;
var GET_MASK = 3;
var GET_DATA = 4;
var INFLATING = 5;
var DEFER_EVENT = 6;
var Receiver$1 = class Receiver extends Writable$1 {
/**
* Creates a Receiver instance.
*
* @param {Object} [options] Options object
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {String} [options.binaryType=nodebuffer] The type for binary data
* @param {Object} [options.extensions] An object containing the negotiated
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/
constructor(options2 = {}) {
super();
this._allowSynchronousEvents = options2.allowSynchronousEvents !== void 0 ? options2.allowSynchronousEvents : true;
this._binaryType = options2.binaryType || BINARY_TYPES$1[0];
this._extensions = options2.extensions || {};
this._isServer = !!options2.isServer;
this._maxPayload = options2.maxPayload | 0;
this._skipUTF8Validation = !!options2.skipUTF8Validation;
this[kWebSocket$3] = void 0;
this._bufferedBytes = 0;
this._buffers = [];
this._compressed = false;
this._payloadLength = 0;
this._mask = void 0;
this._fragmented = 0;
this._masked = false;
this._fin = false;
this._opcode = 0;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragments = [];
this._errored = false;
this._loop = false;
this._state = GET_INFO;
}
/**
* Implements `Writable.prototype._write()`.
*
* @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback
* @private
*/
_write(chunk, encoding, cb) {
if (this._opcode === 8 && this._state == GET_INFO) return cb();
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n2) {
this._bufferedBytes -= n2;
if (n2 === this._buffers[0].length) return this._buffers.shift();
if (n2 < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n2,
buf.length - n2
);
return new FastBuffer(buf.buffer, buf.byteOffset, n2);
}
const dst = Buffer.allocUnsafe(n2);
do {
const buf = this._buffers[0];
const offset2 = dst.length - n2;
if (n2 >= buf.length) {
dst.set(this._buffers.shift(), offset2);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n2), offset2);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n2,
buf.length - n2
);
}
n2 -= buf.length;
} while (n2 > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 48) !== 0) {
const error2 = this.createError(
RangeError,
"RSV2 and RSV3 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_2_3"
);
cb(error2);
return;
}
const compressed = (buf[0] & 64) === 64;
if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error2);
return;
}
this._fin = (buf[0] & 128) === 128;
this._opcode = buf[0] & 15;
this._payloadLength = buf[1] & 127;
if (this._opcode === 0) {
if (compressed) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error2);
return;
}
if (!this._fragmented) {
const error2 = this.createError(
RangeError,
"invalid opcode 0",
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error2);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 1 || this._opcode === 2) {
if (this._fragmented) {
const error2 = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error2);
return;
}
this._compressed = compressed;
} else if (this._opcode > 7 && this._opcode < 11) {
if (!this._fin) {
const error2 = this.createError(
RangeError,
"FIN must be set",
true,
1002,
"WS_ERR_EXPECTED_FIN"
);
cb(error2);
return;
}
if (compressed) {
const error2 = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error2);
return;
}
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
const error2 = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
);
cb(error2);
return;
}
} else {
const error2 = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error2);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 128) === 128;
if (this._isServer) {
if (!this._masked) {
const error2 = this.createError(
RangeError,
"MASK must be set",
true,
1002,
"WS_ERR_EXPECTED_MASK"
);
cb(error2);
return;
}
} else if (this._masked) {
const error2 = this.createError(
RangeError,
"MASK must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_MASK"
);
cb(error2);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
if (num > Math.pow(2, 53 - 32) - 1) {
const error2 = this.createError(
RangeError,
"Unsupported WebSocket frame: payload length > 2^53 - 1",
false,
1009,
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
);
cb(error2);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb) {
if (this._payloadLength && this._opcode < 8) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error2 = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error2);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb) {
let data = EMPTY_BUFFER$2;
if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) {
this._loop = false;
return;
}
data = this.consume(this._payloadLength);
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
unmask(data, this._mask);
}
}
if (this._opcode > 7) {
this.controlMessage(data, cb);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb);
return;
}
if (data.length) {
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName];
perMessageDeflate.decompress(data, this._fin, (err2, buf) => {
if (err2) return cb(err2);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error2 = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error2);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb);
if (this._state === GET_INFO) this.startLoop(cb);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === "nodebuffer") {
data = concat(fragments, messageLength);
} else if (this._binaryType === "arraybuffer") {
data = toArrayBuffer(concat(fragments, messageLength));
} else if (this._binaryType === "blob") {
data = new Blob(fragments);
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit("message", data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", data, true);
this._state = GET_INFO;
this.startLoop(cb);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error2 = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error2);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit("message", buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", buf, false);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb) {
if (this._opcode === 8) {
if (data.length === 0) {
this._loop = false;
this.emit("conclude", 1005, EMPTY_BUFFER$2);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode$1(code)) {
const error2 = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
"WS_ERR_INVALID_CLOSE_CODE"
);
cb(error2);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error2 = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error2);
return;
}
this._loop = false;
this.emit("conclude", code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
/**
* Builds an error object.
*
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message`
* @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error
* @private
*/
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
this._loop = false;
this._errored = true;
const err2 = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message
);
Error.captureStackTrace(err2, this.createError);
err2.code = errorCode;
err2[kStatusCode$1] = statusCode;
return err2;
}
};
var receiver = Receiver$1;
var { randomFillSync } = import_crypto.default;
var PerMessageDeflate$2 = permessageDeflate;
var { EMPTY_BUFFER: EMPTY_BUFFER$1, kWebSocket: kWebSocket$2, NOOP: NOOP$2 } = constants;
var { isBlob: isBlob$1, isValidStatusCode } = validationExports;
var { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports;
var kByteLength = Symbol("kByteLength");
var maskBuffer = Buffer.alloc(4);
var RANDOM_POOL_SIZE = 8 * 1024;
var randomPool;
var randomPoolPointer = RANDOM_POOL_SIZE;
var DEFAULT = 0;
var DEFLATING = 1;
var GET_BLOB_DATA = 2;
var Sender$1 = class Sender {
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions2, generateMask) {
this._extensions = extensions2 || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._queue = [];
this._state = DEFAULT;
this.onerror = NOOP$2;
this[kWebSocket$2] = void 0;
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options2) {
let mask;
let merge3 = false;
let offset2 = 2;
let skipMasking = false;
if (options2.mask) {
mask = options2.maskBuffer || maskBuffer;
if (options2.generateMask) {
options2.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
if (randomPool === void 0) {
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset2 = 6;
}
let dataLength;
if (typeof data === "string") {
if ((!options2.mask || skipMasking) && options2[kByteLength] !== void 0) {
dataLength = options2[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge3 = options2.mask && options2.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset2 += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset2 += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge3 ? dataLength + offset2 : offset2);
target[0] = options2.fin ? options2.opcode | 128 : options2.opcode;
if (options2.rsv1) target[0] |= 64;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options2.mask) return [target, data];
target[1] |= 128;
target[offset2 - 4] = mask[0];
target[offset2 - 3] = mask[1];
target[offset2 - 2] = mask[2];
target[offset2 - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge3) {
applyMask(data, mask, target, offset2, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb) {
let buf;
if (code === void 0) {
buf = EMPTY_BUFFER$1;
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
throw new TypeError("First argument must be a valid error code number");
} else if (data === void 0 || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError("The message must not be greater than 123 bytes");
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === "string") {
buf.write(data, 2);
} else {
buf.set(data, 2);
}
}
const options2 = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 8,
readOnly: false,
rsv1: false
};
if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, buf, false, options2, cb]);
} else {
this.sendFrame(Sender.frame(buf, options2), cb);
}
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
ping(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob$1(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer$1(data);
byteLength = data.length;
readOnly = toBuffer$1.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options2 = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 9,
readOnly,
rsv1: false
};
if (isBlob$1(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options2, cb]);
} else {
this.getBlobData(data, false, options2, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options2, cb]);
} else {
this.sendFrame(Sender.frame(data, options2), cb);
}
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
pong(data, mask, cb) {
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob$1(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer$1(data);
byteLength = data.length;
readOnly = toBuffer$1.readOnly;
}
if (byteLength > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options2 = {
[kByteLength]: byteLength,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 10,
readOnly,
rsv1: false
};
if (isBlob$1(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, false, options2, cb]);
} else {
this.getBlobData(data, false, options2, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, false, options2, cb]);
} else {
this.sendFrame(Sender.frame(data, options2), cb);
}
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
* or text
* @param {Boolean} [options.compress=false] Specifies whether or not to
* compress `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public
*/
send(data, options2, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
let opcode = options2.binary ? 2 : 1;
let rsv1 = options2.compress;
let byteLength;
let readOnly;
if (typeof data === "string") {
byteLength = Buffer.byteLength(data);
readOnly = false;
} else if (isBlob$1(data)) {
byteLength = data.size;
readOnly = false;
} else {
data = toBuffer$1(data);
byteLength = data.length;
readOnly = toBuffer$1.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
rsv1 = byteLength >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options2.fin) this._firstFragment = true;
const opts = {
[kByteLength]: byteLength,
fin: options2.fin,
generateMask: this._generateMask,
mask: options2.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (isBlob$1(data)) {
if (this._state !== DEFAULT) {
this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
} else {
this.getBlobData(data, this._compress, opts, cb);
}
} else if (this._state !== DEFAULT) {
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
} else {
this.dispatch(data, this._compress, opts, cb);
}
}
/**
* Gets the contents of a blob as binary data.
*
* @param {Blob} blob The blob
* @param {Boolean} [compress=false] Specifies whether or not to compress
* the data
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
getBlobData(blob, compress, options2, cb) {
this._bufferedBytes += options2[kByteLength];
this._state = GET_BLOB_DATA;
blob.arrayBuffer().then((arrayBuffer) => {
if (this._socket.destroyed) {
const err2 = new Error(
"The socket was closed while the blob was being read"
);
process.nextTick(callCallbacks, this, err2, cb);
return;
}
this._bufferedBytes -= options2[kByteLength];
const data = toBuffer$1(arrayBuffer);
if (!compress) {
this._state = DEFAULT;
this.sendFrame(Sender.frame(data, options2), cb);
this.dequeue();
} else {
this.dispatch(data, compress, options2, cb);
}
}).catch((err2) => {
process.nextTick(onError, this, err2, cb);
});
}
/**
* Dispatches a message.
*
* @param {(Buffer|String)} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress
* `data`
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
dispatch(data, compress, options2, cb) {
if (!compress) {
this.sendFrame(Sender.frame(data, options2), cb);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName];
this._bufferedBytes += options2[kByteLength];
this._state = DEFLATING;
perMessageDeflate.compress(data, options2.fin, (_, buf) => {
if (this._socket.destroyed) {
const err2 = new Error(
"The socket was closed while data was being compressed"
);
callCallbacks(this, err2, cb);
return;
}
this._bufferedBytes -= options2[kByteLength];
this._state = DEFAULT;
options2.readOnly = false;
this.sendFrame(Sender.frame(buf, options2), cb);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (this._state === DEFAULT && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {Buffer[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb);
this._socket.uncork();
} else {
this._socket.write(list[0], cb);
}
}
};
var sender = Sender$1;
function callCallbacks(sender2, err2, cb) {
if (typeof cb === "function") cb(err2);
for (let i = 0; i < sender2._queue.length; i++) {
const params = sender2._queue[i];
const callback = params[params.length - 1];
if (typeof callback === "function") callback(err2);
}
}
function onError(sender2, err2, cb) {
callCallbacks(sender2, err2, cb);
sender2.onerror(err2);
}
var { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants;
var kCode = Symbol("kCode");
var kData = Symbol("kData");
var kError = Symbol("kError");
var kMessage = Symbol("kMessage");
var kReason = Symbol("kReason");
var kTarget = Symbol("kTarget");
var kType = Symbol("kType");
var kWasClean = Symbol("kWasClean");
var Event$1 = class Event2 {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
};
Object.defineProperty(Event$1.prototype, "target", { enumerable: true });
Object.defineProperty(Event$1.prototype, "type", { enumerable: true });
var CloseEvent = class extends Event$1 {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options2 = {}) {
super(type);
this[kCode] = options2.code === void 0 ? 0 : options2.code;
this[kReason] = options2.reason === void 0 ? "" : options2.reason;
this[kWasClean] = options2.wasClean === void 0 ? false : options2.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
};
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
var ErrorEvent = class extends Event$1 {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options2 = {}) {
super(type);
this[kError] = options2.error === void 0 ? null : options2.error;
this[kMessage] = options2.message === void 0 ? "" : options2.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
};
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
var MessageEvent = class extends Event$1 {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options2 = {}) {
super(type);
this[kData] = options2.data === void 0 ? null : options2.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
};
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
var EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options2 = {}) {
for (const listener2 of this.listeners(type)) {
if (!options2[kForOnEventAttribute$1] && listener2[kListener$1] === handler && !listener2[kForOnEventAttribute$1]) {
return;
}
}
let wrapper;
if (type === "message") {
wrapper = function onMessage(data, isBinary) {
const event = new MessageEvent("message", {
data: isBinary ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "close") {
wrapper = function onClose(code, message) {
const event = new CloseEvent("close", {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "error") {
wrapper = function onError2(error2) {
const event = new ErrorEvent("error", {
error: error2,
message: error2.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "open") {
wrapper = function onOpen() {
const event = new Event$1("open");
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute$1] = !!options2[kForOnEventAttribute$1];
wrapper[kListener$1] = handler;
if (options2.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener2 of this.listeners(type)) {
if (listener2[kListener$1] === handler && !listener2[kForOnEventAttribute$1]) {
this.removeListener(type, listener2);
break;
}
}
}
};
var eventTarget = {
CloseEvent,
ErrorEvent,
Event: Event$1,
EventTarget,
MessageEvent
};
function callListener(listener2, thisArg, event) {
if (typeof listener2 === "object" && listener2.handleEvent) {
listener2.handleEvent.call(listener2, event);
} else {
listener2.call(thisArg, event);
}
}
var { tokenChars: tokenChars$1 } = validationExports;
function push(dest, name2, elem) {
if (dest[name2] === void 0) dest[name2] = [elem];
else dest[name2].push(elem);
}
function parse$2(header) {
const offers = /* @__PURE__ */ Object.create(null);
let params = /* @__PURE__ */ Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === void 0) {
if (end === -1 && tokenChars$1[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name2 = header.slice(start, end);
if (code === 44) {
push(offers, name2, params);
params = /* @__PURE__ */ Object.create(null);
} else {
extensionName = name2;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === void 0) {
if (end === -1 && tokenChars$1[code] === 1) {
if (start === -1) start = i;
} else if (code === 32 || code === 9) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
start = end = -1;
} else if (code === 61 && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
if (isEscaping) {
if (tokenChars$1[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars$1[code] === 1) {
if (start === -1) start = i;
} else if (code === 34 && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 92) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
inQuotes = true;
} else if (end === -1 && tokenChars$1[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 32 || code === 9)) {
if (end === -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value2 = header.slice(start, end);
if (mustUnescape) {
value2 = value2.replace(/\\/g, "");
mustUnescape = false;
}
push(params, paramName, value2);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
paramName = void 0;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 32 || code === 9) {
throw new SyntaxError("Unexpected end of input");
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === void 0) {
push(offers, token, params);
} else {
if (paramName === void 0) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ""));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
function format$1(extensions2) {
return Object.keys(extensions2).map((extension2) => {
let configurations = extensions2[extension2];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations.map((params) => {
return [extension2].concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
})
).join("; ");
}).join(", ");
}).join(", ");
}
var extension$1 = { format: format$1, parse: parse$2 };
var EventEmitter$1 = import_events.default;
var https$2 = import_https.default;
var http$3 = import_http.default;
var net = import_net.default;
var tls = import_tls.default;
var { randomBytes, createHash: createHash$1 } = import_crypto.default;
var { URL: URL$2 } = import_url.default;
var PerMessageDeflate$1 = permessageDeflate;
var Receiver2 = receiver;
var Sender2 = sender;
var { isBlob } = validationExports;
var {
BINARY_TYPES,
EMPTY_BUFFER,
GUID: GUID$1,
kForOnEventAttribute,
kListener,
kStatusCode,
kWebSocket: kWebSocket$1,
NOOP: NOOP$1
} = constants;
var {
EventTarget: { addEventListener, removeEventListener }
} = eventTarget;
var { format, parse: parse$1 } = extension$1;
var { toBuffer } = bufferUtilExports;
var closeTimeout = 30 * 1e3;
var kAborted = Symbol("kAborted");
var protocolVersions = [8, 13];
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
var WebSocket$1 = class WebSocket extends EventEmitter$1 {
/**
* Create a new `WebSocket`.
*
* @param {(String|URL)} address The URL to which to connect
* @param {(String|String[])} [protocols] The subprotocols
* @param {Object} [options] Connection options
*/
constructor(address, protocols, options2) {
super();
this._binaryType = BINARY_TYPES[0];
this._closeCode = 1006;
this._closeFrameReceived = false;
this._closeFrameSent = false;
this._closeMessage = EMPTY_BUFFER;
this._closeTimer = null;
this._errorEmitted = false;
this._extensions = {};
this._paused = false;
this._protocol = "";
this._readyState = WebSocket.CONNECTING;
this._receiver = null;
this._sender = null;
this._socket = null;
if (address !== null) {
this._bufferedAmount = 0;
this._isServer = false;
this._redirects = 0;
if (protocols === void 0) {
protocols = [];
} else if (!Array.isArray(protocols)) {
if (typeof protocols === "object" && protocols !== null) {
options2 = protocols;
protocols = [];
} else {
protocols = [protocols];
}
}
initAsClient(this, address, protocols, options2);
} else {
this._autoPong = options2.autoPong;
this._isServer = true;
}
}
/**
* For historical reasons, the custom "nodebuffer" type is used by the default
* instead of "blob".
*
* @type {String}
*/
get binaryType() {
return this._binaryType;
}
set binaryType(type) {
if (!BINARY_TYPES.includes(type)) return;
this._binaryType = type;
if (this._receiver) this._receiver._binaryType = type;
}
/**
* @type {Number}
*/
get bufferedAmount() {
if (!this._socket) return this._bufferedAmount;
return this._socket._writableState.length + this._sender._bufferedBytes;
}
/**
* @type {String}
*/
get extensions() {
return Object.keys(this._extensions).join();
}
/**
* @type {Boolean}
*/
get isPaused() {
return this._paused;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onclose() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onerror() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onopen() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onmessage() {
return null;
}
/**
* @type {String}
*/
get protocol() {
return this._protocol;
}
/**
* @type {Number}
*/
get readyState() {
return this._readyState;
}
/**
* @type {String}
*/
get url() {
return this._url;
}
/**
* Set up the socket and the internal resources.
*
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options Options object
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Number} [options.maxPayload=0] The maximum allowed message size
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private
*/
setSocket(socket, head, options2) {
const receiver2 = new Receiver2({
allowSynchronousEvents: options2.allowSynchronousEvents,
binaryType: this.binaryType,
extensions: this._extensions,
isServer: this._isServer,
maxPayload: options2.maxPayload,
skipUTF8Validation: options2.skipUTF8Validation
});
const sender2 = new Sender2(socket, this._extensions, options2.generateMask);
this._receiver = receiver2;
this._sender = sender2;
this._socket = socket;
receiver2[kWebSocket$1] = this;
sender2[kWebSocket$1] = this;
socket[kWebSocket$1] = this;
receiver2.on("conclude", receiverOnConclude);
receiver2.on("drain", receiverOnDrain);
receiver2.on("error", receiverOnError);
receiver2.on("message", receiverOnMessage);
receiver2.on("ping", receiverOnPing);
receiver2.on("pong", receiverOnPong);
sender2.onerror = senderOnError;
if (socket.setTimeout) socket.setTimeout(0);
if (socket.setNoDelay) socket.setNoDelay();
if (head.length > 0) socket.unshift(head);
socket.on("close", socketOnClose);
socket.on("data", socketOnData);
socket.on("end", socketOnEnd);
socket.on("error", socketOnError$1);
this._readyState = WebSocket.OPEN;
this.emit("open");
}
/**
* Emit the `'close'` event.
*
* @private
*/
emitClose() {
if (!this._socket) {
this._readyState = WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
return;
}
if (this._extensions[PerMessageDeflate$1.extensionName]) {
this._extensions[PerMessageDeflate$1.extensionName].cleanup();
}
this._receiver.removeAllListeners();
this._readyState = WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
}
/**
* Start a closing handshake.
*
* +----------+ +-----------+ +----------+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
* | +----------+ +-----------+ +----------+ |
* +----------+ +-----------+ |
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
* +----------+ +-----------+ |
* | | | +---+ |
* +------------------------+-->|fin| - - - -
* | +---+ | +---+
* - - - - -|fin|<---------------------+
* +---+
*
* @param {Number} [code] Status code explaining why the connection is closing
* @param {(String|Buffer)} [data] The reason why the connection is
* closing
* @public
*/
close(code, data) {
if (this.readyState === WebSocket.CLOSED) return;
if (this.readyState === WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake$1(this, this._req, msg);
return;
}
if (this.readyState === WebSocket.CLOSING) {
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
this._socket.end();
}
return;
}
this._readyState = WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err2) => {
if (err2) return;
this._closeFrameSent = true;
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
this._socket.end();
}
});
setCloseTimer(this);
}
/**
* Pause the socket.
*
* @public
*/
pause() {
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
return;
}
this._paused = true;
this._socket.pause();
}
/**
* Send a ping.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the ping is sent
* @public
*/
ping(data, mask, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
}
/**
* Send a pong.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the pong is sent
* @public
*/
pong(data, mask, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
}
/**
* Resume the socket.
*
* @public
*/
resume() {
if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
return;
}
this._paused = false;
if (!this._receiver._writableState.needDrain) this._socket.resume();
}
/**
* Send a data message.
*
* @param {*} data The message to send
* @param {Object} [options] Options object
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
* text
* @param {Boolean} [options.compress] Specifies whether or not to compress
* `data`
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when data is written out
* @public
*/
send(data, options2, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof options2 === "function") {
cb = options2;
options2 = {};
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== "string",
mask: !this._isServer,
compress: true,
fin: true,
...options2
};
if (!this._extensions[PerMessageDeflate$1.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}
/**
* Forcibly close the connection.
*
* @public
*/
terminate() {
if (this.readyState === WebSocket.CLOSED) return;
if (this.readyState === WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake$1(this, this._req, msg);
return;
}
if (this._socket) {
this._readyState = WebSocket.CLOSING;
this._socket.destroy();
}
}
};
Object.defineProperty(WebSocket$1, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket$1.prototype, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket$1, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket$1.prototype, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket$1, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket$1.prototype, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket$1, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
Object.defineProperty(WebSocket$1.prototype, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
[
"binaryType",
"bufferedAmount",
"extensions",
"isPaused",
"protocol",
"readyState",
"url"
].forEach((property) => {
Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true });
});
["open", "error", "close", "message"].forEach((method) => {
Object.defineProperty(WebSocket$1.prototype, `on${method}`, {
enumerable: true,
get() {
for (const listener2 of this.listeners(method)) {
if (listener2[kForOnEventAttribute]) return listener2[kListener];
}
return null;
},
set(handler) {
for (const listener2 of this.listeners(method)) {
if (listener2[kForOnEventAttribute]) {
this.removeListener(method, listener2);
break;
}
}
if (typeof handler !== "function") return;
this.addEventListener(method, handler, {
[kForOnEventAttribute]: true
});
}
});
});
WebSocket$1.prototype.addEventListener = addEventListener;
WebSocket$1.prototype.removeEventListener = removeEventListener;
var websocket = WebSocket$1;
function initAsClient(websocket2, address, protocols, options2) {
const opts = {
allowSynchronousEvents: true,
autoPong: true,
protocolVersion: protocolVersions[1],
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: true,
followRedirects: false,
maxRedirects: 10,
...options2,
socketPath: void 0,
hostname: void 0,
protocol: void 0,
timeout: void 0,
method: "GET",
host: void 0,
path: void 0,
port: void 0
};
websocket2._autoPong = opts.autoPong;
if (!protocolVersions.includes(opts.protocolVersion)) {
throw new RangeError(
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
);
}
let parsedUrl;
if (address instanceof URL$2) {
parsedUrl = address;
} else {
try {
parsedUrl = new URL$2(address);
} catch (e2) {
throw new SyntaxError(`Invalid URL: ${address}`);
}
}
if (parsedUrl.protocol === "http:") {
parsedUrl.protocol = "ws:";
} else if (parsedUrl.protocol === "https:") {
parsedUrl.protocol = "wss:";
}
websocket2._url = parsedUrl.href;
const isSecure = parsedUrl.protocol === "wss:";
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
let invalidUrlMessage;
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
} else if (isIpcUrl && !parsedUrl.pathname) {
invalidUrlMessage = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
invalidUrlMessage = "The URL contains a fragment identifier";
}
if (invalidUrlMessage) {
const err2 = new SyntaxError(invalidUrlMessage);
if (websocket2._redirects === 0) {
throw err2;
} else {
emitErrorAndClose(websocket2, err2);
return;
}
}
const defaultPort = isSecure ? 443 : 80;
const key = randomBytes(16).toString("base64");
const request = isSecure ? https$2.request : http$3.request;
const protocolSet = /* @__PURE__ */ new Set();
let perMessageDeflate;
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
opts.defaultPort = opts.defaultPort || defaultPort;
opts.port = parsedUrl.port || defaultPort;
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
opts.headers = {
...opts.headers,
"Sec-WebSocket-Version": opts.protocolVersion,
"Sec-WebSocket-Key": key,
Connection: "Upgrade",
Upgrade: "websocket"
};
opts.path = parsedUrl.pathname + parsedUrl.search;
opts.timeout = opts.handshakeTimeout;
if (opts.perMessageDeflate) {
perMessageDeflate = new PerMessageDeflate$1(
opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
false,
opts.maxPayload
);
opts.headers["Sec-WebSocket-Extensions"] = format({
[PerMessageDeflate$1.extensionName]: perMessageDeflate.offer()
});
}
if (protocols.length) {
for (const protocol of protocols) {
if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
throw new SyntaxError(
"An invalid or duplicated subprotocol was specified"
);
}
protocolSet.add(protocol);
}
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
}
if (opts.origin) {
if (opts.protocolVersion < 13) {
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
} else {
opts.headers.Origin = opts.origin;
}
}
if (parsedUrl.username || parsedUrl.password) {
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
}
if (isIpcUrl) {
const parts = opts.path.split(":");
opts.socketPath = parts[0];
opts.path = parts[1];
}
let req2;
if (opts.followRedirects) {
if (websocket2._redirects === 0) {
websocket2._originalIpc = isIpcUrl;
websocket2._originalSecure = isSecure;
websocket2._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
const headers = options2 && options2.headers;
options2 = { ...options2, headers: {} };
if (headers) {
for (const [key2, value2] of Object.entries(headers)) {
options2.headers[key2.toLowerCase()] = value2;
}
}
} else if (websocket2.listenerCount("redirect") === 0) {
const isSameHost = isIpcUrl ? websocket2._originalIpc ? opts.socketPath === websocket2._originalHostOrSocketPath : false : websocket2._originalIpc ? false : parsedUrl.host === websocket2._originalHostOrSocketPath;
if (!isSameHost || websocket2._originalSecure && !isSecure) {
delete opts.headers.authorization;
delete opts.headers.cookie;
if (!isSameHost) delete opts.headers.host;
opts.auth = void 0;
}
}
if (opts.auth && !options2.headers.authorization) {
options2.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
}
req2 = websocket2._req = request(opts);
if (websocket2._redirects) {
websocket2.emit("redirect", websocket2.url, req2);
}
} else {
req2 = websocket2._req = request(opts);
}
if (opts.timeout) {
req2.on("timeout", () => {
abortHandshake$1(websocket2, req2, "Opening handshake has timed out");
});
}
req2.on("error", (err2) => {
if (req2 === null || req2[kAborted]) return;
req2 = websocket2._req = null;
emitErrorAndClose(websocket2, err2);
});
req2.on("response", (res) => {
const location2 = res.headers.location;
const statusCode = res.statusCode;
if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
if (++websocket2._redirects > opts.maxRedirects) {
abortHandshake$1(websocket2, req2, "Maximum redirects exceeded");
return;
}
req2.abort();
let addr;
try {
addr = new URL$2(location2, address);
} catch (e2) {
const err2 = new SyntaxError(`Invalid URL: ${location2}`);
emitErrorAndClose(websocket2, err2);
return;
}
initAsClient(websocket2, addr, protocols, options2);
} else if (!websocket2.emit("unexpected-response", req2, res)) {
abortHandshake$1(
websocket2,
req2,
`Unexpected server response: ${res.statusCode}`
);
}
});
req2.on("upgrade", (res, socket, head) => {
websocket2.emit("upgrade", res);
if (websocket2.readyState !== WebSocket$1.CONNECTING) return;
req2 = websocket2._req = null;
const upgrade = res.headers.upgrade;
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
abortHandshake$1(websocket2, socket, "Invalid Upgrade header");
return;
}
const digest = createHash$1("sha1").update(key + GUID$1).digest("base64");
if (res.headers["sec-websocket-accept"] !== digest) {
abortHandshake$1(websocket2, socket, "Invalid Sec-WebSocket-Accept header");
return;
}
const serverProt = res.headers["sec-websocket-protocol"];
let protError;
if (serverProt !== void 0) {
if (!protocolSet.size) {
protError = "Server sent a subprotocol but none was requested";
} else if (!protocolSet.has(serverProt)) {
protError = "Server sent an invalid subprotocol";
}
} else if (protocolSet.size) {
protError = "Server sent no subprotocol";
}
if (protError) {
abortHandshake$1(websocket2, socket, protError);
return;
}
if (serverProt) websocket2._protocol = serverProt;
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
if (secWebSocketExtensions !== void 0) {
if (!perMessageDeflate) {
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
abortHandshake$1(websocket2, socket, message);
return;
}
let extensions2;
try {
extensions2 = parse$1(secWebSocketExtensions);
} catch (err2) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake$1(websocket2, socket, message);
return;
}
const extensionNames = Object.keys(extensions2);
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate$1.extensionName) {
const message = "Server indicated an extension that was not requested";
abortHandshake$1(websocket2, socket, message);
return;
}
try {
perMessageDeflate.accept(extensions2[PerMessageDeflate$1.extensionName]);
} catch (err2) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake$1(websocket2, socket, message);
return;
}
websocket2._extensions[PerMessageDeflate$1.extensionName] = perMessageDeflate;
}
websocket2.setSocket(socket, head, {
allowSynchronousEvents: opts.allowSynchronousEvents,
generateMask: opts.generateMask,
maxPayload: opts.maxPayload,
skipUTF8Validation: opts.skipUTF8Validation
});
});
if (opts.finishRequest) {
opts.finishRequest(req2, websocket2);
} else {
req2.end();
}
}
function emitErrorAndClose(websocket2, err2) {
websocket2._readyState = WebSocket$1.CLOSING;
websocket2._errorEmitted = true;
websocket2.emit("error", err2);
websocket2.emitClose();
}
function netConnect(options2) {
options2.path = options2.socketPath;
return net.connect(options2);
}
function tlsConnect(options2) {
options2.path = void 0;
if (!options2.servername && options2.servername !== "") {
options2.servername = net.isIP(options2.host) ? "" : options2.host;
}
return tls.connect(options2);
}
function abortHandshake$1(websocket2, stream4, message) {
websocket2._readyState = WebSocket$1.CLOSING;
const err2 = new Error(message);
Error.captureStackTrace(err2, abortHandshake$1);
if (stream4.setHeader) {
stream4[kAborted] = true;
stream4.abort();
if (stream4.socket && !stream4.socket.destroyed) {
stream4.socket.destroy();
}
process.nextTick(emitErrorAndClose, websocket2, err2);
} else {
stream4.destroy(err2);
stream4.once("error", websocket2.emit.bind(websocket2, "error"));
stream4.once("close", websocket2.emitClose.bind(websocket2));
}
}
function sendAfterClose(websocket2, data, cb) {
if (data) {
const length = isBlob(data) ? data.size : toBuffer(data).length;
if (websocket2._socket) websocket2._sender._bufferedBytes += length;
else websocket2._bufferedAmount += length;
}
if (cb) {
const err2 = new Error(
`WebSocket is not open: readyState ${websocket2.readyState} (${readyStates[websocket2.readyState]})`
);
process.nextTick(cb, err2);
}
}
function receiverOnConclude(code, reason) {
const websocket2 = this[kWebSocket$1];
websocket2._closeFrameReceived = true;
websocket2._closeMessage = reason;
websocket2._closeCode = code;
if (websocket2._socket[kWebSocket$1] === void 0) return;
websocket2._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket2._socket);
if (code === 1005) websocket2.close();
else websocket2.close(code, reason);
}
function receiverOnDrain() {
const websocket2 = this[kWebSocket$1];
if (!websocket2.isPaused) websocket2._socket.resume();
}
function receiverOnError(err2) {
const websocket2 = this[kWebSocket$1];
if (websocket2._socket[kWebSocket$1] !== void 0) {
websocket2._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket2._socket);
websocket2.close(err2[kStatusCode]);
}
if (!websocket2._errorEmitted) {
websocket2._errorEmitted = true;
websocket2.emit("error", err2);
}
}
function receiverOnFinish() {
this[kWebSocket$1].emitClose();
}
function receiverOnMessage(data, isBinary) {
this[kWebSocket$1].emit("message", data, isBinary);
}
function receiverOnPing(data) {
const websocket2 = this[kWebSocket$1];
if (websocket2._autoPong) websocket2.pong(data, !this._isServer, NOOP$1);
websocket2.emit("ping", data);
}
function receiverOnPong(data) {
this[kWebSocket$1].emit("pong", data);
}
function resume(stream4) {
stream4.resume();
}
function senderOnError(err2) {
const websocket2 = this[kWebSocket$1];
if (websocket2.readyState === WebSocket$1.CLOSED) return;
if (websocket2.readyState === WebSocket$1.OPEN) {
websocket2._readyState = WebSocket$1.CLOSING;
setCloseTimer(websocket2);
}
this._socket.end();
if (!websocket2._errorEmitted) {
websocket2._errorEmitted = true;
websocket2.emit("error", err2);
}
}
function setCloseTimer(websocket2) {
websocket2._closeTimer = setTimeout(
websocket2._socket.destroy.bind(websocket2._socket),
closeTimeout
);
}
function socketOnClose() {
const websocket2 = this[kWebSocket$1];
this.removeListener("close", socketOnClose);
this.removeListener("data", socketOnData);
this.removeListener("end", socketOnEnd);
websocket2._readyState = WebSocket$1.CLOSING;
let chunk;
if (!this._readableState.endEmitted && !websocket2._closeFrameReceived && !websocket2._receiver._writableState.errorEmitted && (chunk = websocket2._socket.read()) !== null) {
websocket2._receiver.write(chunk);
}
websocket2._receiver.end();
this[kWebSocket$1] = void 0;
clearTimeout(websocket2._closeTimer);
if (websocket2._receiver._writableState.finished || websocket2._receiver._writableState.errorEmitted) {
websocket2.emitClose();
} else {
websocket2._receiver.on("error", receiverOnFinish);
websocket2._receiver.on("finish", receiverOnFinish);
}
}
function socketOnData(chunk) {
if (!this[kWebSocket$1]._receiver.write(chunk)) {
this.pause();
}
}
function socketOnEnd() {
const websocket2 = this[kWebSocket$1];
websocket2._readyState = WebSocket$1.CLOSING;
websocket2._receiver.end();
this.end();
}
function socketOnError$1() {
const websocket2 = this[kWebSocket$1];
this.removeListener("error", socketOnError$1);
this.on("error", NOOP$1);
if (websocket2) {
websocket2._readyState = WebSocket$1.CLOSING;
this.destroy();
}
}
var { tokenChars } = validationExports;
function parse3(header) {
const protocols = /* @__PURE__ */ new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol2 = header.slice(start, end);
if (protocols.has(protocol2)) {
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
}
protocols.add(protocol2);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError("Unexpected end of input");
}
const protocol = header.slice(start, i);
if (protocols.has(protocol)) {
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
}
protocols.add(protocol);
return protocols;
}
var subprotocol$1 = { parse: parse3 };
var EventEmitter = import_events.default;
var http$2 = import_http.default;
var { createHash } = import_crypto.default;
var extension = extension$1;
var PerMessageDeflate2 = permessageDeflate;
var subprotocol = subprotocol$1;
var WebSocket2 = websocket;
var { GUID, kWebSocket } = constants;
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
var RUNNING = 0;
var CLOSING = 1;
var CLOSED = 2;
var WebSocketServer = class extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options2, callback) {
super();
options2 = {
allowSynchronousEvents: true,
autoPong: true,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
verifyClient: null,
noServer: false,
backlog: null,
// use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket: WebSocket2,
...options2
};
if (options2.port == null && !options2.server && !options2.noServer || options2.port != null && (options2.server || options2.noServer) || options2.server && options2.noServer) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options must be specified'
);
}
if (options2.port != null) {
this._server = http$2.createServer((req2, res) => {
const body = http$2.STATUS_CODES[426];
res.writeHead(426, {
"Content-Length": body.length,
"Content-Type": "text/plain"
});
res.end(body);
});
this._server.listen(
options2.port,
options2.host,
options2.backlog,
callback
);
} else if (options2.server) {
this._server = options2.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, "connection");
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, "listening"),
error: this.emit.bind(this, "error"),
upgrade: (req2, socket, head) => {
this.handleUpgrade(req2, socket, head, emitConnection);
}
});
}
if (options2.perMessageDeflate === true) options2.perMessageDeflate = {};
if (options2.clientTracking) {
this.clients = /* @__PURE__ */ new Set();
this._shouldEmitClose = false;
}
this.options = options2;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once("close", () => {
cb(new Error("The server is not running"));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once("close", cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server2 = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
server2.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req2) {
if (this.options.path) {
const index = req2.url.indexOf("?");
const pathname = index !== -1 ? req2.url.slice(0, index) : req2.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req2, socket, head, cb) {
socket.on("error", socketOnError);
const key = req2.headers["sec-websocket-key"];
const upgrade = req2.headers.upgrade;
const version3 = +req2.headers["sec-websocket-version"];
if (req2.method !== "GET") {
const message = "Invalid HTTP method";
abortHandshakeOrEmitwsClientError(this, req2, socket, 405, message);
return;
}
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
const message = "Invalid Upgrade header";
abortHandshakeOrEmitwsClientError(this, req2, socket, 400, message);
return;
}
if (key === void 0 || !keyRegex.test(key)) {
const message = "Missing or invalid Sec-WebSocket-Key header";
abortHandshakeOrEmitwsClientError(this, req2, socket, 400, message);
return;
}
if (version3 !== 8 && version3 !== 13) {
const message = "Missing or invalid Sec-WebSocket-Version header";
abortHandshakeOrEmitwsClientError(this, req2, socket, 400, message);
return;
}
if (!this.shouldHandle(req2)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req2.headers["sec-websocket-protocol"];
let protocols = /* @__PURE__ */ new Set();
if (secWebSocketProtocol !== void 0) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err2) {
const message = "Invalid Sec-WebSocket-Protocol header";
abortHandshakeOrEmitwsClientError(this, req2, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req2.headers["sec-websocket-extensions"];
const extensions2 = {};
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
const perMessageDeflate = new PerMessageDeflate2(
this.options.perMessageDeflate,
true,
this.options.maxPayload
);
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate2.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
extensions2[PerMessageDeflate2.extensionName] = perMessageDeflate;
}
} catch (err2) {
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
abortHandshakeOrEmitwsClientError(this, req2, socket, 400, message);
return;
}
}
if (this.options.verifyClient) {
const info = {
origin: req2.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`],
secure: !!(req2.socket.authorized || req2.socket.encrypted),
req: req2
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions2,
key,
protocols,
req2,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions2, key, protocols, req2, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions2, key, protocols, req2, socket, head, cb) {
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash("sha1").update(key + GUID).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, void 0, this.options);
if (protocols.size) {
const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req2) : protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions2[PerMessageDeflate2.extensionName]) {
const params = extensions2[PerMessageDeflate2.extensionName].params;
const value2 = extension.format({
[PerMessageDeflate2.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value2}`);
ws._extensions = extensions2;
}
this.emit("headers", headers, req2);
socket.write(headers.concat("\r\n").join("\r\n"));
socket.removeListener("error", socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on("close", () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req2);
}
};
var websocketServer = WebSocketServer;
function addListeners(server2, map2) {
for (const event of Object.keys(map2)) server2.on(event, map2[event]);
return function removeListeners() {
for (const event of Object.keys(map2)) {
server2.removeListener(event, map2[event]);
}
};
}
function emitClose(server2) {
server2._state = CLOSED;
server2.emit("close");
}
function socketOnError() {
this.destroy();
}
function abortHandshake(socket, code, message, headers) {
message = message || http$2.STATUS_CODES[code];
headers = {
Connection: "close",
"Content-Type": "text/html",
"Content-Length": Buffer.byteLength(message),
...headers
};
socket.once("finish", socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
);
}
function abortHandshakeOrEmitwsClientError(server2, req2, socket, code, message) {
if (server2.listenerCount("wsClientError")) {
const err2 = new Error(message);
Error.captureStackTrace(err2, abortHandshakeOrEmitwsClientError);
server2.emit("wsClientError", err2, socket, req2);
} else {
abortHandshake(socket, code, message);
}
}
var WebSocketServerRaw_ = getDefaultExportFromCjs(websocketServer);
var WebSocketServerRaw = process.versions.bun ? (
// @ts-expect-error: Bun defines `import.meta.require`
import.meta.require("ws").WebSocketServer
) : WebSocketServerRaw_;
var HMR_HEADER = "vite-hmr";
var wsServerEvents = [
"connection",
"error",
"headers",
"listening",
"message"
];
function noop$1() {
}
function createWebSocketServer(server2, config2, httpsOptions) {
if (config2.server.ws === false) {
return {
name: "ws",
get clients() {
return /* @__PURE__ */ new Set();
},
async close() {
},
on: noop$1,
off: noop$1,
listen: noop$1,
send: noop$1
};
}
let wss;
let wsHttpServer = void 0;
const hmr = isObject$1(config2.server.hmr) && config2.server.hmr;
const hmrServer = hmr && hmr.server;
const hmrPort = hmr && hmr.port;
const portsAreCompatible = !hmrPort || hmrPort === config2.server.port;
const wsServer = hmrServer || portsAreCompatible && server2;
let hmrServerWsListener;
const customListeners = /* @__PURE__ */ new Map();
const clientsMap = /* @__PURE__ */ new WeakMap();
const port = hmrPort || 24678;
const host = hmr && hmr.host || void 0;
if (wsServer) {
let hmrBase = config2.base;
const hmrPath = hmr ? hmr.path : void 0;
if (hmrPath) {
hmrBase = import_node_path3.default.posix.join(hmrBase, hmrPath);
}
wss = new WebSocketServerRaw({ noServer: true });
hmrServerWsListener = (req2, socket, head) => {
if (req2.headers["sec-websocket-protocol"] === HMR_HEADER && req2.url === hmrBase) {
wss.handleUpgrade(req2, socket, head, (ws) => {
wss.emit("connection", ws, req2);
});
}
};
wsServer.on("upgrade", hmrServerWsListener);
} else {
const route = (_, res) => {
const statusCode = 426;
const body = import_node_http.STATUS_CODES[statusCode];
if (!body)
throw new Error(`No body text found for the ${statusCode} status code`);
res.writeHead(statusCode, {
"Content-Length": body.length,
"Content-Type": "text/plain"
});
res.end(body);
};
if (httpsOptions) {
wsHttpServer = (0, import_node_https.createServer)(httpsOptions, route);
} else {
wsHttpServer = (0, import_node_http.createServer)(route);
}
wss = new WebSocketServerRaw({ server: wsHttpServer });
}
wss.on("connection", (socket) => {
socket.on("message", (raw) => {
if (!customListeners.size) return;
let parsed;
try {
parsed = JSON.parse(String(raw));
} catch {
}
if (!parsed || parsed.type !== "custom" || !parsed.event) return;
const listeners = customListeners.get(parsed.event);
if (!(listeners == null ? void 0 : listeners.size)) return;
const client = getSocketClient(socket);
listeners.forEach((listener2) => listener2(parsed.data, client));
});
socket.on("error", (err2) => {
config2.logger.error(`${colors$1.red(`ws error:`)}
${err2.stack}`, {
timestamp: true,
error: err2
});
});
socket.send(JSON.stringify({ type: "connected" }));
if (bufferedError) {
socket.send(JSON.stringify(bufferedError));
bufferedError = null;
}
});
wss.on("error", (e2) => {
if (e2.code === "EADDRINUSE") {
config2.logger.error(
colors$1.red(`WebSocket server error: Port is already in use`),
{ error: e2 }
);
} else {
config2.logger.error(
colors$1.red(`WebSocket server error:
${e2.stack || e2.message}`),
{ error: e2 }
);
}
});
function getSocketClient(socket) {
if (!clientsMap.has(socket)) {
clientsMap.set(socket, {
send: (...args) => {
let payload;
if (typeof args[0] === "string") {
payload = {
type: "custom",
event: args[0],
data: args[1]
};
} else {
payload = args[0];
}
socket.send(JSON.stringify(payload));
},
socket
});
}
return clientsMap.get(socket);
}
let bufferedError = null;
return {
name: "ws",
listen: () => {
wsHttpServer == null ? void 0 : wsHttpServer.listen(port, host);
},
on: (event, fn) => {
if (wsServerEvents.includes(event)) wss.on(event, fn);
else {
if (!customListeners.has(event)) {
customListeners.set(event, /* @__PURE__ */ new Set());
}
customListeners.get(event).add(fn);
}
},
off: (event, fn) => {
var _a4;
if (wsServerEvents.includes(event)) {
wss.off(event, fn);
} else {
(_a4 = customListeners.get(event)) == null ? void 0 : _a4.delete(fn);
}
},
get clients() {
return new Set(Array.from(wss.clients).map(getSocketClient));
},
send(...args) {
let payload;
if (typeof args[0] === "string") {
payload = {
type: "custom",
event: args[0],
data: args[1]
};
} else {
payload = args[0];
}
if (payload.type === "error" && !wss.clients.size) {
bufferedError = payload;
return;
}
const stringified = JSON.stringify(payload);
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(stringified);
}
});
},
close() {
if (hmrServerWsListener && wsServer) {
wsServer.off("upgrade", hmrServerWsListener);
}
return new Promise((resolve3, reject) => {
wss.clients.forEach((client) => {
client.terminate();
});
wss.close((err2) => {
if (err2) {
reject(err2);
} else {
if (wsHttpServer) {
wsHttpServer.close((err22) => {
if (err22) {
reject(err22);
} else {
resolve3();
}
});
} else {
resolve3();
}
}
});
});
}
};
}
function baseMiddleware(rawBase, middlewareMode) {
return function viteBaseMiddleware(req2, res, next) {
var _a4;
const url2 = req2.url;
const pathname = cleanUrl(url2);
const base = rawBase;
if (pathname.startsWith(base)) {
req2.url = stripBase(url2, base);
return next();
}
if (middlewareMode) {
return next();
}
if (pathname === "/" || pathname === "/index.html") {
res.writeHead(302, {
Location: base + url2.slice(pathname.length)
});
res.end();
return;
}
const redirectPath = withTrailingSlash(url2) !== base ? joinUrlSegments(base, url2) : base;
if ((_a4 = req2.headers.accept) == null ? void 0 : _a4.includes("text/html")) {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end(
`The server is configured with a public base URL of ${base} - did you mean to visit <a href="${redirectPath}">${redirectPath}</a> instead?`
);
return;
} else {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.end(
`The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?`
);
return;
}
};
}
var httpProxy$3 = { exports: {} };
var eventemitter3 = { exports: {} };
(function(module) {
var has = Object.prototype.hasOwnProperty, prefix = "~";
function Events() {
}
if (Object.create) {
Events.prototype = /* @__PURE__ */ Object.create(null);
if (!new Events().__proto__) prefix = false;
}
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== "function") {
throw new TypeError("The listener must be a function");
}
var listener2 = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener2, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener2);
else emitter._events[evt] = [emitter._events[evt], listener2];
return emitter;
}
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
function EventEmitter2() {
this._events = new Events();
this._eventsCount = 0;
}
EventEmitter2.prototype.eventNames = function eventNames() {
var names = [], events2, name2;
if (this._eventsCount === 0) return names;
for (name2 in events2 = this._events) {
if (has.call(events2, name2)) names.push(prefix ? name2.slice(1) : name2);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events2));
}
return names;
};
EventEmitter2.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
EventEmitter2.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt], len = arguments.length, args, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
switch (len) {
case 1:
return listeners.fn.call(listeners.context), true;
case 2:
return listeners.fn.call(listeners.context, a1), true;
case 3:
return listeners.fn.call(listeners.context, a1, a2), true;
case 4:
return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5:
return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6:
return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len - 1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
switch (len) {
case 1:
listeners[i].fn.call(listeners[i].context);
break;
case 2:
listeners[i].fn.call(listeners[i].context, a1);
break;
case 3:
listeners[i].fn.call(listeners[i].context, a1, a2);
break;
case 4:
listeners[i].fn.call(listeners[i].context, a1, a2, a3);
break;
default:
if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
EventEmitter2.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
EventEmitter2.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events2 = [], length = listeners.length; i < length; i++) {
if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
events2.push(listeners[i]);
}
}
if (events2.length) this._events[evt] = events2.length === 1 ? events2[0] : events2;
else clearEvent(this, evt);
}
return this;
};
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
EventEmitter2.prefixed = prefix;
EventEmitter2.EventEmitter = EventEmitter2;
{
module.exports = EventEmitter2;
}
})(eventemitter3);
var eventemitter3Exports = eventemitter3.exports;
var common$3 = {};
var requiresPort = function required(port, protocol) {
protocol = protocol.split(":")[0];
port = +port;
if (!port) return false;
switch (protocol) {
case "http":
case "ws":
return port !== 80;
case "https":
case "wss":
return port !== 443;
case "ftp":
return port !== 21;
case "gopher":
return port !== 70;
case "file":
return false;
}
return port !== 0;
};
(function(exports2) {
var common2 = exports2, url2 = import_url.default, required2 = requiresPort;
var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, isSSL = /^https|wss/;
common2.isSSL = isSSL;
common2.setupOutgoing = function(outgoing, options2, req2, forward) {
outgoing.port = options2[forward || "target"].port || (isSSL.test(options2[forward || "target"].protocol) ? 443 : 80);
[
"host",
"hostname",
"socketPath",
"pfx",
"key",
"passphrase",
"cert",
"ca",
"ciphers",
"secureProtocol"
].forEach(
function(e2) {
outgoing[e2] = options2[forward || "target"][e2];
}
);
outgoing.method = options2.method || req2.method;
outgoing.headers = Object.assign({}, req2.headers);
if (options2.headers) {
Object.assign(outgoing.headers, options2.headers);
}
if (options2.auth) {
outgoing.auth = options2.auth;
}
if (options2.ca) {
outgoing.ca = options2.ca;
}
if (isSSL.test(options2[forward || "target"].protocol)) {
outgoing.rejectUnauthorized = typeof options2.secure === "undefined" ? true : options2.secure;
}
outgoing.agent = options2.agent || false;
outgoing.localAddress = options2.localAddress;
if (!outgoing.agent) {
outgoing.headers = outgoing.headers || {};
if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) {
outgoing.headers.connection = "close";
}
}
var target = options2[forward || "target"];
var targetPath = target && options2.prependPath !== false ? target.path || "" : "";
var outgoingPath = !options2.toProxy ? url2.parse(req2.url).path || "" : req2.url;
outgoingPath = !options2.ignorePath ? outgoingPath : "";
outgoing.path = common2.urlJoin(targetPath, outgoingPath);
if (options2.changeOrigin) {
outgoing.headers.host = required2(outgoing.port, options2[forward || "target"].protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
}
return outgoing;
};
common2.setupSocket = function(socket) {
socket.setTimeout(0);
socket.setNoDelay(true);
socket.setKeepAlive(true, 0);
return socket;
};
common2.getPort = function(req2) {
var res = req2.headers.host ? req2.headers.host.match(/:(\d+)/) : "";
return res ? res[1] : common2.hasEncryptedConnection(req2) ? "443" : "80";
};
common2.hasEncryptedConnection = function(req2) {
return Boolean(req2.connection.encrypted || req2.connection.pair);
};
common2.urlJoin = function() {
var args = Array.prototype.slice.call(arguments), lastIndex = args.length - 1, last = args[lastIndex], lastSegs = last.split("?"), retSegs;
args[lastIndex] = lastSegs.shift();
retSegs = [
args.filter(Boolean).join("/").replace(/\/+/g, "/").replace("http:/", "http://").replace("https:/", "https://")
];
retSegs.push.apply(retSegs, lastSegs);
return retSegs.join("?");
};
common2.rewriteCookieProperty = function rewriteCookieProperty(header, config2, property) {
if (Array.isArray(header)) {
return header.map(function(headerElement) {
return rewriteCookieProperty(headerElement, config2, property);
});
}
return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), function(match2, prefix, previousValue) {
var newValue;
if (previousValue in config2) {
newValue = config2[previousValue];
} else if ("*" in config2) {
newValue = config2["*"];
} else {
return match2;
}
if (newValue) {
return prefix + newValue;
} else {
return "";
}
});
};
function hasPort(host) {
return !!~host.indexOf(":");
}
})(common$3);
var url$1 = import_url.default;
var common$2 = common$3;
var redirectRegex = /^201|30(1|2|7|8)$/;
var webOutgoing = {
// <--
/**
* If is a HTTP 1.0 request, remove chunk headers
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
removeChunked: function removeChunked(req2, res, proxyRes) {
if (req2.httpVersion === "1.0") {
delete proxyRes.headers["transfer-encoding"];
}
},
/**
* If is a HTTP 1.0 request, set the correct connection header
* or if connection header not present, then use `keep-alive`
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
setConnection: function setConnection(req2, res, proxyRes) {
if (req2.httpVersion === "1.0") {
proxyRes.headers.connection = req2.headers.connection || "close";
} else if (req2.httpVersion !== "2.0" && !proxyRes.headers.connection) {
proxyRes.headers.connection = req2.headers.connection || "keep-alive";
}
},
setRedirectHostRewrite: function setRedirectHostRewrite(req2, res, proxyRes, options2) {
if ((options2.hostRewrite || options2.autoRewrite || options2.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(proxyRes.statusCode)) {
var target = url$1.parse(options2.target);
var u = url$1.parse(proxyRes.headers["location"]);
if (target.host != u.host) {
return;
}
if (options2.hostRewrite) {
u.host = options2.hostRewrite;
} else if (options2.autoRewrite) {
u.host = req2.headers["host"];
}
if (options2.protocolRewrite) {
u.protocol = options2.protocolRewrite;
}
proxyRes.headers["location"] = u.format();
}
},
/**
* Copy headers from proxyResponse to response
* set each header in response object.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
* @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain
*
* @api private
*/
writeHeaders: function writeHeaders(req2, res, proxyRes, options2) {
var rewriteCookieDomainConfig = options2.cookieDomainRewrite, rewriteCookiePathConfig = options2.cookiePathRewrite, preserveHeaderKeyCase = options2.preserveHeaderKeyCase, rawHeaderKeyMap, setHeader = function(key2, header) {
if (header == void 0) return;
if (rewriteCookieDomainConfig && key2.toLowerCase() === "set-cookie") {
header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
}
if (rewriteCookiePathConfig && key2.toLowerCase() === "set-cookie") {
header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
}
res.setHeader(String(key2).trim(), header);
};
if (typeof rewriteCookieDomainConfig === "string") {
rewriteCookieDomainConfig = { "*": rewriteCookieDomainConfig };
}
if (typeof rewriteCookiePathConfig === "string") {
rewriteCookiePathConfig = { "*": rewriteCookiePathConfig };
}
if (preserveHeaderKeyCase && proxyRes.rawHeaders != void 0) {
rawHeaderKeyMap = {};
for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
var key = proxyRes.rawHeaders[i];
rawHeaderKeyMap[key.toLowerCase()] = key;
}
}
Object.keys(proxyRes.headers).forEach(function(key2) {
var header = proxyRes.headers[key2];
if (preserveHeaderKeyCase && rawHeaderKeyMap) {
key2 = rawHeaderKeyMap[key2] || key2;
}
setHeader(key2, header);
});
},
/**
* Set the statusCode from the proxyResponse
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {proxyResponse} Res Response object from the proxy request
*
* @api private
*/
writeStatusCode: function writeStatusCode(req2, res, proxyRes) {
if (proxyRes.statusMessage) {
res.statusCode = proxyRes.statusCode;
res.statusMessage = proxyRes.statusMessage;
} else {
res.statusCode = proxyRes.statusCode;
}
}
};
var followRedirects$1 = { exports: {} };
var debug$6;
var debug_1 = function() {
if (!debug$6) {
try {
debug$6 = srcExports$1("follow-redirects");
} catch (error2) {
}
if (typeof debug$6 !== "function") {
debug$6 = function() {
};
}
}
debug$6.apply(null, arguments);
};
var url = import_url.default;
var URL$1 = url.URL;
var http$1 = import_http.default;
var https$1 = import_https.default;
var Writable = import_stream.default.Writable;
var assert = import_assert.default;
var debug$5 = debug_1;
var useNativeURL = false;
try {
assert(new URL$1());
} catch (error2) {
useNativeURL = error2.code === "ERR_INVALID_URL";
}
var preservedUrlFields = [
"auth",
"host",
"hostname",
"href",
"path",
"pathname",
"port",
"protocol",
"query",
"search",
"hash"
];
var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
var eventHandlers = /* @__PURE__ */ Object.create(null);
events.forEach(function(event) {
eventHandlers[event] = function(arg1, arg2, arg3) {
this._redirectable.emit(event, arg1, arg2, arg3);
};
});
var InvalidUrlError = createErrorType(
"ERR_INVALID_URL",
"Invalid URL",
TypeError
);
var RedirectionError = createErrorType(
"ERR_FR_REDIRECTION_FAILURE",
"Redirected request failed"
);
var TooManyRedirectsError = createErrorType(
"ERR_FR_TOO_MANY_REDIRECTS",
"Maximum number of redirects exceeded",
RedirectionError
);
var MaxBodyLengthExceededError = createErrorType(
"ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
"Request body larger than maxBodyLength limit"
);
var WriteAfterEndError = createErrorType(
"ERR_STREAM_WRITE_AFTER_END",
"write after end"
);
var destroy = Writable.prototype.destroy || noop;
function RedirectableRequest(options2, responseCallback) {
Writable.call(this);
this._sanitizeOptions(options2);
this._options = options2;
this._ended = false;
this._ending = false;
this._redirectCount = 0;
this._redirects = [];
this._requestBodyLength = 0;
this._requestBodyBuffers = [];
if (responseCallback) {
this.on("response", responseCallback);
}
var self2 = this;
this._onNativeResponse = function(response) {
try {
self2._processResponse(response);
} catch (cause) {
self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
}
};
this._performRequest();
}
RedirectableRequest.prototype = Object.create(Writable.prototype);
RedirectableRequest.prototype.abort = function() {
destroyRequest(this._currentRequest);
this._currentRequest.abort();
this.emit("abort");
};
RedirectableRequest.prototype.destroy = function(error2) {
destroyRequest(this._currentRequest, error2);
destroy.call(this, error2);
return this;
};
RedirectableRequest.prototype.write = function(data, encoding, callback) {
if (this._ending) {
throw new WriteAfterEndError();
}
if (!isString(data) && !isBuffer(data)) {
throw new TypeError("data should be a string, Buffer or Uint8Array");
}
if (isFunction(encoding)) {
callback = encoding;
encoding = null;
}
if (data.length === 0) {
if (callback) {
callback();
}
return;
}
if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
this._requestBodyLength += data.length;
this._requestBodyBuffers.push({ data, encoding });
this._currentRequest.write(data, encoding, callback);
} else {
this.emit("error", new MaxBodyLengthExceededError());
this.abort();
}
};
RedirectableRequest.prototype.end = function(data, encoding, callback) {
if (isFunction(data)) {
callback = data;
data = encoding = null;
} else if (isFunction(encoding)) {
callback = encoding;
encoding = null;
}
if (!data) {
this._ended = this._ending = true;
this._currentRequest.end(null, null, callback);
} else {
var self2 = this;
var currentRequest = this._currentRequest;
this.write(data, encoding, function() {
self2._ended = true;
currentRequest.end(null, null, callback);
});
this._ending = true;
}
};
RedirectableRequest.prototype.setHeader = function(name2, value2) {
this._options.headers[name2] = value2;
this._currentRequest.setHeader(name2, value2);
};
RedirectableRequest.prototype.removeHeader = function(name2) {
delete this._options.headers[name2];
this._currentRequest.removeHeader(name2);
};
RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
var self2 = this;
function destroyOnTimeout(socket) {
socket.setTimeout(msecs);
socket.removeListener("timeout", socket.destroy);
socket.addListener("timeout", socket.destroy);
}
function startTimer(socket) {
if (self2._timeout) {
clearTimeout(self2._timeout);
}
self2._timeout = setTimeout(function() {
self2.emit("timeout");
clearTimer();
}, msecs);
destroyOnTimeout(socket);
}
function clearTimer() {
if (self2._timeout) {
clearTimeout(self2._timeout);
self2._timeout = null;
}
self2.removeListener("abort", clearTimer);
self2.removeListener("error", clearTimer);
self2.removeListener("response", clearTimer);
self2.removeListener("close", clearTimer);
if (callback) {
self2.removeListener("timeout", callback);
}
if (!self2.socket) {
self2._currentRequest.removeListener("socket", startTimer);
}
}
if (callback) {
this.on("timeout", callback);
}
if (this.socket) {
startTimer(this.socket);
} else {
this._currentRequest.once("socket", startTimer);
}
this.on("socket", destroyOnTimeout);
this.on("abort", clearTimer);
this.on("error", clearTimer);
this.on("response", clearTimer);
this.on("close", clearTimer);
return this;
};
[
"flushHeaders",
"getHeader",
"setNoDelay",
"setSocketKeepAlive"
].forEach(function(method) {
RedirectableRequest.prototype[method] = function(a, b) {
return this._currentRequest[method](a, b);
};
});
["aborted", "connection", "socket"].forEach(function(property) {
Object.defineProperty(RedirectableRequest.prototype, property, {
get: function() {
return this._currentRequest[property];
}
});
});
RedirectableRequest.prototype._sanitizeOptions = function(options2) {
if (!options2.headers) {
options2.headers = {};
}
if (options2.host) {
if (!options2.hostname) {
options2.hostname = options2.host;
}
delete options2.host;
}
if (!options2.pathname && options2.path) {
var searchPos = options2.path.indexOf("?");
if (searchPos < 0) {
options2.pathname = options2.path;
} else {
options2.pathname = options2.path.substring(0, searchPos);
options2.search = options2.path.substring(searchPos);
}
}
};
RedirectableRequest.prototype._performRequest = function() {
var protocol = this._options.protocol;
var nativeProtocol = this._options.nativeProtocols[protocol];
if (!nativeProtocol) {
throw new TypeError("Unsupported protocol " + protocol);
}
if (this._options.agents) {
var scheme = protocol.slice(0, -1);
this._options.agent = this._options.agents[scheme];
}
var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
request._redirectable = this;
for (var event of events) {
request.on(event, eventHandlers[event]);
}
this._currentUrl = /^\//.test(this._options.path) ? url.format(this._options) : (
// When making a request to a proxy, […]
// a client MUST send the target URI in absolute-form […].
this._options.path
);
if (this._isRedirect) {
var i = 0;
var self2 = this;
var buffers = this._requestBodyBuffers;
(function writeNext(error2) {
if (request === self2._currentRequest) {
if (error2) {
self2.emit("error", error2);
} else if (i < buffers.length) {
var buffer = buffers[i++];
if (!request.finished) {
request.write(buffer.data, buffer.encoding, writeNext);
}
} else if (self2._ended) {
request.end();
}
}
})();
}
};
RedirectableRequest.prototype._processResponse = function(response) {
var statusCode = response.statusCode;
if (this._options.trackRedirects) {
this._redirects.push({
url: this._currentUrl,
headers: response.headers,
statusCode
});
}
var location2 = response.headers.location;
if (!location2 || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
response.responseUrl = this._currentUrl;
response.redirects = this._redirects;
this.emit("response", response);
this._requestBodyBuffers = [];
return;
}
destroyRequest(this._currentRequest);
response.destroy();
if (++this._redirectCount > this._options.maxRedirects) {
throw new TooManyRedirectsError();
}
var requestHeaders;
var beforeRedirect = this._options.beforeRedirect;
if (beforeRedirect) {
requestHeaders = Object.assign({
// The Host header was set by nativeProtocol.request
Host: response.req.getHeader("host")
}, this._options.headers);
}
var method = this._options.method;
if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that
// the server is redirecting the user agent to a different resource […]
// A user agent can perform a retrieval request targeting that URI
// (a GET or HEAD request if using HTTP) […]
statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
this._options.method = "GET";
this._requestBodyBuffers = [];
removeMatchingHeaders(/^content-/i, this._options.headers);
}
var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
var currentUrlParts = parseUrl(this._currentUrl);
var currentHost = currentHostHeader || currentUrlParts.host;
var currentUrl = /^\w+:/.test(location2) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost }));
var redirectUrl = resolveUrl(location2, currentUrl);
debug$5("redirecting to", redirectUrl.href);
this._isRedirect = true;
spreadUrlObject(redirectUrl, this._options);
if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
}
if (isFunction(beforeRedirect)) {
var responseDetails = {
headers: response.headers,
statusCode
};
var requestDetails = {
url: currentUrl,
method,
headers: requestHeaders
};
beforeRedirect(this._options, responseDetails, requestDetails);
this._sanitizeOptions(this._options);
}
this._performRequest();
};
function wrap(protocols) {
var exports2 = {
maxRedirects: 21,
maxBodyLength: 10 * 1024 * 1024
};
var nativeProtocols = {};
Object.keys(protocols).forEach(function(scheme) {
var protocol = scheme + ":";
var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
var wrappedProtocol = exports2[scheme] = Object.create(nativeProtocol);
function request(input, options2, callback) {
if (isURL(input)) {
input = spreadUrlObject(input);
} else if (isString(input)) {
input = spreadUrlObject(parseUrl(input));
} else {
callback = options2;
options2 = validateUrl(input);
input = { protocol };
}
if (isFunction(options2)) {
callback = options2;
options2 = null;
}
options2 = Object.assign({
maxRedirects: exports2.maxRedirects,
maxBodyLength: exports2.maxBodyLength
}, input, options2);
options2.nativeProtocols = nativeProtocols;
if (!isString(options2.host) && !isString(options2.hostname)) {
options2.hostname = "::1";
}
assert.equal(options2.protocol, protocol, "protocol mismatch");
debug$5("options", options2);
return new RedirectableRequest(options2, callback);
}
function get2(input, options2, callback) {
var wrappedRequest = wrappedProtocol.request(input, options2, callback);
wrappedRequest.end();
return wrappedRequest;
}
Object.defineProperties(wrappedProtocol, {
request: { value: request, configurable: true, enumerable: true, writable: true },
get: { value: get2, configurable: true, enumerable: true, writable: true }
});
});
return exports2;
}
function noop() {
}
function parseUrl(input) {
var parsed;
if (useNativeURL) {
parsed = new URL$1(input);
} else {
parsed = validateUrl(url.parse(input));
if (!isString(parsed.protocol)) {
throw new InvalidUrlError({ input });
}
}
return parsed;
}
function resolveUrl(relative2, base) {
return useNativeURL ? new URL$1(relative2, base) : parseUrl(url.resolve(base, relative2));
}
function validateUrl(input) {
if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
throw new InvalidUrlError({ input: input.href || input });
}
if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
throw new InvalidUrlError({ input: input.href || input });
}
return input;
}
function spreadUrlObject(urlObject, target) {
var spread = target || {};
for (var key of preservedUrlFields) {
spread[key] = urlObject[key];
}
if (spread.hostname.startsWith("[")) {
spread.hostname = spread.hostname.slice(1, -1);
}
if (spread.port !== "") {
spread.port = Number(spread.port);
}
spread.path = spread.search ? spread.pathname + spread.search : spread.pathname;
return spread;
}
function removeMatchingHeaders(regex2, headers) {
var lastValue;
for (var header in headers) {
if (regex2.test(header)) {
lastValue = headers[header];
delete headers[header];
}
}
return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
}
function createErrorType(code, message, baseClass) {
function CustomError(properties) {
Error.captureStackTrace(this, this.constructor);
Object.assign(this, properties || {});
this.code = code;
this.message = this.cause ? message + ": " + this.cause.message : message;
}
CustomError.prototype = new (baseClass || Error)();
Object.defineProperties(CustomError.prototype, {
constructor: {
value: CustomError,
enumerable: false
},
name: {
value: "Error [" + code + "]",
enumerable: false
}
});
return CustomError;
}
function destroyRequest(request, error2) {
for (var event of events) {
request.removeListener(event, eventHandlers[event]);
}
request.on("error", noop);
request.destroy(error2);
}
function isSubdomain(subdomain, domain) {
assert(isString(subdomain) && isString(domain));
var dot = subdomain.length - domain.length - 1;
return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
}
function isString(value2) {
return typeof value2 === "string" || value2 instanceof String;
}
function isFunction(value2) {
return typeof value2 === "function";
}
function isBuffer(value2) {
return typeof value2 === "object" && "length" in value2;
}
function isURL(value2) {
return URL$1 && value2 instanceof URL$1;
}
followRedirects$1.exports = wrap({ http: http$1, https: https$1 });
followRedirects$1.exports.wrap = wrap;
var followRedirectsExports = followRedirects$1.exports;
var httpNative = import_http.default;
var httpsNative = import_https.default;
var web_o = webOutgoing;
var common$1 = common$3;
var followRedirects = followRedirectsExports;
web_o = Object.keys(web_o).map(function(pass) {
return web_o[pass];
});
var nativeAgents = { http: httpNative, https: httpsNative };
var webIncoming = {
/**
* Sets `content-length` to '0' if request is of DELETE type.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
deleteLength: function deleteLength(req2, res, options2) {
if ((req2.method === "DELETE" || req2.method === "OPTIONS") && !req2.headers["content-length"]) {
req2.headers["content-length"] = "0";
delete req2.headers["transfer-encoding"];
}
},
/**
* Sets timeout in request socket if it was specified in options.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
timeout: function timeout(req2, res, options2) {
if (options2.timeout) {
req2.socket.setTimeout(options2.timeout);
}
},
/**
* Sets `x-forwarded-*` headers if specified in config.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
XHeaders: function XHeaders(req2, res, options2) {
if (!options2.xfwd) return;
var encrypted = req2.isSpdy || common$1.hasEncryptedConnection(req2);
var values = {
for: req2.connection.remoteAddress || req2.socket.remoteAddress,
port: common$1.getPort(req2),
proto: encrypted ? "https" : "http"
};
["for", "port", "proto"].forEach(function(header) {
req2.headers["x-forwarded-" + header] = (req2.headers["x-forwarded-" + header] || "") + (req2.headers["x-forwarded-" + header] ? "," : "") + values[header];
});
req2.headers["x-forwarded-host"] = req2.headers["x-forwarded-host"] || req2.headers["host"] || "";
},
/**
* Does the actual proxying. If `forward` is enabled fires up
* a ForwardStream, same happens for ProxyStream. The request
* just dies otherwise.
*
* @param {ClientRequest} Req Request object
* @param {IncomingMessage} Res Response object
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
stream: function stream2(req2, res, options2, _, server2, clb) {
server2.emit("start", req2, res, options2.target || options2.forward);
var agents = options2.followRedirects ? followRedirects : nativeAgents;
var http2 = agents.http;
var https2 = agents.https;
if (options2.forward) {
var forwardReq = (options2.forward.protocol === "https:" ? https2 : http2).request(
common$1.setupOutgoing(options2.ssl || {}, options2, req2, "forward")
);
var forwardError = createErrorHandler(forwardReq, options2.forward);
req2.on("error", forwardError);
forwardReq.on("error", forwardError);
(options2.buffer || req2).pipe(forwardReq);
if (!options2.target) {
return res.end();
}
}
var proxyReq = (options2.target.protocol === "https:" ? https2 : http2).request(
common$1.setupOutgoing(options2.ssl || {}, options2, req2)
);
proxyReq.on("socket", function(socket) {
if (server2 && !proxyReq.getHeader("expect")) {
server2.emit("proxyReq", proxyReq, req2, res, options2);
}
});
if (options2.proxyTimeout) {
proxyReq.setTimeout(options2.proxyTimeout, function() {
proxyReq.abort();
});
}
req2.on("aborted", function() {
proxyReq.abort();
});
var proxyError = createErrorHandler(proxyReq, options2.target);
req2.on("error", proxyError);
proxyReq.on("error", proxyError);
function createErrorHandler(proxyReq2, url2) {
return function proxyError2(err2) {
if (req2.socket.destroyed && err2.code === "ECONNRESET") {
server2.emit("econnreset", err2, req2, res, url2);
return proxyReq2.abort();
}
if (clb) {
clb(err2, req2, res, url2);
} else {
server2.emit("error", err2, req2, res, url2);
}
};
}
(options2.buffer || req2).pipe(proxyReq);
proxyReq.on("response", function(proxyRes) {
if (server2) {
server2.emit("proxyRes", proxyRes, req2, res);
}
if (!res.headersSent && !options2.selfHandleResponse) {
for (var i = 0; i < web_o.length; i++) {
if (web_o[i](req2, res, proxyRes, options2)) {
break;
}
}
}
if (!res.finished) {
proxyRes.on("end", function() {
if (server2) server2.emit("end", req2, res, proxyRes);
});
if (!options2.selfHandleResponse) proxyRes.pipe(res);
} else {
if (server2) server2.emit("end", req2, res, proxyRes);
}
});
}
};
var http = import_http.default;
var https = import_https.default;
var common = common$3;
var wsIncoming = {
/**
* WebSocket requests must have the `GET` method and
* the `upgrade:websocket` header
*
* @param {ClientRequest} Req Request object
* @param {Socket} Websocket
*
* @api private
*/
checkMethodAndHeader: function checkMethodAndHeader(req2, socket) {
if (req2.method !== "GET" || !req2.headers.upgrade) {
socket.destroy();
return true;
}
if (req2.headers.upgrade.toLowerCase() !== "websocket") {
socket.destroy();
return true;
}
},
/**
* Sets `x-forwarded-*` headers if specified in config.
*
* @param {ClientRequest} Req Request object
* @param {Socket} Websocket
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
XHeaders: function XHeaders2(req2, socket, options2) {
if (!options2.xfwd) return;
var values = {
for: req2.connection.remoteAddress || req2.socket.remoteAddress,
port: common.getPort(req2),
proto: common.hasEncryptedConnection(req2) ? "wss" : "ws"
};
["for", "port", "proto"].forEach(function(header) {
req2.headers["x-forwarded-" + header] = (req2.headers["x-forwarded-" + header] || "") + (req2.headers["x-forwarded-" + header] ? "," : "") + values[header];
});
},
/**
* Does the actual proxying. Make the request and upgrade it
* send the Switching Protocols request and pipe the sockets.
*
* @param {ClientRequest} Req Request object
* @param {Socket} Websocket
* @param {Object} Options Config object passed to the proxy
*
* @api private
*/
stream: function stream3(req2, socket, options2, head, server2, clb) {
var createHttpHeader = function(line, headers) {
return Object.keys(headers).reduce(function(head2, key) {
var value2 = headers[key];
if (!Array.isArray(value2)) {
head2.push(key + ": " + value2);
return head2;
}
for (var i = 0; i < value2.length; i++) {
head2.push(key + ": " + value2[i]);
}
return head2;
}, [line]).join("\r\n") + "\r\n\r\n";
};
common.setupSocket(socket);
if (head && head.length) socket.unshift(head);
var proxyReq = (common.isSSL.test(options2.target.protocol) ? https : http).request(
common.setupOutgoing(options2.ssl || {}, options2, req2)
);
if (server2) {
server2.emit("proxyReqWs", proxyReq, req2, socket, options2, head);
}
proxyReq.on("error", onOutgoingError);
proxyReq.on("response", function(res) {
if (!res.upgrade) {
socket.write(createHttpHeader("HTTP/" + res.httpVersion + " " + res.statusCode + " " + res.statusMessage, res.headers));
res.pipe(socket);
}
});
proxyReq.on("upgrade", function(proxyRes, proxySocket, proxyHead) {
proxySocket.on("error", onOutgoingError);
proxySocket.on("end", function() {
server2.emit("close", proxyRes, proxySocket, proxyHead);
});
socket.on("error", function() {
proxySocket.end();
});
common.setupSocket(proxySocket);
if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols", proxyRes.headers));
proxySocket.pipe(socket).pipe(proxySocket);
server2.emit("open", proxySocket);
server2.emit("proxySocket", proxySocket);
});
return proxyReq.end();
function onOutgoingError(err2) {
if (clb) {
clb(err2, req2, socket);
} else {
server2.emit("error", err2, req2, socket);
}
socket.end();
}
}
};
(function(module) {
var httpProxy2 = module.exports, parse_url = import_url.default.parse, EE3 = eventemitter3Exports, http2 = import_http.default, https2 = import_https.default, web = webIncoming, ws = wsIncoming;
httpProxy2.Server = ProxyServer2;
function createRightProxy(type) {
return function(options2) {
return function(req2, res) {
var passes = type === "ws" ? this.wsPasses : this.webPasses, args = [].slice.call(arguments), cntr = args.length - 1, head, cbl;
if (typeof args[cntr] === "function") {
cbl = args[cntr];
cntr--;
}
var requestOptions = options2;
if (!(args[cntr] instanceof Buffer) && args[cntr] !== res) {
requestOptions = Object.assign({}, options2);
Object.assign(requestOptions, args[cntr]);
cntr--;
}
if (args[cntr] instanceof Buffer) {
head = args[cntr];
}
["target", "forward"].forEach(function(e2) {
if (typeof requestOptions[e2] === "string")
requestOptions[e2] = parse_url(requestOptions[e2]);
});
if (!requestOptions.target && !requestOptions.forward) {
return this.emit("error", new Error("Must provide a proper URL as target"));
}
for (var i = 0; i < passes.length; i++) {
if (passes[i](req2, res, requestOptions, head, this, cbl)) {
break;
}
}
};
};
}
httpProxy2.createRightProxy = createRightProxy;
function ProxyServer2(options2) {
EE3.call(this);
options2 = options2 || {};
options2.prependPath = options2.prependPath === false ? false : true;
this.web = this.proxyRequest = createRightProxy("web")(options2);
this.ws = this.proxyWebsocketRequest = createRightProxy("ws")(options2);
this.options = options2;
this.webPasses = Object.keys(web).map(function(pass) {
return web[pass];
});
this.wsPasses = Object.keys(ws).map(function(pass) {
return ws[pass];
});
this.on("error", this.onError, this);
}
import_util.default.inherits(ProxyServer2, EE3);
ProxyServer2.prototype.onError = function(err2) {
if (this.listeners("error").length === 1) {
throw err2;
}
};
ProxyServer2.prototype.listen = function(port, hostname) {
var self2 = this, closure = function(req2, res) {
self2.web(req2, res);
};
this._server = this.options.ssl ? https2.createServer(this.options.ssl, closure) : http2.createServer(closure);
if (this.options.ws) {
this._server.on("upgrade", function(req2, socket, head) {
self2.ws(req2, socket, head);
});
}
this._server.listen(port, hostname);
return this;
};
ProxyServer2.prototype.close = function(callback) {
var self2 = this;
if (this._server) {
this._server.close(done);
}
function done() {
self2._server = null;
if (callback) {
callback.apply(null, arguments);
}
}
};
ProxyServer2.prototype.before = function(type, passName, callback) {
if (type !== "ws" && type !== "web") {
throw new Error("type must be `web` or `ws`");
}
var passes = type === "ws" ? this.wsPasses : this.webPasses, i = false;
passes.forEach(function(v, idx) {
if (v.name === passName) i = idx;
});
if (i === false) throw new Error("No such pass");
passes.splice(i, 0, callback);
};
ProxyServer2.prototype.after = function(type, passName, callback) {
if (type !== "ws" && type !== "web") {
throw new Error("type must be `web` or `ws`");
}
var passes = type === "ws" ? this.wsPasses : this.webPasses, i = false;
passes.forEach(function(v, idx) {
if (v.name === passName) i = idx;
});
if (i === false) throw new Error("No such pass");
passes.splice(i++, 0, callback);
};
})(httpProxy$3);
var httpProxyExports = httpProxy$3.exports;
var ProxyServer = httpProxyExports.Server;
function createProxyServer(options2) {
return new ProxyServer(options2);
}
ProxyServer.createProxyServer = createProxyServer;
ProxyServer.createServer = createProxyServer;
ProxyServer.createProxy = createProxyServer;
var httpProxy$2 = ProxyServer;
var httpProxy = httpProxy$2;
var httpProxy$1 = getDefaultExportFromCjs(httpProxy);
var debug$4 = createDebugger("vite:proxy");
var rewriteOriginHeader = (proxyReq, options2, config2) => {
if (options2.rewriteWsOrigin) {
const { target } = options2;
if (proxyReq.headersSent) {
config2.logger.warn(
colors$1.yellow(
`Unable to rewrite Origin header as headers are already sent.`
)
);
return;
}
if (proxyReq.getHeader("origin") && target) {
const changedOrigin = typeof target === "object" ? `${target.protocol}//${target.host}` : target;
proxyReq.setHeader("origin", changedOrigin);
}
}
};
function proxyMiddleware(httpServer, options2, config2) {
const proxies = {};
Object.keys(options2).forEach((context) => {
let opts = options2[context];
if (!opts) {
return;
}
if (typeof opts === "string") {
opts = { target: opts, changeOrigin: true };
}
const proxy = httpProxy$1.createProxyServer(opts);
if (opts.configure) {
opts.configure(proxy, opts);
}
proxy.on("error", (err2, req2, originalRes) => {
const res = originalRes;
if (!res) {
config2.logger.error(
`${colors$1.red(`http proxy error: ${err2.message}`)}
${err2.stack}`,
{
timestamp: true,
error: err2
}
);
} else if ("req" in res) {
config2.logger.error(
`${colors$1.red(`http proxy error: ${originalRes.req.url}`)}
${err2.stack}`,
{
timestamp: true,
error: err2
}
);
if (!res.headersSent && !res.writableEnded) {
res.writeHead(500, {
"Content-Type": "text/plain"
}).end();
}
} else {
config2.logger.error(`${colors$1.red(`ws proxy error:`)}
${err2.stack}`, {
timestamp: true,
error: err2
});
res.end();
}
});
proxy.on("proxyReqWs", (proxyReq, req2, socket, options22, head) => {
rewriteOriginHeader(proxyReq, options22, config2);
socket.on("error", (err2) => {
config2.logger.error(
`${colors$1.red(`ws proxy socket error:`)}
${err2.stack}`,
{
timestamp: true,
error: err2
}
);
});
});
proxy.on("proxyRes", (proxyRes, req2, res) => {
res.on("close", () => {
if (!res.writableEnded) {
debug$4 == null ? void 0 : debug$4("destroying proxyRes in proxyRes close event");
proxyRes.destroy();
}
});
});
proxies[context] = [proxy, { ...opts }];
});
if (httpServer) {
httpServer.on("upgrade", (req2, socket, head) => {
var _a4, _b3;
const url2 = req2.url;
for (const context in proxies) {
if (doesProxyContextMatchUrl(context, url2)) {
const [proxy, opts] = proxies[context];
if (opts.ws || ((_a4 = opts.target) == null ? void 0 : _a4.toString().startsWith("ws:")) || ((_b3 = opts.target) == null ? void 0 : _b3.toString().startsWith("wss:"))) {
if (opts.rewrite) {
req2.url = opts.rewrite(url2);
}
debug$4 == null ? void 0 : debug$4(`${req2.url} -> ws ${opts.target}`);
proxy.ws(req2, socket, head);
return;
}
}
}
});
}
return function viteProxyMiddleware(req2, res, next) {
const url2 = req2.url;
for (const context in proxies) {
if (doesProxyContextMatchUrl(context, url2)) {
const [proxy, opts] = proxies[context];
const options22 = {};
if (opts.bypass) {
const bypassResult = opts.bypass(req2, res, opts);
if (typeof bypassResult === "string") {
req2.url = bypassResult;
debug$4 == null ? void 0 : debug$4(`bypass: ${req2.url} -> ${bypassResult}`);
return next();
} else if (bypassResult === false) {
debug$4 == null ? void 0 : debug$4(`bypass: ${req2.url} -> 404`);
res.statusCode = 404;
return res.end();
}
}
debug$4 == null ? void 0 : debug$4(`${req2.url} -> ${opts.target || opts.forward}`);
if (opts.rewrite) {
req2.url = opts.rewrite(req2.url);
}
proxy.web(req2, res, options22);
return;
}
}
next();
};
}
function doesProxyContextMatchUrl(context, url2) {
return context[0] === "^" && new RegExp(context).test(url2) || url2.startsWith(context);
}
var debug$3 = createDebugger("vite:html-fallback");
function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) {
return function viteHtmlFallbackMiddleware(req2, res, next) {
if (
// Only accept GET or HEAD
req2.method !== "GET" && req2.method !== "HEAD" || // Exclude default favicon requests
req2.url === "/favicon.ico" || // Require Accept: text/html or */*
!(req2.headers.accept === void 0 || // equivalent to `Accept: */*`
req2.headers.accept === "" || // equivalent to `Accept: */*`
req2.headers.accept.includes("text/html") || req2.headers.accept.includes("*/*"))
) {
return next();
}
const url2 = cleanUrl(req2.url);
const pathname = decodeURIComponent(url2);
if (pathname.endsWith(".html")) {
const filePath = import_node_path3.default.join(root, pathname);
if (fsUtils.existsSync(filePath)) {
debug$3 == null ? void 0 : debug$3(`Rewriting ${req2.method} ${req2.url} to ${url2}`);
req2.url = url2;
return next();
}
} else if (pathname[pathname.length - 1] === "/") {
const filePath = import_node_path3.default.join(root, pathname, "index.html");
if (fsUtils.existsSync(filePath)) {
const newUrl = url2 + "index.html";
debug$3 == null ? void 0 : debug$3(`Rewriting ${req2.method} ${req2.url} to ${newUrl}`);
req2.url = newUrl;
return next();
}
} else {
const filePath = import_node_path3.default.join(root, pathname + ".html");
if (fsUtils.existsSync(filePath)) {
const newUrl = url2 + ".html";
debug$3 == null ? void 0 : debug$3(`Rewriting ${req2.method} ${req2.url} to ${newUrl}`);
req2.url = newUrl;
return next();
}
}
if (spaFallback) {
debug$3 == null ? void 0 : debug$3(`Rewriting ${req2.method} ${req2.url} to /index.html`);
req2.url = "/index.html";
}
next();
};
}
var debug$2 = createDebugger("vite:send", {
onlyWhenFocused: true
});
var alias = {
js: "text/javascript",
css: "text/css",
html: "text/html",
json: "application/json"
};
function send(req2, res, content, type, options2) {
const {
etag: etag2 = getEtag(content, { weak: true }),
cacheControl = "no-cache",
headers,
map: map2
} = options2;
if (res.writableEnded) {
return;
}
if (req2.headers["if-none-match"] === etag2) {
res.statusCode = 304;
res.end();
return;
}
res.setHeader("Content-Type", alias[type] || type);
res.setHeader("Cache-Control", cacheControl);
res.setHeader("Etag", etag2);
if (headers) {
for (const name2 in headers) {
res.setHeader(name2, headers[name2]);
}
}
if (map2 && "version" in map2 && map2.mappings) {
if (type === "js" || type === "css") {
content = getCodeWithSourcemap(type, content.toString(), map2);
}
} else if (type === "js" && (!map2 || map2.mappings !== "")) {
const code = content.toString();
if (convertSourceMap.mapFileCommentRegex.test(code)) {
debug$2 == null ? void 0 : debug$2(`Skipped injecting fallback sourcemap for ${req2.url}`);
} else {
const urlWithoutTimestamp = removeTimestampQuery(req2.url);
const ms2 = new MagicString(code);
content = getCodeWithSourcemap(
type,
code,
ms2.generateMap({
source: import_node_path3.default.basename(urlWithoutTimestamp),
hires: "boundary",
includeContent: true
})
);
}
}
res.statusCode = 200;
res.end(content);
return;
}
var debugCache = createDebugger("vite:cache");
var knownIgnoreList = /* @__PURE__ */ new Set(["/", "/favicon.ico"]);
function cachedTransformMiddleware(server2) {
return function viteCachedTransformMiddleware(req2, res, next) {
var _a4;
const ifNoneMatch = req2.headers["if-none-match"];
if (ifNoneMatch) {
const moduleByEtag = server2.moduleGraph.getModuleByEtag(ifNoneMatch);
if (((_a4 = moduleByEtag == null ? void 0 : moduleByEtag.transformResult) == null ? void 0 : _a4.etag) === ifNoneMatch) {
const maybeMixedEtag = isCSSRequest(req2.url);
if (!maybeMixedEtag) {
debugCache == null ? void 0 : debugCache(`[304] ${prettifyUrl(req2.url, server2.config.root)}`);
res.statusCode = 304;
return res.end();
}
}
}
next();
};
}
function transformMiddleware(server2) {
const { root, publicDir } = server2.config;
const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
const publicPath = `${publicDir.slice(root.length)}/`;
return async function viteTransformMiddleware(req2, res, next) {
var _a4, _b3, _c2, _d2, _e2, _f2;
if (req2.method !== "GET" || knownIgnoreList.has(req2.url)) {
return next();
}
let url2;
try {
url2 = decodeURI(removeTimestampQuery(req2.url)).replace(
NULL_BYTE_PLACEHOLDER,
"\0"
);
} catch (e2) {
return next(e2);
}
const withoutQuery = cleanUrl(url2);
try {
const isSourceMap = withoutQuery.endsWith(".map");
if (isSourceMap) {
const depsOptimizer = getDepsOptimizer(server2.config, false);
if (depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepUrl(url2)) {
const sourcemapPath = url2.startsWith(FS_PREFIX) ? fsPathFromId(url2) : normalizePath$3(import_node_path3.default.resolve(server2.config.root, url2.slice(1)));
try {
const map2 = JSON.parse(
await import_promises.default.readFile(sourcemapPath, "utf-8")
);
applySourcemapIgnoreList(
map2,
sourcemapPath,
server2.config.server.sourcemapIgnoreList,
server2.config.logger
);
return send(req2, res, JSON.stringify(map2), "json", {
headers: server2.config.server.headers
});
} catch (e2) {
const dummySourceMap = {
version: 3,
file: sourcemapPath.replace(/\.map$/, ""),
sources: [],
sourcesContent: [],
names: [],
mappings: ";;;;;;;;;"
};
return send(req2, res, JSON.stringify(dummySourceMap), "json", {
cacheControl: "no-cache",
headers: server2.config.server.headers
});
}
} else {
const originalUrl = url2.replace(/\.map($|\?)/, "$1");
const map2 = (_b3 = (_a4 = await server2.moduleGraph.getModuleByUrl(originalUrl, false)) == null ? void 0 : _a4.transformResult) == null ? void 0 : _b3.map;
if (map2) {
return send(req2, res, JSON.stringify(map2), "json", {
headers: server2.config.server.headers
});
} else {
return next();
}
}
}
if (publicDirInRoot && url2.startsWith(publicPath)) {
warnAboutExplicitPublicPathInUrl(url2);
}
if (isJSRequest(url2) || isImportRequest(url2) || isCSSRequest(url2) || isHTMLProxy(url2)) {
url2 = removeImportQuery(url2);
url2 = unwrapId$1(url2);
if (isCSSRequest(url2)) {
if (((_c2 = req2.headers.accept) == null ? void 0 : _c2.includes("text/css")) && !isDirectRequest(url2)) {
url2 = injectQuery(url2, "direct");
}
const ifNoneMatch = req2.headers["if-none-match"];
if (ifNoneMatch && ((_e2 = (_d2 = await server2.moduleGraph.getModuleByUrl(url2, false)) == null ? void 0 : _d2.transformResult) == null ? void 0 : _e2.etag) === ifNoneMatch) {
debugCache == null ? void 0 : debugCache(`[304] ${prettifyUrl(url2, server2.config.root)}`);
res.statusCode = 304;
return res.end();
}
}
const result = await transformRequest(url2, server2, {
html: (_f2 = req2.headers.accept) == null ? void 0 : _f2.includes("text/html")
});
if (result) {
const depsOptimizer = getDepsOptimizer(server2.config, false);
const type = isDirectCSSRequest(url2) ? "css" : "js";
const isDep = DEP_VERSION_RE.test(url2) || (depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepUrl(url2));
return send(req2, res, result.code, type, {
etag: result.etag,
// allow browser to cache npm deps!
cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
headers: server2.config.server.headers,
map: result.map
});
}
}
} catch (e2) {
if ((e2 == null ? void 0 : e2.code) === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) {
if (!res.writableEnded) {
res.statusCode = 504;
res.statusMessage = "Optimize Deps Processing Error";
res.end();
}
server2.config.logger.error(e2.message);
return;
}
if ((e2 == null ? void 0 : e2.code) === ERR_OUTDATED_OPTIMIZED_DEP) {
if (!res.writableEnded) {
res.statusCode = 504;
res.statusMessage = "Outdated Optimize Dep";
res.end();
}
return;
}
if ((e2 == null ? void 0 : e2.code) === ERR_CLOSED_SERVER) {
if (!res.writableEnded) {
res.statusCode = 504;
res.statusMessage = "Outdated Request";
res.end();
}
return;
}
if ((e2 == null ? void 0 : e2.code) === ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR) {
if (!res.writableEnded) {
res.statusCode = 404;
res.end();
}
server2.config.logger.warn(colors$1.yellow(e2.message));
return;
}
if ((e2 == null ? void 0 : e2.code) === ERR_LOAD_URL) {
return next();
}
return next(e2);
}
next();
};
function warnAboutExplicitPublicPathInUrl(url2) {
let warning;
if (isImportRequest(url2)) {
const rawUrl = removeImportQuery(url2);
if (urlRE.test(url2)) {
warning = `Assets in the public directory are served at the root path.
Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(
rawUrl.replace(publicPath, "/")
)}.`;
} else {
warning = `Assets in public directory cannot be imported from JavaScript.
If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(
rawUrl.replace(publicPath, "/src/")
)} instead of ${colors$1.cyan(rawUrl)}.
If you intend to use the URL of that asset, use ${colors$1.cyan(
injectQuery(rawUrl.replace(publicPath, "/"), "url")
)}.`;
}
} else {
warning = `Files in the public directory are served at the root path.
Instead of ${colors$1.cyan(url2)}, use ${colors$1.cyan(
url2.replace(publicPath, "/")
)}.`;
}
server2.config.logger.warn(colors$1.yellow(warning));
}
}
function createDevHtmlTransformFn(config2) {
const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(
config2.plugins,
config2.logger
);
const transformHooks = [
preImportMapHook(config2),
injectCspNonceMetaTagHook(config2),
...preHooks,
htmlEnvHook(config2),
devHtmlHook,
...normalHooks,
...postHooks,
injectNonceAttributeTagHook(config2),
postImportMapHook()
];
return (server2, url2, html, originalUrl) => {
return applyHtmlTransforms(html, transformHooks, {
path: url2,
filename: getHtmlFilename(url2, server2),
server: server2,
originalUrl
});
};
}
function getHtmlFilename(url2, server2) {
if (url2.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(url2));
} else {
return decodeURIComponent(
normalizePath$3(import_node_path3.default.join(server2.config.root, url2.slice(1)))
);
}
}
function shouldPreTransform(url2, config2) {
return !checkPublicFile(url2, config2) && (isJSRequest(url2) || isCSSRequest(url2));
}
var wordCharRE = /\w/;
function isBareRelative(url2) {
return wordCharRE.test(url2[0]) && !url2.includes(":");
}
var isSrcSet = (attr) => attr.name === "srcset" && attr.prefix === void 0;
var processNodeUrl = (url2, useSrcSetReplacer, config2, htmlPath, originalUrl, server2, isClassicScriptLink) => {
const replacer = (url22) => {
if (server2 == null ? void 0 : server2.moduleGraph) {
const mod = server2.moduleGraph.urlToModuleMap.get(url22);
if (mod && mod.lastHMRTimestamp > 0) {
url22 = injectQuery(url22, `t=${mod.lastHMRTimestamp}`);
}
}
if (url22[0] === "/" && url22[1] !== "/" || // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets
// path will add `/a/` prefix, it will caused 404.
//
// skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace.
//
// rewrite `./index.js` -> `localhost:5173/a/index.js`.
// rewrite `../index.js` -> `localhost:5173/index.js`.
// rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`.
(url22[0] === "." || isBareRelative(url22)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") {
url22 = import_node_path3.default.posix.join(config2.base, url22);
}
if (server2 && !isClassicScriptLink && shouldPreTransform(url22, config2)) {
let preTransformUrl;
if (url22[0] === "/" && url22[1] !== "/") {
preTransformUrl = url22;
} else if (url22[0] === "." || isBareRelative(url22)) {
preTransformUrl = import_node_path3.default.posix.join(
config2.base,
import_node_path3.default.posix.dirname(htmlPath),
url22
);
}
if (preTransformUrl) {
preTransformRequest(server2, preTransformUrl, config2.base);
}
}
return url22;
};
const processedUrl = useSrcSetReplacer ? processSrcSetSync(url2, ({ url: url22 }) => replacer(url22)) : replacer(url2);
return processedUrl;
};
var devHtmlHook = async (html, { path: htmlPath, filename, server: server2, originalUrl }) => {
const { config: config2, moduleGraph, watcher } = server2;
const base = config2.base || "/";
let proxyModulePath;
let proxyModuleUrl;
const trailingSlash = htmlPath.endsWith("/");
if (!trailingSlash && getFsUtils(config2).existsSync(filename)) {
proxyModulePath = htmlPath;
proxyModuleUrl = proxyModulePath;
} else {
const validPath = `${htmlPath}${trailingSlash ? "index.html" : ""}`;
proxyModulePath = `\0${validPath}`;
proxyModuleUrl = wrapId$1(proxyModulePath);
}
proxyModuleUrl = joinUrlSegments(base, proxyModuleUrl);
const s = new MagicString(html);
let inlineModuleIndex = -1;
const proxyCacheUrl = decodeURI(
cleanUrl(proxyModulePath).replace(normalizePath$3(config2.root), "")
);
const styleUrl = [];
const inlineStyles = [];
const addInlineModule = (node2, ext2) => {
inlineModuleIndex++;
const contentNode = node2.childNodes[0];
const code = contentNode.value;
let map2;
if (proxyModulePath[0] !== "\0") {
map2 = new MagicString(html).snip(
contentNode.sourceCodeLocation.startOffset,
contentNode.sourceCodeLocation.endOffset
).generateMap({ hires: "boundary" });
map2.sources = [filename];
map2.file = filename;
}
addToHTMLProxyCache(config2, proxyCacheUrl, inlineModuleIndex, { code, map: map2 });
const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext2}`;
const module = server2 == null ? void 0 : server2.moduleGraph.getModuleById(modulePath);
if (module) {
server2 == null ? void 0 : server2.moduleGraph.invalidateModule(module);
}
s.update(
node2.sourceCodeLocation.startOffset,
node2.sourceCodeLocation.endOffset,
`<script type="module" src="${modulePath}"><\/script>`
);
preTransformRequest(server2, modulePath, base);
};
await traverseHtml(html, filename, (node2) => {
if (!nodeIsElement(node2)) {
return;
}
if (node2.nodeName === "script") {
const { src: src2, sourceCodeLocation, isModule } = getScriptInfo(node2);
if (src2) {
const processedUrl = processNodeUrl(
src2.value,
isSrcSet(src2),
config2,
htmlPath,
originalUrl,
server2,
!isModule
);
if (processedUrl !== src2.value) {
overwriteAttrValue(s, sourceCodeLocation, processedUrl);
}
} else if (isModule && node2.childNodes.length) {
addInlineModule(node2, "js");
} else if (node2.childNodes.length) {
const scriptNode = node2.childNodes[node2.childNodes.length - 1];
for (const {
url: url2,
start,
end
} of extractImportExpressionFromClassicScript(scriptNode)) {
const processedUrl = processNodeUrl(
url2,
false,
config2,
htmlPath,
originalUrl
);
if (processedUrl !== url2) {
s.update(start, end, processedUrl);
}
}
}
}
const inlineStyle = findNeedTransformStyleAttribute(node2);
if (inlineStyle) {
inlineModuleIndex++;
inlineStyles.push({
index: inlineModuleIndex,
location: inlineStyle.location,
code: inlineStyle.attr.value
});
}
if (node2.nodeName === "style" && node2.childNodes.length) {
const children = node2.childNodes[0];
styleUrl.push({
start: children.sourceCodeLocation.startOffset,
end: children.sourceCodeLocation.endOffset,
code: children.value
});
}
const assetAttrs = assetAttrsConfig[node2.nodeName];
if (assetAttrs) {
for (const p of node2.attrs) {
const attrKey = getAttrKey(p);
if (p.value && assetAttrs.includes(attrKey)) {
const processedUrl = processNodeUrl(
p.value,
isSrcSet(p),
config2,
htmlPath,
originalUrl
);
if (processedUrl !== p.value) {
overwriteAttrValue(
s,
node2.sourceCodeLocation.attrs[attrKey],
processedUrl
);
}
}
}
}
});
await Promise.all([
...styleUrl.map(async ({ start, end, code }, index) => {
const url2 = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
const mod = await moduleGraph.ensureEntryFromUrl(url2, false);
ensureWatchedFile(watcher, mod.file, config2.root);
const result = await server2.pluginContainer.transform(code, mod.id);
let content = "";
if (result) {
if (result.map && "version" in result.map) {
if (result.map.mappings) {
await injectSourcesContent(
result.map,
proxyModulePath,
config2.logger
);
}
content = getCodeWithSourcemap("css", result.code, result.map);
} else {
content = result.code;
}
}
s.overwrite(start, end, content);
}),
...inlineStyles.map(async ({ index, location: location2, code }) => {
const url2 = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
const mod = await moduleGraph.ensureEntryFromUrl(url2, false);
ensureWatchedFile(watcher, mod.file, config2.root);
await (server2 == null ? void 0 : server2.pluginContainer.transform(code, mod.id));
const hash2 = getHash(cleanUrl(mod.id));
const result = htmlProxyResult.get(`${hash2}_${index}`);
overwriteAttrValue(s, location2, result ?? "");
})
]);
html = s.toString();
return {
html,
tags: [
{
tag: "script",
attrs: {
type: "module",
src: import_node_path3.default.posix.join(base, CLIENT_PUBLIC_PATH)
},
injectTo: "head-prepend"
}
]
};
};
function indexHtmlMiddleware(root, server2) {
const isDev = isDevServer(server2);
const fsUtils = getFsUtils(server2.config);
return async function viteIndexHtmlMiddleware(req2, res, next) {
if (res.writableEnded) {
return next();
}
const url2 = req2.url && cleanUrl(req2.url);
if ((url2 == null ? void 0 : url2.endsWith(".html")) && req2.headers["sec-fetch-dest"] !== "script") {
let filePath;
if (isDev && url2.startsWith(FS_PREFIX)) {
filePath = decodeURIComponent(fsPathFromId(url2));
} else {
filePath = import_node_path3.default.join(root, decodeURIComponent(url2));
}
if (fsUtils.existsSync(filePath)) {
const headers = isDev ? server2.config.server.headers : server2.config.preview.headers;
try {
let html = await import_promises.default.readFile(filePath, "utf-8");
if (isDev) {
html = await server2.transformIndexHtml(url2, html, req2.originalUrl);
}
return send(req2, res, html, "html", { headers });
} catch (e2) {
return next(e2);
}
}
}
next();
};
}
function preTransformRequest(server2, url2, base) {
if (!server2.config.server.preTransformRequests) return;
try {
url2 = unwrapId$1(stripBase(decodeURI(url2), base));
} catch {
return;
}
server2.warmupRequest(url2);
}
var logTime = createDebugger("vite:time");
function timeMiddleware(root) {
return function viteTimeMiddleware(req2, res, next) {
const start = import_node_perf_hooks.performance.now();
const end = res.end;
res.end = (...args) => {
logTime == null ? void 0 : logTime(`${timeFrom(start)} ${prettifyUrl(req2.url, root)}`);
return end.call(res, ...args);
};
next();
};
}
var ModuleNode = class {
/**
* @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
*/
constructor(url2, setIsSelfAccepting = true) {
/**
* Public served url path, starts with /
*/
__publicField(this, "url");
/**
* Resolved file system path + query
*/
__publicField(this, "id", null);
__publicField(this, "file", null);
__publicField(this, "type");
__publicField(this, "info");
__publicField(this, "meta");
__publicField(this, "importers", /* @__PURE__ */ new Set());
__publicField(this, "clientImportedModules", /* @__PURE__ */ new Set());
__publicField(this, "ssrImportedModules", /* @__PURE__ */ new Set());
__publicField(this, "acceptedHmrDeps", /* @__PURE__ */ new Set());
__publicField(this, "acceptedHmrExports", null);
__publicField(this, "importedBindings", null);
__publicField(this, "isSelfAccepting");
__publicField(this, "transformResult", null);
__publicField(this, "ssrTransformResult", null);
__publicField(this, "ssrModule", null);
__publicField(this, "ssrError", null);
__publicField(this, "lastHMRTimestamp", 0);
/**
* `import.meta.hot.invalidate` is called by the client.
* If there's multiple clients, multiple `invalidate` request is received.
* This property is used to dedupe those request to avoid multiple updates happening.
* @internal
*/
__publicField(this, "lastHMRInvalidationReceived", false);
__publicField(this, "lastInvalidationTimestamp", 0);
/**
* If the module only needs to update its imports timestamp (e.g. within an HMR chain),
* it is considered soft-invalidated. In this state, its `transformResult` should exist,
* and the next `transformRequest` for this module will replace the timestamps.
*
* By default the value is `undefined` if it's not soft/hard-invalidated. If it gets
* soft-invalidated, this will contain the previous `transformResult` value. If it gets
* hard-invalidated, this will be set to `'HARD_INVALIDATED'`.
* @internal
*/
__publicField(this, "invalidationState");
/**
* @internal
*/
__publicField(this, "ssrInvalidationState");
/**
* The module urls that are statically imported in the code. This information is separated
* out from `importedModules` as only importers that statically import the module can be
* soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated.
* @internal
*/
__publicField(this, "staticImportedUrls");
this.url = url2;
this.type = isDirectCSSRequest(url2) ? "css" : "js";
if (setIsSelfAccepting) {
this.isSelfAccepting = false;
}
}
get importedModules() {
const importedModules = new Set(this.clientImportedModules);
for (const module of this.ssrImportedModules) {
importedModules.add(module);
}
return importedModules;
}
};
var ModuleGraph = class {
constructor(resolveId) {
__publicField(this, "urlToModuleMap", /* @__PURE__ */ new Map());
__publicField(this, "idToModuleMap", /* @__PURE__ */ new Map());
__publicField(this, "etagToModuleMap", /* @__PURE__ */ new Map());
// a single file may corresponds to multiple modules with different queries
__publicField(this, "fileToModulesMap", /* @__PURE__ */ new Map());
__publicField(this, "safeModulesPath", /* @__PURE__ */ new Set());
/**
* @internal
*/
__publicField(this, "_unresolvedUrlToModuleMap", /* @__PURE__ */ new Map());
/**
* @internal
*/
__publicField(this, "_ssrUnresolvedUrlToModuleMap", /* @__PURE__ */ new Map());
/** @internal */
__publicField(this, "_hasResolveFailedErrorModules", /* @__PURE__ */ new Set());
this.resolveId = resolveId;
}
async getModuleByUrl(rawUrl, ssr) {
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
const mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
if (mod) {
return mod;
}
const [url2] = await this._resolveUrl(rawUrl, ssr);
return this.urlToModuleMap.get(url2);
}
getModuleById(id) {
return this.idToModuleMap.get(removeTimestampQuery(id));
}
getModulesByFile(file) {
return this.fileToModulesMap.get(file);
}
onFileChange(file) {
const mods = this.getModulesByFile(file);
if (mods) {
const seen2 = /* @__PURE__ */ new Set();
mods.forEach((mod) => {
this.invalidateModule(mod, seen2);
});
}
}
onFileDelete(file) {
const mods = this.getModulesByFile(file);
if (mods) {
mods.forEach((mod) => {
mod.importedModules.forEach((importedMod) => {
importedMod.importers.delete(mod);
});
});
}
}
invalidateModule(mod, seen2 = /* @__PURE__ */ new Set(), timestamp2 = Date.now(), isHmr = false, softInvalidate = false) {
var _a4;
const prevInvalidationState = mod.invalidationState;
const prevSsrInvalidationState = mod.ssrInvalidationState;
if (softInvalidate) {
mod.invalidationState ?? (mod.invalidationState = mod.transformResult ?? "HARD_INVALIDATED");
mod.ssrInvalidationState ?? (mod.ssrInvalidationState = mod.ssrTransformResult ?? "HARD_INVALIDATED");
} else {
mod.invalidationState = "HARD_INVALIDATED";
mod.ssrInvalidationState = "HARD_INVALIDATED";
}
if (seen2.has(mod) && prevInvalidationState === mod.invalidationState && prevSsrInvalidationState === mod.ssrInvalidationState) {
return;
}
seen2.add(mod);
if (isHmr) {
mod.lastHMRTimestamp = timestamp2;
mod.lastHMRInvalidationReceived = false;
} else {
mod.lastInvalidationTimestamp = timestamp2;
}
const etag2 = (_a4 = mod.transformResult) == null ? void 0 : _a4.etag;
if (etag2) this.etagToModuleMap.delete(etag2);
mod.transformResult = null;
mod.ssrTransformResult = null;
mod.ssrModule = null;
mod.ssrError = null;
mod.importers.forEach((importer) => {
var _a5;
if (!importer.acceptedHmrDeps.has(mod)) {
const shouldSoftInvalidateImporter = ((_a5 = importer.staticImportedUrls) == null ? void 0 : _a5.has(mod.url)) || softInvalidate;
this.invalidateModule(
importer,
seen2,
timestamp2,
isHmr,
shouldSoftInvalidateImporter
);
}
});
this._hasResolveFailedErrorModules.delete(mod);
}
invalidateAll() {
const timestamp2 = Date.now();
const seen2 = /* @__PURE__ */ new Set();
this.idToModuleMap.forEach((mod) => {
this.invalidateModule(mod, seen2, timestamp2);
});
}
/**
* Update the module graph based on a module's updated imports information
* If there are dependencies that no longer have any importers, they are
* returned as a Set.
*
* @param staticImportedUrls Subset of `importedModules` where they're statically imported in code.
* This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing.
*/
async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr, staticImportedUrls) {
mod.isSelfAccepting = isSelfAccepting;
const prevImports = ssr ? mod.ssrImportedModules : mod.clientImportedModules;
let noLongerImported;
let resolvePromises = [];
let resolveResults = new Array(importedModules.size);
let index = 0;
for (const imported of importedModules) {
const nextIndex = index++;
if (typeof imported === "string") {
resolvePromises.push(
this.ensureEntryFromUrl(imported, ssr).then((dep) => {
dep.importers.add(mod);
resolveResults[nextIndex] = dep;
})
);
} else {
imported.importers.add(mod);
resolveResults[nextIndex] = imported;
}
}
if (resolvePromises.length) {
await Promise.all(resolvePromises);
}
const nextImports = new Set(resolveResults);
if (ssr) {
mod.ssrImportedModules = nextImports;
} else {
mod.clientImportedModules = nextImports;
}
prevImports.forEach((dep) => {
if (!mod.clientImportedModules.has(dep) && !mod.ssrImportedModules.has(dep)) {
dep.importers.delete(mod);
if (!dep.importers.size) {
(noLongerImported || (noLongerImported = /* @__PURE__ */ new Set())).add(dep);
}
}
});
resolvePromises = [];
resolveResults = new Array(acceptedModules.size);
index = 0;
for (const accepted of acceptedModules) {
const nextIndex = index++;
if (typeof accepted === "string") {
resolvePromises.push(
this.ensureEntryFromUrl(accepted, ssr).then((dep) => {
resolveResults[nextIndex] = dep;
})
);
} else {
resolveResults[nextIndex] = accepted;
}
}
if (resolvePromises.length) {
await Promise.all(resolvePromises);
}
mod.acceptedHmrDeps = new Set(resolveResults);
mod.staticImportedUrls = staticImportedUrls;
mod.acceptedHmrExports = acceptedExports;
mod.importedBindings = importedBindings;
return noLongerImported;
}
async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting);
}
/**
* @internal
*/
async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true, resolved) {
rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
let mod = this._getUnresolvedUrlToModule(rawUrl, ssr);
if (mod) {
return mod;
}
const modPromise = (async () => {
const [url2, resolvedId, meta] = await this._resolveUrl(
rawUrl,
ssr,
resolved
);
mod = this.idToModuleMap.get(resolvedId);
if (!mod) {
mod = new ModuleNode(url2, setIsSelfAccepting);
if (meta) mod.meta = meta;
this.urlToModuleMap.set(url2, mod);
mod.id = resolvedId;
this.idToModuleMap.set(resolvedId, mod);
const file = mod.file = cleanUrl(resolvedId);
let fileMappedModules = this.fileToModulesMap.get(file);
if (!fileMappedModules) {
fileMappedModules = /* @__PURE__ */ new Set();
this.fileToModulesMap.set(file, fileMappedModules);
}
fileMappedModules.add(mod);
} else if (!this.urlToModuleMap.has(url2)) {
this.urlToModuleMap.set(url2, mod);
}
this._setUnresolvedUrlToModule(rawUrl, mod, ssr);
return mod;
})();
this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr);
return modPromise;
}
// some deps, like a css file referenced via @import, don't have its own
// url because they are inlined into the main css import. But they still
// need to be represented in the module graph so that they can trigger
// hmr in the importing css file.
createFileOnlyEntry(file) {
file = normalizePath$3(file);
let fileMappedModules = this.fileToModulesMap.get(file);
if (!fileMappedModules) {
fileMappedModules = /* @__PURE__ */ new Set();
this.fileToModulesMap.set(file, fileMappedModules);
}
const url2 = `${FS_PREFIX}${file}`;
for (const m of fileMappedModules) {
if (m.url === url2 || m.id === file) {
return m;
}
}
const mod = new ModuleNode(url2);
mod.file = file;
fileMappedModules.add(mod);
return mod;
}
// for incoming urls, it is important to:
// 1. remove the HMR timestamp query (?t=xxxx) and the ?import query
// 2. resolve its extension so that urls with or without extension all map to
// the same module
async resolveUrl(url2, ssr) {
url2 = removeImportQuery(removeTimestampQuery(url2));
const mod = await this._getUnresolvedUrlToModule(url2, ssr);
if (mod == null ? void 0 : mod.id) {
return [mod.url, mod.id, mod.meta];
}
return this._resolveUrl(url2, ssr);
}
updateModuleTransformResult(mod, result, ssr) {
var _a4;
if (ssr) {
mod.ssrTransformResult = result;
} else {
const prevEtag = (_a4 = mod.transformResult) == null ? void 0 : _a4.etag;
if (prevEtag) this.etagToModuleMap.delete(prevEtag);
mod.transformResult = result;
if (result == null ? void 0 : result.etag) this.etagToModuleMap.set(result.etag, mod);
}
}
getModuleByEtag(etag2) {
return this.etagToModuleMap.get(etag2);
}
/**
* @internal
*/
_getUnresolvedUrlToModule(url2, ssr) {
return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url2);
}
/**
* @internal
*/
_setUnresolvedUrlToModule(url2, mod, ssr) {
(ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).set(url2, mod);
}
/**
* @internal
*/
async _resolveUrl(url2, ssr, alreadyResolved) {
const resolved = alreadyResolved ?? await this.resolveId(url2, !!ssr);
const resolvedId = (resolved == null ? void 0 : resolved.id) || url2;
if (url2 !== resolvedId && !url2.includes("\0") && !url2.startsWith(`virtual:`)) {
const ext2 = (0, import_node_path3.extname)(cleanUrl(resolvedId));
if (ext2) {
const pathname = cleanUrl(url2);
if (!pathname.endsWith(ext2)) {
url2 = pathname + ext2 + url2.slice(pathname.length);
}
}
}
return [url2, resolvedId, resolved == null ? void 0 : resolved.meta];
}
};
function notFoundMiddleware() {
return function vite404Middleware(_, res) {
res.statusCode = 404;
res.end();
};
}
var ROOT_FILES = [
// '.git',
// https://pnpm.io/workspaces/
"pnpm-workspace.yaml",
// https://rushjs.io/pages/advanced/config_files/
// 'rush.json',
// https://nx.dev/latest/react/getting-started/nx-setup
// 'workspace.json',
// 'nx.json',
// https://github.com/lerna/lerna#lernajson
"lerna.json"
];
function hasWorkspacePackageJSON(root) {
const path3 = (0, import_node_path3.join)(root, "package.json");
if (!isFileReadable(path3)) {
return false;
}
try {
const content = JSON.parse(import_node_fs2.default.readFileSync(path3, "utf-8")) || {};
return !!content.workspaces;
} catch {
return false;
}
}
function hasRootFile(root) {
return ROOT_FILES.some((file) => import_node_fs2.default.existsSync((0, import_node_path3.join)(root, file)));
}
function hasPackageJSON(root) {
const path3 = (0, import_node_path3.join)(root, "package.json");
return import_node_fs2.default.existsSync(path3);
}
function searchForPackageRoot(current, root = current) {
if (hasPackageJSON(current)) return current;
const dir = (0, import_node_path3.dirname)(current);
if (!dir || dir === current) return root;
return searchForPackageRoot(dir, root);
}
function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
if (hasRootFile(current)) return current;
if (hasWorkspacePackageJSON(current)) return current;
const dir = (0, import_node_path3.dirname)(current);
if (!dir || dir === current) return root;
return searchForWorkspaceRoot(dir, root);
}
function warmupFiles(server2) {
var _a4, _b3;
const options2 = server2.config.server.warmup;
const root = server2.config.root;
if ((_a4 = options2 == null ? void 0 : options2.clientFiles) == null ? void 0 : _a4.length) {
mapFiles(options2.clientFiles, root).then((files) => {
for (const file of files) {
warmupFile(server2, file, false);
}
});
}
if ((_b3 = options2 == null ? void 0 : options2.ssrFiles) == null ? void 0 : _b3.length) {
mapFiles(options2.ssrFiles, root).then((files) => {
for (const file of files) {
warmupFile(server2, file, true);
}
});
}
}
async function warmupFile(server2, file, ssr) {
if (file.endsWith(".html")) {
const url2 = htmlFileToUrl(file, server2.config.root);
if (url2) {
try {
const html = await import_promises.default.readFile(file, "utf-8");
await server2.transformIndexHtml(url2, html);
} catch (e2) {
server2.config.logger.error(
`Pre-transform error (${colors$1.cyan(file)}): ${e2.message}`,
{
error: e2,
timestamp: true
}
);
}
}
} else {
const url2 = fileToUrl(file, server2.config.root);
await server2.warmupRequest(url2, { ssr });
}
}
function htmlFileToUrl(file, root) {
const url2 = import_node_path3.default.relative(root, file);
if (url2[0] === ".") return;
return "/" + normalizePath$3(url2);
}
function fileToUrl(file, root) {
const url2 = import_node_path3.default.relative(root, file);
if (url2[0] === ".") {
return import_node_path3.default.posix.join(FS_PREFIX, normalizePath$3(file));
}
return "/" + normalizePath$3(url2);
}
function mapFiles(files, root) {
return glob(files, {
cwd: root,
absolute: true
});
}
function createServer(inlineConfig = {}) {
return _createServer(inlineConfig, { hotListen: true });
}
async function _createServer(inlineConfig = {}, options2) {
var _a4, _b3, _c2;
const config2 = await resolveConfig(inlineConfig, "serve");
const initPublicFilesPromise = initPublicFiles(config2);
const { root, server: serverConfig } = config2;
const httpsOptions = await resolveHttpsConfig(config2.server.https);
const { middlewareMode } = serverConfig;
const resolvedOutDirs = getResolvedOutDirs(
config2.root,
config2.build.outDir,
(_a4 = config2.build.rollupOptions) == null ? void 0 : _a4.output
);
const emptyOutDir = resolveEmptyOutDir(
config2.build.emptyOutDir,
config2.root,
resolvedOutDirs
);
const resolvedWatchOptions = resolveChokidarOptions(
config2,
{
disableGlobbing: true,
...serverConfig.watch
},
resolvedOutDirs,
emptyOutDir
);
const middlewares = connect$1();
const httpServer = middlewareMode ? null : await resolveHttpServer(serverConfig, middlewares, httpsOptions);
const ws = createWebSocketServer(httpServer, config2, httpsOptions);
const hot = createHMRBroadcaster().addChannel(ws).addChannel(createServerHMRChannel());
if (typeof config2.server.hmr === "object" && config2.server.hmr.channels) {
config2.server.hmr.channels.forEach((channel) => hot.addChannel(channel));
}
const publicFiles = await initPublicFilesPromise;
const { publicDir } = config2;
if (httpServer) {
setClientErrorHandler(httpServer, config2.logger);
}
const watchEnabled = serverConfig.watch !== null;
const watcher = watchEnabled ? chokidar.watch(
// config file dependencies and env file might be outside of root
[
root,
...config2.configFileDependencies,
...getEnvFilesForMode(config2.mode, config2.envDir),
// Watch the public directory explicitly because it might be outside
// of the root directory.
...publicDir && publicFiles ? [publicDir] : []
],
resolvedWatchOptions
) : createNoopWatcher(resolvedWatchOptions);
const moduleGraph = new ModuleGraph(
(url2, ssr) => container.resolveId(url2, void 0, { ssr })
);
const container = await createPluginContainer(config2, moduleGraph, watcher);
const closeHttpServer = createServerCloseFn(httpServer);
const devHtmlTransformFn = createDevHtmlTransformFn(config2);
const onCrawlEndCallbacks = [];
const crawlEndFinder = setupOnCrawlEnd(() => {
onCrawlEndCallbacks.forEach((cb) => cb());
});
function waitForRequestsIdle(ignoredId) {
return crawlEndFinder.waitForRequestsIdle(ignoredId);
}
function _registerRequestProcessing(id, done) {
crawlEndFinder.registerRequestProcessing(id, done);
}
function _onCrawlEnd(cb) {
onCrawlEndCallbacks.push(cb);
}
let server2 = {
config: config2,
middlewares,
httpServer,
watcher,
pluginContainer: container,
ws,
hot,
moduleGraph,
resolvedUrls: null,
// will be set on listen
ssrTransform(code, inMap, url2, originalCode = code) {
return ssrTransform(code, inMap, url2, originalCode, server2.config);
},
transformRequest(url2, options22) {
return transformRequest(url2, server2, options22);
},
async warmupRequest(url2, options22) {
try {
await transformRequest(url2, server2, options22);
} catch (e2) {
if ((e2 == null ? void 0 : e2.code) === ERR_OUTDATED_OPTIMIZED_DEP || (e2 == null ? void 0 : e2.code) === ERR_CLOSED_SERVER) {
return;
}
server2.config.logger.error(`Pre-transform error: ${e2.message}`, {
error: e2,
timestamp: true
});
}
},
transformIndexHtml(url2, html, originalUrl) {
return devHtmlTransformFn(server2, url2, html, originalUrl);
},
async ssrLoadModule(url2, opts) {
return ssrLoadModule(url2, server2, void 0, opts == null ? void 0 : opts.fixStacktrace);
},
async ssrFetchModule(url2, importer) {
return ssrFetchModule(server2, url2, importer);
},
ssrFixStacktrace(e2) {
ssrFixStacktrace(e2, moduleGraph);
},
ssrRewriteStacktrace(stack) {
return ssrRewriteStacktrace(stack, moduleGraph);
},
async reloadModule(module) {
if (serverConfig.hmr !== false && module.file) {
updateModules(module.file, [module], Date.now(), server2);
}
},
async listen(port, isRestart) {
await startServer(server2, port);
if (httpServer) {
server2.resolvedUrls = await resolveServerUrls(
httpServer,
config2.server,
config2
);
if (!isRestart && config2.server.open) server2.openBrowser();
}
return server2;
},
openBrowser() {
var _a5, _b4;
const options22 = server2.config.server;
const url2 = ((_a5 = server2.resolvedUrls) == null ? void 0 : _a5.local[0]) ?? ((_b4 = server2.resolvedUrls) == null ? void 0 : _b4.network[0]);
if (url2) {
const path22 = typeof options22.open === "string" ? new URL(options22.open, url2).href : url2;
if (server2.config.server.preTransformRequests) {
setTimeout(() => {
const getMethod = path22.startsWith("https:") ? import_node_https.get : import_node_http.get;
getMethod(
path22,
{
headers: {
// Allow the history middleware to redirect to /index.html
Accept: "text/html"
}
},
(res) => {
res.on("end", () => {
});
}
).on("error", () => {
}).end();
}, 0);
}
openBrowser(path22, true, server2.config.logger);
} else {
server2.config.logger.warn("No URL available to open in browser");
}
},
async close() {
var _a5, _b4;
if (!middlewareMode) {
teardownSIGTERMListener(closeServerAndExit);
}
await Promise.allSettled([
watcher.close(),
hot.close(),
container.close(),
crawlEndFinder == null ? void 0 : crawlEndFinder.cancel(),
(_a5 = getDepsOptimizer(server2.config)) == null ? void 0 : _a5.close(),
(_b4 = getDepsOptimizer(server2.config, true)) == null ? void 0 : _b4.close(),
closeHttpServer()
]);
while (server2._pendingRequests.size > 0) {
await Promise.allSettled(
[...server2._pendingRequests.values()].map(
(pending) => pending.request
)
);
}
server2.resolvedUrls = null;
},
printUrls() {
if (server2.resolvedUrls) {
printServerUrls(
server2.resolvedUrls,
serverConfig.host,
config2.logger.info
);
} else if (middlewareMode) {
throw new Error("cannot print server URLs in middleware mode.");
} else {
throw new Error(
"cannot print server URLs before server.listen is called."
);
}
},
bindCLIShortcuts(options22) {
bindCLIShortcuts(server2, options22);
},
async restart(forceOptimize) {
if (!server2._restartPromise) {
server2._forceOptimizeOnRestart = !!forceOptimize;
server2._restartPromise = restartServer(server2).finally(() => {
server2._restartPromise = null;
server2._forceOptimizeOnRestart = false;
});
}
return server2._restartPromise;
},
waitForRequestsIdle,
_registerRequestProcessing,
_onCrawlEnd,
_setInternalServer(_server) {
server2 = _server;
},
_restartPromise: null,
_importGlobMap: /* @__PURE__ */ new Map(),
_forceOptimizeOnRestart: false,
_pendingRequests: /* @__PURE__ */ new Map(),
_fsDenyGlob: picomatch$4(
// matchBase: true does not work as it's documented
// https://github.com/micromatch/picomatch/issues/89
// convert patterns without `/` on our side for now
config2.server.fs.deny.map(
(pattern2) => pattern2.includes("/") ? pattern2 : `**/${pattern2}`
),
{
matchBase: false,
nocase: true,
dot: true
}
),
_shortcutsOptions: void 0
};
const reflexServer = new Proxy(server2, {
get: (_, property) => {
return server2[property];
},
set: (_, property, value2) => {
server2[property] = value2;
return true;
}
});
const closeServerAndExit = async () => {
try {
await server2.close();
} finally {
process.exit();
}
};
if (!middlewareMode) {
setupSIGTERMListener(closeServerAndExit);
}
const onHMRUpdate = async (type, file) => {
if (serverConfig.hmr !== false) {
try {
await handleHMRUpdate(type, file, server2);
} catch (err2) {
hot.send({
type: "error",
err: prepareError(err2)
});
}
}
};
const onFileAddUnlink = async (file, isUnlink) => {
var _a5;
file = normalizePath$3(file);
await container.watchChange(file, { event: isUnlink ? "delete" : "create" });
if (publicDir && publicFiles) {
if (file.startsWith(publicDir)) {
const path22 = file.slice(publicDir.length);
publicFiles[isUnlink ? "delete" : "add"](path22);
if (!isUnlink) {
const moduleWithSamePath = await moduleGraph.getModuleByUrl(path22);
const etag2 = (_a5 = moduleWithSamePath == null ? void 0 : moduleWithSamePath.transformResult) == null ? void 0 : _a5.etag;
if (etag2) {
moduleGraph.etagToModuleMap.delete(etag2);
}
}
}
}
if (isUnlink) moduleGraph.onFileDelete(file);
await onHMRUpdate(isUnlink ? "delete" : "create", file);
};
watcher.on("change", async (file) => {
file = normalizePath$3(file);
await container.watchChange(file, { event: "update" });
moduleGraph.onFileChange(file);
await onHMRUpdate("update", file);
});
(_c2 = (_b3 = getFsUtils(config2)).initWatcher) == null ? void 0 : _c2.call(_b3, watcher);
watcher.on("add", (file) => {
onFileAddUnlink(file, false);
});
watcher.on("unlink", (file) => {
onFileAddUnlink(file, true);
});
hot.on("vite:invalidate", async ({ path: path22, message }) => {
const mod = moduleGraph.urlToModuleMap.get(path22);
if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
mod.lastHMRInvalidationReceived = true;
config2.logger.info(
colors$1.yellow(`hmr invalidate `) + colors$1.dim(path22) + (message ? ` ${message}` : ""),
{ timestamp: true }
);
const file = getShortName(mod.file, config2.root);
updateModules(
file,
[...mod.importers],
mod.lastHMRTimestamp,
server2,
true
);
}
});
if (!middlewareMode && httpServer) {
httpServer.once("listening", () => {
serverConfig.port = httpServer.address().port;
});
}
const postHooks = [];
for (const hook of config2.getSortedPluginHooks("configureServer")) {
postHooks.push(await hook(reflexServer));
}
if (process.env.DEBUG) {
middlewares.use(timeMiddleware(root));
}
const { cors } = serverConfig;
if (cors !== false) {
middlewares.use(corsMiddleware(typeof cors === "boolean" ? {} : cors));
}
middlewares.use(cachedTransformMiddleware(server2));
const { proxy } = serverConfig;
if (proxy) {
const middlewareServer = (isObject$1(middlewareMode) ? middlewareMode.server : null) || httpServer;
middlewares.use(proxyMiddleware(middlewareServer, proxy, config2));
}
if (config2.base !== "/") {
middlewares.use(baseMiddleware(config2.rawBase, !!middlewareMode));
}
middlewares.use("/__open-in-editor", launchEditorMiddleware$1());
middlewares.use(function viteHMRPingMiddleware(req2, res, next) {
if (req2.headers["accept"] === "text/x-vite-ping") {
res.writeHead(204).end();
} else {
next();
}
});
if (publicDir) {
middlewares.use(servePublicMiddleware(server2, publicFiles));
}
middlewares.use(transformMiddleware(server2));
middlewares.use(serveRawFsMiddleware(server2));
middlewares.use(serveStaticMiddleware(server2));
if (config2.appType === "spa" || config2.appType === "mpa") {
middlewares.use(
htmlFallbackMiddleware(
root,
config2.appType === "spa",
getFsUtils(config2)
)
);
}
postHooks.forEach((fn) => fn && fn());
if (config2.appType === "spa" || config2.appType === "mpa") {
middlewares.use(indexHtmlMiddleware(root, server2));
middlewares.use(notFoundMiddleware());
}
middlewares.use(errorMiddleware(server2, !!middlewareMode));
let initingServer;
let serverInited = false;
const initServer = async () => {
if (serverInited) return;
if (initingServer) return initingServer;
initingServer = async function() {
await container.buildStart({});
if (isDepsOptimizerEnabled(config2, false)) {
await initDepsOptimizer(config2, server2);
}
warmupFiles(server2);
initingServer = void 0;
serverInited = true;
}();
return initingServer;
};
if (!middlewareMode && httpServer) {
const listen2 = httpServer.listen.bind(httpServer);
httpServer.listen = async (port, ...args) => {
try {
hot.listen();
await initServer();
} catch (e2) {
httpServer.emit("error", e2);
return;
}
return listen2(port, ...args);
};
} else {
if (options2.hotListen) {
hot.listen();
}
await initServer();
}
return server2;
}
async function startServer(server2, inlinePort) {
const httpServer = server2.httpServer;
if (!httpServer) {
throw new Error("Cannot call server.listen in middleware mode.");
}
const options2 = server2.config.server;
const hostname = await resolveHostname(options2.host);
const configPort = inlinePort ?? options2.port;
const port = (!configPort || configPort === server2._configServerPort ? server2._currentServerPort : configPort) ?? DEFAULT_DEV_PORT;
server2._configServerPort = configPort;
const serverPort = await httpServerStart(httpServer, {
port,
strictPort: options2.strictPort,
host: hostname.host,
logger: server2.config.logger
});
server2._currentServerPort = serverPort;
}
function createServerCloseFn(server2) {
if (!server2) {
return () => Promise.resolve();
}
let hasListened = false;
const openSockets = /* @__PURE__ */ new Set();
server2.on("connection", (socket) => {
openSockets.add(socket);
socket.on("close", () => {
openSockets.delete(socket);
});
});
server2.once("listening", () => {
hasListened = true;
});
return () => new Promise((resolve3, reject) => {
openSockets.forEach((s) => s.destroy());
if (hasListened) {
server2.close((err2) => {
if (err2) {
reject(err2);
} else {
resolve3();
}
});
} else {
resolve3();
}
});
}
function resolvedAllowDir(root, dir) {
return normalizePath$3(import_node_path3.default.resolve(root, dir));
}
function resolveServerOptions(root, raw, logger) {
var _a4, _b3, _c2, _d2, _e2;
const server2 = {
preTransformRequests: true,
...raw,
sourcemapIgnoreList: (raw == null ? void 0 : raw.sourcemapIgnoreList) === false ? () => false : (raw == null ? void 0 : raw.sourcemapIgnoreList) || isInNodeModules$1,
middlewareMode: (raw == null ? void 0 : raw.middlewareMode) || false
};
let allowDirs = (_a4 = server2.fs) == null ? void 0 : _a4.allow;
const deny = ((_b3 = server2.fs) == null ? void 0 : _b3.deny) || [".env", ".env.*", "*.{crt,pem}"];
if (!allowDirs) {
allowDirs = [searchForWorkspaceRoot(root)];
}
if (process.versions.pnp) {
try {
const enableGlobalCache = (0, import_node_child_process.execSync)("yarn config get enableGlobalCache", { cwd: root }).toString().trim() === "true";
const yarnCacheDir = (0, import_node_child_process.execSync)(
`yarn config get ${enableGlobalCache ? "globalFolder" : "cacheFolder"}`,
{ cwd: root }
).toString().trim();
allowDirs.push(yarnCacheDir);
} catch (e2) {
logger.warn(`Get yarn cache dir error: ${e2.message}`, {
timestamp: true
});
}
}
allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) {
allowDirs.push(resolvedClientDir);
}
server2.fs = {
strict: ((_c2 = server2.fs) == null ? void 0 : _c2.strict) ?? true,
allow: allowDirs,
deny,
cachedChecks: (_d2 = server2.fs) == null ? void 0 : _d2.cachedChecks
};
if ((_e2 = server2.origin) == null ? void 0 : _e2.endsWith("/")) {
server2.origin = server2.origin.slice(0, -1);
logger.warn(
colors$1.yellow(
`${colors$1.bold("(!)")} server.origin should not end with "/". Using "${server2.origin}" instead.`
)
);
}
return server2;
}
async function restartServer(server2) {
global.__vite_start_time = import_node_perf_hooks.performance.now();
const shortcutsOptions = server2._shortcutsOptions;
let inlineConfig = server2.config.inlineConfig;
if (server2._forceOptimizeOnRestart) {
inlineConfig = mergeConfig(inlineConfig, {
optimizeDeps: {
force: true
}
});
}
{
let newServer = null;
try {
newServer = await _createServer(inlineConfig, { hotListen: false });
} catch (err2) {
server2.config.logger.error(err2.message, {
timestamp: true
});
server2.config.logger.error("server restart failed", { timestamp: true });
return;
}
await server2.close();
const middlewares = server2.middlewares;
newServer._configServerPort = server2._configServerPort;
newServer._currentServerPort = server2._currentServerPort;
Object.assign(server2, newServer);
middlewares.stack = newServer.middlewares.stack;
server2.middlewares = middlewares;
newServer._setInternalServer(server2);
}
const {
logger,
server: { port, middlewareMode }
} = server2.config;
if (!middlewareMode) {
await server2.listen(port, true);
} else {
server2.hot.listen();
}
logger.info("server restarted.", { timestamp: true });
if (shortcutsOptions) {
shortcutsOptions.print = false;
bindCLIShortcuts(server2, shortcutsOptions);
}
}
async function restartServerWithUrls(server2) {
if (server2.config.server.middlewareMode) {
await server2.restart();
return;
}
const { port: prevPort, host: prevHost } = server2.config.server;
const prevUrls = server2.resolvedUrls;
await server2.restart();
const {
logger,
server: { port, host }
} = server2.config;
if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || host !== prevHost || diffDnsOrderChange(prevUrls, server2.resolvedUrls)) {
logger.info("");
server2.printUrls();
}
}
var callCrawlEndIfIdleAfterMs = 50;
function setupOnCrawlEnd(onCrawlEnd) {
const registeredIds = /* @__PURE__ */ new Set();
const seenIds = /* @__PURE__ */ new Set();
const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
let timeoutHandle;
let cancelled = false;
function cancel() {
cancelled = true;
}
let crawlEndCalled = false;
function callOnCrawlEnd() {
if (!cancelled && !crawlEndCalled) {
crawlEndCalled = true;
onCrawlEnd();
}
onCrawlEndPromiseWithResolvers.resolve();
}
function registerRequestProcessing(id, done) {
if (!seenIds.has(id)) {
seenIds.add(id);
registeredIds.add(id);
done().catch(() => {
}).finally(() => markIdAsDone(id));
}
}
function waitForRequestsIdle(ignoredId) {
if (ignoredId) {
seenIds.add(ignoredId);
markIdAsDone(ignoredId);
}
return onCrawlEndPromiseWithResolvers.promise;
}
function markIdAsDone(id) {
if (registeredIds.has(id)) {
registeredIds.delete(id);
checkIfCrawlEndAfterTimeout();
}
}
function checkIfCrawlEndAfterTimeout() {
if (cancelled || registeredIds.size > 0) return;
if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(
callOnCrawlEndWhenIdle,
callCrawlEndIfIdleAfterMs
);
}
async function callOnCrawlEndWhenIdle() {
if (cancelled || registeredIds.size > 0) return;
callOnCrawlEnd();
}
return {
registerRequestProcessing,
waitForRequestsIdle,
cancel
};
}
var debugHmr = createDebugger("vite:hmr");
var whitespaceRE = /\s/;
var normalizedClientDir = normalizePath$3(CLIENT_DIR);
function getShortName(file, root) {
return file.startsWith(withTrailingSlash(root)) ? import_node_path3.default.posix.relative(root, file) : file;
}
async function handleHMRUpdate(type, file, server2) {
const { hot, config: config2, moduleGraph } = server2;
const shortFile = getShortName(file, config2.root);
const isConfig = file === config2.configFile;
const isConfigDependency = config2.configFileDependencies.some(
(name2) => file === name2
);
const isEnv = config2.inlineConfig.envFile !== false && getEnvFilesForMode(config2.mode, config2.envDir).includes(file);
if (isConfig || isConfigDependency || isEnv) {
debugHmr == null ? void 0 : debugHmr(`[config change] ${colors$1.dim(shortFile)}`);
config2.logger.info(
colors$1.green(
`${normalizePath$3(
import_node_path3.default.relative(process.cwd(), file)
)} changed, restarting server...`
),
{ clear: true, timestamp: true }
);
try {
await restartServerWithUrls(server2);
} catch (e2) {
config2.logger.error(colors$1.red(e2));
}
return;
}
debugHmr == null ? void 0 : debugHmr(`[file change] ${colors$1.dim(shortFile)}`);
if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
hot.send({
type: "full-reload",
path: "*",
triggeredBy: import_node_path3.default.resolve(config2.root, file)
});
return;
}
const mods = new Set(moduleGraph.getModulesByFile(file));
if (type === "create") {
for (const mod of moduleGraph._hasResolveFailedErrorModules) {
mods.add(mod);
}
}
if (type === "create" || type === "delete") {
for (const mod of getAffectedGlobModules(file, server2)) {
mods.add(mod);
}
}
const timestamp2 = Date.now();
const hmrContext = {
file,
timestamp: timestamp2,
modules: [...mods],
read: () => readModifiedFile(file),
server: server2
};
if (type === "update") {
for (const hook of config2.getSortedPluginHooks("handleHotUpdate")) {
const filteredModules = await hook(hmrContext);
if (filteredModules) {
hmrContext.modules = filteredModules;
}
}
}
if (!hmrContext.modules.length) {
if (file.endsWith(".html")) {
config2.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), {
clear: true,
timestamp: true
});
hot.send({
type: "full-reload",
path: config2.server.middlewareMode ? "*" : "/" + normalizePath$3(import_node_path3.default.relative(config2.root, file))
});
} else {
debugHmr == null ? void 0 : debugHmr(`[no modules matched] ${colors$1.dim(shortFile)}`);
}
return;
}
updateModules(shortFile, hmrContext.modules, timestamp2, server2);
}
function updateModules(file, modules, timestamp2, { config: config2, hot, moduleGraph }, afterInvalidation) {
const updates = [];
const invalidatedModules = /* @__PURE__ */ new Set();
const traversedModules = /* @__PURE__ */ new Set();
let needFullReload = modules.length === 0;
for (const mod of modules) {
const boundaries = [];
const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries);
moduleGraph.invalidateModule(mod, invalidatedModules, timestamp2, true);
if (needFullReload) {
continue;
}
if (hasDeadEnd) {
needFullReload = hasDeadEnd;
continue;
}
updates.push(
...boundaries.map(
({ boundary, acceptedVia, isWithinCircularImport }) => ({
type: `${boundary.type}-update`,
timestamp: timestamp2,
path: normalizeHmrUrl(boundary.url),
acceptedPath: normalizeHmrUrl(acceptedVia.url),
explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
isWithinCircularImport,
// browser modules are invalidated by changing ?t= query,
// but in ssr we control the module system, so we can directly remove them form cache
ssrInvalidates: getSSRInvalidatedImporters(acceptedVia)
})
)
);
}
if (needFullReload) {
const reason = typeof needFullReload === "string" ? colors$1.dim(` (${needFullReload})`) : "";
config2.logger.info(
colors$1.green(`page reload `) + colors$1.dim(file) + reason,
{ clear: !afterInvalidation, timestamp: true }
);
hot.send({
type: "full-reload",
triggeredBy: import_node_path3.default.resolve(config2.root, file)
});
return;
}
if (updates.length === 0) {
debugHmr == null ? void 0 : debugHmr(colors$1.yellow(`no update happened `) + colors$1.dim(file));
return;
}
config2.logger.info(
colors$1.green(`hmr update `) + colors$1.dim([...new Set(updates.map((u) => u.path))].join(", ")),
{ clear: !afterInvalidation, timestamp: true }
);
hot.send({
type: "update",
updates
});
}
function populateSSRImporters(module, timestamp2, seen2 = /* @__PURE__ */ new Set()) {
module.ssrImportedModules.forEach((importer) => {
if (seen2.has(importer)) {
return;
}
if (importer.lastHMRTimestamp === timestamp2 || importer.lastInvalidationTimestamp === timestamp2) {
seen2.add(importer);
populateSSRImporters(importer, timestamp2, seen2);
}
});
return seen2;
}
function getSSRInvalidatedImporters(module) {
return [...populateSSRImporters(module, module.lastHMRTimestamp)].map(
(m) => m.file
);
}
function areAllImportsAccepted(importedBindings, acceptedExports) {
for (const binding of importedBindings) {
if (!acceptedExports.has(binding)) {
return false;
}
}
return true;
}
function propagateUpdate(node2, traversedModules, boundaries, currentChain = [node2]) {
if (traversedModules.has(node2)) {
return false;
}
traversedModules.add(node2);
if (node2.id && node2.isSelfAccepting === void 0) {
debugHmr == null ? void 0 : debugHmr(
`[propagate update] stop propagation because not analyzed: ${colors$1.dim(
node2.id
)}`
);
return false;
}
if (node2.isSelfAccepting) {
boundaries.push({
boundary: node2,
acceptedVia: node2,
isWithinCircularImport: isNodeWithinCircularImports(node2, currentChain)
});
for (const importer of node2.importers) {
if (isCSSRequest(importer.url) && !currentChain.includes(importer)) {
propagateUpdate(
importer,
traversedModules,
boundaries,
currentChain.concat(importer)
);
}
}
return false;
}
if (node2.acceptedHmrExports) {
boundaries.push({
boundary: node2,
acceptedVia: node2,
isWithinCircularImport: isNodeWithinCircularImports(node2, currentChain)
});
} else {
if (!node2.importers.size) {
return true;
}
if (!isCSSRequest(node2.url) && [...node2.importers].every((i) => isCSSRequest(i.url))) {
return true;
}
}
for (const importer of node2.importers) {
const subChain = currentChain.concat(importer);
if (importer.acceptedHmrDeps.has(node2)) {
boundaries.push({
boundary: importer,
acceptedVia: node2,
isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
});
continue;
}
if (node2.id && node2.acceptedHmrExports && importer.importedBindings) {
const importedBindingsFromNode = importer.importedBindings.get(node2.id);
if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node2.acceptedHmrExports)) {
continue;
}
}
if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) {
return true;
}
}
return false;
}
function isNodeWithinCircularImports(node2, nodeChain, currentChain = [node2], traversedModules = /* @__PURE__ */ new Set()) {
if (traversedModules.has(node2)) {
return false;
}
traversedModules.add(node2);
for (const importer of node2.importers) {
if (importer === node2) continue;
if (isCSSRequest(importer.url)) continue;
const importerIndex = nodeChain.indexOf(importer);
if (importerIndex > -1) {
if (debugHmr) {
const importChain = [
importer,
...[...currentChain].reverse(),
...nodeChain.slice(importerIndex, -1).reverse()
];
debugHmr(
colors$1.yellow(`circular imports detected: `) + importChain.map((m) => colors$1.dim(m.url)).join(" -> ")
);
}
return true;
}
if (!currentChain.includes(importer)) {
const result = isNodeWithinCircularImports(
importer,
nodeChain,
currentChain.concat(importer),
traversedModules
);
if (result) return result;
}
}
return false;
}
function handlePrunedModules(mods, { hot }) {
const t2 = Date.now();
mods.forEach((mod) => {
mod.lastHMRTimestamp = t2;
mod.lastHMRInvalidationReceived = false;
debugHmr == null ? void 0 : debugHmr(`[dispose] ${colors$1.dim(mod.file)}`);
});
hot.send({
type: "prune",
paths: [...mods].map((m) => m.url)
});
}
function lexAcceptedHmrDeps(code, start, urls) {
let state = 0;
let prevState = 0;
let currentDep = "";
function addDep(index) {
urls.add({
url: currentDep,
start: index - currentDep.length - 1,
end: index + 1
});
currentDep = "";
}
for (let i = start; i < code.length; i++) {
const char = code.charAt(i);
switch (state) {
case 0:
case 4:
if (char === `'`) {
prevState = state;
state = 1;
} else if (char === `"`) {
prevState = state;
state = 2;
} else if (char === "`") {
prevState = state;
state = 3;
} else if (whitespaceRE.test(char)) {
continue;
} else {
if (state === 0) {
if (char === `[`) {
state = 4;
} else {
return true;
}
} else if (state === 4) {
if (char === `]`) {
return false;
} else if (char === ",") {
continue;
} else {
error(i);
}
}
}
break;
case 1:
if (char === `'`) {
addDep(i);
if (prevState === 0) {
return false;
} else {
state = prevState;
}
} else {
currentDep += char;
}
break;
case 2:
if (char === `"`) {
addDep(i);
if (prevState === 0) {
return false;
} else {
state = prevState;
}
} else {
currentDep += char;
}
break;
case 3:
if (char === "`") {
addDep(i);
if (prevState === 0) {
return false;
} else {
state = prevState;
}
} else if (char === "$" && code.charAt(i + 1) === "{") {
error(i);
} else {
currentDep += char;
}
break;
default:
throw new Error("unknown import.meta.hot lexer state");
}
}
return false;
}
function lexAcceptedHmrExports(code, start, exportNames) {
const urls = /* @__PURE__ */ new Set();
lexAcceptedHmrDeps(code, start, urls);
for (const { url: url2 } of urls) {
exportNames.add(url2);
}
return urls.size > 0;
}
function normalizeHmrUrl(url2) {
if (url2[0] !== "." && url2[0] !== "/") {
url2 = wrapId$1(url2);
}
return url2;
}
function error(pos) {
const err2 = new Error(
`import.meta.hot.accept() can only accept string literals or an Array of string literals.`
);
err2.pos = pos;
throw err2;
}
async function readModifiedFile(file) {
const content = await import_promises.default.readFile(file, "utf-8");
if (!content) {
const mtime = (await import_promises.default.stat(file)).mtimeMs;
for (let n2 = 0; n2 < 10; n2++) {
await new Promise((r2) => setTimeout(r2, 10));
const newMtime = (await import_promises.default.stat(file)).mtimeMs;
if (newMtime !== mtime) {
break;
}
}
return await import_promises.default.readFile(file, "utf-8");
} else {
return content;
}
}
function createHMRBroadcaster() {
const channels = [];
const readyChannels = /* @__PURE__ */ new WeakSet();
const broadcaster = {
get channels() {
return [...channels];
},
addChannel(channel) {
if (channels.some((c) => c.name === channel.name)) {
throw new Error(`HMR channel "${channel.name}" is already defined.`);
}
channels.push(channel);
return broadcaster;
},
on(event, listener2) {
if (event === "connection") {
const channels2 = this.channels;
channels2.forEach(
(channel) => channel.on("connection", () => {
readyChannels.add(channel);
if (channels2.every((c) => readyChannels.has(c))) {
listener2();
}
})
);
return;
}
channels.forEach((channel) => channel.on(event, listener2));
return;
},
off(event, listener2) {
channels.forEach((channel) => channel.off(event, listener2));
return;
},
send(...args) {
channels.forEach((channel) => channel.send(...args));
},
listen() {
channels.forEach((channel) => channel.listen());
},
close() {
return Promise.all(channels.map((channel) => channel.close()));
}
};
return broadcaster;
}
function createServerHMRChannel() {
const innerEmitter = new import_node_events.EventEmitter();
const outsideEmitter = new import_node_events.EventEmitter();
return {
name: "ssr",
send(...args) {
let payload;
if (typeof args[0] === "string") {
payload = {
type: "custom",
event: args[0],
data: args[1]
};
} else {
payload = args[0];
}
outsideEmitter.emit("send", payload);
},
off(event, listener2) {
innerEmitter.off(event, listener2);
},
on: (event, listener2) => {
innerEmitter.on(event, listener2);
},
close() {
innerEmitter.removeAllListeners();
outsideEmitter.removeAllListeners();
},
listen() {
innerEmitter.emit("connection");
},
api: {
innerEmitter,
outsideEmitter
}
};
}
var debug$1 = createDebugger("vite:import-analysis");
var clientDir = normalizePath$3(CLIENT_DIR);
var skipRE = /\.(?:map|json)(?:$|\?)/;
var canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
var optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
var optimizedDepDynamicRE = /-[A-Z\d]{8}\.js/;
var hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
var urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
var templateLiteralRE = /^\s*`(.*)`\s*$/;
function isExplicitImportRequired(url2) {
return !isJSRequest(url2) && !isCSSRequest(url2);
}
function extractImportedBindings(id, source, importSpec, importedBindings) {
let bindings = importedBindings.get(id);
if (!bindings) {
bindings = /* @__PURE__ */ new Set();
importedBindings.set(id, bindings);
}
const isDynamic = importSpec.d > -1;
const isMeta = importSpec.d === -2;
if (isDynamic || isMeta) {
bindings.add("*");
return;
}
const exp = source.slice(importSpec.ss, importSpec.se);
ESM_STATIC_IMPORT_RE.lastIndex = 0;
const match2 = ESM_STATIC_IMPORT_RE.exec(exp);
if (!match2) {
return;
}
const staticImport = {
type: "static",
code: match2[0],
start: match2.index,
end: match2.index + match2[0].length,
imports: match2.groups.imports,
specifier: match2.groups.specifier
};
const parsed = parseStaticImport(staticImport);
if (!parsed) {
return;
}
if (parsed.namespacedImport) {
bindings.add("*");
}
if (parsed.defaultImport) {
bindings.add("default");
}
if (parsed.namedImports) {
for (const name2 of Object.keys(parsed.namedImports)) {
bindings.add(name2);
}
}
}
function importAnalysisPlugin(config2) {
var _a4;
const { root, base } = config2;
const fsUtils = getFsUtils(config2);
const clientPublicPath = import_node_path3.default.posix.join(base, CLIENT_PUBLIC_PATH);
const enablePartialAccept = (_a4 = config2.experimental) == null ? void 0 : _a4.hmrPartialAccept;
const matchAlias = getAliasPatternMatcher(config2.resolve.alias);
let server2;
let _env;
let _ssrEnv;
function getEnv(ssr) {
if (!_ssrEnv || !_env) {
const importMetaEnvKeys = {};
const userDefineEnv = {};
for (const key in config2.env) {
importMetaEnvKeys[key] = JSON.stringify(config2.env[key]);
}
for (const key in config2.define) {
if (key.startsWith("import.meta.env.")) {
userDefineEnv[key.slice(16)] = config2.define[key];
}
}
const env2 = `import.meta.env = ${serializeDefine({
...importMetaEnvKeys,
SSR: "__vite_ssr__",
...userDefineEnv
})};`;
_ssrEnv = env2.replace("__vite_ssr__", "true");
_env = env2.replace("__vite_ssr__", "false");
}
return ssr ? _ssrEnv : _env;
}
return {
name: "vite:import-analysis",
configureServer(_server) {
server2 = _server;
},
async transform(source, importer, options2) {
if (!server2) {
return null;
}
const ssr = (options2 == null ? void 0 : options2.ssr) === true;
if (canSkipImportAnalysis(importer)) {
debug$1 == null ? void 0 : debug$1(colors$1.dim(`[skipped] ${prettifyUrl(importer, root)}`));
return null;
}
const msAtStart = debug$1 ? import_node_perf_hooks.performance.now() : 0;
await init;
let imports;
let exports2;
source = stripBomTag(source);
try {
[imports, exports2] = parse$d(source);
} catch (_e2) {
const e2 = _e2;
const { message, showCodeFrame } = createParseErrorInfo(
importer,
source
);
this.error(message, showCodeFrame ? e2.idx : void 0);
}
const depsOptimizer = getDepsOptimizer(config2, ssr);
const { moduleGraph } = server2;
const importerModule = moduleGraph.getModuleById(importer);
if (!importerModule) {
throwOutdatedRequest(importer);
}
if (!imports.length && !this._addedImports) {
importerModule.isSelfAccepting = false;
debug$1 == null ? void 0 : debug$1(
`${timeFrom(msAtStart)} ${colors$1.dim(
`[no imports] ${prettifyUrl(importer, root)}`
)}`
);
return source;
}
let hasHMR = false;
let isSelfAccepting = false;
let hasEnv = false;
let needQueryInjectHelper = false;
let s;
const str = () => s || (s = new MagicString(source));
let isPartiallySelfAccepting = false;
const importedBindings = enablePartialAccept ? /* @__PURE__ */ new Map() : null;
const toAbsoluteUrl = (url2) => import_node_path3.default.posix.resolve(import_node_path3.default.posix.dirname(importerModule.url), url2);
const normalizeUrl = async (url2, pos, forceSkipImportAnalysis = false) => {
var _a5, _b3;
url2 = stripBase(url2, base);
let importerFile = importer;
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
if (moduleListContains(optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude, url2)) {
if (depsOptimizer) {
await depsOptimizer.scanProcessing;
for (const optimizedModule of depsOptimizer.metadata.depInfoList) {
if (!optimizedModule.src) continue;
if (optimizedModule.file === importerModule.file) {
importerFile = optimizedModule.src;
}
}
}
}
const resolved = await this.resolve(url2, importerFile);
if (!resolved || ((_b3 = (_a5 = resolved.meta) == null ? void 0 : _a5["vite:alias"]) == null ? void 0 : _b3.noResolved)) {
if (ssr) {
return [url2, url2];
}
importerModule.isSelfAccepting = false;
moduleGraph._hasResolveFailedErrorModules.add(importerModule);
return this.error(
`Failed to resolve import "${url2}" from "${normalizePath$3(
import_node_path3.default.relative(process.cwd(), importerFile)
)}". Does the file exist?`,
pos
);
}
if (isExternalUrl(resolved.id)) {
return [resolved.id, resolved.id];
}
const isRelative2 = url2[0] === ".";
const isSelfImport = !isRelative2 && cleanUrl(url2) === cleanUrl(importer);
if (resolved.id.startsWith(withTrailingSlash(root))) {
url2 = resolved.id.slice(root.length);
} else if ((depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepFile(resolved.id)) || // vite-plugin-react isn't following the leading \0 virtual module convention.
// This is a temporary hack to avoid expensive fs checks for React apps.
// We'll remove this as soon we're able to fix the react plugins.
resolved.id !== "/@react-refresh" && import_node_path3.default.isAbsolute(resolved.id) && fsUtils.existsSync(cleanUrl(resolved.id))) {
url2 = import_node_path3.default.posix.join(FS_PREFIX, resolved.id);
} else {
url2 = resolved.id;
}
if (url2[0] !== "." && url2[0] !== "/") {
url2 = wrapId$1(resolved.id);
}
if (!ssr) {
if (isExplicitImportRequired(url2)) {
url2 = injectQuery(url2, "import");
} else if ((isRelative2 || isSelfImport) && !DEP_VERSION_RE.test(url2)) {
const versionMatch = importer.match(DEP_VERSION_RE);
if (versionMatch) {
url2 = injectQuery(url2, versionMatch[1]);
}
}
try {
const depModule = await moduleGraph._ensureEntryFromUrl(
unwrapId$1(url2),
ssr,
canSkipImportAnalysis(url2) || forceSkipImportAnalysis,
resolved
);
if (depModule.lastHMRTimestamp > 0) {
url2 = injectQuery(url2, `t=${depModule.lastHMRTimestamp}`);
}
} catch (e2) {
e2.pos = pos;
throw e2;
}
url2 = joinUrlSegments(base, url2);
}
return [url2, resolved.id];
};
const orderedImportedUrls = new Array(imports.length);
const orderedAcceptedUrls = new Array(
imports.length
);
const orderedAcceptedExports = new Array(
imports.length
);
await Promise.all(
imports.map(async (importSpecifier, index) => {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex,
a: attributeIndex
} = importSpecifier;
let specifier = importSpecifier.n;
const rawUrl = source.slice(start, end);
if (rawUrl === "import.meta") {
const prop = source.slice(end, end + 4);
if (prop === ".hot") {
hasHMR = true;
const endHot = end + 4 + (source[end + 4] === "?" ? 1 : 0);
if (source.slice(endHot, endHot + 7) === ".accept") {
if (source.slice(endHot, endHot + 14) === ".acceptExports") {
const importAcceptedExports = orderedAcceptedExports[index] = /* @__PURE__ */ new Set();
lexAcceptedHmrExports(
source,
source.indexOf("(", endHot + 14) + 1,
importAcceptedExports
);
isPartiallySelfAccepting = true;
} else {
const importAcceptedUrls = orderedAcceptedUrls[index] = /* @__PURE__ */ new Set();
if (lexAcceptedHmrDeps(
source,
source.indexOf("(", endHot + 7) + 1,
importAcceptedUrls
)) {
isSelfAccepting = true;
}
}
}
} else if (prop === ".env") {
hasEnv = true;
}
return;
} else if (templateLiteralRE.test(rawUrl)) {
if (!(rawUrl.includes("${") && rawUrl.includes("}"))) {
specifier = rawUrl.replace(templateLiteralRE, "$1");
}
}
const isDynamicImport = dynamicIndex > -1;
if (!isDynamicImport && attributeIndex > -1) {
str().remove(end + 1, expEnd);
}
if (specifier !== void 0) {
if (isExternalUrl(specifier) || isDataUrl(specifier)) {
return;
}
if (ssr && !matchAlias(specifier)) {
if (shouldExternalizeForSSR(specifier, importer, config2)) {
return;
}
if (isBuiltin(specifier)) {
return;
}
}
if (specifier === clientPublicPath) {
return;
}
if (specifier[0] === "/" && !(config2.assetsInclude(cleanUrl(specifier)) || urlRE.test(specifier)) && checkPublicFile(specifier, config2)) {
throw new Error(
`Cannot import non-asset file ${specifier} which is inside /public. JS/CSS files inside /public are copied as-is on build and can only be referenced via <script src> or <link href> in html. If you want to get the URL of that file, use ${injectQuery(
specifier,
"url"
)} instead.`
);
}
const [url2, resolvedId] = await normalizeUrl(specifier, start);
server2 == null ? void 0 : server2.moduleGraph.safeModulesPath.add(
fsPathFromUrl(stripBase(url2, base))
);
if (url2 !== specifier) {
let rewriteDone = false;
if ((depsOptimizer == null ? void 0 : depsOptimizer.isOptimizedDepFile(resolvedId)) && !optimizedDepChunkRE.test(resolvedId)) {
const file = cleanUrl(resolvedId);
const needsInterop2 = await optimizedDepNeedsInterop(
depsOptimizer.metadata,
file,
config2,
ssr
);
if (needsInterop2 === void 0) {
if (!optimizedDepDynamicRE.test(file)) {
config2.logger.error(
colors$1.red(
`Vite Error, ${url2} optimized info should be defined`
)
);
}
} else if (needsInterop2) {
debug$1 == null ? void 0 : debug$1(`${url2} needs interop`);
interopNamedImports(
str(),
importSpecifier,
url2,
index,
importer,
config2
);
rewriteDone = true;
}
} else if (url2.includes(browserExternalId) && source.slice(expStart, start).includes("{")) {
interopNamedImports(
str(),
importSpecifier,
url2,
index,
importer,
config2
);
rewriteDone = true;
}
if (!rewriteDone) {
const rewrittenUrl = JSON.stringify(url2);
const s2 = isDynamicImport ? start : start - 1;
const e2 = isDynamicImport ? end : end + 1;
str().overwrite(s2, e2, rewrittenUrl, {
contentOnly: true
});
}
}
const hmrUrl = unwrapId$1(stripBase(url2, base));
const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
if (isLocalImport) {
orderedImportedUrls[index] = hmrUrl;
}
if (enablePartialAccept && importedBindings) {
extractImportedBindings(
resolvedId,
source,
importSpecifier,
importedBindings
);
}
if (!isDynamicImport && isLocalImport && config2.server.preTransformRequests) {
const url22 = removeImportQuery(hmrUrl);
server2.warmupRequest(url22, { ssr });
}
} else if (!importer.startsWith(withTrailingSlash(clientDir))) {
if (!isInNodeModules$1(importer)) {
const hasViteIgnore = hasViteIgnoreRE.test(
// complete expression inside parens
source.slice(dynamicIndex + 1, end)
);
if (!hasViteIgnore) {
this.warn(
`
` + colors$1.cyan(importerModule.file) + `
` + colors$1.reset(generateCodeFrame(source, start, end)) + colors$1.yellow(
`
The above dynamic import cannot be analyzed by Vite.
See ${colors$1.blue(
`https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations`
)} for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.
`
)
);
}
}
if (!ssr) {
if (!urlIsStringRE.test(rawUrl) || isExplicitImportRequired(rawUrl.slice(1, -1))) {
needQueryInjectHelper = true;
str().overwrite(
start,
end,
`__vite__injectQuery(${rawUrl}, 'import')`,
{ contentOnly: true }
);
}
}
}
})
);
const _orderedImportedUrls = orderedImportedUrls.filter(isDefined);
const importedUrls = new Set(_orderedImportedUrls);
const staticImportedUrls = new Set(
_orderedImportedUrls.map((url2) => removeTimestampQuery(url2))
);
const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
const isClassicWorker = importer.includes(WORKER_FILE_ID) && importer.includes("type=classic");
if (hasEnv && !isClassicWorker) {
str().prepend(getEnv(ssr));
}
if (hasHMR && !ssr && !isClassicWorker) {
debugHmr == null ? void 0 : debugHmr(
`${isSelfAccepting ? `[self-accepts]` : isPartiallySelfAccepting ? `[accepts-exports]` : acceptedUrls.size ? `[accepts-deps]` : `[detected api usage]`} ${prettifyUrl(importer, root)}`
);
str().prepend(
`import { createHotContext as __vite__createHotContext } from "${clientPublicPath}";import.meta.hot = __vite__createHotContext(${JSON.stringify(
normalizeHmrUrl(importerModule.url)
)});`
);
}
if (needQueryInjectHelper) {
if (isClassicWorker) {
str().append("\n" + __vite__injectQuery.toString());
} else {
str().prepend(
`import { injectQuery as __vite__injectQuery } from "${clientPublicPath}";`
);
}
}
const normalizedAcceptedUrls = /* @__PURE__ */ new Set();
for (const { url: url2, start, end } of acceptedUrls) {
const [normalized] = await moduleGraph.resolveUrl(
toAbsoluteUrl(url2),
ssr
);
normalizedAcceptedUrls.add(normalized);
str().overwrite(start, end, JSON.stringify(normalized), {
contentOnly: true
});
}
if (!isCSSRequest(importer) || SPECIAL_QUERY_RE.test(importer)) {
const pluginImports = this._addedImports;
if (pluginImports) {
(await Promise.all(
[...pluginImports].map((id) => normalizeUrl(id, 0, true))
)).forEach(([url2]) => importedUrls.add(url2));
}
if (ssr && importerModule.isSelfAccepting) {
isSelfAccepting = true;
}
if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports2.length && exports2.every((e2) => acceptedExports.has(e2.n))) {
isSelfAccepting = true;
}
const prunedImports = await moduleGraph.updateModuleInfo(
importerModule,
importedUrls,
importedBindings,
normalizedAcceptedUrls,
isPartiallySelfAccepting ? acceptedExports : null,
isSelfAccepting,
ssr,
staticImportedUrls
);
if (hasHMR && prunedImports) {
handlePrunedModules(prunedImports, server2);
}
}
debug$1 == null ? void 0 : debug$1(
`${timeFrom(msAtStart)} ${colors$1.dim(
`[${importedUrls.size} imports rewritten] ${prettifyUrl(
importer,
root
)}`
)}`
);
if (s) {
return transformStableResult(s, importer, config2);
} else {
return source;
}
}
};
}
function mergeAcceptedUrls(orderedUrls) {
const acceptedUrls = /* @__PURE__ */ new Set();
for (const urls of orderedUrls) {
if (!urls) continue;
for (const url2 of urls) acceptedUrls.add(url2);
}
return acceptedUrls;
}
function createParseErrorInfo(importer, source) {
const isVue = importer.endsWith(".vue");
const isJsx = importer.endsWith(".jsx") || importer.endsWith(".tsx");
const maybeJSX = !isVue && isJSRequest(importer);
const probablyBinary = source.includes(
"<22>"
);
const msg = isVue ? `Install @vitejs/plugin-vue to handle .vue files.` : maybeJSX ? isJsx ? `If you use tsconfig.json, make sure to not set jsx to preserve.` : `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.` : `You may need to install appropriate plugins to handle the ${import_node_path3.default.extname(
importer
)} file format, or if it's an asset, add "**/*${import_node_path3.default.extname(
importer
)}" to \`assetsInclude\` in your configuration.`;
return {
message: `Failed to parse source for import analysis because the content contains invalid JS syntax. ` + msg,
showCodeFrame: !probablyBinary
};
}
var interopHelper = (m) => (m == null ? void 0 : m.__esModule) ? m : { ...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {}, default: m };
function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config2) {
const source = str.original;
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex
} = importSpecifier;
const exp = source.slice(expStart, expEnd);
if (dynamicIndex > -1) {
str.overwrite(
expStart,
expEnd,
`import('${rewrittenUrl}').then(m => (${interopHelper.toString()})(m.default))` + getLineBreaks(exp),
{ contentOnly: true }
);
} else {
const rawUrl = source.slice(start, end);
const rewritten = transformCjsImport(
exp,
rewrittenUrl,
rawUrl,
importIndex,
importer,
config2
);
if (rewritten) {
str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
contentOnly: true
});
} else {
str.overwrite(
start,
end,
rewrittenUrl + getLineBreaks(source.slice(start, end)),
{
contentOnly: true
}
);
}
}
}
function getLineBreaks(str) {
return str.includes("\n") ? "\n".repeat(str.split("\n").length - 1) : "";
}
function transformCjsImport(importExp, url2, rawUrl, importIndex, importer, config2) {
const node2 = parseAst(importExp).body[0];
if (config2.command === "serve" && node2.type === "ExportAllDeclaration" && !node2.exported) {
config2.logger.warn(
colors$1.yellow(
`
Unable to interop \`${importExp}\` in ${importer}, this may lose module exports. Please export "${rawUrl}" as ESM or use named exports instead, e.g. \`export { A, B } from "${rawUrl}"\``
)
);
} else if (node2.type === "ImportDeclaration" || node2.type === "ExportNamedDeclaration") {
if (!node2.specifiers.length) {
return `import "${url2}"`;
}
const importNames = [];
const exportNames = [];
let defaultExports = "";
for (const spec of node2.specifiers) {
if (spec.type === "ImportSpecifier" && spec.imported.type === "Identifier") {
const importedName = spec.imported.name;
const localName = spec.local.name;
importNames.push({ importedName, localName });
} else if (spec.type === "ImportDefaultSpecifier") {
importNames.push({
importedName: "default",
localName: spec.local.name
});
} else if (spec.type === "ImportNamespaceSpecifier") {
importNames.push({ importedName: "*", localName: spec.local.name });
} else if (spec.type === "ExportSpecifier" && spec.exported.type === "Identifier") {
const importedName = spec.local.name;
const exportedName = spec.exported.name;
if (exportedName === "default") {
defaultExports = makeLegalIdentifier(
`__vite__cjsExportDefault_${importIndex}`
);
importNames.push({ importedName, localName: defaultExports });
} else {
const localName = makeLegalIdentifier(
`__vite__cjsExport_${exportedName}`
);
importNames.push({ importedName, localName });
exportNames.push(`${localName} as ${exportedName}`);
}
}
}
const cjsModuleName = makeLegalIdentifier(
`__vite__cjsImport${importIndex}_${rawUrl}`
);
const lines = [`import ${cjsModuleName} from "${url2}"`];
importNames.forEach(({ importedName, localName }) => {
if (importedName === "*") {
lines.push(
`const ${localName} = (${interopHelper.toString()})(${cjsModuleName})`
);
} else if (importedName === "default") {
lines.push(
`const ${localName} = ${cjsModuleName}.__esModule ? ${cjsModuleName}.default : ${cjsModuleName}`
);
} else {
lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
}
});
if (defaultExports) {
lines.push(`export default ${defaultExports}`);
}
if (exportNames.length) {
lines.push(`export { ${exportNames.join(", ")} }`);
}
return lines.join("; ");
}
}
function __vite__injectQuery(url2, queryToInject) {
if (url2[0] !== "." && url2[0] !== "/") {
return url2;
}
const pathname = url2.replace(/[?#].*$/, "");
const { search, hash: hash2 } = new URL(url2, "http://vitejs.dev");
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash2 || ""}`;
}
var isModernFlag = `__VITE_IS_MODERN__`;
var preloadMethod = `__vitePreload`;
var preloadMarker = `__VITE_PRELOAD__`;
var preloadHelperId = "\0vite/preload-helper.js";
var preloadMarkerRE = new RegExp(preloadMarker, "g");
var dynamicImportPrefixRE = /import\s*\(/;
var dynamicImportTreeshakenRE = /((?:\bconst\s+|\blet\s+|\bvar\s+|,\s*)(\{[^{}.=]+\})\s*=\s*await\s+import\([^)]+\))|(\(\s*await\s+import\([^)]+\)\s*\)(\??\.[\w$]+))|\bimport\([^)]+\)(\s*\.then\(\s*(?:function\s*)?\(\s*\{([^{}.=]+)\}\))/g;
function toRelativePath(filename, importer) {
const relPath = import_node_path3.default.posix.relative(import_node_path3.default.posix.dirname(importer), filename);
return relPath[0] === "." ? relPath : `./${relPath}`;
}
function indexOfMatchInSlice(str, reg, pos = 0) {
reg.lastIndex = pos;
const result = reg.exec(str);
return (result == null ? void 0 : result.index) ?? -1;
}
function detectScriptRel() {
const relList = typeof document !== "undefined" && document.createElement("link").relList;
return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
}
function preload(baseModule, deps, importerUrl) {
let promise2 = Promise.resolve();
if (__VITE_IS_MODERN__ && deps && deps.length > 0) {
const links = document.getElementsByTagName("link");
const cspNonceMeta = document.querySelector(
"meta[property=csp-nonce]"
);
const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
promise2 = Promise.all(
deps.map((dep) => {
dep = assetsURL(dep, importerUrl);
if (dep in seen) return;
seen[dep] = true;
const isCss = dep.endsWith(".css");
const cssSelector = isCss ? '[rel="stylesheet"]' : "";
const isBaseRelative = !!importerUrl;
if (isBaseRelative) {
for (let i = links.length - 1; i >= 0; i--) {
const link2 = links[i];
if (link2.href === dep && (!isCss || link2.rel === "stylesheet")) {
return;
}
}
} else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
return;
}
const link = document.createElement("link");
link.rel = isCss ? "stylesheet" : scriptRel;
if (!isCss) {
link.as = "script";
link.crossOrigin = "";
}
link.href = dep;
if (cspNonce) {
link.setAttribute("nonce", cspNonce);
}
document.head.appendChild(link);
if (isCss) {
return new Promise((res, rej) => {
link.addEventListener("load", res);
link.addEventListener(
"error",
() => rej(new Error(`Unable to preload CSS for ${dep}`))
);
});
}
})
);
}
return promise2.then(() => baseModule()).catch((err2) => {
const e2 = new Event("vite:preloadError", { cancelable: true });
e2.payload = err2;
window.dispatchEvent(e2);
if (!e2.defaultPrevented) {
throw err2;
}
});
}
function buildImportAnalysisPlugin(config2) {
const ssr = !!config2.build.ssr;
const isWorker = config2.isWorker;
const insertPreload = !(ssr || !!config2.build.lib || isWorker);
const resolveModulePreloadDependencies = config2.build.modulePreload && config2.build.modulePreload.resolveDependencies;
const renderBuiltUrl = config2.experimental.renderBuiltUrl;
const customModulePreloadPaths = !!(resolveModulePreloadDependencies || renderBuiltUrl);
const isRelativeBase = config2.base === "./" || config2.base === "";
const optimizeModulePreloadRelativePaths = isRelativeBase && !customModulePreloadPaths;
const { modulePreload } = config2.build;
const scriptRel2 = modulePreload && modulePreload.polyfill ? `'modulepreload'` : `(${detectScriptRel.toString()})()`;
const assetsURL2 = customModulePreloadPaths ? (
// If `experimental.renderBuiltUrl` or `build.modulePreload.resolveDependencies` are used
// the dependencies are already resolved. To avoid the need for `new URL(dep, import.meta.url)`
// a helper `__vitePreloadRelativeDep` is used to resolve from relative paths which can be minimized.
`function(dep, importerUrl) { return dep[0] === '.' ? new URL(dep, importerUrl).href : dep }`
) : optimizeModulePreloadRelativePaths ? (
// If there isn't custom resolvers affecting the deps list, deps in the list are relative
// to the current chunk and are resolved to absolute URL by the __vitePreload helper itself.
// The importerUrl is passed as third parameter to __vitePreload in this case
`function(dep, importerUrl) { return new URL(dep, importerUrl).href }`
) : (
// If the base isn't relative, then the deps are relative to the projects `outDir` and the base
// is appended inside __vitePreload too.
`function(dep) { return ${JSON.stringify(config2.base)}+dep }`
);
const preloadCode = `const scriptRel = ${scriptRel2};const assetsURL = ${assetsURL2};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
return {
name: "vite:build-import-analysis",
resolveId(id) {
if (id === preloadHelperId) {
return id;
}
},
load(id) {
if (id === preloadHelperId) {
return preloadCode;
}
},
async transform(source, importer) {
var _a4, _b3, _c2, _d2, _e2;
if (isInNodeModules$1(importer) && !dynamicImportPrefixRE.test(source)) {
return;
}
await init;
let imports = [];
try {
imports = parse$d(source)[0];
} catch (_e3) {
const e2 = _e3;
const { message, showCodeFrame } = createParseErrorInfo(
importer,
source
);
this.error(message, showCodeFrame ? e2.idx : void 0);
}
if (!imports.length) {
return null;
}
const dynamicImports = {};
if (insertPreload) {
let match2;
while (match2 = dynamicImportTreeshakenRE.exec(source)) {
if (match2[1]) {
dynamicImports[dynamicImportTreeshakenRE.lastIndex] = {
declaration: `const ${match2[2]}`,
names: (_a4 = match2[2]) == null ? void 0 : _a4.trim()
};
continue;
}
if (match2[3]) {
let names2 = ((_b3 = match2[4].match(/\.([^.?]+)/)) == null ? void 0 : _b3[1]) || "";
if (names2 === "default") {
names2 = "default: __vite_default__";
}
dynamicImports[dynamicImportTreeshakenRE.lastIndex - ((_c2 = match2[4]) == null ? void 0 : _c2.length) - 1] = { declaration: `const {${names2}}`, names: `{ ${names2} }` };
continue;
}
const names = (_d2 = match2[6]) == null ? void 0 : _d2.trim();
dynamicImports[dynamicImportTreeshakenRE.lastIndex - ((_e2 = match2[5]) == null ? void 0 : _e2.length)] = { declaration: `const {${names}}`, names: `{ ${names} }` };
}
}
let s;
const str = () => s || (s = new MagicString(source));
let needPreloadHelper = false;
for (let index = 0; index < imports.length; index++) {
const {
s: start,
e: end,
ss: expStart,
se: expEnd,
d: dynamicIndex,
a: attributeIndex
} = imports[index];
const isDynamicImport = dynamicIndex > -1;
if (!isDynamicImport && attributeIndex > -1) {
str().remove(end + 1, expEnd);
}
if (isDynamicImport && insertPreload && // Only preload static urls
(source[start] === '"' || source[start] === "'" || source[start] === "`")) {
needPreloadHelper = true;
const { declaration, names } = dynamicImports[expEnd] || {};
if (names) {
str().prependLeft(
expStart,
`${preloadMethod}(async () => { ${declaration} = await `
);
str().appendRight(expEnd, `;return ${names}}`);
} else {
str().prependLeft(expStart, `${preloadMethod}(() => `);
}
str().appendRight(
expEnd,
`,${isModernFlag}?${preloadMarker}:void 0${optimizeModulePreloadRelativePaths || customModulePreloadPaths ? ",import.meta.url" : ""})`
);
}
}
if (needPreloadHelper && insertPreload && !source.includes(`const ${preloadMethod} =`)) {
str().prepend(`import { ${preloadMethod} } from "${preloadHelperId}";`);
}
if (s) {
return {
code: s.toString(),
map: config2.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
};
}
},
renderChunk(code, _, { format: format2 }) {
if (code.indexOf(isModernFlag) > -1) {
const re = new RegExp(isModernFlag, "g");
const isModern = String(format2 === "es");
if (config2.build.sourcemap) {
const s = new MagicString(code);
let match2;
while (match2 = re.exec(code)) {
s.update(match2.index, match2.index + isModernFlag.length, isModern);
}
return {
code: s.toString(),
map: s.generateMap({ hires: "boundary" })
};
} else {
return code.replace(re, isModern);
}
}
return null;
},
generateBundle({ format: format2 }, bundle) {
if (format2 !== "es") {
return;
}
if (!insertPreload) {
const removedPureCssFiles = removedPureCssFilesCache.get(config2);
if (removedPureCssFiles && removedPureCssFiles.size > 0) {
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk" && chunk.code.includes("import")) {
const code = chunk.code;
let imports;
try {
imports = parse$d(code)[0].filter((i) => i.d > -1);
} catch (e2) {
const loc = numberToPos(code, e2.idx);
this.error({
name: e2.name,
message: e2.message,
stack: e2.stack,
cause: e2.cause,
pos: e2.idx,
loc: { ...loc, file: chunk.fileName },
frame: generateCodeFrame(code, loc)
});
}
for (const imp of imports) {
const {
n: name2,
s: start,
e: end,
ss: expStart,
se: expEnd
} = imp;
let url2 = name2;
if (!url2) {
const rawUrl = code.slice(start, end);
if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
url2 = rawUrl.slice(1, -1);
}
if (!url2) continue;
const normalizedFile = import_node_path3.default.posix.join(
import_node_path3.default.posix.dirname(chunk.fileName),
url2
);
if (removedPureCssFiles.has(normalizedFile)) {
chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
}
}
}
}
}
return;
}
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk" && chunk.code.indexOf(preloadMarker) > -1) {
const code = chunk.code;
let imports;
try {
imports = parse$d(code)[0].filter((i) => i.d > -1);
} catch (e2) {
const loc = numberToPos(code, e2.idx);
this.error({
name: e2.name,
message: e2.message,
stack: e2.stack,
cause: e2.cause,
pos: e2.idx,
loc: { ...loc, file: chunk.fileName },
frame: generateCodeFrame(code, loc)
});
}
const s = new MagicString(code);
const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
const fileDeps = [];
const addFileDep = (url2, runtime = false) => {
const index = fileDeps.findIndex((dep) => dep.url === url2);
if (index === -1) {
return fileDeps.push({ url: url2, runtime }) - 1;
} else {
return index;
}
};
if (imports.length) {
for (let index = 0; index < imports.length; index++) {
const {
n: name2,
s: start,
e: end,
ss: expStart,
se: expEnd
} = imports[index];
let url2 = name2;
if (!url2) {
const rawUrl = code.slice(start, end);
if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
url2 = rawUrl.slice(1, -1);
}
const deps = /* @__PURE__ */ new Set();
let hasRemovedPureCssChunk = false;
let normalizedFile = void 0;
if (url2) {
normalizedFile = import_node_path3.default.posix.join(
import_node_path3.default.posix.dirname(chunk.fileName),
url2
);
const ownerFilename = chunk.fileName;
const analyzed = /* @__PURE__ */ new Set();
const addDeps = (filename) => {
if (filename === ownerFilename) return;
if (analyzed.has(filename)) return;
analyzed.add(filename);
const chunk2 = bundle[filename];
if (chunk2) {
deps.add(chunk2.fileName);
if (chunk2.type === "chunk") {
chunk2.imports.forEach(addDeps);
chunk2.viteMetadata.importedCss.forEach((file2) => {
deps.add(file2);
});
}
} else {
const removedPureCssFiles = removedPureCssFilesCache.get(config2);
const chunk3 = removedPureCssFiles.get(filename);
if (chunk3) {
if (chunk3.viteMetadata.importedCss.size) {
chunk3.viteMetadata.importedCss.forEach((file2) => {
deps.add(file2);
});
hasRemovedPureCssChunk = true;
}
s.update(expStart, expEnd, "Promise.resolve({})");
}
}
};
addDeps(normalizedFile);
}
let markerStartPos2 = indexOfMatchInSlice(
code,
preloadMarkerRE,
end
);
if (markerStartPos2 === -1 && imports.length === 1) {
markerStartPos2 = indexOfMatchInSlice(code, preloadMarkerRE);
}
if (markerStartPos2 > 0) {
const depsArray = deps.size > 1 || // main chunk is removed
hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? (
// CSS deps use the same mechanism as module preloads, so even if disabled,
// we still need to pass these deps to the preload helper in dynamic imports.
[...deps].filter((d) => d.endsWith(".css"))
) : [...deps] : [];
let renderedDeps;
if (normalizedFile && customModulePreloadPaths) {
const { modulePreload: modulePreload2 } = config2.build;
const resolveDependencies = modulePreload2 ? modulePreload2.resolveDependencies : void 0;
let resolvedDeps;
if (resolveDependencies) {
const cssDeps = [];
const otherDeps = [];
for (const dep of depsArray) {
(dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
}
resolvedDeps = [
...resolveDependencies(normalizedFile, otherDeps, {
hostId: file,
hostType: "js"
}),
...cssDeps
];
} else {
resolvedDeps = depsArray;
}
renderedDeps = resolvedDeps.map((dep) => {
const replacement = toOutputFilePathInJS(
dep,
"asset",
chunk.fileName,
"js",
config2,
toRelativePath
);
if (typeof replacement === "string") {
return addFileDep(replacement);
}
return addFileDep(replacement.runtime, true);
});
} else {
renderedDeps = depsArray.map(
(d) => (
// Don't include the assets dir if the default asset file names
// are used, the path will be reconstructed by the import preload helper
optimizeModulePreloadRelativePaths ? addFileDep(toRelativePath(d, file)) : addFileDep(d)
)
);
}
s.update(
markerStartPos2,
markerStartPos2 + preloadMarker.length,
renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`
);
rewroteMarkerStartPos.add(markerStartPos2);
}
}
}
if (fileDeps.length > 0) {
const fileDepsCode = `[${fileDeps.map(
(fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)
).join(",")}]`;
const mapDepsCode = `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=${fileDepsCode})))=>i.map(i=>d[i]);
`;
if (code.startsWith("#!")) {
s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
} else {
s.prepend(mapDepsCode);
}
}
let markerStartPos = indexOfMatchInSlice(code, preloadMarkerRE);
while (markerStartPos >= 0) {
if (!rewroteMarkerStartPos.has(markerStartPos)) {
s.update(
markerStartPos,
markerStartPos + preloadMarker.length,
"void 0"
);
}
markerStartPos = indexOfMatchInSlice(
code,
preloadMarkerRE,
markerStartPos + preloadMarker.length
);
}
if (s.hasChanged()) {
chunk.code = s.toString();
if (config2.build.sourcemap && chunk.map) {
const nextMap = s.generateMap({
source: chunk.fileName,
hires: "boundary"
});
const map2 = combineSourcemaps(chunk.fileName, [
nextMap,
chunk.map
]);
map2.toUrl = () => genSourceMapUrl(map2);
chunk.map = map2;
if (config2.build.sourcemap === "inline") {
chunk.code = chunk.code.replace(
convertSourceMap.mapFileCommentRegex,
""
);
chunk.code += `
//# sourceMappingURL=${genSourceMapUrl(map2)}`;
} else if (config2.build.sourcemap) {
const mapAsset = bundle[chunk.fileName + ".map"];
if (mapAsset && mapAsset.type === "asset") {
mapAsset.source = map2.toString();
}
}
}
}
}
}
}
};
}
function ssrManifestPlugin(config2) {
const ssrManifest = {};
const base = config2.base;
return {
name: "vite:ssr-manifest",
generateBundle(_options2, bundle) {
for (const file in bundle) {
const chunk = bundle[file];
if (chunk.type === "chunk") {
for (const id in chunk.modules) {
const normalizedId = normalizePath$3((0, import_node_path3.relative)(config2.root, id));
const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
if (!chunk.isEntry) {
mappedChunks.push(joinUrlSegments(base, chunk.fileName));
chunk.viteMetadata.importedCss.forEach((file2) => {
mappedChunks.push(joinUrlSegments(base, file2));
});
}
chunk.viteMetadata.importedAssets.forEach((file2) => {
mappedChunks.push(joinUrlSegments(base, file2));
});
}
if (chunk.code.includes(preloadMethod)) {
const code = chunk.code;
let imports = [];
try {
imports = parse$d(code)[0].filter((i) => i.n && i.d > -1);
} catch (_e2) {
const e2 = _e2;
const loc = numberToPos(code, e2.idx);
this.error({
name: e2.name,
message: e2.message,
stack: e2.stack,
cause: e2.cause,
pos: e2.idx,
loc: { ...loc, file: chunk.fileName },
frame: generateCodeFrame(code, loc)
});
}
if (imports.length) {
for (let index = 0; index < imports.length; index++) {
const { s: start, e: end, n: name2 } = imports[index];
const url2 = code.slice(start, end);
const deps = [];
const ownerFilename = chunk.fileName;
const analyzed = /* @__PURE__ */ new Set();
const addDeps = (filename) => {
if (filename === ownerFilename) return;
if (analyzed.has(filename)) return;
analyzed.add(filename);
const chunk2 = bundle[filename];
if (chunk2) {
chunk2.viteMetadata.importedCss.forEach((file2) => {
deps.push(joinUrlSegments(base, file2));
});
chunk2.imports.forEach(addDeps);
}
};
const normalizedFile = normalizePath$3(
(0, import_node_path3.join)((0, import_node_path3.dirname)(chunk.fileName), url2.slice(1, -1))
);
addDeps(normalizedFile);
ssrManifest[(0, import_node_path3.basename)(name2)] = deps;
}
}
}
}
}
this.emitFile({
fileName: typeof config2.build.ssrManifest === "string" ? config2.build.ssrManifest : ".vite/ssr-manifest.json",
type: "asset",
source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
});
}
};
}
function loadFallbackPlugin() {
return {
name: "vite:load-fallback",
async load(id) {
try {
const cleanedId = cleanUrl(id);
const content = await import_promises.default.readFile(cleanedId, "utf-8");
this.addWatchFile(cleanedId);
return content;
} catch (e2) {
const content = await import_promises.default.readFile(id, "utf-8");
this.addWatchFile(id);
return content;
}
}
};
}
function completeSystemWrapPlugin() {
const SystemJSWrapRE = /System.register\(.*?(\(exports\)|\(\))/g;
return {
name: "vite:force-systemjs-wrap-complete",
renderChunk(code, chunk, opts) {
if (opts.format === "system") {
return {
code: code.replace(
SystemJSWrapRE,
(s, s1) => s.replace(s1, "(exports, module)")
),
map: null
};
}
}
};
}
function resolveBuildOptions(raw, logger, root) {
const deprecatedPolyfillModulePreload = raw == null ? void 0 : raw.polyfillModulePreload;
if (raw) {
const { polyfillModulePreload, ...rest } = raw;
raw = rest;
if (deprecatedPolyfillModulePreload !== void 0) {
logger.warn(
"polyfillModulePreload is deprecated. Use modulePreload.polyfill instead."
);
}
if (deprecatedPolyfillModulePreload === false && raw.modulePreload === void 0) {
raw.modulePreload = { polyfill: false };
}
}
const modulePreload = raw == null ? void 0 : raw.modulePreload;
const defaultModulePreload = {
polyfill: true
};
const defaultBuildOptions = {
outDir: "dist",
assetsDir: "assets",
assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
cssCodeSplit: !(raw == null ? void 0 : raw.lib),
sourcemap: false,
rollupOptions: {},
minify: (raw == null ? void 0 : raw.ssr) ? false : "esbuild",
terserOptions: {},
write: true,
emptyOutDir: null,
copyPublicDir: true,
manifest: false,
lib: false,
ssr: false,
ssrManifest: false,
ssrEmitAssets: false,
reportCompressedSize: true,
chunkSizeWarningLimit: 500,
watch: null
};
const userBuildOptions = raw ? mergeConfig(defaultBuildOptions, raw) : defaultBuildOptions;
const resolved = {
target: "modules",
cssTarget: false,
...userBuildOptions,
commonjsOptions: {
include: [/node_modules/],
extensions: [".js", ".cjs"],
...userBuildOptions.commonjsOptions
},
dynamicImportVarsOptions: {
warnOnError: true,
exclude: [/node_modules/],
...userBuildOptions.dynamicImportVarsOptions
},
// Resolve to false | object
modulePreload: modulePreload === false ? false : typeof modulePreload === "object" ? {
...defaultModulePreload,
...modulePreload
} : defaultModulePreload
};
if (resolved.target === "modules") {
resolved.target = ESBUILD_MODULES_TARGET;
} else if (resolved.target === "esnext" && resolved.minify === "terser") {
try {
const terserPackageJsonPath = requireResolveFromRootWithFallback(
root,
"terser/package.json"
);
const terserPackageJson = JSON.parse(
import_node_fs2.default.readFileSync(terserPackageJsonPath, "utf-8")
);
const v = terserPackageJson.version.split(".");
if (v[0] === "5" && v[1] < 16) {
resolved.target = "es2021";
}
} catch {
}
}
if (!resolved.cssTarget) {
resolved.cssTarget = resolved.target;
}
if (resolved.minify === "false") {
resolved.minify = false;
} else if (resolved.minify === true) {
resolved.minify = "esbuild";
}
if (resolved.cssMinify == null) {
resolved.cssMinify = !!resolved.minify;
}
return resolved;
}
async function resolveBuildPlugins(config2) {
const options2 = config2.build;
const { commonjsOptions } = options2;
const usePluginCommonjs = !Array.isArray(commonjsOptions == null ? void 0 : commonjsOptions.include) || (commonjsOptions == null ? void 0 : commonjsOptions.include.length) !== 0;
const rollupOptionsPlugins = options2.rollupOptions.plugins;
return {
pre: [
completeSystemWrapPlugin(),
...usePluginCommonjs ? [commonjs(options2.commonjsOptions)] : [],
dataURIPlugin(),
...(await asyncFlatten(arraify(rollupOptionsPlugins))).filter(
Boolean
),
...config2.isWorker ? [webWorkerPostPlugin()] : []
],
post: [
buildImportAnalysisPlugin(config2),
...config2.esbuild !== false ? [buildEsbuildPlugin(config2)] : [],
...options2.minify ? [terserPlugin(config2)] : [],
...!config2.isWorker ? [
...options2.manifest ? [manifestPlugin(config2)] : [],
...options2.ssrManifest ? [ssrManifestPlugin(config2)] : [],
buildReporterPlugin(config2)
] : [],
loadFallbackPlugin()
]
};
}
async function build(inlineConfig = {}) {
var _a4, _b3, _c2, _d2, _e2;
const config2 = await resolveConfig(
inlineConfig,
"build",
"production",
"production"
);
const options2 = config2.build;
const ssr = !!options2.ssr;
const libOptions = options2.lib;
config2.logger.info(
colors$1.cyan(
`vite v${VERSION} ${colors$1.green(
`building ${ssr ? `SSR bundle ` : ``}for ${config2.mode}...`
)}`
)
);
const resolve3 = (p) => import_node_path3.default.resolve(config2.root, p);
const input = libOptions ? ((_a4 = options2.rollupOptions) == null ? void 0 : _a4.input) || (typeof libOptions.entry === "string" ? resolve3(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve3) : Object.fromEntries(
Object.entries(libOptions.entry).map(([alias2, file]) => [
alias2,
resolve3(file)
])
)) : typeof options2.ssr === "string" ? resolve3(options2.ssr) : ((_b3 = options2.rollupOptions) == null ? void 0 : _b3.input) || resolve3("index.html");
if (ssr && typeof input === "string" && input.endsWith(".html")) {
throw new Error(
`rollupOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.`
);
}
if (config2.build.cssCodeSplit === false) {
const inputs = typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input);
if (inputs.some((input2) => input2.endsWith(".css"))) {
throw new Error(
`When "build.cssCodeSplit: false" is set, "rollupOptions.input" should not include CSS files.`
);
}
}
const outDir = resolve3(options2.outDir);
const plugins2 = ssr ? config2.plugins.map((p) => injectSsrFlagToHooks(p)) : config2.plugins;
const rollupOptions = {
preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
cache: config2.build.watch ? void 0 : false,
...options2.rollupOptions,
input,
plugins: plugins2,
external: (_c2 = options2.rollupOptions) == null ? void 0 : _c2.external,
onwarn(warning, warn2) {
onRollupWarning(warning, warn2, config2);
}
};
function extractStack(e2) {
const { stack, name: name2 = "Error", message } = e2;
if (!stack) {
return stack;
}
const expectedPrefix = `${name2}: ${message}
`;
if (stack.startsWith(expectedPrefix)) {
return stack.slice(expectedPrefix.length);
}
return stack;
}
const normalizeCodeFrame = (frame) => {
const trimmedPadding = frame.replace(/^\n|\n$/g, "");
return `
${trimmedPadding}
`;
};
const enhanceRollupError = (e2) => {
const stackOnly = extractStack(e2);
let msg = colors$1.red((e2.plugin ? `[${e2.plugin}] ` : "") + e2.message);
if (e2.id) {
msg += `
file: ${colors$1.cyan(
e2.id + (e2.loc ? `:${e2.loc.line}:${e2.loc.column}` : "")
)}`;
}
if (e2.frame) {
msg += `
` + colors$1.yellow(normalizeCodeFrame(e2.frame));
}
e2.message = msg;
if (stackOnly !== void 0) {
e2.stack = `${e2.message}
${stackOnly}`;
}
};
const outputBuildError = (e2) => {
enhanceRollupError(e2);
clearLine();
config2.logger.error(e2.message, { error: e2 });
};
let bundle;
let startTime;
try {
const buildOutputOptions = (output = {}) => {
var _a5;
if (output.output) {
config2.logger.warn(
`You've set "rollupOptions.output.output" in your config. This is deprecated and will override all Vite.js default output options. Please use "rollupOptions.output" instead.`
);
}
if (output.file) {
throw new Error(
`Vite does not support "rollupOptions.output.file". Please use "rollupOptions.output.dir" and "rollupOptions.output.entryFileNames" instead.`
);
}
if (output.sourcemap) {
config2.logger.warnOnce(
colors$1.yellow(
`Vite does not support "rollupOptions.output.sourcemap". Please use "build.sourcemap" instead.`
)
);
}
const ssrNodeBuild = ssr && config2.ssr.target === "node";
const ssrWorkerBuild = ssr && config2.ssr.target === "webworker";
const format2 = output.format || "es";
const jsExt = ssrNodeBuild || libOptions ? resolveOutputJsExtension(
format2,
(_a5 = findNearestPackageData(config2.root, config2.packageCache)) == null ? void 0 : _a5.data.type
) : "js";
return {
dir: outDir,
// Default format is 'es' for regular and for SSR builds
format: format2,
exports: "auto",
sourcemap: options2.sourcemap,
name: libOptions ? libOptions.name : void 0,
hoistTransitiveImports: libOptions ? false : void 0,
// es2015 enables `generatedCode.symbols`
// - #764 add `Symbol.toStringTag` when build es module into cjs chunk
// - #1048 add `Symbol.toStringTag` for module default export
generatedCode: "es2015",
entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name: name2 }) => resolveLibFilename(
libOptions,
format2,
name2,
config2.root,
jsExt,
config2.packageCache
) : import_node_path3.default.posix.join(options2.assetsDir, `[name]-[hash].${jsExt}`),
chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : import_node_path3.default.posix.join(options2.assetsDir, `[name]-[hash].${jsExt}`),
assetFileNames: libOptions ? `[name].[ext]` : import_node_path3.default.posix.join(options2.assetsDir, `[name]-[hash].[ext]`),
inlineDynamicImports: output.format === "umd" || output.format === "iife" || ssrWorkerBuild && (typeof input === "string" || Object.keys(input).length === 1),
...output
};
};
const outputs = resolveBuildOutputs(
(_d2 = options2.rollupOptions) == null ? void 0 : _d2.output,
libOptions,
config2.logger
);
const normalizedOutputs = [];
if (Array.isArray(outputs)) {
for (const resolvedOutput of outputs) {
normalizedOutputs.push(buildOutputOptions(resolvedOutput));
}
} else {
normalizedOutputs.push(buildOutputOptions(outputs));
}
const resolvedOutDirs = getResolvedOutDirs(
config2.root,
options2.outDir,
(_e2 = options2.rollupOptions) == null ? void 0 : _e2.output
);
const emptyOutDir = resolveEmptyOutDir(
options2.emptyOutDir,
config2.root,
resolvedOutDirs,
config2.logger
);
if (config2.build.watch) {
config2.logger.info(colors$1.cyan(`
watching for file changes...`));
const resolvedChokidarOptions = resolveChokidarOptions(
config2,
config2.build.watch.chokidar,
resolvedOutDirs,
emptyOutDir
);
const { watch: watch2 } = await import("./rollup-CIAQV775.js");
const watcher = watch2({
...rollupOptions,
output: normalizedOutputs,
watch: {
...config2.build.watch,
chokidar: resolvedChokidarOptions
}
});
watcher.on("event", (event) => {
if (event.code === "BUNDLE_START") {
config2.logger.info(colors$1.cyan(`
build started...`));
if (options2.write) {
prepareOutDir(resolvedOutDirs, emptyOutDir, config2);
}
} else if (event.code === "BUNDLE_END") {
event.result.close();
config2.logger.info(colors$1.cyan(`built in ${event.duration}ms.`));
} else if (event.code === "ERROR") {
outputBuildError(event.error);
}
});
return watcher;
}
const { rollup } = await import("./rollup-CIAQV775.js");
startTime = Date.now();
bundle = await rollup(rollupOptions);
if (options2.write) {
prepareOutDir(resolvedOutDirs, emptyOutDir, config2);
}
const res = [];
for (const output of normalizedOutputs) {
res.push(await bundle[options2.write ? "write" : "generate"](output));
}
config2.logger.info(
`${colors$1.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`
);
return Array.isArray(outputs) ? res : res[0];
} catch (e2) {
enhanceRollupError(e2);
clearLine();
if (startTime) {
config2.logger.error(
`${colors$1.red("x")} Build failed in ${displayTime(Date.now() - startTime)}`
);
startTime = void 0;
}
throw e2;
} finally {
if (bundle) await bundle.close();
}
}
function prepareOutDir(outDirs, emptyOutDir, config2) {
const outDirsArray = [...outDirs];
for (const outDir of outDirs) {
if (emptyOutDir !== false && import_node_fs2.default.existsSync(outDir)) {
const skipDirs = outDirsArray.map((dir) => {
const relative2 = import_node_path3.default.relative(outDir, dir);
if (relative2 && !relative2.startsWith("..") && !import_node_path3.default.isAbsolute(relative2)) {
return relative2;
}
return "";
}).filter(Boolean);
emptyDir(outDir, [...skipDirs, ".git"]);
}
if (config2.build.copyPublicDir && config2.publicDir && import_node_fs2.default.existsSync(config2.publicDir)) {
if (!areSeparateFolders(outDir, config2.publicDir)) {
config2.logger.warn(
colors$1.yellow(
`
${colors$1.bold(
`(!)`
)} The public directory feature may not work correctly. outDir ${colors$1.white(
colors$1.dim(outDir)
)} and publicDir ${colors$1.white(
colors$1.dim(config2.publicDir)
)} are not separate folders.
`
)
);
}
copyDir(config2.publicDir, outDir);
}
}
}
function getPkgName(name2) {
return (name2 == null ? void 0 : name2[0]) === "@" ? name2.split("/")[1] : name2;
}
function resolveOutputJsExtension(format2, type = "commonjs") {
if (type === "module") {
return format2 === "cjs" || format2 === "umd" ? "cjs" : "js";
} else {
return format2 === "es" ? "mjs" : "js";
}
}
function resolveLibFilename(libOptions, format2, entryName, root, extension2, packageCache) {
var _a4;
if (typeof libOptions.fileName === "function") {
return libOptions.fileName(format2, entryName);
}
const packageJson2 = (_a4 = findNearestPackageData(root, packageCache)) == null ? void 0 : _a4.data;
const name2 = libOptions.fileName || (packageJson2 && typeof libOptions.entry === "string" ? getPkgName(packageJson2.name) : entryName);
if (!name2)
throw new Error(
'Name in package.json is required if option "build.lib.fileName" is not provided.'
);
extension2 ?? (extension2 = resolveOutputJsExtension(format2, packageJson2 == null ? void 0 : packageJson2.type));
if (format2 === "cjs" || format2 === "es") {
return `${name2}.${extension2}`;
}
return `${name2}.${format2}.${extension2}`;
}
function resolveBuildOutputs(outputs, libOptions, logger) {
if (libOptions) {
const libHasMultipleEntries = typeof libOptions.entry !== "string" && Object.values(libOptions.entry).length > 1;
const libFormats = libOptions.formats || (libHasMultipleEntries ? ["es", "cjs"] : ["es", "umd"]);
if (!Array.isArray(outputs)) {
if (libFormats.includes("umd") || libFormats.includes("iife")) {
if (libHasMultipleEntries) {
throw new Error(
'Multiple entry points are not supported when output formats include "umd" or "iife".'
);
}
if (!libOptions.name) {
throw new Error(
'Option "build.lib.name" is required when output formats include "umd" or "iife".'
);
}
}
return libFormats.map((format2) => ({ ...outputs, format: format2 }));
}
if (libOptions.formats) {
logger.warn(
colors$1.yellow(
'"build.lib.formats" will be ignored because "build.rollupOptions.output" is already an array format.'
)
);
}
outputs.forEach((output) => {
if ((output.format === "umd" || output.format === "iife") && !output.name) {
throw new Error(
'Entries in "build.rollupOptions.output" must specify "name" when the format is "umd" or "iife".'
);
}
});
}
return outputs;
}
var warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
var dynamicImportWarningIgnoreList = [
`Unsupported expression`,
`statically analyzed`
];
function clearLine() {
const tty = process.stdout.isTTY && !process.env.CI;
if (tty) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
}
}
function onRollupWarning(warning, warn2, config2) {
var _a4;
const viteWarn = (warnLog) => {
let warning2;
if (typeof warnLog === "function") {
warning2 = warnLog();
} else {
warning2 = warnLog;
}
if (typeof warning2 === "object") {
if (warning2.code === "UNRESOLVED_IMPORT") {
const id = warning2.id;
const exporter = warning2.exporter;
if (!id || !id.endsWith("?commonjs-external")) {
throw new Error(
`[vite]: Rollup failed to resolve import "${exporter}" from "${id}".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
\`build.rollupOptions.external\``
);
}
}
if (warning2.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some(
(msg) => warning2.message.includes(msg)
)) {
return;
}
if (warningIgnoreList.includes(warning2.code)) {
return;
}
if (warning2.code === "PLUGIN_WARNING") {
config2.logger.warn(
`${colors$1.bold(
colors$1.yellow(`[plugin:${warning2.plugin}]`)
)} ${colors$1.yellow(warning2.message)}`
);
return;
}
}
warn2(warnLog);
};
clearLine();
const userOnWarn = (_a4 = config2.build.rollupOptions) == null ? void 0 : _a4.onwarn;
if (userOnWarn) {
userOnWarn(warning, viteWarn);
} else {
viteWarn(warning);
}
}
function resolveUserExternal(user, id, parentId, isResolved) {
if (typeof user === "function") {
return user(id, parentId, isResolved);
} else if (Array.isArray(user)) {
return user.some((test) => isExternal(id, test));
} else {
return isExternal(id, user);
}
}
function isExternal(id, test) {
if (typeof test === "string") {
return id === test;
} else {
return test.test(id);
}
}
function injectSsrFlagToHooks(plugin) {
const { resolveId, load: load2, transform: transform2 } = plugin;
return {
...plugin,
resolveId: wrapSsrResolveId(resolveId),
load: wrapSsrLoad(load2),
transform: wrapSsrTransform(transform2)
};
}
function wrapSsrResolveId(hook) {
if (!hook) return;
const fn = getHookHandler(hook);
const handler = function(id, importer, options2) {
return fn.call(this, id, importer, injectSsrFlag(options2));
};
if ("handler" in hook) {
return {
...hook,
handler
};
} else {
return handler;
}
}
function wrapSsrLoad(hook) {
if (!hook) return;
const fn = getHookHandler(hook);
const handler = function(id, ...args) {
return fn.call(this, id, injectSsrFlag(args[0]));
};
if ("handler" in hook) {
return {
...hook,
handler
};
} else {
return handler;
}
}
function wrapSsrTransform(hook) {
if (!hook) return;
const fn = getHookHandler(hook);
const handler = function(code, importer, ...args) {
return fn.call(this, code, importer, injectSsrFlag(args[0]));
};
if ("handler" in hook) {
return {
...hook,
handler
};
} else {
return handler;
}
}
function injectSsrFlag(options2) {
return { ...options2 ?? {}, ssr: true };
}
var needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
var quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
var backSlashRegEx = /\\/g;
function escapeId(id) {
if (!needsEscapeRegEx.test(id)) return id;
return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
}
var getResolveUrl = (path22, URL2 = "URL") => `new ${URL2}(${path22}).href`;
var getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(
`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ""}document.currentScript && document.currentScript.src || document.baseURI`
);
var getFileUrlFromFullPath = (path22) => `require('u' + 'rl').pathToFileURL(${path22}).href`;
var getFileUrlFromRelativePath = (path22) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path22)}'`);
var relativeUrlMechanisms = {
amd: (relativePath) => {
if (relativePath[0] !== ".") relativePath = "./" + relativePath;
return getResolveUrl(
`require.toUrl('${escapeId(relativePath)}'), document.baseURI`
);
},
cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(
relativePath
)} : ${getRelativeUrlFromDocument(relativePath)})`,
es: (relativePath) => getResolveUrl(
`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`
),
iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
// NOTE: make sure rollup generate `module` params
system: (relativePath) => getResolveUrl(
`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`
),
umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(
relativePath
)} : ${getRelativeUrlFromDocument(relativePath, true)})`
};
var customRelativeUrlMechanisms = {
...relativeUrlMechanisms,
"worker-iife": (relativePath) => getResolveUrl(
`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`
)
};
function toOutputFilePathInJS(filename, type, hostId, hostType, config2, toRelative) {
const { renderBuiltUrl } = config2.experimental;
let relative2 = config2.base === "" || config2.base === "./";
if (renderBuiltUrl) {
const result = renderBuiltUrl(filename, {
hostId,
hostType,
type,
ssr: !!config2.build.ssr
});
if (typeof result === "object") {
if (result.runtime) {
return { runtime: result.runtime };
}
if (typeof result.relative === "boolean") {
relative2 = result.relative;
}
} else if (result) {
return result;
}
}
if (relative2 && !config2.build.ssr) {
return toRelative(filename, hostId);
}
return joinUrlSegments(config2.base, filename);
}
function createToImportMetaURLBasedRelativeRuntime(format2, isWorker) {
const formatLong = isWorker && format2 === "iife" ? "worker-iife" : format2;
const toRelativePath2 = customRelativeUrlMechanisms[formatLong];
return (filename, importer) => ({
runtime: toRelativePath2(
import_node_path3.default.posix.relative(import_node_path3.default.dirname(importer), filename)
)
});
}
function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config2, toRelative) {
const { renderBuiltUrl } = config2.experimental;
let relative2 = config2.base === "" || config2.base === "./";
if (renderBuiltUrl) {
const result = renderBuiltUrl(filename, {
hostId,
hostType,
type,
ssr: !!config2.build.ssr
});
if (typeof result === "object") {
if (result.runtime) {
throw new Error(
`{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
);
}
if (typeof result.relative === "boolean") {
relative2 = result.relative;
}
} else if (result) {
return result;
}
}
if (relative2 && !config2.build.ssr) {
return toRelative(filename, hostId);
} else {
return joinUrlSegments(config2.base, filename);
}
}
var toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
var toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
function areSeparateFolders(a, b) {
const na = normalizePath$3(a);
const nb = normalizePath$3(b);
return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
}
var build$1 = {
__proto__: null,
build,
createToImportMetaURLBasedRelativeRuntime,
onRollupWarning,
resolveBuildOptions,
resolveBuildOutputs,
resolveBuildPlugins,
resolveLibFilename,
resolveUserExternal,
toOutputFilePathInCss,
toOutputFilePathInHtml,
toOutputFilePathInJS,
toOutputFilePathWithoutRuntime
};
var NOOP = () => {
};
var MIMES = /text|javascript|\/json|xml/i;
function getChunkSize(chunk, enc) {
return chunk ? Buffer.byteLength(chunk, enc) : 0;
}
function compression({ threshold = 1024, level = -1, brotli = false, gzip: gzip2 = true, mimes: mimes2 = MIMES } = {}) {
const brotliOpts = typeof brotli === "object" && brotli || {};
const gzipOpts = typeof gzip2 === "object" && gzip2 || {};
if (!import_zlib.default.createBrotliCompress) brotli = false;
return (req2, res, next = NOOP) => {
const accept = req2.headers["accept-encoding"] + "";
const encoding = (brotli && accept.match(/\bbr\b/) || gzip2 && accept.match(/\bgzip\b/) || [])[0];
if (req2.method === "HEAD" || !encoding) return next();
let compress;
let pendingListeners = [];
let pendingStatus = 0;
let started = false;
let size = 0;
function start() {
started = true;
size = res.getHeader("Content-Length") | 0 || size;
const compressible = mimes2.test(
String(res.getHeader("Content-Type") || "text/plain")
);
const cleartext = !res.getHeader("Content-Encoding");
const listeners = pendingListeners || [];
if (compressible && cleartext && size >= threshold) {
res.setHeader("Content-Encoding", encoding);
res.removeHeader("Content-Length");
if (encoding === "br") {
compress = import_zlib.default.createBrotliCompress({
params: Object.assign({
[import_zlib.default.constants.BROTLI_PARAM_QUALITY]: level,
[import_zlib.default.constants.BROTLI_PARAM_SIZE_HINT]: size
}, brotliOpts)
});
} else {
compress = import_zlib.default.createGzip(
Object.assign({ level }, gzipOpts)
);
}
compress.on("data", (chunk) => write.call(res, chunk) || compress.pause());
on.call(res, "drain", () => compress.resume());
compress.on("end", () => end.call(res));
listeners.forEach((p) => compress.on.apply(compress, p));
} else {
pendingListeners = null;
listeners.forEach((p) => on.apply(res, p));
}
writeHead.call(res, pendingStatus || res.statusCode);
}
const { end, write, on, writeHead } = res;
res.writeHead = function(status2, reason, headers) {
if (typeof reason !== "string") [headers, reason] = [reason, headers];
if (headers) for (let k in headers) res.setHeader(k, headers[k]);
pendingStatus = status2;
return this;
};
res.write = function(chunk, enc) {
size += getChunkSize(chunk, enc);
if (!started) start();
if (!compress) return write.apply(this, arguments);
return compress.write.apply(compress, arguments);
};
res.end = function(chunk, enc) {
if (arguments.length > 0 && typeof chunk !== "function") {
size += getChunkSize(chunk, enc);
}
if (!started) start();
if (!compress) return end.apply(this, arguments);
return compress.end.apply(compress, arguments);
};
res.on = function(type, listener2) {
if (!pendingListeners) on.call(this, type, listener2);
else if (compress) compress.on(type, listener2);
else pendingListeners.push([type, listener2]);
return this;
};
next();
};
}
function resolvePreviewOptions(preview2, server2) {
return {
port: preview2 == null ? void 0 : preview2.port,
strictPort: (preview2 == null ? void 0 : preview2.strictPort) ?? server2.strictPort,
host: (preview2 == null ? void 0 : preview2.host) ?? server2.host,
https: (preview2 == null ? void 0 : preview2.https) ?? server2.https,
open: (preview2 == null ? void 0 : preview2.open) ?? server2.open,
proxy: (preview2 == null ? void 0 : preview2.proxy) ?? server2.proxy,
cors: (preview2 == null ? void 0 : preview2.cors) ?? server2.cors,
headers: (preview2 == null ? void 0 : preview2.headers) ?? server2.headers
};
}
async function preview(inlineConfig = {}) {
var _a4, _b3, _c2, _d2;
const config2 = await resolveConfig(
inlineConfig,
"serve",
"production",
"production",
true
);
const distDir = import_node_path3.default.resolve(config2.root, config2.build.outDir);
if (!import_node_fs2.default.existsSync(distDir) && // error if no plugins implement `configurePreviewServer`
config2.plugins.every((plugin) => !plugin.configurePreviewServer) && // error if called in CLI only. programmatic usage could access `httpServer`
// and affect file serving
((_a4 = process.argv[1]) == null ? void 0 : _a4.endsWith(import_node_path3.default.normalize("bin/vite.js"))) && process.argv[2] === "preview") {
throw new Error(
`The directory "${config2.build.outDir}" does not exist. Did you build your project?`
);
}
const app = connect$1();
const httpServer = await resolveHttpServer(
config2.preview,
app,
await resolveHttpsConfig((_b3 = config2.preview) == null ? void 0 : _b3.https)
);
setClientErrorHandler(httpServer, config2.logger);
const options2 = config2.preview;
const logger = config2.logger;
const closeHttpServer = createServerCloseFn(httpServer);
const server2 = {
config: config2,
middlewares: app,
httpServer,
async close() {
teardownSIGTERMListener(closeServerAndExit);
await closeHttpServer();
},
resolvedUrls: null,
printUrls() {
if (server2.resolvedUrls) {
printServerUrls(server2.resolvedUrls, options2.host, logger.info);
} else {
throw new Error("cannot print server URLs before server is listening.");
}
},
bindCLIShortcuts(options22) {
bindCLIShortcuts(server2, options22);
}
};
const closeServerAndExit = async () => {
try {
await server2.close();
} finally {
process.exit();
}
};
setupSIGTERMListener(closeServerAndExit);
const postHooks = [];
for (const hook of config2.getSortedPluginHooks("configurePreviewServer")) {
postHooks.push(await hook(server2));
}
const { cors } = config2.preview;
if (cors !== false) {
app.use(corsMiddleware(typeof cors === "boolean" ? {} : cors));
}
const { proxy } = config2.preview;
if (proxy) {
app.use(proxyMiddleware(httpServer, proxy, config2));
}
app.use(compression());
if (config2.base !== "/") {
app.use(baseMiddleware(config2.rawBase, false));
}
const headers = config2.preview.headers;
const viteAssetMiddleware = (...args) => sirv(distDir, {
etag: true,
dev: true,
extensions: [],
ignores: false,
setHeaders(res) {
if (headers) {
for (const name2 in headers) {
res.setHeader(name2, headers[name2]);
}
}
},
shouldServe(filePath) {
return shouldServeFile(filePath, distDir);
}
})(...args);
app.use(viteAssetMiddleware);
if (config2.appType === "spa" || config2.appType === "mpa") {
app.use(htmlFallbackMiddleware(distDir, config2.appType === "spa"));
}
postHooks.forEach((fn) => fn && fn());
if (config2.appType === "spa" || config2.appType === "mpa") {
app.use(indexHtmlMiddleware(distDir, server2));
app.use(notFoundMiddleware());
}
const hostname = await resolveHostname(options2.host);
const port = options2.port ?? DEFAULT_PREVIEW_PORT;
await httpServerStart(httpServer, {
port,
strictPort: options2.strictPort,
host: hostname.host,
logger
});
server2.resolvedUrls = await resolveServerUrls(
httpServer,
config2.preview,
config2
);
if (options2.open) {
const url2 = ((_c2 = server2.resolvedUrls) == null ? void 0 : _c2.local[0]) ?? ((_d2 = server2.resolvedUrls) == null ? void 0 : _d2.network[0]);
if (url2) {
const path22 = typeof options2.open === "string" ? new URL(options2.open, url2).href : url2;
openBrowser(path22, true, logger);
}
}
return server2;
}
function resolveSSROptions(ssr, preserveSymlinks) {
ssr ?? (ssr = {});
const optimizeDeps2 = ssr.optimizeDeps ?? {};
const target = "node";
return {
target,
...ssr,
optimizeDeps: {
...optimizeDeps2,
noDiscovery: true,
// always true for ssr
esbuildOptions: {
preserveSymlinks,
...optimizeDeps2.esbuildOptions
}
}
};
}
var debug = createDebugger("vite:config");
var promisifiedRealpath = (0, import_node_util.promisify)(import_node_fs2.default.realpath);
function defineConfig(config2) {
return config2;
}
function checkBadCharactersInPath(path22, logger) {
const badChars = [];
if (path22.includes("#")) {
badChars.push("#");
}
if (path22.includes("?")) {
badChars.push("?");
}
if (badChars.length > 0) {
const charString = badChars.map((c) => `"${c}"`).join(" and ");
const inflectedChars = badChars.length > 1 ? "characters" : "character";
logger.warn(
colors$1.yellow(
`The project root contains the ${charString} ${inflectedChars} (${colors$1.cyan(
path22
)}), which may not work when running Vite. Consider renaming the directory to remove the characters.`
)
);
}
}
async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false) {
var _a4, _b3, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2, _q2, _r2;
let config2 = inlineConfig;
let configFileDependencies = [];
let mode2 = inlineConfig.mode || defaultMode;
const isNodeEnvSet = true;
const packageCache = /* @__PURE__ */ new Map();
if (!isNodeEnvSet) {
process.env.NODE_ENV = defaultNodeEnv;
}
const configEnv = {
mode: mode2,
command,
isSsrBuild: command === "build" && !!((_a4 = config2.build) == null ? void 0 : _a4.ssr),
isPreview
};
let { configFile } = config2;
if (configFile !== false) {
const loadResult = await loadConfigFromFile(
configEnv,
configFile,
config2.root,
config2.logLevel,
config2.customLogger
);
if (loadResult) {
config2 = mergeConfig(loadResult.config, config2);
configFile = loadResult.path;
configFileDependencies = loadResult.dependencies;
}
}
mode2 = inlineConfig.mode || config2.mode || mode2;
configEnv.mode = mode2;
const filterPlugin = (p) => {
if (!p) {
return false;
} else if (!p.apply) {
return true;
} else if (typeof p.apply === "function") {
return p.apply({ ...config2, mode: mode2 }, configEnv);
} else {
return p.apply === command;
}
};
const rawUserPlugins = (await asyncFlatten(config2.plugins || [])).filter(filterPlugin);
const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawUserPlugins);
const userPlugins = [...prePlugins, ...normalPlugins, ...postPlugins];
config2 = await runConfigHook(config2, userPlugins, configEnv);
const logger = createLogger(config2.logLevel, {
allowClearScreen: config2.clearScreen,
customLogger: config2.customLogger
});
const resolvedRoot = normalizePath$3(
config2.root ? import_node_path3.default.resolve(config2.root) : process.cwd()
);
checkBadCharactersInPath(resolvedRoot, logger);
const clientAlias = [
{
find: /^\/?@vite\/env/,
replacement: import_node_path3.default.posix.join(FS_PREFIX, normalizePath$3(ENV_ENTRY))
},
{
find: /^\/?@vite\/client/,
replacement: import_node_path3.default.posix.join(FS_PREFIX, normalizePath$3(CLIENT_ENTRY))
}
];
const resolvedAlias = normalizeAlias(
mergeAlias(clientAlias, ((_b3 = config2.resolve) == null ? void 0 : _b3.alias) || [])
);
const resolveOptions = {
mainFields: ((_c2 = config2.resolve) == null ? void 0 : _c2.mainFields) ?? DEFAULT_MAIN_FIELDS,
conditions: ((_d2 = config2.resolve) == null ? void 0 : _d2.conditions) ?? [],
extensions: ((_e2 = config2.resolve) == null ? void 0 : _e2.extensions) ?? DEFAULT_EXTENSIONS,
dedupe: ((_f2 = config2.resolve) == null ? void 0 : _f2.dedupe) ?? [],
preserveSymlinks: ((_g2 = config2.resolve) == null ? void 0 : _g2.preserveSymlinks) ?? false,
alias: resolvedAlias
};
if (
// @ts-expect-error removed field
((_h2 = config2.resolve) == null ? void 0 : _h2.browserField) === false && resolveOptions.mainFields.includes("browser")
) {
logger.warn(
colors$1.yellow(
`\`resolve.browserField\` is set to false, but the option is removed in favour of the 'browser' string in \`resolve.mainFields\`. You may want to update \`resolve.mainFields\` to remove the 'browser' string and preserve the previous browser behaviour.`
)
);
}
const envDir = config2.envDir ? normalizePath$3(import_node_path3.default.resolve(resolvedRoot, config2.envDir)) : resolvedRoot;
const userEnv = inlineConfig.envFile !== false && loadEnv(mode2, envDir, resolveEnvPrefix(config2));
const userNodeEnv = process.env.VITE_USER_NODE_ENV;
if (!isNodeEnvSet && userNodeEnv) {
if (userNodeEnv === "development") {
process.env.NODE_ENV = "development";
} else {
logger.warn(
`NODE_ENV=${userNodeEnv} is not supported in the .env file. Only NODE_ENV=development is supported to create a development build of your project. If you need to set process.env.NODE_ENV, you can set it in the Vite config instead.`
);
}
}
const isProduction = false;
const isBuild = command === "build";
const relativeBaseShortcut = config2.base === "" || config2.base === "./";
const resolvedBase = relativeBaseShortcut ? !isBuild || ((_i2 = config2.build) == null ? void 0 : _i2.ssr) ? "/" : "./" : resolveBaseUrl(config2.base, isBuild, logger) ?? "/";
const resolvedBuildOptions = resolveBuildOptions(
config2.build,
logger,
resolvedRoot
);
const pkgDir = (_j2 = findNearestPackageData(resolvedRoot, packageCache)) == null ? void 0 : _j2.dir;
const cacheDir = normalizePath$3(
config2.cacheDir ? import_node_path3.default.resolve(resolvedRoot, config2.cacheDir) : pkgDir ? import_node_path3.default.join(pkgDir, `node_modules/.vite`) : import_node_path3.default.join(resolvedRoot, `.vite`)
);
const assetsFilter = config2.assetsInclude && (!Array.isArray(config2.assetsInclude) || config2.assetsInclude.length) ? createFilter2(config2.assetsInclude) : () => false;
const createResolver = (options2) => {
let aliasContainer;
let resolverContainer;
return async (id, importer, aliasOnly, ssr2) => {
var _a5;
let container;
if (aliasOnly) {
container = aliasContainer || (aliasContainer = await createPluginContainer({
...resolved,
plugins: [alias$1({ entries: resolved.resolve.alias })]
}));
} else {
container = resolverContainer || (resolverContainer = await createPluginContainer({
...resolved,
plugins: [
alias$1({ entries: resolved.resolve.alias }),
resolvePlugin({
...resolved.resolve,
root: resolvedRoot,
isProduction,
isBuild: command === "build",
ssrConfig: resolved.ssr,
asSrc: true,
preferRelative: false,
tryIndex: true,
...options2,
idOnly: true,
fsUtils: getFsUtils(resolved)
})
]
}));
}
return (_a5 = await container.resolveId(id, importer, {
ssr: ssr2,
scan: options2 == null ? void 0 : options2.scan
})) == null ? void 0 : _a5.id;
};
};
const { publicDir } = config2;
const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath$3(
import_node_path3.default.resolve(
resolvedRoot,
typeof publicDir === "string" ? publicDir : "public"
)
) : "";
const server2 = resolveServerOptions(resolvedRoot, config2.server, logger);
const ssr = resolveSSROptions(config2.ssr, resolveOptions.preserveSymlinks);
const optimizeDeps2 = config2.optimizeDeps || {};
const BASE_URL = resolvedBase;
let resolved;
let createUserWorkerPlugins = (_k2 = config2.worker) == null ? void 0 : _k2.plugins;
if (Array.isArray(createUserWorkerPlugins)) {
createUserWorkerPlugins = () => {
var _a5;
return (_a5 = config2.worker) == null ? void 0 : _a5.plugins;
};
logger.warn(
colors$1.yellow(
`worker.plugins is now a function that returns an array of plugins. Please update your Vite config accordingly.
`
)
);
}
const createWorkerPlugins = async function(bundleChain) {
const rawWorkerUserPlugins = (await asyncFlatten((createUserWorkerPlugins == null ? void 0 : createUserWorkerPlugins()) || [])).filter(filterPlugin);
let workerConfig = mergeConfig({}, config2);
const [workerPrePlugins, workerNormalPlugins, workerPostPlugins] = sortUserPlugins(rawWorkerUserPlugins);
const workerUserPlugins = [
...workerPrePlugins,
...workerNormalPlugins,
...workerPostPlugins
];
workerConfig = await runConfigHook(
workerConfig,
workerUserPlugins,
configEnv
);
const workerResolved = {
...workerConfig,
...resolved,
isWorker: true,
mainConfig: resolved,
bundleChain
};
const resolvedWorkerPlugins = await resolvePlugins(
workerResolved,
workerPrePlugins,
workerNormalPlugins,
workerPostPlugins
);
await Promise.all(
createPluginHookUtils(resolvedWorkerPlugins).getSortedPluginHooks("configResolved").map((hook) => hook(workerResolved))
);
return resolvedWorkerPlugins;
};
const resolvedWorkerOptions = {
format: ((_l2 = config2.worker) == null ? void 0 : _l2.format) || "iife",
plugins: createWorkerPlugins,
rollupOptions: ((_m2 = config2.worker) == null ? void 0 : _m2.rollupOptions) || {}
};
resolved = {
configFile: configFile ? normalizePath$3(configFile) : void 0,
configFileDependencies: configFileDependencies.map(
(name2) => normalizePath$3(import_node_path3.default.resolve(name2))
),
inlineConfig,
root: resolvedRoot,
base: withTrailingSlash(resolvedBase),
rawBase: resolvedBase,
resolve: resolveOptions,
publicDir: resolvedPublicDir,
cacheDir,
command,
mode: mode2,
ssr,
isWorker: false,
mainConfig: null,
bundleChain: [],
isProduction,
plugins: userPlugins,
css: resolveCSSOptions(config2.css),
esbuild: config2.esbuild === false ? false : {
jsxDev: !isProduction,
...config2.esbuild
},
server: server2,
build: resolvedBuildOptions,
preview: resolvePreviewOptions(config2.preview, server2),
envDir,
env: {
...userEnv,
BASE_URL,
MODE: mode2,
DEV: !isProduction,
PROD: isProduction
},
assetsInclude(file) {
return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
},
logger,
packageCache,
createResolver,
optimizeDeps: {
holdUntilCrawlEnd: true,
...optimizeDeps2,
esbuildOptions: {
preserveSymlinks: resolveOptions.preserveSymlinks,
...optimizeDeps2.esbuildOptions
}
},
worker: resolvedWorkerOptions,
appType: config2.appType ?? "spa",
experimental: {
importGlobRestoreExtension: false,
hmrPartialAccept: false,
...config2.experimental
},
getSortedPlugins: void 0,
getSortedPluginHooks: void 0
};
resolved = {
...config2,
...resolved
};
resolved.plugins = await resolvePlugins(
resolved,
prePlugins,
normalPlugins,
postPlugins
);
Object.assign(resolved, createPluginHookUtils(resolved.plugins));
await Promise.all(
resolved.getSortedPluginHooks("configResolved").map((hook) => hook(resolved))
);
optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
optimizeDepsDisabledBackwardCompatibility(
resolved,
resolved.ssr.optimizeDeps,
"ssr."
);
debug == null ? void 0 : debug(`using resolved config: %O`, {
...resolved,
plugins: resolved.plugins.map((p) => p.name),
worker: {
...resolved.worker,
plugins: `() => plugins`
}
});
if (((_n2 = config2.build) == null ? void 0 : _n2.terserOptions) && config2.build.minify && config2.build.minify !== "terser") {
logger.warn(
colors$1.yellow(
`build.terserOptions is specified but build.minify is not set to use Terser. Note Vite now defaults to use esbuild for minification. If you still prefer Terser, set build.minify to "terser".`
)
);
}
const outputOption = ((_p2 = (_o2 = config2.build) == null ? void 0 : _o2.rollupOptions) == null ? void 0 : _p2.output) ?? [];
if (Array.isArray(outputOption)) {
const assetFileNamesList = outputOption.map(
(output) => output.assetFileNames
);
if (assetFileNamesList.length > 1) {
const firstAssetFileNames = assetFileNamesList[0];
const hasDifferentReference = assetFileNamesList.some(
(assetFileNames) => assetFileNames !== firstAssetFileNames
);
if (hasDifferentReference) {
resolved.logger.warn(
colors$1.yellow(`
assetFileNames isn't equal for every build.rollupOptions.output. A single pattern across all outputs is supported by Vite.
`)
);
}
}
}
if (
// @ts-expect-error Option removed
((_q2 = config2.legacy) == null ? void 0 : _q2.buildSsrCjsExternalHeuristics) || // @ts-expect-error Option removed
((_r2 = config2.ssr) == null ? void 0 : _r2.format) === "cjs"
) {
resolved.logger.warn(
colors$1.yellow(`
(!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format were be removed in Vite 5.
The only SSR Output format is ESM. Find more information at https://github.com/vitejs/vite/discussions/13816.
`)
);
}
const resolvedBuildOutDir = normalizePath$3(
import_node_path3.default.resolve(resolved.root, resolved.build.outDir)
);
if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) {
resolved.logger.warn(
colors$1.yellow(`
(!) build.outDir must not be the same directory of root or a parent directory of root as this could cause Vite to overwriting source files with build outputs.
`)
);
}
return resolved;
}
function resolveBaseUrl(base = "/", isBuild, logger) {
if (base[0] === ".") {
logger.warn(
colors$1.yellow(
colors$1.bold(
`(!) invalid "base" option: "${base}". The value can only be an absolute URL, "./", or an empty string.`
)
)
);
return "/";
}
const isExternal2 = isExternalUrl(base);
if (!isExternal2 && base[0] !== "/") {
logger.warn(
colors$1.yellow(
colors$1.bold(`(!) "base" option should start with a slash.`)
)
);
}
if (!isBuild || !isExternal2) {
base = new URL(base, "http://vitejs.dev").pathname;
if (base[0] !== "/") {
base = "/" + base;
}
}
return base;
}
function sortUserPlugins(plugins2) {
const prePlugins = [];
const postPlugins = [];
const normalPlugins = [];
if (plugins2) {
plugins2.flat().forEach((p) => {
if (p.enforce === "pre") prePlugins.push(p);
else if (p.enforce === "post") postPlugins.push(p);
else normalPlugins.push(p);
});
}
return [prePlugins, normalPlugins, postPlugins];
}
async function loadConfigFromFile(configEnv, configFile, configRoot = process.cwd(), logLevel, customLogger) {
const start = import_node_perf_hooks.performance.now();
const getTime = () => `${(import_node_perf_hooks.performance.now() - start).toFixed(2)}ms`;
let resolvedPath;
if (configFile) {
resolvedPath = import_node_path3.default.resolve(configFile);
} else {
for (const filename of DEFAULT_CONFIG_FILES) {
const filePath = import_node_path3.default.resolve(configRoot, filename);
if (!import_node_fs2.default.existsSync(filePath)) continue;
resolvedPath = filePath;
break;
}
}
if (!resolvedPath) {
debug == null ? void 0 : debug("no config file found.");
return null;
}
const isESM = isFilePathESM(resolvedPath);
try {
const bundled = await bundleConfigFile(resolvedPath, isESM);
const userConfig = await loadConfigFromBundledFile(
resolvedPath,
bundled.code,
isESM
);
debug == null ? void 0 : debug(`bundled config file loaded in ${getTime()}`);
const config2 = await (typeof userConfig === "function" ? userConfig(configEnv) : userConfig);
if (!isObject$1(config2)) {
throw new Error(`config must export or return an object.`);
}
return {
path: normalizePath$3(resolvedPath),
config: config2,
dependencies: bundled.dependencies
};
} catch (e2) {
createLogger(logLevel, { customLogger }).error(
colors$1.red(`failed to load config from ${resolvedPath}`),
{
error: e2
}
);
throw e2;
}
}
async function bundleConfigFile(fileName, isESM) {
const dirnameVarName = "__vite_injected_original_dirname";
const filenameVarName = "__vite_injected_original_filename";
const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
const result = await (0, import_esbuild.build)({
absWorkingDir: process.cwd(),
entryPoints: [fileName],
write: false,
target: ["node18"],
platform: "node",
bundle: true,
format: isESM ? "esm" : "cjs",
mainFields: ["main"],
sourcemap: "inline",
metafile: true,
define: {
__dirname: dirnameVarName,
__filename: filenameVarName,
"import.meta.url": importMetaUrlVarName,
"import.meta.dirname": dirnameVarName,
"import.meta.filename": filenameVarName
},
plugins: [
{
name: "externalize-deps",
setup(build2) {
const packageCache = /* @__PURE__ */ new Map();
const resolveByViteResolver = (id, importer, isRequire2) => {
var _a4;
return (_a4 = tryNodeResolve(
id,
importer,
{
root: import_node_path3.default.dirname(fileName),
isBuild: true,
isProduction: true,
preferRelative: false,
tryIndex: true,
mainFields: [],
conditions: [],
overrideConditions: ["node"],
dedupe: [],
extensions: DEFAULT_EXTENSIONS,
preserveSymlinks: false,
packageCache,
isRequire: isRequire2
},
false
)) == null ? void 0 : _a4.id;
};
build2.onResolve(
{ filter: /^[^.].*/ },
async ({ path: id, importer, kind }) => {
if (kind === "entry-point" || import_node_path3.default.isAbsolute(id) || isNodeBuiltin(id)) {
return;
}
if (isBuiltin(id)) {
return { external: true };
}
const isImport = isESM || kind === "dynamic-import";
let idFsPath;
try {
idFsPath = resolveByViteResolver(id, importer, !isImport);
} catch (e2) {
if (!isImport) {
let canResolveWithImport = false;
try {
canResolveWithImport = !!resolveByViteResolver(
id,
importer,
false
);
} catch {
}
if (canResolveWithImport) {
throw new Error(
`Failed to resolve ${JSON.stringify(
id
)}. This package is ESM only but it was tried to load by \`require\`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`
);
}
}
throw e2;
}
if (idFsPath && isImport) {
idFsPath = (0, import_node_url2.pathToFileURL)(idFsPath).href;
}
if (idFsPath && !isImport && isFilePathESM(idFsPath, packageCache)) {
throw new Error(
`${JSON.stringify(
id
)} resolved to an ESM file. ESM file cannot be loaded by \`require\`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`
);
}
return {
path: idFsPath,
external: true
};
}
);
}
},
{
name: "inject-file-scope-variables",
setup(build2) {
build2.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
const contents = await import_promises.default.readFile(args.path, "utf-8");
const injectValues = `const ${dirnameVarName} = ${JSON.stringify(
import_node_path3.default.dirname(args.path)
)};const ${filenameVarName} = ${JSON.stringify(args.path)};const ${importMetaUrlVarName} = ${JSON.stringify(
(0, import_node_url2.pathToFileURL)(args.path).href
)};`;
return {
loader: args.path.endsWith("ts") ? "ts" : "js",
contents: injectValues + contents
};
});
}
}
]
});
const { text } = result.outputFiles[0];
return {
code: text,
dependencies: result.metafile ? Object.keys(result.metafile.inputs) : []
};
}
var _require = (0, import_node_module.createRequire)(import.meta.url);
async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
if (isESM) {
const fileBase = `${fileName}.timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
const fileNameTmp = `${fileBase}.mjs`;
const fileUrl = `${(0, import_node_url2.pathToFileURL)(fileBase)}.mjs`;
await import_promises.default.writeFile(fileNameTmp, bundledCode);
try {
return (await import(fileUrl)).default;
} finally {
import_node_fs2.default.unlink(fileNameTmp, () => {
});
}
} else {
const extension2 = import_node_path3.default.extname(fileName);
const realFileName = await promisifiedRealpath(fileName);
const loaderExt = extension2 in _require.extensions ? extension2 : ".js";
const defaultLoader = _require.extensions[loaderExt];
_require.extensions[loaderExt] = (module, filename) => {
if (filename === realFileName) {
module._compile(bundledCode, filename);
} else {
defaultLoader(module, filename);
}
};
delete _require.cache[_require.resolve(fileName)];
const raw = _require(fileName);
_require.extensions[loaderExt] = defaultLoader;
return raw.__esModule ? raw.default : raw;
}
}
async function runConfigHook(config2, plugins2, configEnv) {
let conf = config2;
for (const p of getSortedPluginsByHook("config", plugins2)) {
const hook = p.config;
const handler = getHookHandler(hook);
if (handler) {
const res = await handler(conf, configEnv);
if (res) {
conf = mergeConfig(conf, res);
}
}
}
return conf;
}
function getDepOptimizationConfig(config2, ssr) {
return ssr ? config2.ssr.optimizeDeps : config2.optimizeDeps;
}
function isDepsOptimizerEnabled(config2, ssr) {
var _a4;
const optimizeDeps2 = getDepOptimizationConfig(config2, ssr);
return !(optimizeDeps2.noDiscovery && !((_a4 = optimizeDeps2.include) == null ? void 0 : _a4.length));
}
function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps2, optimizeDepsPath = "") {
var _a4, _b3;
const optimizeDepsDisabled = optimizeDeps2.disabled;
if (optimizeDepsDisabled !== void 0) {
if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
const commonjsOptionsInclude = (_b3 = (_a4 = resolved.build) == null ? void 0 : _a4.commonjsOptions) == null ? void 0 : _b3.include;
const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
optimizeDeps2.noDiscovery = true;
optimizeDeps2.include = void 0;
if (commonjsPluginDisabled) {
resolved.build.commonjsOptions.include = void 0;
}
resolved.logger.warn(
colors$1.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
To disable the deps optimizer, set ${optimizeDepsPath}optimizeDeps.noDiscovery to true and ${optimizeDepsPath}optimizeDeps.include as undefined or empty.
Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
${commonjsPluginDisabled ? "Empty config.build.commonjsOptions.include will be ignored to support CJS during build. This config should also be removed." : ""}
`)
);
} else if (optimizeDepsDisabled === false || optimizeDepsDisabled === "build") {
resolved.logger.warn(
colors$1.yellow(`(!) Experimental ${optimizeDepsPath}optimizeDeps.disabled and deps pre-bundling during build were removed in Vite 5.1.
Setting it to ${optimizeDepsDisabled} now has no effect.
Please remove ${optimizeDepsPath}optimizeDeps.disabled from your config.
`)
);
}
}
}
export {
require_node_util,
require_child_process,
require_crypto,
require_main,
VERSION,
require_node_events,
require_node_stream,
require_node_string_decoder,
require_node_child_process,
require_net,
require_http,
require_node_crypto,
require_node_dns,
require_module,
require_node_assert,
require_node_v8,
require_node_worker_threads,
require_node_buffer,
require_querystring,
require_node_readline,
require_zlib,
require_buffer,
require_https,
require_tls,
require_assert,
require_node_zlib,
commonjsGlobal,
getDefaultExportFromCjs,
createFilter2 as createFilter,
isInNodeModules$1,
rollupVersion,
normalizePath$3,
arraify,
mergeConfig,
mergeAlias,
createLogger,
transformWithEsbuild,
loadEnv,
resolveEnvPrefix,
preprocessCSS,
formatPostcssSourceMap,
buildErrorMessage,
optimizeDeps,
isFileServingAllowed,
fetchModule,
send,
searchForWorkspaceRoot,
createServer,
build,
preview,
defineConfig,
resolveConfig,
sortUserPlugins,
loadConfigFromFile
};
/*! Bundled license information:
rollup/dist/es/parseAst.js:
(*
@license
Rollup.js v4.19.1
Sat, 27 Jul 2024 04:53:31 GMT - commit 8b967917c2923dc6a02ca1238261387aefa2cb2f
https://github.com/rollup/rollup
Released under the MIT License.
*)
vite/dist/node/chunks/dep-mCdpKltl.js:
(*!
* is-extglob <https://github.com/jonschlinkert/is-extglob>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*)
(*!
* is-glob <https://github.com/jonschlinkert/is-glob>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*)
(*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Released under the MIT License.
*)
(*!
* to-regex-range <https://github.com/micromatch/to-regex-range>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*)
(*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Licensed under the MIT License.
*)
(*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
(*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
(**
* Autoload Config for PostCSS
*
* @author Michael Ciniawsky @michael-ciniawsky <michael.ciniawsky@gmail.com>
* @license MIT
*
* @module postcss-load-config
* @version 2.1.0
*
* @requires comsiconfig
* @requires ./options
* @requires ./plugins
*)
(*!
* encodeurl
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* escape-html
* Copyright(c) 2012-2013 TJ Holowaychuk
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
*)
(*!
* ee-first
* Copyright(c) 2014 Jonathan Ong
* MIT Licensed
*)
(*!
* on-finished
* Copyright(c) 2013 Jonathan Ong
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* parseurl
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* statuses
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* unpipe
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* finalhandler
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*)
(*
object-assign
(c) Sindre Sorhus
@license MIT
*)
(*!
* vary
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*)
(*!
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*)
(*!
* etag
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*)
vite/dist/node/chunks/dep-mCdpKltl.js:
(*!
* Array of passes.
*
* A `pass` is just a function that is executed on `req, res, options`
* so that you can easily add new checks while still keeping the base
* flexible.
*)
(*!
* Array of passes.
*
* A `pass` is just a function that is executed on `req, socket, options`
* so that you can easily add new checks while still keeping the base
* flexible.
*)
(*!
* Caron dimonio, con occhi di bragia
* loro accennando, tutte le raccoglie;
* batte col remo qualunque sadagia
*
* Charon the demon, with the eyes of glede,
* Beckoning to them, collects them all together,
* Beats with his oar whoever lags behind
*
* Dante - The Divine Comedy (Canto III)
*)
*/
//# sourceMappingURL=chunk-UIZRH6IJ.js.map