import { A as OPTIMIZABLE_ENTRY_RE, B as __esmMin, C as ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, D as JS_TYPES_RE, E as FS_PREFIX, F as defaultAllowedOrigins, H as __require, I as loopbackHosts, L as wildcardHosts, M as SPECIAL_QUERY_RE, N as VERSION, O as KNOWN_ASSET_TYPES, P as VITE_PACKAGE_DIR, R as require_picocolors, S as ENV_PUBLIC_PATH, T as ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET, U as __toCommonJS, V as __exportAll, W as __toESM, _ as DEFAULT_SERVER_CONDITIONS, a as CLIENT_ENTRY, b as DEV_PROD_CONDITION, c as DEFAULT_ASSETS_INLINE_LIMIT, d as DEFAULT_CLIENT_MAIN_FIELDS, f as DEFAULT_CONFIG_FILES, g as DEFAULT_PREVIEW_PORT, h as DEFAULT_EXTERNAL_CONDITIONS, i as CLIENT_DIR, j as ROLLUP_HOOKS, k as METADATA_FILENAME, l as DEFAULT_ASSETS_RE, m as DEFAULT_EXTENSIONS, n as createLogger, o as CLIENT_PUBLIC_PATH, p as DEFAULT_DEV_PORT, r as printServerUrls, s as CSS_LANGS_RE, t as LogLevels, u as DEFAULT_CLIENT_CONDITIONS, v as DEFAULT_SERVER_MAIN_FIELDS, w as ERR_OPTIMIZE_DEPS_PROCESSING_ERROR, x as ENV_ENTRY, y as DEP_VERSION_RE, z as __commonJSMin } from "./logger.js";
import { Module, builtinModules, createRequire } from "node:module";
import { parseAst, parseAstAsync } from "rolldown/parseAst";
import { esmExternalRequirePlugin, esmExternalRequirePlugin as esmExternalRequirePlugin$1 } from "rolldown/plugins";
import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, transformSync } from "rolldown/utils";
import * as fs$2 from "node:fs";
import fs, { existsSync, readFileSync } from "node:fs";
import path, { basename, dirname, extname, isAbsolute, join, normalize, posix, relative, resolve, sep } from "node:path";
import fsp, { constants } from "node:fs/promises";
import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
import { format, formatWithOptions, inspect, parseEnv, promisify, stripVTControlCharacters } from "node:util";
import { performance as performance$1 } from "node:perf_hooks";
import crypto from "node:crypto";
import pm from "picomatch";
import { MessageChannel, Worker } from "node:worker_threads";
import { VERSION as rolldownVersion, rolldown } from "rolldown";
import os from "node:os";
import net from "node:net";
import childProcess, { exec, execFile, execSync } from "node:child_process";
import { promises } from "node:dns";
import { isatty } from "node:tty";
import path$1, { isAbsolute as isAbsolute$1, join as join$1, posix as posix$1, resolve as resolve$1, win32 } from "path";
import { exactRegex, makeIdFiltersToMatchWithQuery, prefixRegex, withFilter } from "rolldown/filter";
import { dev, oxcRuntimePlugin, resolveTsconfig, scan, viteAliasPlugin, viteBuildImportAnalysisPlugin, viteDynamicImportVarsPlugin, viteImportGlobPlugin, viteJsonPlugin, viteLoadFallbackPlugin, viteManifestPlugin, viteModulePreloadPolyfillPlugin, viteReporterPlugin, viteResolvePlugin, viteTransformPlugin, viteWebWorkerPostPlugin } from "rolldown/experimental";
import readline from "node:readline";
import isModuleSyncConditionEnabled from "#module-sync-enabled";
import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby";
import assert from "node:assert";
import process$1 from "node:process";
import v8 from "node:v8";
import { EventEmitter } from "node:events";
import { STATUS_CODES, createServer, get } from "node:http";
import { createServer as createServer$1, get as get$1 } from "node:https";
import { readdirSync, statSync } from "fs";
import { ESModulesEvaluator, ModuleRunner, createNodeImportMeta } from "vite/module-runner";
import { Buffer as Buffer$1 } from "node:buffer";
import zlib from "zlib";
import * as qs from "node:querystring";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
//#region ../../node_modules/.pnpm/@voidzero-dev+vite-task-client@0.2.0/node_modules/@voidzero-dev/vite-task-client/src/index.js
/**
* @typedef {{ tracked?: boolean }} GetEnvOptions
*/
/**
* @typedef {string | { prefix: string }} GetEnvsQuery
*/
/**
* Methods exposed by the napi addon. Keep this shape in sync with the
* `RunnerClient` returned by `load()` in
* `crates/vite_task_client_napi/src/lib.rs` — any new method added there
* needs a matching entry here, and vice versa.
*
* @type {{
*   ignoreInput: (path: string) => void,
*   ignoreOutput: (path: string) => void,
*   disableCache: () => void,
*   getEnv: (name: string, options?: GetEnvOptions) => string | undefined,
*   getEnvs: (query: GetEnvsQuery, options?: GetEnvOptions) => Record<string, string>,
* } | null | undefined}
*/
let addon;
function load$1() {
	if (addon !== void 0) return addon;
	try {
		const path = process.env["VP_RUN_NODE_CLIENT_PATH"];
		if (path) {
			addon = createRequire(import.meta.url)(path).load();
			return addon;
		}
	} catch {}
	addon = null;
	return addon;
}
/**
* Tell the runner to ignore reads under `path` when inferring cache inputs.
*
* No-op when not running inside a runner.
*
* @param {string} path
* @returns {void}
*/
function ignoreInput(path) {
	load$1()?.ignoreInput(path);
}
/**
* Tell the runner to ignore writes under `path` when inferring cache outputs.
*
* No-op when not running inside a runner.
*
* @param {string} path
* @returns {void}
*/
function ignoreOutput(path) {
	load$1()?.ignoreOutput(path);
}
/**
* Tell the runner not to cache this run.
*
* No-op when not running inside a runner.
*
* @returns {void}
*/
function disableCache() {
	load$1()?.disableCache();
}
/**
* Ask the runner for the value of the env var `name` and return it, or
* `undefined` when the runner has no such env.
*
* With `tracked: true` (the default) the runner records `name` as a
* dependency, so a change to its value invalidates this run's cache entry.
*
* Has no effect on `process.env`; the caller decides what to do with the
* returned value. Returns `undefined` when not running inside a runner.
*
* @param {string} name
* @param {{ tracked?: boolean }} [options]
* @returns {string | undefined}
*/
function getEnv(name, options) {
	const a = load$1();
	if (!a) return void 0;
	return a.getEnv(name, options);
}
/**
* Ask the runner for matching envs and return the match-set as a plain object.
*
* Pass a glob string (e.g. `VITE_*`) to use glob matching, or pass
* `{ prefix: 'VITE_' }` to match env names by literal prefix.
*
* With `tracked: true` (the default) the runner records the pattern as a
* dependency, so adding, removing, or changing a matching env invalidates
* this run's cache entry.
*
* Has no effect on `process.env`; the caller decides what to do with the
* returned values. Returns an empty object when not running inside a runner.
*
* @param {GetEnvsQuery} query
* @param {GetEnvOptions} [options]
* @returns {Record<string, string>}
*/
function getEnvs(query, options) {
	const a = load$1();
	if (!a) return {};
	return a.getEnvs(query, options);
}
//#endregion
//#region ../../node_modules/.pnpm/fresh-import@0.2.1/node_modules/fresh-import/dist/index.js
const instanceId = Math.random().toString(36).slice(2);
const relativeImportRE = /^\.{1,2}(?:\/|\\)/;
function escapeRegExp(value) {
	return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* The tracking query name `fresh-import-<instance>`, where `<instance>` is a
* random value unique to this loaded module instance. Any two instances (even
* two copies of the same build loaded into the same process) get distinct
* names, so each hook only recognizes the imports it tagged itself.
*/
function buildQueryName() {
	return `fresh-import-${instanceId}`;
}
/**
* Build the regex that matches the tracking query `?<name>=<id>,<context>`
* (or the `&<name>=...` form).
*/
function buildQueryRE(queryName) {
	return new RegExp(`(?:\\?|&)${escapeRegExp(queryName)}=(\\d+),([^&]+)(?:&|$)`);
}
/**
* Build the tracking query `?<name>=<id>,<context>` that `collect` appends to
* the entry specifier. `id` cache-busts the import (a distinct URL forces a
* fresh evaluation) and `context` tags the import graph so the resolve hook can
* attribute resolved dependencies back to the originating collect.
*/
function formatTrackingQuery(queryName, id, context) {
	return `?${queryName}=${id},${context}`;
}
/**
* Shared body of the resolve hook for both the on-thread and off-thread
* importers. Given an already-resolved `result`, decides whether it is a tracked
* relative file dependency; if so, reports it via `onDependency` and tags the
* URL so the query propagates to its own dependencies.
*
* The sync/async difference between the two hooks lives entirely in the caller
* (which awaits `nextResolve` or not); this function performs no I/O. `result`
* is mutated in place and returned.
*/
function trackResolved(specifier, context, result, queryName, queryRE, onDependency) {
	const isRelativeImport = relativeImportRE.test(specifier);
	if (result.format === "builtin" || !isRelativeImport) return result;
	if (!context.parentURL || queryRE.test(result.url) || !result.url.startsWith("file:")) return result;
	const m = queryRE.exec(context.parentURL);
	if (m) {
		const [, id, contextFile] = m;
		onDependency(contextFile, result.url);
		result.url = result.url.replace(/(\?)|$/, (_n, n1) => `?${queryName}=${id},${contextFile}${n1 === "?" ? "&" : ""}`);
	}
	return result;
}
var loader_default = "data:text/javascript,Math.random().toString(36).slice(2);%0Aconst relativeImportRE = /^\\.{1,2}(%3F:\\/|\\\\)/;%0Afunction escapeRegExp(value) {%0A%09return value.replace(/[.*+%3F^${}()|[\\]\\\\]/g, \"\\\\$&\");%0A}%0A/**%0A* Build the regex that matches the tracking query `%3F<name>=<id>,<context>`%0A* (or the `&<name>=...` form).%0A*/%0Afunction buildQueryRE(queryName) {%0A%09return new RegExp(`(%3F:\\\\%3F|&)${escapeRegExp(queryName)}=(\\\\d+),([^&]+)(%3F:&|$)`);%0A}%0A/**%0A* Shared body of the resolve hook for both the on-thread and off-thread%0A* importers. Given an already-resolved `result`, decides whether it is a tracked%0A* relative file dependency; if so, reports it via `onDependency` and tags the%0A* URL so the query propagates to its own dependencies.%0A*%0A* The sync/async difference between the two hooks lives entirely in the caller%0A* (which awaits `nextResolve` or not); this function performs no I/O. `result`%0A* is mutated in place and returned.%0A*/%0Afunction trackResolved(specifier, context, result, queryName, queryRE, onDependency) {%0A%09const isRelativeImport = relativeImportRE.test(specifier);%0A%09if (result.format === \"builtin\" || !isRelativeImport) return result;%0A%09if (!context.parentURL || queryRE.test(result.url) || !result.url.startsWith(\"file:\")) return result;%0A%09const m = queryRE.exec(context.parentURL);%0A%09if (m) {%0A%09%09const [, id, contextFile] = m;%0A%09%09onDependency(contextFile, result.url);%0A%09%09result.url = result.url.replace(/(\\%3F)|$/, (_n, n1) => `%3F${queryName}=${id},${contextFile}${n1 === \"%3F\" %3F \"&\" : \"\"}`);%0A%09}%0A%09return result;%0A}%0A//%23endregion%0A//%23region src/off-thread/loader.ts%0Alet port;%0Alet queryName;%0Alet queryRE;%0Aconst initialize = async (data) => {%0A%09port = data.port;%0A%09queryName = data.queryName;%0A%09queryRE = buildQueryRE(queryName);%0A};%0Aconst resolve = async (specifier, context, nextResolve) => {%0A%09return trackResolved(specifier, context, await nextResolve(specifier, context), queryName, queryRE, (ctx, url) => {%0A%09%09port.postMessage({%0A%09%09%09context: ctx,%0A%09%09%09url%0A%09%09});%0A%09});%0A};%0A//%23endregion%0Aexport { initialize, resolve };%0A";
let nextId$1 = 0;
/**
* Off-thread importer: registers an ESM loader in a worker thread via
* `Module.register` and receives tracked dependencies over a `MessagePort`.
* Used on Node versions without `Module.registerHooks`.
*/
function createOffThreadImporter() {
	const queryName = buildQueryName();
	const { port1, port2 } = new MessageChannel();
	Module.register(loader_default, {
		data: {
			port: port2,
			queryName
		},
		transferList: [port2]
	});
	port1.unref();
	return { async collect(specifier) {
		const id = nextId$1++;
		const depsList = /* @__PURE__ */ new Set();
		const onMessage = (e) => {
			if (e.context === specifier) depsList.add(e.url);
		};
		port1.on("message", onMessage);
		port1.unref();
		try {
			const result = await import(specifier + formatTrackingQuery(queryName, id, specifier));
			await new Promise((resolve) => setImmediate(resolve));
			return {
				result,
				dependencies: [...depsList].filter((url) => url.startsWith("file:")).map((url) => fileURLToPath(url))
			};
		} finally {
			port1.off("message", onMessage);
		}
	} };
}
let nextId = 0;
/**
* On-thread importer: registers synchronous resolution hooks via
* `Module.registerHooks` (Node 22.15+/23.5+).
*/
function createOnThreadImporter() {
	const registry = /* @__PURE__ */ new Map();
	const queryName = buildQueryName();
	const queryRE = buildQueryRE(queryName);
	const resolve = (specifier, context, nextResolve) => {
		return trackResolved(specifier, context, nextResolve(specifier, context), queryName, queryRE, (ctx, url) => {
			registry.get(ctx)?.add(url);
		});
	};
	Module.registerHooks({ resolve });
	return { async collect(specifier) {
		const id = nextId++;
		const depsList = /* @__PURE__ */ new Set();
		registry.set(specifier, depsList);
		try {
			return {
				result: await import(specifier + formatTrackingQuery(queryName, id, specifier)),
				dependencies: [...depsList].filter((url) => url.startsWith("file:")).map((url) => fileURLToPath(url))
			};
		} finally {
			registry.delete(specifier);
		}
	} };
}
/**
* Create the importer best suited to the current runtime, or `undefined` if it
* provides neither module-hook API.
*/
function createImporter() {
	if (Module.registerHooks) return createOnThreadImporter();
	if (Module.register) return createOffThreadImporter();
}
let importer;
let initialized = false;
/**
* Import an ESM entry in its own fresh module graph (separate from Node's module
* cache and from other concurrent imports) and report the dependency files it
* pulled in.
*
* Each call re-evaluates the entry in a fresh graph; concurrent calls stay
* isolated from one another. Only statically-imported relative dependencies are
* tracked, not dynamic imports.
*
* Returns `undefined` on runtimes that provide neither `Module.registerHooks`
* nor `Module.register`.
*/
function freshImport(specifier) {
	if (!initialized) {
		importer = createImporter();
		initialized = true;
	}
	return importer?.collect(specifier);
}
//#endregion
//#region src/shared/constants.ts
/**
* Prefix for resolved Ids that are not valid browser import specifiers
*/
const VALID_ID_PREFIX = `/@id/`;
/**
* Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
* module ID with `\0`, a convention from the rollup ecosystem.
* This prevents other plugins from trying to process the id (like node resolution),
* and core features like sourcemaps can use this info to differentiate between
* virtual modules and regular files.
* `\0` is not a permitted char in import URLs so we have to replace them during
* import analysis. The id will be decoded back before entering the plugins pipeline.
* These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
* modules in the browser end up encoded as `/@id/__x00__{id}`
*/
const NULL_BYTE_PLACEHOLDER = `__x00__`;
let SOURCEMAPPING_URL = "sourceMa";
SOURCEMAPPING_URL += "ppingURL";
const MODULE_RUNNER_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-generated";
const ERR_OUTDATED_OPTIMIZED_DEP = "ERR_OUTDATED_OPTIMIZED_DEP";
//#endregion
//#region src/shared/utils.ts
const isWindows = typeof process !== "undefined" && process.platform === "win32";
/**
* Prepend `/@id/` and replace null byte so the id is URL-safe.
* This is prepended to resolved ids that are not valid browser
* import specifiers by the importAnalysis plugin.
*/
function wrapId(id) {
	return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
}
/**
* Undo {@link wrapId}'s `/@id/` and null byte replacements.
*/
function unwrapId(id) {
	return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
}
const windowsSlashRE = /\\/g;
function slash(p) {
	return p.replace(windowsSlashRE, "/");
}
const postfixRE = /[?#].*$/;
function cleanUrl(url) {
	return url.replace(postfixRE, "");
}
function splitFileAndPostfix(path) {
	const file = cleanUrl(path);
	return {
		file,
		postfix: path.slice(file.length)
	};
}
function withTrailingSlash(path) {
	if (path[path.length - 1] !== "/") return `${path}/`;
	return path;
}
function promiseWithResolvers() {
	let resolve;
	let reject;
	return {
		promise: new Promise((_resolve, _reject) => {
			resolve = _resolve;
			reject = _reject;
		}),
		resolve,
		reject
	};
}
//#endregion
//#region src/module-runner/importMetaResolver.ts
const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/";
const customizationHooksModule = `

export async function resolve(specifier, context, nextResolve) {
  if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
    const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
    const [parsedSpecifier, parsedImporter] = JSON.parse(data)
    specifier = parsedSpecifier
    context.parentURL = parsedImporter
  }
  return nextResolve(specifier, context)
}

`;
function customizationHookResolve(specifier, context, nextResolve) {
	if (specifier.startsWith(customizationHookNamespace)) {
		const data = specifier.slice(42);
		const [parsedSpecifier, parsedImporter] = JSON.parse(data);
		specifier = parsedSpecifier;
		context.parentURL = parsedImporter;
	}
	return nextResolve(specifier, context);
}
let isHookRegistered = false;
function createImportMetaResolver() {
	if (isHookRegistered) return importMetaResolveWithCustomHook;
	let module;
	try {
		module = typeof process !== "undefined" ? process.getBuiltinModule("node:module").Module : void 0;
	} catch {
		return;
	}
	if (!module) return;
	if (module.registerHooks) {
		module.registerHooks({ resolve: customizationHookResolve });
		isHookRegistered = true;
		return importMetaResolveWithCustomHook;
	}
	if (!module.register) return;
	try {
		const hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
		module.register(hookModuleContent);
	} catch (e) {
		if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
		throw e;
	}
	isHookRegistered = true;
	return importMetaResolveWithCustomHook;
}
function importMetaResolveWithCustomHook(specifier, importer) {
	return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
}
const importMetaResolveWithCustomHookString = `

  (() => {
    const resolve = 'resolve'
    return (specifier, importer) =>
      import.meta[resolve](
        \`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
      )
  })()

`;
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
var comma$1 = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar$1 = /* @__PURE__ */ new Uint8Array(64);
var charToInt$1 = /* @__PURE__ */ new Uint8Array(128);
for (let i = 0; i < chars$1.length; i++) {
	const c = chars$1.charCodeAt(i);
	intToChar$1[i] = c;
	charToInt$1[c] = i;
}
function decodeInteger$1(reader, relative) {
	let value = 0;
	let shift = 0;
	let integer = 0;
	do {
		integer = charToInt$1[reader.next()];
		value |= (integer & 31) << shift;
		shift += 5;
	} while (integer & 32);
	const shouldNegate = value & 1;
	value >>>= 1;
	if (shouldNegate) value = -2147483648 | -value;
	return relative + value;
}
function encodeInteger(builder, num, relative) {
	let delta = num - relative;
	delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
	do {
		let clamped = delta & 31;
		delta >>>= 5;
		if (delta > 0) clamped |= 32;
		builder.write(intToChar$1[clamped]);
	} while (delta > 0);
	return num;
}
function hasMoreVlq$1(reader, max) {
	if (reader.pos >= max) return false;
	return reader.peek() !== comma$1;
}
var bufLength = 1024 * 16;
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
	return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
} } : { decode(buf) {
	let out = "";
	for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
	return out;
} };
var StringWriter = class {
	constructor() {
		this.pos = 0;
		this.out = "";
		this.buffer = new Uint8Array(bufLength);
	}
	write(v) {
		const { buffer } = this;
		buffer[this.pos++] = v;
		if (this.pos === bufLength) {
			this.out += td.decode(buffer);
			this.pos = 0;
		}
	}
	flush() {
		const { buffer, out, pos } = this;
		return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
	}
};
var StringReader$1 = class {
	constructor(buffer) {
		this.pos = 0;
		this.buffer = buffer;
	}
	next() {
		return this.buffer.charCodeAt(this.pos++);
	}
	peek() {
		return this.buffer.charCodeAt(this.pos);
	}
	indexOf(char) {
		const { buffer, pos } = this;
		const idx = buffer.indexOf(char, pos);
		return idx === -1 ? buffer.length : idx;
	}
};
function decode$1(mappings) {
	const { length } = mappings;
	const reader = new StringReader$1(mappings);
	const decoded = [];
	let genColumn = 0;
	let sourcesIndex = 0;
	let sourceLine = 0;
	let sourceColumn = 0;
	let namesIndex = 0;
	do {
		const semi = reader.indexOf(";");
		const line = [];
		let sorted = true;
		let lastCol = 0;
		genColumn = 0;
		while (reader.pos < semi) {
			let seg;
			genColumn = decodeInteger$1(reader, genColumn);
			if (genColumn < lastCol) sorted = false;
			lastCol = genColumn;
			if (hasMoreVlq$1(reader, semi)) {
				sourcesIndex = decodeInteger$1(reader, sourcesIndex);
				sourceLine = decodeInteger$1(reader, sourceLine);
				sourceColumn = decodeInteger$1(reader, sourceColumn);
				if (hasMoreVlq$1(reader, semi)) {
					namesIndex = decodeInteger$1(reader, namesIndex);
					seg = [
						genColumn,
						sourcesIndex,
						sourceLine,
						sourceColumn,
						namesIndex
					];
				} else seg = [
					genColumn,
					sourcesIndex,
					sourceLine,
					sourceColumn
				];
			} else seg = [genColumn];
			line.push(seg);
			reader.pos++;
		}
		if (!sorted) sort$1(line);
		decoded.push(line);
		reader.pos = semi + 1;
	} while (reader.pos <= length);
	return decoded;
}
function sort$1(line) {
	line.sort(sortComparator$2);
}
function sortComparator$2(a, b) {
	return a[0] - b[0];
}
function encode$1(decoded) {
	const writer = new StringWriter();
	let sourcesIndex = 0;
	let sourceLine = 0;
	let sourceColumn = 0;
	let namesIndex = 0;
	for (let i = 0; i < decoded.length; i++) {
		const line = decoded[i];
		if (i > 0) writer.write(semicolon);
		if (line.length === 0) continue;
		let genColumn = 0;
		for (let j = 0; j < line.length; j++) {
			const segment = line[j];
			if (j > 0) writer.write(comma$1);
			genColumn = encodeInteger(writer, segment[0], genColumn);
			if (segment.length === 1) continue;
			sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
			sourceLine = encodeInteger(writer, segment[2], sourceLine);
			sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
			if (segment.length === 4) continue;
			namesIndex = encodeInteger(writer, segment[4], namesIndex);
		}
	}
	return writer.flush();
}
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
const schemeRegex = /^[\w+.-]+:\/\//;
/**
* Matches the parts of a URL:
* 1. Scheme, including ":", guaranteed.
* 2. User/password, including "@", optional.
* 3. Host, guaranteed.
* 4. Port, including ":", optional.
* 5. Path, including "/", optional.
* 6. Query, including "?", optional.
* 7. Hash, including "#", optional.
*/
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
/**
* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
*
* 1. Host, optional.
* 2. Path, which may include "/", guaranteed.
* 3. Query, including "?", optional.
* 4. Hash, including "#", optional.
*/
const 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 match = urlRegex.exec(input);
	return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
}
function parseFileUrl(input) {
	const match = fileRegex.exec(input);
	const path = match[2];
	return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
}
function makeUrl(scheme, user, host, port, path, query, hash) {
	return {
		scheme,
		user,
		host,
		port,
		path,
		query,
		hash,
		type: 7
	};
}
function parseUrl(input) {
	if (isSchemeRelativeUrl(input)) {
		const url = parseAbsoluteUrl("http:" + input);
		url.scheme = "";
		url.type = 6;
		return url;
	}
	if (isAbsolutePath(input)) {
		const url = parseAbsoluteUrl("http://foo.com" + input);
		url.scheme = "";
		url.host = "";
		url.type = 5;
		return url;
	}
	if (isFileUrl(input)) return parseFileUrl(input);
	if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);
	const url = parseAbsoluteUrl("http://foo.com/" + input);
	url.scheme = "";
	url.host = "";
	url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
	return url;
}
function stripPathFilename(path) {
	if (path.endsWith("/..")) return path;
	const index = path.lastIndexOf("/");
	return path.slice(0, index + 1);
}
function mergePaths(url, base) {
	normalizePath$2(base, base.type);
	if (url.path === "/") url.path = base.path;
	else url.path = stripPathFilename(base.path) + url.path;
}
/**
* The path can have empty directories "//", unneeded parents "foo/..", or current directory
* "foo/.". We need to normalize to a standard representation.
*/
function normalizePath$2(url, type) {
	const rel = type <= 4;
	const pieces = url.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 path = "";
	for (let i = 1; i < pointer; i++) path += "/" + pieces[i];
	if (!path || addTrailingSlash && !path.endsWith("/..")) path += "/";
	url.path = path;
}
/**
* Attempts to resolve `input` URL/path relative to `base`.
*/
function resolve$4(input, base) {
	if (!input && !base) return "";
	const url = parseUrl(input);
	let inputType = url.type;
	if (base && inputType !== 7) {
		const baseUrl = parseUrl(base);
		const baseType = baseUrl.type;
		switch (inputType) {
			case 1: url.hash = baseUrl.hash;
			case 2: url.query = baseUrl.query;
			case 3:
			case 4: mergePaths(url, baseUrl);
			case 5:
				url.user = baseUrl.user;
				url.host = baseUrl.host;
				url.port = baseUrl.port;
			case 6: url.scheme = baseUrl.scheme;
		}
		if (baseType > inputType) inputType = baseType;
	}
	normalizePath$2(url, inputType);
	const queryHash = url.query + url.hash;
	switch (inputType) {
		case 2:
		case 3: return queryHash;
		case 4: {
			const path = url.path.slice(1);
			if (!path) return queryHash || ".";
			if (isRelative(base || input) && !isRelative(path)) return "./" + path + queryHash;
			return path + queryHash;
		}
		case 5: return url.path + queryHash;
		default: return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
	}
}
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
function stripFilename(path) {
	if (!path) return "";
	const index = path.lastIndexOf("/");
	return path.slice(0, index + 1);
}
function resolver(mapUrl, sourceRoot) {
	const from = stripFilename(mapUrl);
	const prefix = sourceRoot ? sourceRoot + "/" : "";
	return (source) => resolve$4(prefix + (source || ""), from);
}
var COLUMN$2 = 0;
var SOURCES_INDEX$2 = 1;
var SOURCE_LINE$2 = 2;
var SOURCE_COLUMN$2 = 3;
var NAMES_INDEX$2 = 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$2] < line[j - 1][COLUMN$2]) return false;
	return true;
}
function sortSegments(line, owned) {
	if (!owned) line = line.slice();
	return line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
	return a[COLUMN$2] - b[COLUMN$2];
}
var found$1 = false;
function binarySearch$1(haystack, needle, low, high) {
	while (low <= high) {
		const mid = low + (high - low >> 1);
		const cmp = haystack[mid][COLUMN$2] - needle;
		if (cmp === 0) {
			found$1 = true;
			return mid;
		}
		if (cmp < 0) low = mid + 1;
		else high = mid - 1;
	}
	found$1 = false;
	return low - 1;
}
function upperBound$1(haystack, needle, index) {
	for (let i = index + 1; i < haystack.length; index = i++) if (haystack[i][COLUMN$2] !== needle) break;
	return index;
}
function lowerBound$1(haystack, needle, index) {
	for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN$2] !== needle) break;
	return index;
}
function memoizedState$1() {
	return {
		lastKey: -1,
		lastNeedle: -1,
		lastIndex: -1
	};
}
function memoizedBinarySearch$1(haystack, needle, state, key) {
	const { lastKey, lastNeedle, lastIndex } = state;
	let low = 0;
	let high = haystack.length - 1;
	if (key === lastKey) {
		if (needle === lastNeedle) {
			found$1 = lastIndex !== -1 && haystack[lastIndex][COLUMN$2] === needle;
			return lastIndex;
		}
		if (needle >= lastNeedle) low = lastIndex === -1 ? 0 : lastIndex;
		else high = lastIndex;
	}
	state.lastKey = key;
	state.lastNeedle = needle;
	return state.lastIndex = binarySearch$1(haystack, needle, low, high);
}
function parse$3(map) {
	return typeof map === "string" ? JSON.parse(map) : map;
}
var LINE_GTR_ZERO$1 = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO$1 = "`column` must be greater than or equal to 0 (columns start at column 0)";
var TraceMap = class {
	constructor(map, mapUrl) {
		const isString = typeof map === "string";
		if (!isString && map._decodedMemo) return map;
		const parsed = parse$3(map);
		const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
		this.version = version;
		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 resolve = resolver(mapUrl, sourceRoot);
		this.resolvedSources = sources.map(resolve);
		const { mappings } = parsed;
		if (typeof mappings === "string") {
			this._encoded = mappings;
			this._decoded = void 0;
		} else if (Array.isArray(mappings)) {
			this._encoded = void 0;
			this._decoded = maybeSort(mappings, isString);
		} else if (parsed.sections) throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
		else throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
		this._decodedMemo = memoizedState$1();
		this._bySources = void 0;
		this._bySourceMemos = void 0;
	}
};
function cast$2(map) {
	return map;
}
function decodedMappings$1(map) {
	var _a;
	return (_a = cast$2(map))._decoded || (_a._decoded = decode$1(cast$2(map)._encoded));
}
function traceSegment(map, line, column) {
	const decoded = decodedMappings$1(map);
	if (line >= decoded.length) return null;
	const segments = decoded[line];
	const index = traceSegmentInternal$1(segments, cast$2(map)._decodedMemo, line, column, 1);
	return index === -1 ? null : segments[index];
}
function originalPositionFor$2(map, needle) {
	let { line, column, bias } = needle;
	line--;
	if (line < 0) throw new Error(LINE_GTR_ZERO$1);
	if (column < 0) throw new Error(COL_GTR_EQ_ZERO$1);
	const decoded = decodedMappings$1(map);
	if (line >= decoded.length) return OMapping$1(null, null, null, null);
	const segments = decoded[line];
	const index = traceSegmentInternal$1(segments, cast$2(map)._decodedMemo, line, column, bias || 1);
	if (index === -1) return OMapping$1(null, null, null, null);
	const segment = segments[index];
	if (segment.length === 1) return OMapping$1(null, null, null, null);
	const { names, resolvedSources } = map;
	return OMapping$1(resolvedSources[segment[SOURCES_INDEX$2]], segment[SOURCE_LINE$2] + 1, segment[SOURCE_COLUMN$2], segment.length === 5 ? names[segment[NAMES_INDEX$2]] : null);
}
function OMapping$1(source, line, column, name) {
	return {
		source,
		line,
		column,
		name
	};
}
function traceSegmentInternal$1(segments, memo, line, column, bias) {
	let index = memoizedBinarySearch$1(segments, column, memo, line);
	if (found$1) index = (bias === -1 ? upperBound$1 : lowerBound$1)(segments, column, index);
	else if (bias === -1) index++;
	if (index === -1 || index === segments.length) return -1;
	return index;
}
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs
var SetArray = class {
	constructor() {
		this._indexes = { __proto__: null };
		this.array = [];
	}
};
function cast$1(set) {
	return set;
}
function get$2(setarr, key) {
	return cast$1(setarr)._indexes[key];
}
function put(setarr, key) {
	const index = get$2(setarr, key);
	if (index !== void 0) return index;
	const { array, _indexes: indexes } = cast$1(setarr);
	return indexes[key] = array.push(key) - 1;
}
function remove(setarr, key) {
	const index = get$2(setarr, key);
	if (index === void 0) return;
	const { array, _indexes: indexes } = cast$1(setarr);
	for (let i = index + 1; i < array.length; i++) {
		const k = array[i];
		array[i - 1] = k;
		indexes[k]--;
	}
	indexes[key] = void 0;
	array.pop();
}
var COLUMN$1 = 0;
var SOURCES_INDEX$1 = 1;
var SOURCE_LINE$1 = 2;
var SOURCE_COLUMN$1 = 3;
var NAMES_INDEX$1 = 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 cast2(map) {
	return map;
}
var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
	return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content);
};
function setSourceContent(map, source, content) {
	const { _sources: sources, _sourcesContent: sourcesContent } = cast2(map);
	const index = put(sources, source);
	sourcesContent[index] = content;
}
function setIgnore(map, source, ignore = true) {
	const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast2(map);
	const index = put(sources, source);
	if (index === sourcesContent.length) sourcesContent[index] = null;
	if (ignore) put(ignoreList, index);
	else remove(ignoreList, index);
}
function toDecodedMap(map) {
	const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast2(map);
	removeEmptyFinalLines(mappings);
	return {
		version: 3,
		file: map.file || void 0,
		names: names.array,
		sourceRoot: map.sourceRoot || void 0,
		sources: sources.array,
		sourcesContent,
		mappings,
		ignoreList: ignoreList.array
	};
}
function toEncodedMap(map) {
	const decoded = toDecodedMap(map);
	return Object.assign({}, decoded, { mappings: encode$1(decoded.mappings) });
}
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
	const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast2(map);
	const line = getIndex(mappings, genLine);
	const index = getColumnIndex(line, genColumn);
	if (!source) {
		if (skipable && skipSourceless(line, index)) return;
		return insert(line, index, [genColumn]);
	}
	const sourcesIndex = put(sources, source);
	const namesIndex = name ? put(names, name) : NO_NAME;
	if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null;
	if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) return;
	return insert(line, index, name ? [
		genColumn,
		sourcesIndex,
		sourceLine,
		sourceColumn,
		namesIndex
	] : [
		genColumn,
		sourcesIndex,
		sourceLine,
		sourceColumn
	]);
}
function getIndex(arr, index) {
	for (let i = arr.length; i <= index; i++) arr[i] = [];
	return arr[index];
}
function getColumnIndex(line, genColumn) {
	let index = line.length;
	for (let i = index - 1; i >= 0; index = i--) if (genColumn >= line[i][COLUMN$1]) break;
	return index;
}
function insert(array, index, value) {
	for (let i = array.length; i > index; i--) array[i] = array[i - 1];
	array[index] = value;
}
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;
	return line[index - 1].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$1] && sourceLine === prev[SOURCE_LINE$1] && sourceColumn === prev[SOURCE_COLUMN$1] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX$1] : NO_NAME);
}
//#endregion
//#region ../../node_modules/.pnpm/@jridgewell+remapping@2.3.5/node_modules/@jridgewell/remapping/dist/remapping.mjs
var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
var EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content, ignore) {
	return {
		source,
		line,
		column,
		name,
		content,
		ignore
	};
}
function Source(map, sources, source, content, ignore) {
	return {
		map,
		sources,
		source,
		content,
		ignore
	};
}
function MapSource(map, sources) {
	return Source(map, 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 } = tree;
	const rootNames = map.names;
	const rootMappings = decodedMappings$1(map);
	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$1(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
				if (traced == null) continue;
			}
			const { column, line, name, content, source, ignore } = traced;
			maybeAddSegment(gen, i, genCol, source, line, column, name);
			if (source && content != null) setSourceContent(gen, source, content);
			if (ignore) setIgnore(gen, source, true);
		}
	}
	return gen;
}
function originalPositionFor$1(source, line, column, name) {
	if (!source.map) return SegmentObject(source.source, line, column, name, 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$1(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
}
function asArray(value) {
	if (Array.isArray(value)) return value;
	return [value];
}
function buildSourceMapTree(input, loader) {
	const maps = asArray(input).map((m) => new TraceMap(m, ""));
	const map = 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$1(map, loader, "", 0);
	for (let i = maps.length - 1; i >= 0; i--) tree = MapSource(maps[i], [tree]);
	return tree;
}
function build$1(map, loader, importer, importerDepth) {
	const { resolvedSources, sourcesContent, ignoreList } = map;
	const depth = importerDepth + 1;
	return MapSource(map, resolvedSources.map((sourceFile, i) => {
		const ctx = {
			importer,
			depth,
			source: sourceFile || "",
			content: void 0,
			ignore: void 0
		};
		const sourceMap = loader(ctx.source, ctx);
		const { source, content, ignore } = ctx;
		if (sourceMap) return build$1(new TraceMap(sourceMap, source), loader, source, depth);
		return OriginalSource(source, content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null, ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false);
	}));
}
var SourceMap$1 = class {
	constructor(map, options) {
		const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
		this.version = out.version;
		this.file = out.file;
		this.mappings = out.mappings;
		this.names = out.names;
		this.ignoreList = out.ignoreList;
		this.sourceRoot = out.sourceRoot;
		this.sources = out.sources;
		if (!options.excludeContent) this.sourcesContent = out.sourcesContent;
	}
	toString() {
		return JSON.stringify(this);
	}
};
function remapping(input, loader, options) {
	const opts = typeof options === "object" ? options : {
		excludeContent: !!options,
		decodedMappings: false
	};
	return new SourceMap$1(traceMappings(buildSourceMapTree(input, loader)), opts);
}
//#endregion
//#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/core.js
function coerce(value) {
	if (value instanceof Error) return value.stack || value.message;
	return value;
}
function selectColor(colors, namespace) {
	let hash = 0;
	for (let i = 0; i < namespace.length; i++) {
		hash = (hash << 5) - hash + namespace.charCodeAt(i);
		hash |= 0;
	}
	return colors[Math.abs(hash) % colors.length];
}
function matchesTemplate(search, template) {
	let searchIndex = 0;
	let templateIndex = 0;
	let starIndex = -1;
	let matchIndex = 0;
	while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
		starIndex = templateIndex;
		matchIndex = searchIndex;
		templateIndex++;
	} else {
		searchIndex++;
		templateIndex++;
	}
	else if (starIndex !== -1) {
		templateIndex = starIndex + 1;
		matchIndex++;
		searchIndex = matchIndex;
	} else return false;
	while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
	return templateIndex === template.length;
}
function humanize(value) {
	if (value >= 1e3) return `${(value / 1e3).toFixed(1)}s`;
	return `${value}ms`;
}
function setup(useColors, colors, log, load, save, formatArgs, init) {
	const createDebug = (namespace) => {
		let prevTime;
		let enableOverride;
		let namespacesCache;
		let enabledCache;
		const debug = (...args) => {
			if (!debug.enabled) return;
			const curr = Date.now();
			debug.diff = curr - (prevTime || curr);
			debug.prev = prevTime;
			debug.curr = curr;
			prevTime = curr;
			args[0] = coerce(args[0]);
			if (typeof args[0] !== "string") args.unshift("%O");
			let index = 0;
			args[0] = args[0].replace(/%([a-z%])/gi, (match, format) => {
				if (match === "%%") return "%";
				index++;
				const formatter = createDebug.formatters[format];
				if (typeof formatter === "function") {
					match = formatter.call(debug, args[index]);
					args.splice(index, 1);
					index--;
				}
				return match;
			});
			createDebug.formatArgs.call(debug, args);
			(debug.log || createDebug.log).apply(debug, args);
		};
		function extend(namespace$1, delimiter = ":") {
			const newDebug = createDebug(this.namespace + delimiter + namespace$1);
			newDebug.log = this.log;
			return newDebug;
		}
		debug.namespace = namespace;
		debug.useColors = useColors;
		debug.color = selectColor(colors, namespace);
		debug.extend = extend;
		debug.log = log;
		Object.defineProperty(debug, "enabled", {
			enumerable: true,
			configurable: false,
			get: () => {
				if (enableOverride != null) return enableOverride;
				if (namespacesCache !== createDebug.namespaces) {
					namespacesCache = createDebug.namespaces;
					enabledCache = createDebug.enabled(namespace);
				}
				return enabledCache;
			},
			set: (v) => {
				enableOverride = v;
			}
		});
		init && init(debug);
		return debug;
	};
	function enable(namespaces) {
		save(namespaces);
		createDebug.namespaces = namespaces;
		createDebug.names = [];
		createDebug.skips = [];
		const split = namespaces.trim().replace(/\s+/g, ",").split(",").filter(Boolean);
		for (const ns of split) if (ns[0] === "-") createDebug.skips.push(ns.slice(1));
		else createDebug.names.push(ns);
	}
	function disable() {
		const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => `-${namespace}`)].join(",");
		createDebug.enable("");
		return namespaces;
	}
	function enabled(name) {
		for (const skip of createDebug.skips) if (matchesTemplate(name, skip)) return false;
		for (const ns of createDebug.names) if (matchesTemplate(name, ns)) return true;
		return false;
	}
	createDebug.namespaces = "";
	createDebug.formatters = {};
	createDebug.enable = enable;
	createDebug.disable = disable;
	createDebug.enabled = enabled;
	createDebug.names = [];
	createDebug.skips = [];
	createDebug.selectColor = (ns) => selectColor(colors, ns);
	createDebug.formatArgs = formatArgs;
	createDebug.log = log;
	createDebug.enable(load());
	return createDebug;
}
var init_core = __esmMin((() => {}));
//#endregion
//#region ../../node_modules/.pnpm/obug@1.0.2_ms@2.1.3/node_modules/obug/dist/node.js
var node_exports = /* @__PURE__ */ __exportAll({
	createDebug: () => createDebug,
	default: () => node_default,
	formatArgs: () => formatArgs,
	log: () => log,
	"module.exports": () => createDebug
});
function log(...args) {
	process.stderr.write(`${formatWithOptions(inspectOpts, ...args)}\n`);
}
function load() {
	return process.env.DEBUG || "";
}
function save(namespaces) {
	if (namespaces) process.env.DEBUG = namespaces;
	else delete process.env.DEBUG;
}
function useColors() {
	return "colors" in inspectOpts ? Boolean(inspectOpts.colors) : isatty(process.stderr.fd);
}
function formatArgs(args) {
	const { namespace: name, useColors: useColors$1 } = this;
	if (useColors$1) {
		const c = this.color;
		const colorCode = `\u001B[3${c < 8 ? c : `8;5;${c}`}`;
		const prefix = `  ${colorCode};1m${name} \u001B[0m`;
		args[0] = prefix + args[0].split("\n").join(`\n${prefix}`);
		args.push(`${colorCode}m+${humanize$1(this.diff)}\u001B[0m`);
	} else args[0] = `${getDate()}${name} ${args[0]}`;
}
function getDate() {
	if (inspectOpts.hideDate) return "";
	return `${(/* @__PURE__ */ new Date()).toISOString()} `;
}
function init$1(debug) {
	debug.inspectOpts = Object.assign({}, inspectOpts);
}
var require$1, colors$38, inspectOpts, humanize$1, createDebug, node_default;
var init_node = __esmMin((() => {
	init_core();
	require$1 = createRequire(import.meta.url);
	colors$38 = process.stderr.getColorDepth && process.stderr.getColorDepth() > 2 ? [
		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
	] : [
		6,
		2,
		3,
		4,
		5,
		1
	];
	inspectOpts = Object.keys(process.env).filter((key) => {
		return /^debug_/i.test(key);
	}).reduce((obj, key) => {
		const prop = key.slice(6).toLowerCase().replace(/_([a-z])/g, (_, k) => k.toUpperCase());
		let value = process.env[key];
		if (value === "null") value = null;
		else if (/^yes|on|true|enabled$/i.test(value)) value = true;
		else if (/^no|off|false|disabled$/i.test(value)) value = false;
		else value = Number(value);
		obj[prop] = value;
		return obj;
	}, {});
	try {
		humanize$1 = require$1("ms");
	} catch (_unused) {
		humanize$1 = humanize;
	}
	createDebug = setup(useColors(), colors$38, log, load, save, formatArgs, init$1);
	createDebug.inspectOpts = inspectOpts;
	createDebug.formatters.o = function(v) {
		this.inspectOpts.colors = this.useColors;
		return inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
	};
	createDebug.formatters.O = function(v) {
		this.inspectOpts.colors = this.useColors;
		return inspect(v, this.inspectOpts);
	};
	node_default = createDebug;
	createDebug.default = createDebug;
	createDebug.debug = createDebug;
}));
//#endregion
//#region ../../node_modules/.pnpm/@rollup+pluginutils@5.4.0_rollup@4.59.0/node_modules/@rollup/pluginutils/dist/es/index.js
function isArray(arg) {
	return Array.isArray(arg);
}
function ensureArray(thing) {
	if (isArray(thing)) return thing;
	if (thing == null) return [];
	return [thing];
}
const normalizePathRegExp = new RegExp(`\\${win32.sep}`, "g");
const normalizePath$1 = function normalizePath(filename) {
	return filename.replace(normalizePathRegExp, posix$1.sep);
};
function getMatcherString$1(id, resolutionBase) {
	if (resolutionBase === false || isAbsolute$1(id) || id.startsWith("**")) return normalizePath$1(id);
	const basePath = normalizePath$1(resolve$1(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&");
	return posix$1.join(basePath, normalizePath$1(id));
}
const createFilter$2 = function createFilter(include, exclude, options) {
	const resolutionBase = options && options.resolve;
	const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => {
		return pm(getMatcherString$1(id, resolutionBase), { dot: true })(what);
	} };
	const includeMatchers = ensureArray(include).map(getMatcher);
	const excludeMatchers = ensureArray(exclude).map(getMatcher);
	if (!includeMatchers.length && !excludeMatchers.length) return (id) => typeof id === "string" && !id.includes("\0");
	return function result(id) {
		if (typeof id !== "string") return false;
		if (id.includes("\0")) return false;
		const pathId = normalizePath$1(id);
		for (let i = 0; i < excludeMatchers.length; ++i) {
			const matcher = excludeMatchers[i];
			if (matcher instanceof RegExp) matcher.lastIndex = 0;
			if (matcher.test(pathId)) return false;
		}
		for (let i = 0; i < includeMatchers.length; ++i) {
			const matcher = includeMatchers[i];
			if (matcher instanceof RegExp) matcher.lastIndex = 0;
			if (matcher.test(pathId)) return true;
		}
		return !includeMatchers.length;
	};
};
const forbiddenIdentifiers = new Set(`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 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`.split(" "));
forbiddenIdentifiers.add("");
const makeLegalIdentifier = function makeLegalIdentifier(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(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 ? `\n${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 ? `\n${baseIndent}` : ""}]`;
}
function serializeObject(obj, indent, baseIndent) {
	let output = "{";
	const separator = indent ? `\n${baseIndent}${indent}` : "";
	const entries = Object.entries(obj);
	for (let i = 0; i < entries.length; i++) {
		const [key, value] = entries[i];
		const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
		output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value, indent, baseIndent + indent)}`;
	}
	return `${output}${indent ? `\n${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(key)})`;
	}
	if (typeof obj === "bigint") return `${obj}n`;
	return stringify(obj);
}
const hasStringIsWellFormed = "isWellFormed" in String.prototype;
function isWellFormedString(input) {
	if (hasStringIsWellFormed) return input.isWellFormed();
	return !/\p{Surrogate}/u.test(input);
}
const identifierNameRE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
const dataToEsm = function dataToEsm(data, options = {}) {
	var _a, _b;
	const t = options.compact ? "" : "indent" in options ? options.indent : "	";
	const _ = options.compact ? "" : " ";
	const n = options.compact ? "" : "\n";
	const declarationType = options.preferConst ? "const" : "var";
	if (options.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
		const code = serialize(data, options.compact ? null : t, "");
		return `export default${_ || (/^[{[\-\/]/.test(code) ? "" : " ")}${code};`;
	}
	let maxUnderbarPrefixLength = 0;
	for (const key of Object.keys(data)) {
		const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
		if (underbarPrefixLength > maxUnderbarPrefixLength) maxUnderbarPrefixLength = underbarPrefixLength;
	}
	const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
	let namedExportCode = "";
	const defaultExportRows = [];
	const arbitraryNameExportRows = [];
	for (const [key, value] of Object.entries(data)) if (key === makeLegalIdentifier(key)) {
		if (options.objectShorthand) defaultExportRows.push(key);
		else defaultExportRows.push(`${key}:${_}${key}`);
		namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
	} else {
		defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, "")}`);
		if (key !== "default") {
			const isIdentifierName = identifierNameRE.test(key);
			if (isIdentifierName || options.includeArbitraryNames && isWellFormedString(key)) {
				const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
				namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
				arbitraryNameExportRows.push(`${variableName} as ${isIdentifierName ? key : JSON.stringify(key)}`);
			}
		}
	}
	const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : "";
	const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
	return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
};
//#endregion
//#region src/shared/builtin.ts
function createIsBuiltin(builtins) {
	const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string"));
	const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string");
	return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
}
//#endregion
//#region src/node/packages.ts
let pnp;
if (process.versions.pnp) try {
	pnp = createRequire(
		/** #__KEEP__ */
		import.meta.url
	)("pnpapi");
} catch {}
function invalidatePackageData(packageCache, pkgPath) {
	const pkgDir = normalizePath(path.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?.has(cacheKey)) return packageCache.get(cacheKey);
		try {
			const pkg = pnp.resolveToUnqualified(pkgName, basedir, { considerBuiltins: false });
			if (!pkg) return null;
			const pkgData = loadPackageData(path.join(pkg, "package.json"));
			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 = path.join(basedir, "node_modules", pkgName, "package.json");
		try {
			if (fs.existsSync(pkg)) {
				const pkgData = loadPackageData(preserveSymlinks ? pkg : safeRealpathSync(pkg));
				if (packageCache) setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks);
				return pkgData;
			}
		} catch {}
		const nextBasedir = path.dirname(basedir);
		if (nextBasedir === basedir) break;
		basedir = nextBasedir;
	}
	return null;
}
function findNearestPackageData(basedir, packageCache) {
	const originalBasedir = basedir;
	while (basedir) {
		if (packageCache) {
			const cached = getFnpdCache(packageCache, basedir, originalBasedir);
			if (cached) return cached;
		}
		const pkgPath = path.join(basedir, "package.json");
		if (tryStatSync(pkgPath)?.isFile()) try {
			const pkgData = loadPackageData(pkgPath);
			if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
			return pkgData;
		} catch {}
		const nextBasedir = path.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(path.dirname(nearestPackage.dir), packageCache));
}
function loadPackageData(pkgPath) {
	const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
	const pkgDir = normalizePath(path.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 hasSideEffects = createFilter$1(sideEffects.map((sideEffect) => {
		if (sideEffect.includes("/")) return sideEffect;
		return `**/${sideEffect}`;
	}), null, { resolve: pkgDir });
	else hasSideEffects = () => null;
	const resolvedCache = {};
	return {
		dir: pkgDir,
		data,
		hasSideEffects,
		setResolvedCache(key, entry, options) {
			resolvedCache[getResolveCacheKey(key, options)] = entry;
		},
		getResolvedCache(key, options) {
			return resolvedCache[getResolveCacheKey(key, options)];
		}
	};
}
function getResolveCacheKey(key, options) {
	return [
		key,
		options.isRequire ? "1" : "0",
		options.conditions.join("_"),
		options.extensions.join("_"),
		options.mainFields.join("_")
	].join("|");
}
function findNearestNodeModules(basedir) {
	while (basedir) {
		const pkgPath = path.join(basedir, "node_modules");
		if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath;
		const nextBasedir = path.dirname(basedir);
		if (nextBasedir === basedir) break;
		basedir = nextBasedir;
	}
	return null;
}
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(pkg.dir) && !watchedDirs.has(pkg.dir)) {
			watchedDirs.add(pkg.dir);
			watchFile(path.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, path.normalize(id));
		}
	};
}
/**
* Get cached `resolvePackageData` value based on `basedir`. When one is found,
* and we've already traversed some directories between `basedir` and `originalBasedir`,
* we cache the value for those in-between directories as well.
*
* This makes it so the fs is only read once for a shared `basedir`.
*/
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}`;
}
/**
* Get cached `findNearestPackageData` value based on `basedir`. When one is found,
* and we've already traversed some directories between `basedir` and `originalBasedir`,
* we cache the value for those in-between directories as well.
*
* This makes it so the fs is only read once for a shared `basedir`.
*/
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}`;
}
/**
* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
* @param shorterDir Shorter dir path, e.g. `/User/foo`
*/
function traverseBetweenDirs(longerDir, shorterDir, cb) {
	while (longerDir !== shorterDir) {
		cb(longerDir);
		longerDir = path.dirname(longerDir);
	}
}
//#endregion
//#region src/node/utils.ts
var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
init_node();
const createFilter$1 = createFilter$2;
const invalidUrlPathCharRE = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
const replaceNestedIdRE = /\s*>\s*/g;
const flattenId = (id) => {
	return limitFlattenIdLength(id.replaceAll(/_+/g, "$&__").replaceAll("/", "_").replaceAll(".", "__").replace(replaceNestedIdRE, "_n_").replace(invalidUrlPathCharRE, (c) => "_0" + c.charCodeAt(0).toString(16) + "_"));
};
const FLATTEN_ID_MAX_FILE_LENGTH = 170;
const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
	if (id.length <= limit) return id;
	return id.slice(0, limit - 9) + "_" + getHash(id);
};
const normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
const NODE_BUILTIN_NAMESPACE = "node:";
const BUN_BUILTIN_NAMESPACE = "bun:";
const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
const isBuiltinCache = /* @__PURE__ */ new WeakMap();
function isBuiltin(builtins, id) {
	let isBuiltin = isBuiltinCache.get(builtins);
	if (!isBuiltin) {
		isBuiltin = createIsBuiltin(builtins);
		isBuiltinCache.set(builtins, isBuiltin);
	}
	return isBuiltin(id);
}
const nodeLikeBuiltins = [
	...nodeBuiltins,
	new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
	new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
];
function isNodeLikeBuiltin(id) {
	return isBuiltin(nodeLikeBuiltins, id);
}
function isNodeBuiltin(id) {
	if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
	return nodeBuiltins.includes(id);
}
function isInNodeModules(id) {
	return id.includes("node_modules");
}
function moduleListContains(moduleList, id) {
	return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
}
function isOptimizable(id, optimizeDeps) {
	const { extensions } = optimizeDeps;
	return OPTIMIZABLE_ENTRY_RE.test(id) || (extensions?.some((ext) => id.endsWith(ext)) ?? false);
}
const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
const _dirname = path.dirname(fileURLToPath(
	/** #__KEEP__ */
	import.meta.url
));
const rollupVersion = "4.23.0";
const filter = process.env.VITE_DEBUG_FILTER;
const DEBUG = process.env.DEBUG;
function createDebugger(namespace, options = {}) {
	const log = node_default(namespace);
	const { onlyWhenFocused, depth } = options;
	if (depth && log.inspectOpts && log.inspectOpts.depth == null) log.inspectOpts.depth = options.depth;
	let enabled = log.enabled;
	if (enabled && onlyWhenFocused) enabled = !!DEBUG?.includes(typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace);
	if (enabled) return (...args) => {
		if (!filter || args.some((a) => a?.includes?.(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 (!fs.existsSync(CLIENT_ENTRY)) throw new Error("cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY);
	return fs.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
}
const isCaseInsensitiveFS = testCaseInsensitiveFS();
const VOLUME_RE = /^[A-Z]:/i;
function normalizePath(id) {
	return path.posix.normalize(isWindows ? slash(id) : id);
}
function fsPathFromId(id) {
	const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id);
	return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
}
function fsPathFromUrl(url) {
	return fsPathFromId(cleanUrl(url));
}
/**
* Check if dir is a parent of file
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param dir - normalized absolute path
* @param file - normalized absolute path
* @returns true if dir is a parent of file
*/
function isParentDirectory(dir, file) {
	dir = withTrailingSlash(dir);
	return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
}
/**
* Check if 2 file name are identical
*
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param file1 - normalized absolute path
* @param file2 - normalized absolute path
* @returns true if both files url are identical
*/
function isSameFilePath(file1, file2) {
	return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
}
const externalRE = /^([a-z]+:)?\/\//;
const isExternalUrl = (url) => externalRE.test(url);
const dataUrlRE = /^\s*data:/i;
const isDataUrl = (url) => dataUrlRE.test(url);
const virtualModuleRE = /^virtual-module:.*/;
const virtualModulePrefix = "virtual-module:";
const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
const isJSRequest = (url) => {
	url = cleanUrl(url);
	if (knownJsSrcRE.test(url)) return true;
	if (!path.extname(url) && url[url.length - 1] !== "/") return true;
	return false;
};
const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
const importQueryRE = /(\?|&)import=?(?:&|$)/;
const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
const InternalPrefixRE = new RegExp(`^(?:${[
	FS_PREFIX,
	VALID_ID_PREFIX,
	CLIENT_PUBLIC_PATH,
	ENV_PUBLIC_PATH
].join("|")})`);
const trailingSeparatorRE = /[?&]$/;
const isImportRequest = (url) => importQueryRE.test(url);
const isInternalRequest = (url) => InternalPrefixRE.test(url);
function removeImportQuery(url) {
	return url.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
}
function removeDirectQuery(url) {
	return url.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
}
const urlRE$1 = /(\?|&)url(?:&|$)/;
const rawRE$1 = /(\?|&)raw(?:&|$)/;
function removeUrlQuery(url) {
	return url.replace(urlRE$1, "$1").replace(trailingSeparatorRE, "");
}
function injectQuery(url, queryToInject) {
	const { file, postfix } = splitFileAndPostfix(url);
	return `${isWindows ? slash(file) : file}?${queryToInject}${postfix[0] === "?" ? `&${postfix.slice(1)}` : postfix}`;
}
const timestampRE = /\bt=\d{13}&?\b/;
function removeTimestampQuery(url) {
	return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
}
async function asyncReplace(input, re, replacer) {
	let match;
	let remaining = input;
	let rewritten = "";
	while (match = re.exec(remaining)) {
		rewritten += remaining.slice(0, match.index);
		rewritten += await replacer(match);
		remaining = remaining.slice(match.index + match[0].length);
	}
	rewritten += remaining;
	return rewritten;
}
function timeFrom(start, subtract = 0) {
	const time = performance$1.now() - start - subtract;
	const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
	if (time < 10) return import_picocolors.default.green(timeString);
	else if (time < 50) return import_picocolors.default.yellow(timeString);
	else return import_picocolors.default.red(timeString);
}
/**
* pretty url for logging.
*/
function prettifyUrl(url, root) {
	url = removeTimestampQuery(url);
	const isAbsoluteFile = url.startsWith(root);
	if (isAbsoluteFile || url.startsWith(FS_PREFIX)) {
		const file = path.posix.relative(root, isAbsoluteFile ? url : fsPathFromId(url));
		return import_picocolors.default.dim(file);
	} else return import_picocolors.default.dim(url);
}
function isObject$1(value) {
	return Object.prototype.toString.call(value) === "[object Object]";
}
function isDefined(value) {
	return value != null;
}
function tryStatSync(file) {
	try {
		return fs.statSync(file, { throwIfNoEntry: false });
	} catch {}
}
function lookupFile(dir, fileNames) {
	while (dir) {
		for (const fileName of fileNames) {
			const fullPath = path.join(dir, fileName);
			if (tryStatSync(fullPath)?.isFile()) return fullPath;
		}
		const parentDir = path.dirname(dir);
		if (parentDir === dir) return;
		dir = parentDir;
	}
}
function isFilePathESM(filePath, packageCache) {
	if (/\.m[jt]s$/.test(filePath)) return true;
	else if (/\.c[jt]s$/.test(filePath)) return false;
	else try {
		return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
	} catch {
		return false;
	}
}
const splitRE = /\r?\n/g;
const range = 2;
function pad(source, n = 2) {
	return source.split(splitRE).map((l) => ` `.repeat(n) + l).join(`\n`);
}
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, offset) {
	if (typeof offset !== "number") return offset;
	if (offset > source.length) throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
	const lines = source.slice(0, offset).split(splitRE);
	return {
		line: lines.length,
		column: lines[lines.length - 1].length
	};
}
const MAX_DISPLAY_LEN = 120;
const ELLIPSIS = "...";
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 lastPosLine = end !== void 0 ? numberToPos(source, end).line : numberToPos(source, start).line + range;
	const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1);
	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;
				const lineLength = lines[j].length;
				const pad = Math.max(start - (count - lineLength), 0);
				const underlineLength = Math.max(1, end > count ? lineLength - pad : end - start);
				let displayLine = lines[j];
				let underlinePad = pad;
				if (lineLength > MAX_DISPLAY_LEN) {
					let startIdx = 0;
					if (j === i) {
						if (underlineLength > MAX_DISPLAY_LEN) startIdx = pad;
						else {
							const center = pad + Math.floor(underlineLength / 2);
							startIdx = Math.max(0, center - Math.floor(MAX_DISPLAY_LEN / 2));
						}
						underlinePad = Math.max(0, pad - startIdx) + (startIdx > 0 ? 3 : 0);
					}
					const prefix = startIdx > 0 ? ELLIPSIS : "";
					const suffix = lineLength - startIdx > MAX_DISPLAY_LEN ? ELLIPSIS : "";
					const sliceLen = MAX_DISPLAY_LEN - prefix.length - suffix.length;
					displayLine = prefix + displayLine.slice(startIdx, startIdx + sliceLen) + suffix;
				}
				res.push(`${line}${" ".repeat(lineNumberWidth - String(line).length)}|  ${displayLine}`);
				if (j === i) {
					const underline = "^".repeat(Math.min(underlineLength, MAX_DISPLAY_LEN));
					res.push(`${" ".repeat(lineNumberWidth)}|  ` + " ".repeat(underlinePad) + underline);
				} else if (j > i) {
					if (end > count) {
						const length = Math.max(Math.min(end - count, lineLength), 1);
						const underline = "^".repeat(Math.min(length, MAX_DISPLAY_LEN));
						res.push(`${" ".repeat(lineNumberWidth)}|  ` + underline);
					}
					count += lineLength + 1;
				}
			}
			break;
		}
		count++;
	}
	return res.join("\n");
}
function isFileReadable(filename) {
	if (!tryStatSync(filename)) return false;
	try {
		fs.accessSync(filename, fs.constants.R_OK);
		return true;
	} catch {
		return false;
	}
}
const splitFirstDirRE = /(.+?)[\\/](.+)/;
/**
* Delete every file and subdirectory. **The given directory must exist.**
* Pass an optional `skip` array to preserve files under the root directory.
*/
function emptyDir(dir, skip) {
	const skipInDir = [];
	let nested = null;
	if (skip?.length) for (const file of skip) if (path.dirname(file) !== ".") {
		const matched = splitFirstDirRE.exec(file);
		if (matched) {
			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 fs.readdirSync(dir)) {
		if (skipInDir.includes(file)) continue;
		if (nested?.has(file)) emptyDir(path.resolve(dir, file), nested.get(file));
		else fs.rmSync(path.resolve(dir, file), {
			recursive: true,
			force: true
		});
	}
}
function copyDir(srcDir, destDir) {
	fs.mkdirSync(destDir, { recursive: true });
	for (const file of fs.readdirSync(srcDir)) {
		const srcFile = path.resolve(srcDir, file);
		if (srcFile === destDir) continue;
		const destFile = path.resolve(destDir, file);
		if (fs.statSync(srcFile).isDirectory()) copyDir(srcFile, destFile);
		else fs.copyFileSync(srcFile, destFile);
	}
}
const ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
async function recursiveReaddir(dir) {
	if (!fs.existsSync(dir)) return [];
	let dirents;
	try {
		dirents = await fsp.readdir(dir, { withFileTypes: true });
	} catch (e) {
		if (e.code === "EACCES") return [];
		throw e;
	}
	if (dirents.some((dirent) => dirent.isSymbolicLink())) {
		const err = /* @__PURE__ */ new Error("Symbolic links are not supported in recursiveReaddir");
		err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
		throw err;
	}
	return (await Promise.all(dirents.map((dirent) => {
		const res = path.resolve(dir, dirent.name);
		return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath(res);
	}))).flat(1);
}
let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs.realpathSync.native;
const windowsNetworkMap = /* @__PURE__ */ new Map();
function windowsMappedRealpathSync(path) {
	const realPath = fs.realpathSync.native(path);
	if (realPath.startsWith("\\\\")) {
		for (const [network, volume] of windowsNetworkMap) if (realPath.startsWith(network)) return realPath.replace(network, volume);
	}
	return realPath;
}
const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
let firstSafeRealPathSyncRun = false;
function windowsSafeRealPathSync(path) {
	if (!firstSafeRealPathSyncRun) {
		optimizeSafeRealPathSync();
		firstSafeRealPathSyncRun = true;
	}
	return fs.realpathSync(path);
}
function optimizeSafeRealPathSync() {
	try {
		fs.realpathSync.native(path.resolve("./"));
	} catch (error) {
		if (error.message.includes("EISDIR: illegal operation on a directory")) {
			safeRealpathSync = fs.realpathSync;
			return;
		}
	}
	exec("net use", { windowsHide: true }, (error, stdout) => {
		if (error) return;
		const lines = stdout.split("\n");
		for (const line of lines) {
			const m = parseNetUseRE.exec(line);
			if (m) windowsNetworkMap.set(m[2], m[1]);
		}
		if (windowsNetworkMap.size === 0) safeRealpathSync = fs.realpathSync.native;
		else safeRealpathSync = windowsMappedRealpathSync;
	});
}
function ensureWatchedFile(watcher, file, root) {
	if (file && !file.startsWith(withTrailingSlash(root)) && !file.includes("\0") && fs.existsSync(file)) watcher.add(path.resolve(file));
}
function joinSrcset(ret) {
	return ret.map(({ url, descriptor }) => url + (descriptor ? ` ${descriptor}` : "")).join(", ");
}
/**
This regex represents a loose rule of an “image candidate string” and "image set options".

@see https://html.spec.whatwg.org/multipage/images.html#srcset-attribute
@see https://drafts.csswg.org/css-images-4/#image-set-notation

The Regex has named capturing groups `url` and `descriptor`.
The `url` group can be:
* any CSS function
* CSS string (single or double-quoted)
* URL string (unquoted)
The `descriptor` is anything after the space and before the comma.
*/
const imageCandidateRegex = /(?:^|\s|(?<=,))(?<url>[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?<descriptor>\w[^,]+))?(?:,|$)/g;
const escapedSpaceCharacters = /(?: |\\t|\\n|\\f|\\r)+/g;
function parseSrcset(string) {
	const matches = string.trim().replace(escapedSpaceCharacters, " ").replace(/\r?\n/, "").replace(/,\s+/, ", ").replaceAll(/\s+/g, " ").matchAll(imageCandidateRegex);
	return Array.from(matches, ({ groups }) => ({
		url: groups?.url?.trim() ?? "",
		descriptor: groups?.descriptor?.trim() ?? ""
	})).filter(({ url }) => !!url);
}
function processSrcSet(srcs, replacer) {
	return Promise.all(parseSrcset(srcs).map(async ({ url, descriptor }) => ({
		url: await replacer({
			url,
			descriptor
		}),
		descriptor
	}))).then(joinSrcset);
}
function processSrcSetSync(srcs, replacer) {
	return joinSrcset(parseSrcset(srcs).map(({ url, descriptor }) => ({
		url: replacer({
			url,
			descriptor
		}),
		descriptor
	})));
}
const windowsDriveRE$1 = /^[A-Z]:/;
const replaceWindowsDriveRE = /^([A-Z]):\//;
const linuxAbsolutePathRE = /^\/[^/]/;
function escapeToLinuxLikePath(path) {
	if (windowsDriveRE$1.test(path)) return path.replace(replaceWindowsDriveRE, "/windows/$1/");
	if (linuxAbsolutePathRE.test(path)) return `/linux${path}`;
	return path;
}
const revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
function unescapeToLinuxLikePath(path) {
	if (path.startsWith("/linux/")) return path.slice(6);
	if (path.startsWith("/windows/")) return path.replace(revertWindowsDriveRE, "$1:/");
	return path;
}
const nullSourceMap = {
	names: [],
	sources: [],
	mappings: "",
	version: 3
};
/**
* Combines multiple sourcemaps into a single sourcemap.
* Note that the length of sourcemapList must be 2.
*/
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;
	});
	const escapedFilename = escapeToLinuxLikePath(filename);
	let map;
	let mapIndex = 1;
	if (sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0) map = remapping(sourcemapList, () => null);
	else map = remapping(sourcemapList[0], function loader(sourcefile) {
		if (sourcefile === escapedFilename && sourcemapList[mapIndex]) return sourcemapList[mapIndex++];
		else return null;
	});
	if (!map.file) delete map.file;
	map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
	map.file = filename;
	return map;
}
function unique(arr) {
	return Array.from(new Set(arr));
}
/**
* Returns resolved localhost address when `dns.lookup` result differs from DNS
*
* `dns.lookup` result is same when defaultResultOrder is `verbatim`.
* Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same.
* For example, when IPv6 is not supported on that machine/network.
*/
function getLocalhostAddressIfDiffersFromDNS() {
	if (promises.getDefaultResultOrder && promises.getDefaultResultOrder() === "verbatim") return;
	return Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]).then(([nodeResult, dnsResult]) => {
		return nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address ? 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 name = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
	if (host === "localhost") {
		const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
		if (localhostAddr) name = localhostAddr;
	}
	return {
		host,
		name
	};
}
function extractHostnamesFromCerts(certs) {
	const certList = certs ? arraify(certs) : [];
	if (certList.length === 0) return [];
	return unique(certList.map((cert) => {
		try {
			return new crypto.X509Certificate(cert);
		} catch {
			return null;
		}
	}).flatMap((cert) => cert?.subjectAltName ? extractHostnamesFromSubjectAltName(cert.subjectAltName) : []));
}
function resolveServerUrls(server, options, hostname, httpsOptions, config) {
	const address = server.address();
	const isAddressInfo = (x) => x?.address;
	if (!isAddressInfo(address)) return {
		local: [],
		network: []
	};
	const local = [];
	const network = [];
	const protocol = options.https ? "https" : "http";
	const port = address.port;
	const base = config.rawBase === "./" || config.rawBase === "" ? "/" : config.rawBase;
	if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
		let hostnameName = hostname.name;
		if (hostnameName.includes(":")) hostnameName = `[${hostnameName}]`;
		const address = `${protocol}://${hostnameName}:${port}${base}`;
		if (loopbackHosts.has(hostname.host)) local.push(address);
		else network.push(address);
	} else Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter((detail) => detail.address && detail.family === "IPv4").forEach((detail) => {
		let host = detail.address.replace("127.0.0.1", hostname.name);
		if (host.includes(":")) host = `[${host}]`;
		const url = `${protocol}://${host}:${port}${base}`;
		if (detail.address.includes("127.0.0.1")) local.push(url);
		else network.push(url);
	});
	const hostnamesFromCert = extractHostnamesFromCerts(httpsOptions?.cert);
	if (hostnamesFromCert.length > 0) {
		const existings = /* @__PURE__ */ new Set([...local, ...network]);
		local.push(...hostnamesFromCert.map((hostname) => `${protocol}://${hostname}:${port}${base}`).filter((url) => !existings.has(url)));
	}
	return {
		local,
		network
	};
}
function extractHostnamesFromSubjectAltName(subjectAltName) {
	const hostnames = [];
	let remaining = subjectAltName;
	while (remaining) {
		const nameEndIndex = remaining.indexOf(":");
		const name = remaining.slice(0, nameEndIndex);
		remaining = remaining.slice(nameEndIndex + 1);
		if (!remaining) break;
		const isQuoted = remaining[0] === "\"";
		let value;
		if (isQuoted) {
			const endQuoteIndex = remaining.indexOf("\"", 1);
			value = JSON.parse(remaining.slice(0, endQuoteIndex + 1));
			remaining = remaining.slice(endQuoteIndex + 1);
		} else {
			const maybeEndIndex = remaining.indexOf(",");
			const endIndex = maybeEndIndex === -1 ? remaining.length : maybeEndIndex;
			value = remaining.slice(0, endIndex);
			remaining = remaining.slice(endIndex);
		}
		remaining = remaining.slice(1).trimStart();
		if (name === "DNS" && value !== "[::1]" && !(value.startsWith("*.") && net.isIPv4(value.slice(2)))) hostnames.push(value.replace("*", "vite"));
	}
	return hostnames;
}
function arraify(target) {
	return Array.isArray(target) ? target : [target];
}
const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
const singlelineCommentsRE = /\/\/.*/g;
const requestQuerySplitRE = /\?(?!.*[/|}])/;
const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
const blankReplacer = (match) => " ".repeat(match.length);
function getHash(text, length = 8) {
	const h = crypto.hash("sha256", text, "hex").substring(0, length);
	if (length <= 64) return h;
	return h.padEnd(length, "_");
}
function emptyCssComments(raw) {
	return raw.replace(multilineCommentsRE, blankReplacer);
}
function backwardCompatibleWorkerPlugins(plugins) {
	if (Array.isArray(plugins)) return plugins;
	if (typeof plugins === "function") return plugins();
	return [];
}
function deepClone(value) {
	if (Array.isArray(value)) return value.map((v) => deepClone(v));
	if (isObject$1(value)) {
		const cloned = {};
		for (const key in value) cloned[key] = deepClone(value[key]);
		return cloned;
	}
	if (typeof value === "function") return value;
	if (value instanceof RegExp) return new RegExp(value);
	if (typeof value === "object" && value != null) throw new Error("Cannot deep clone non-plain object");
	return value;
}
function mergeWithDefaultsRecursively(defaults, values) {
	const merged = defaults;
	for (const key in values) {
		const value = values[key];
		if (value === void 0) continue;
		const existing = merged[key];
		if (existing === void 0) {
			merged[key] = value;
			continue;
		}
		if (isObject$1(existing) && isObject$1(value)) {
			merged[key] = mergeWithDefaultsRecursively(existing, value);
			continue;
		}
		merged[key] = value;
	}
	return merged;
}
const environmentPathRE = /^environments\.[^.]+$/;
function mergeWithDefaults(defaults, values) {
	return mergeWithDefaultsRecursively(deepClone(defaults), values);
}
const runtimeDeprecatedPath = /* @__PURE__ */ new Set(["optimizeDeps", "ssr.optimizeDeps"]);
const rollupOptionsDeprecationCall = (() => {
	return () => {
		const method = process.env.VITE_DEPRECATION_TRACE ? "trace" : "warn";
		console[method]("`optimizeDeps.rollupOptions` / `ssr.optimizeDeps.rollupOptions` is deprecated. Use `optimizeDeps.rolldownOptions` instead. Note that this option may be set by a plugin. " + (method === "trace" ? "Showing trace because VITE_DEPRECATION_TRACE is set." : "Set VITE_DEPRECATION_TRACE=1 to see where it is called."));
	};
})();
function setupRollupOptionCompat(buildConfig, path) {
	buildConfig.rolldownOptions ??= buildConfig.rollupOptions;
	if (runtimeDeprecatedPath.has(path) && buildConfig.rollupOptions && buildConfig.rolldownOptions !== buildConfig.rollupOptions) rollupOptionsDeprecationCall();
	Object.defineProperty(buildConfig, "rollupOptions", {
		get() {
			return buildConfig.rolldownOptions;
		},
		set(newValue) {
			if (runtimeDeprecatedPath.has(path)) rollupOptionsDeprecationCall();
			buildConfig.rolldownOptions = newValue;
		},
		configurable: true,
		enumerable: true
	});
}
const rollupOptionsRootPaths = /* @__PURE__ */ new Set([
	"build",
	"worker",
	"optimizeDeps",
	"ssr.optimizeDeps"
]);
/**
* Sets up `rollupOptions` compat proxies for an environment.
*/
function setupRollupOptionCompatForEnvironment(environment) {
	if (!isObject$1(environment)) return environment;
	const merged = { ...environment };
	if (isObject$1(merged.build)) setupRollupOptionCompat(merged.build, "build");
	return merged;
}
function hasBothRollupOptionsAndRolldownOptions(options) {
	for (const opt of [
		options.build,
		options.worker,
		options.optimizeDeps,
		options.ssr?.optimizeDeps
	]) if (opt != null && opt.rollupOptions != null && opt.rolldownOptions != null && opt.rollupOptions !== opt.rolldownOptions) return true;
	return false;
}
const wsOptionKeys = [
	"protocol",
	"host",
	"port",
	"clientPort",
	"path",
	"timeout",
	"server"
];
const hmrWsOptionsDeprecationCall = /* @__PURE__ */ (() => {
	let logged = false;
	return () => {
		if (logged) return;
		logged = true;
		const method = process.env.VITE_DEPRECATION_TRACE ? "trace" : "warn";
		console[method]("`server.hmr.protocol/host/port/path/clientPort/timeout/server` is deprecated. Use `server.ws.*` instead. Note that this option may be set by a plugin. " + (method === "trace" ? "Showing trace because VITE_DEPRECATION_TRACE is set." : "Set VITE_DEPRECATION_TRACE=1 to see where it is called."));
	};
})();
function setupHmrWsOptionCompat(serverConfig) {
	if (serverConfig.hmr === false || serverConfig.ws === false) return;
	if (serverConfig.hmr === true) serverConfig.hmr = {};
	const hmrConfig = serverConfig.hmr;
	const wsConfig = serverConfig.ws ? { ...serverConfig.ws } : {};
	if (hmrConfig) {
		for (const key of wsOptionKeys) if (hmrConfig[key] !== void 0) wsConfig[key] ??= hmrConfig[key];
	}
	serverConfig.ws = wsConfig;
	const hmrProxy = hmrConfig || {};
	for (const key of wsOptionKeys) Object.defineProperty(hmrProxy, key, {
		get() {
			return serverConfig.ws?.[key];
		},
		set(newValue) {
			hmrWsOptionsDeprecationCall();
			if (typeof serverConfig.ws === "object") serverConfig.ws[key] = newValue;
		},
		configurable: true,
		enumerable: true
	});
	serverConfig.hmr = hmrProxy;
}
function mergeConfigRecursively(defaults, overrides, rootPath) {
	const merged = { ...defaults };
	if (rollupOptionsRootPaths.has(rootPath)) setupRollupOptionCompat(merged, rootPath);
	if (rootPath === "server") setupHmrWsOptionCompat(merged);
	if (rootPath === "server.hmr") for (const key of wsOptionKeys) Object.defineProperty(merged, key, Object.getOwnPropertyDescriptor(defaults, key));
	for (const key in overrides) {
		const value = overrides[key];
		if (value == null) continue;
		let existing = merged[key];
		if (key === "rollupOptions" && rollupOptionsRootPaths.has(rootPath)) {
			if (overrides.rolldownOptions) continue;
			existing = merged.rolldownOptions;
		}
		if (existing == null) {
			if (rootPath === "" && key === "environments" && isObject$1(value)) {
				const environments = { ...value };
				for (const envName in environments) environments[envName] = setupRollupOptionCompatForEnvironment(environments[envName]);
				merged[key] = environments;
			} else if (rootPath === "environments") merged[key] = setupRollupOptionCompatForEnvironment(value);
			else merged[key] = value;
			continue;
		}
		if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
			merged[key] = mergeAlias(existing, value);
			continue;
		} else if (key === "assetsInclude" && rootPath === "") {
			merged[key] = [].concat(existing, value);
			continue;
		} else if (((key === "noExternal" || key === "external") && (rootPath === "ssr" || rootPath === "resolve") || key === "allowedHosts" && rootPath === "server") && (existing === true || value === true)) {
			merged[key] = true;
			continue;
		} else if (key === "plugins" && rootPath === "worker") {
			merged[key] = () => [...backwardCompatibleWorkerPlugins(existing), ...backwardCompatibleWorkerPlugins(value)];
			continue;
		} else if (key === "server" && (rootPath === "server.hmr" || rootPath === "server.ws")) {
			merged[key] = value;
			continue;
		}
		if (Array.isArray(existing) || Array.isArray(value)) {
			merged[key] = [...arraify(existing), ...arraify(value)];
			continue;
		}
		if (isObject$1(existing) && isObject$1(value)) {
			merged[key] = mergeConfigRecursively(existing, value, rootPath && !environmentPathRE.test(rootPath) ? `${rootPath}.${key}` : key);
			continue;
		}
		merged[key] = value;
	}
	return merged;
}
function mergeConfig(defaults, overrides, isRoot = true) {
	if (typeof defaults === "function" || typeof overrides === "function") throw new Error(`Cannot merge config in form of callback`);
	return mergeConfigRecursively(defaults, 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(o = []) {
	return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map((find) => normalizeSingleAlias({
		find,
		replacement: o[find]
	}));
}
function normalizeSingleAlias({ find, replacement, customResolver }) {
	if (typeof find === "string" && find.endsWith("/") && replacement.endsWith("/")) {
		find = find.slice(0, find.length - 1);
		replacement = replacement.slice(0, replacement.length - 1);
	}
	const alias = {
		find,
		replacement
	};
	if (customResolver) alias.customResolver = customResolver;
	return alias;
}
/**
* Transforms transpiled code result where line numbers aren't altered,
* so we can skip sourcemap generation during dev
*/
function transformStableResult(s, id, config) {
	return {
		code: s.toString(),
		map: config.command === "build" && config.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?.then));
	return arr;
}
function stripBomTag(content) {
	if (content.charCodeAt(0) === 65279) return content.slice(1);
	return content;
}
/**
* Determine if a file is being requested with the correct case, to ensure
* consistent behavior between dev and prod and across operating systems.
*/
function shouldServeFile(filePath, root) {
	if (!isCaseInsensitiveFS) return true;
	return hasCorrectCase(filePath, root);
}
/**
* Note that we can't use realpath here, because we don't want to follow
* symlinks.
*/
function hasCorrectCase(file, assets) {
	if (file === assets) return true;
	const parent = path.dirname(file);
	if (fs.readdirSync(parent).includes(path.basename(file))) return hasCorrectCase(parent, assets);
	return false;
}
function joinUrlSegments(a, b) {
	if (!a || !b) return a || b || "";
	if (a.endsWith("/")) 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(path, base) {
	if (path === base) return "/";
	const devBase = withTrailingSlash(base);
	return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
}
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) {
	return new Function(`
    var console, exports, global, module, process, require
    return (\n${rawValue}\n)
  `)();
}
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];
}
function getPkgName(name) {
	return name[0] === "@" ? name.split("/")[1] : name;
}
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
	return str.replace(escapeRegexRE, "\\$&");
}
function getPackageManagerCommand(type = "install") {
	const packageManager = process.env.npm_config_user_agent?.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(server) {
	return "pluginContainer" in server;
}
function createSerialPromiseQueue() {
	let previousTask;
	return { async run(f) {
		const thisTask = f();
		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 = Math.floor(time / 60);
	const seconds = Math.round(time % 60);
	if (seconds === 60) return `${mins + 1}m`;
	return `${mins}m${seconds < 1 ? "" : ` ${seconds}s`}`;
}
/**
* Encodes the URI path portion (ignores part after ? or #)
*/
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;
}
/**
* Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments
* that can handle un-encoded URIs, where `%` is the only ambiguous character.
*/
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;
}
function decodeURIIfPossible(input) {
	try {
		return decodeURI(input);
	} catch {
		return;
	}
}
const sigtermCallbacks = /* @__PURE__ */ new Set();
const parentSigtermCallback = async (signal, exitCode) => {
	await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)));
};
const setupSIGTERMListener = (callback) => {
	if (sigtermCallbacks.size === 0) {
		process.once("SIGTERM", parentSigtermCallback);
		if (process.env.CI !== "true") process.stdin.on("end", parentSigtermCallback);
	}
	sigtermCallbacks.add(callback);
};
const teardownSIGTERMListener = (callback) => {
	sigtermCallbacks.delete(callback);
	if (sigtermCallbacks.size === 0) {
		process.off("SIGTERM", parentSigtermCallback);
		if (process.env.CI !== "true") process.stdin.off("end", parentSigtermCallback);
	}
};
function getServerUrlByHost(resolvedUrls, host) {
	if (typeof host === "string") {
		const matchedUrl = [...resolvedUrls?.local ?? [], ...resolvedUrls?.network ?? []].find((url) => url.includes(host));
		if (matchedUrl) return matchedUrl;
	}
	return resolvedUrls?.local[0] ?? resolvedUrls?.network[0];
}
let lastDateNow = 0;
/**
* Similar to `Date.now()`, but strictly monotonically increasing.
*
* This function will never return the same value.
* Thus, the value may differ from the actual time.
*
* related: https://github.com/vitejs/vite/issues/19804
*/
function monotonicDateNow() {
	const now = Date.now();
	if (now > lastDateNow) {
		lastDateNow = now;
		return lastDateNow;
	}
	lastDateNow++;
	return lastDateNow;
}
function formatAndTruncateFileList(files) {
	const MAX_LOG_LENGTH = 500;
	let log = "";
	let truncated = false;
	for (let i = 0; i < files.length; i++) {
		const file = files[i];
		if (log === "") log = file;
		else if (log.length + 2 + file.length < MAX_LOG_LENGTH) log += ", " + file;
		else {
			log += ` and ${files.length - i} more`;
			truncated = true;
			break;
		}
	}
	return {
		formatted: log,
		truncated
	};
}
const hashbangRE = /^#!.*\n/;
function getFileStartIndex(code) {
	return hashbangRE.exec(code)?.[0].length ?? 0;
}
//#endregion
//#region src/node/plugin.ts
async function resolveEnvironmentPlugins(environment) {
	const environmentPlugins = [];
	for (const plugin of environment.getTopLevelConfig().plugins) {
		if (plugin.applyToEnvironment) {
			const applied = await plugin.applyToEnvironment(environment);
			if (!applied) continue;
			if (applied !== true) {
				environmentPlugins.push(...(await asyncFlatten(arraify(applied))).filter(Boolean));
				continue;
			}
		}
		environmentPlugins.push(plugin);
	}
	return environmentPlugins;
}
/**
* @experimental
*/
function perEnvironmentPlugin(name, applyToEnvironment) {
	return {
		name,
		applyToEnvironment
	};
}
//#endregion
//#region src/node/plugins/reporter.ts
function buildReporterPlugin(config) {
	return perEnvironmentPlugin("native:reporter", (env) => {
		const tty = process.stdout.isTTY && !process.env.CI;
		const shouldLogInfo = LogLevels[config.logLevel || "info"] >= LogLevels.info;
		const assetsDir = path.join(env.config.build.assetsDir, "/");
		return viteReporterPlugin({
			root: env.config.root,
			isTty: !!tty,
			isLib: !!env.config.build.lib,
			assetsDir,
			chunkLimit: env.config.build.chunkSizeWarningLimit,
			logInfo: shouldLogInfo ? (msg) => env.logger.info(msg) : void 0,
			reportCompressedSize: env.config.build.reportCompressedSize,
			warnLargeChunks: env.config.build.minify && !env.config.build.lib && env.config.consumer === "client"
		});
	});
}
//#endregion
//#region src/node/plugins/esbuild.ts
const debug$14 = createDebugger("vite:esbuild");
const IIFE_BEGIN_RE$1 = /(?:const|var)\s+\S+\s*=\s*\(?function\([^()]*\)\s*\{\s*"use strict";/;
const validExtensionRE$1 = /\.\w+$/;
const defaultEsbuildSupported = {
	"dynamic-import": true,
	"import-meta": true
};
let esbuild;
const importEsbuild$1 = () => {
	esbuild ||= import("esbuild");
	return esbuild;
};
let warnedTransformWithEsbuild = false;
const warnTransformWithEsbuildUsageOnce = () => {
	if (warnedTransformWithEsbuild) return;
	warnedTransformWithEsbuild = true;
	console.warn(import_picocolors.default.yellow("`transformWithEsbuild` is deprecated and will be removed in the future. Please migrate to `transformWithOxc`."));
};
async function transformWithEsbuild(code, filename, options, inMap, config, watcher, ignoreEsbuildWarning = false) {
	let loader = options?.loader;
	if (!loader) {
		const ext = path.extname(validExtensionRE$1.test(filename) ? filename : cleanUrl(filename)).slice(1);
		if (ext === "cjs" || ext === "mjs") loader = "js";
		else if (ext === "cts" || ext === "mts") loader = "ts";
		else loader = ext;
	}
	let tsconfigRaw = options?.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 result = resolveTsconfig(filename, getTSConfigResolutionCache(config));
			if (result) {
				const { tsconfig: loadedTsconfig, tsconfigFilePaths } = result;
				if (watcher && config) for (const tsconfigFile of tsconfigFilePaths) ensureWatchedFile(watcher, tsconfigFile, config.root);
				const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
				for (const field of meaningfulFields) if (field in loadedCompilerOptions) compilerOptionsForFile[field] = loadedCompilerOptions[field];
			}
		}
		const compilerOptions = {
			...compilerOptionsForFile,
			...tsconfigRaw?.compilerOptions
		};
		if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) compilerOptions.useDefineForClassFields = false;
		if (options) {
			if (options.jsx) compilerOptions.jsx = void 0;
			if (options.jsxFactory) compilerOptions.jsxFactory = void 0;
			if (options.jsxFragment) compilerOptions.jsxFragmentFactory = void 0;
			if (options.jsxImportSource) compilerOptions.jsxImportSource = void 0;
		}
		tsconfigRaw = {
			...tsconfigRaw,
			compilerOptions
		};
	}
	const resolvedOptions = {
		sourcemap: true,
		sourcefile: filename,
		...options,
		loader,
		tsconfigRaw
	};
	delete resolvedOptions.include;
	delete resolvedOptions.exclude;
	delete resolvedOptions.jsxInject;
	let transform;
	try {
		transform = (await importEsbuild$1()).transform;
	} catch (e) {
		throw new Error("Failed to load `transformWithEsbuild`. It is deprecated and it now requires esbuild to be installed separately. If you are a package author, please migrate to `transformWithOxc` instead.", { cause: e });
	}
	if (!ignoreEsbuildWarning) warnTransformWithEsbuildUsageOnce();
	try {
		const result = await transform(code, resolvedOptions);
		let map;
		if (inMap && resolvedOptions.sourcemap) {
			const nextMap = JSON.parse(result.map);
			nextMap.sourcesContent = [];
			map = combineSourcemaps(filename, [nextMap, inMap]);
		} else map = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
		return {
			...result,
			map
		};
	} catch (e) {
		debug$14?.(`esbuild error with options used: `, resolvedOptions);
		if (e.errors) {
			e.frame = "";
			e.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.";
				e.frame += `\n` + prettifyMessage(m, code);
			});
			e.loc = e.errors[0].location;
		}
		throw e;
	}
}
const rollupToEsbuildFormatMap = {
	es: "esm",
	cjs: "cjs",
	iife: void 0
};
const injectEsbuildHelpers = (esbuildCode, format) => {
	const contentIndex = format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE$1), 0) : format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
	if (contentIndex > 0) {
		const esbuildHelpers = esbuildCode.slice(0, contentIndex);
		return esbuildCode.slice(contentIndex).replace("\"use strict\";", (m) => m + esbuildHelpers);
	}
	return esbuildCode;
};
const buildEsbuildPlugin = () => {
	return {
		name: "vite:esbuild-transpile",
		applyToEnvironment(environment) {
			return environment.config.esbuild !== false;
		},
		async renderChunk(code, chunk, opts) {
			if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return null;
			const config = this.environment.config;
			const options = resolveEsbuildTranspileOptions(config, opts.format);
			if (!options) return null;
			const res = await transformWithEsbuild(code, chunk.fileName, options, void 0, config, void 0, true);
			if (config.build.lib) res.code = injectEsbuildHelpers(res.code, opts.format);
			return res;
		}
	};
};
function resolveEsbuildTranspileOptions(config, format) {
	const target = config.build.target;
	const minify = config.build.minify === "esbuild";
	if ((!target || target === "esnext") && !minify) return null;
	const isEsLibBuild = config.build.lib && format === "es";
	const esbuildOptions = config.esbuild || {};
	const options = {
		...esbuildOptions,
		loader: "js",
		target: target || void 0,
		format: rollupToEsbuildFormatMap[format],
		supported: {
			...defaultEsbuildSupported,
			...esbuildOptions.supported
		}
	};
	if (!minify) return {
		...options,
		minify: false,
		minifyIdentifiers: false,
		minifySyntax: false,
		minifyWhitespace: false,
		treeShaking: false
	};
	if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) if (isEsLibBuild) return {
		...options,
		minify: false,
		minifyIdentifiers: options.minifyIdentifiers ?? true,
		minifySyntax: options.minifySyntax ?? true,
		minifyWhitespace: false,
		treeShaking: true
	};
	else return {
		...options,
		minify: false,
		minifyIdentifiers: options.minifyIdentifiers ?? true,
		minifySyntax: options.minifySyntax ?? true,
		minifyWhitespace: options.minifyWhitespace ?? true,
		treeShaking: true
	};
	if (isEsLibBuild) return {
		...options,
		minify: false,
		minifyIdentifiers: true,
		minifySyntax: true,
		minifyWhitespace: false,
		treeShaking: true
	};
	else return {
		...options,
		minify: true,
		treeShaking: true
	};
}
function prettifyMessage(m, code) {
	let res = import_picocolors.default.yellow(m.text);
	if (m.location) res += `\n` + generateCodeFrame(code, m.location);
	return res + `\n`;
}
let globalTSConfigResolutionCache;
const tsconfigResolutionCacheMap = /* @__PURE__ */ new WeakMap();
function getTSConfigResolutionCache(config) {
	if (!config) return globalTSConfigResolutionCache ??= new TsconfigCache();
	let cache = tsconfigResolutionCacheMap.get(config);
	if (!cache) {
		cache = new TsconfigCache();
		tsconfigResolutionCacheMap.set(config, cache);
	}
	return cache;
}
function reloadOnTsconfigChange(server, changedFile) {
	if (changedFile.endsWith(".json")) {
		const cache = getTSConfigResolutionCache(server.config);
		if (changedFile.endsWith("/tsconfig.json")) {
			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
			});
			for (const environment of Object.values(server.environments)) environment.moduleGraph.invalidateAll();
			cache.clear();
			for (const environment of Object.values(server.environments)) environment.hot.send({
				type: "full-reload",
				path: "*"
			});
		}
	}
}
//#endregion
//#region ../../node_modules/.pnpm/artichokie@0.4.4/node_modules/artichokie/dist/index.js
const AsyncFunction = async function() {}.constructor;
const codeToDataUrl = (code) => `data:application/javascript,${encodeURIComponent(code + "\n//# sourceURL=[worker-eval(artichokie)]")}`;
const viteSsrDynamicImport = "__vite_ssr_dynamic_import__";
const stackBlitzImport = "𝐢𝐦𝐩𝐨𝐫𝐭";
var Worker$1 = class {
	/** @internal */
	_isModule;
	/** @internal */
	_code;
	/** @internal */
	_parentFunctions;
	/** @internal */
	_max;
	/** @internal */
	_pool;
	/** @internal */
	_idlePool;
	/** @internal */
	_queue;
	constructor(fn, options = {}) {
		this._isModule = options.type === "module";
		this._code = genWorkerCode(fn, this._isModule, 5 * 1e3, options.parentFunctions ?? {});
		this._parentFunctions = options.parentFunctions ?? {};
		const defaultMax = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
		this._max = options.max || defaultMax;
		this._pool = [];
		this._idlePool = [];
		this._queue = [];
	}
	async run(...args) {
		const worker = await this._getAvailableWorker();
		return new Promise((resolve, reject) => {
			worker.currentResolve = resolve;
			worker.currentReject = reject;
			worker.postMessage({ args });
		});
	}
	stop() {
		this._pool.forEach((w) => w.unref());
		this._queue.forEach(([, reject]) => reject(/* @__PURE__ */ new Error("Main worker pool stopped before a worker was available.")));
		this._pool = [];
		this._idlePool = [];
		this._queue = [];
	}
	/** @internal */
	_createWorker(parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState) {
		const options = {
			workerData: [
				parentFunctionSyncMessagePort,
				parentFunctionAsyncMessagePort,
				lockState
			],
			transferList: [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort]
		};
		if (this._isModule) return new Worker(new URL(codeToDataUrl(this._code)), options);
		return new Worker(this._code, {
			...options,
			eval: true
		});
	}
	/** @internal */
	async _getAvailableWorker() {
		if (this._idlePool.length) return this._idlePool.shift();
		if (this._pool.length < this._max) {
			const parentFunctionResponder = createParentFunctionResponder(this._parentFunctions);
			const worker = this._createWorker(parentFunctionResponder.workerPorts.sync, parentFunctionResponder.workerPorts.async, parentFunctionResponder.lockState);
			worker.on("message", async (args) => {
				if ("result" in args) {
					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?.(args.error);
					worker.currentReject = null;
				}
				this._assignDoneWorker(worker);
			});
			worker.on("error", (err) => {
				worker.currentReject?.(err);
				worker.currentReject = null;
				parentFunctionResponder.close();
			});
			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(/* @__PURE__ */ new Error(`Worker stopped with non-0 exit code ${code}`));
					worker.currentReject = null;
					parentFunctionResponder.close();
				}
			});
			this._pool.push(worker);
			return worker;
		}
		let resolve;
		let reject;
		const onWorkerAvailablePromise = new Promise((r, rj) => {
			resolve = r;
			reject = rj;
		});
		this._queue.push([resolve, reject]);
		return onWorkerAvailablePromise;
	}
	/** @internal */
	_assignDoneWorker(worker) {
		if (this._queue.length) {
			const [resolve] = this._queue.shift();
			resolve(worker);
			return;
		}
		this._idlePool.push(worker);
	}
};
function createParentFunctionResponder(parentFunctions) {
	const lockState = new Int32Array(new SharedArrayBuffer(4));
	const unlock = () => {
		Atomics.store(lockState, 0, 0);
		Atomics.notify(lockState, 0);
	};
	const parentFunctionSyncMessageChannel = new MessageChannel();
	const parentFunctionAsyncMessageChannel = new MessageChannel();
	const parentFunctionSyncMessagePort = parentFunctionSyncMessageChannel.port1;
	const parentFunctionAsyncMessagePort = parentFunctionAsyncMessageChannel.port1;
	const syncResponse = (data) => {
		parentFunctionSyncMessagePort.postMessage(data);
		unlock();
	};
	parentFunctionSyncMessagePort.on("message", async (args) => {
		let syncResult;
		try {
			syncResult = parentFunctions[args.name](...args.args);
		} catch (error) {
			syncResponse({
				id: args.id,
				error
			});
			return;
		}
		if (!(typeof syncResult === "object" && syncResult !== null && "then" in syncResult && typeof syncResult.then === "function")) {
			syncResponse({
				id: args.id,
				result: syncResult
			});
			return;
		}
		syncResponse({
			id: args.id,
			isAsync: true
		});
		try {
			const result = await syncResult;
			parentFunctionAsyncMessagePort.postMessage({
				id: args.id,
				result
			});
		} catch (error) {
			parentFunctionAsyncMessagePort.postMessage({
				id: args.id,
				error
			});
		}
	});
	parentFunctionSyncMessagePort.unref();
	return {
		close: () => {
			parentFunctionSyncMessagePort.close();
			parentFunctionAsyncMessagePort.close();
		},
		lockState,
		workerPorts: {
			sync: parentFunctionSyncMessageChannel.port2,
			async: parentFunctionAsyncMessageChannel.port2
		}
	};
}
function genWorkerCode(fn, isModule, waitTimeout, parentFunctions) {
	const createLock = (performance, lockState) => {
		return {
			lock: () => {
				Atomics.store(lockState, 0, 1);
			},
			waitUnlock: () => {
				let utilizationBefore;
				while (true) {
					const status = Atomics.wait(lockState, 0, 1, waitTimeout);
					if (status === "timed-out") {
						if (utilizationBefore === void 0) {
							utilizationBefore = performance.eventLoopUtilization();
							continue;
						}
						utilizationBefore = performance.eventLoopUtilization(utilizationBefore);
						if (utilizationBefore.utilization > .9) continue;
						throw new Error(status);
					}
					break;
				}
			}
		};
	};
	const createParentFunctionRequester = (syncPort, asyncPort, receive, lock) => {
		let id = 0;
		const resolvers = /* @__PURE__ */ new Map();
		const call = (key) => (...args) => {
			id++;
			lock.lock();
			syncPort.postMessage({
				id,
				name: key,
				args
			});
			lock.waitUnlock();
			let received;
			for (let i = 0; i < 10; i++) {
				received = receive(syncPort);
				if (received !== void 0) break;
			}
			if (received === void 0) throw new Error("Failed to receive message from sync port after 10 attempts");
			const resArgs = received.message;
			if (resArgs.isAsync) {
				let resolve, reject;
				const promise = new Promise((res, rej) => {
					resolve = res;
					reject = rej;
				});
				resolvers.set(id, {
					resolve,
					reject
				});
				return promise;
			}
			if ("error" in resArgs) throw resArgs.error;
			else return resArgs.result;
		};
		asyncPort.on("message", (args) => {
			const id = args.id;
			if (resolvers.has(id)) {
				const { resolve, reject } = resolvers.get(id);
				resolvers.delete(id);
				if ("result" in args) resolve(args.result);
				else reject(args.error);
			}
		});
		return { call };
	};
	const fnString = fn.toString().replaceAll(stackBlitzImport, "import").replaceAll(viteSsrDynamicImport, "import");
	return `
${isModule ? "import { parentPort, receiveMessageOnPort, workerData } from 'worker_threads'" : "const { parentPort, receiveMessageOnPort, workerData } = require('worker_threads')"}
${isModule ? "import { performance } from 'node:perf_hooks'" : "const { performance } = require('node:perf_hooks')"}
const [parentFunctionSyncMessagePort, parentFunctionAsyncMessagePort, lockState] = workerData
const waitTimeout = ${waitTimeout}
const createLock = ${createLock.toString()}
const parentFunctionRequester = (${createParentFunctionRequester.toString()})(
  parentFunctionSyncMessagePort,
  parentFunctionAsyncMessagePort,
  receiveMessageOnPort,
  createLock(performance, lockState)
)

const doWorkPromise = (async () => {
  ${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctionRequester.call(${JSON.stringify(key)});`).join("\n")}
  return await (${fnString})()
})()
let doWork

parentPort.on('message', async (args) => {
  doWork ||= await doWorkPromise

  try {
    const res = await doWork(...args.args)
    parentPort.postMessage({ result: res })
  } catch (e) {
    parentPort.postMessage({ error: e })
  }
})
  `;
}
const importRe = /\bimport\s*\(/g;
const internalImportName = "__artichokie_local_import__";
var FakeWorker = class {
	/** @internal */
	_fn;
	constructor(fn, options = {}) {
		const declareRequire = options.type !== "module";
		const argsAndCode = genFakeWorkerArgsAndCode(fn, declareRequire, options.parentFunctions ?? {});
		const localImport = (specifier) => import(specifier);
		const args = [
			...declareRequire ? [createRequire(import.meta.url)] : [],
			localImport,
			options.parentFunctions
		];
		this._fn = new AsyncFunction(...argsAndCode)(...args);
	}
	async run(...args) {
		try {
			return await (await this._fn)(...args);
		} catch (err) {
			if (err instanceof ReferenceError) err.message += ". Maybe you forgot to pass the function to parentFunction?";
			throw err;
		}
	}
	stop() {}
};
function genFakeWorkerArgsAndCode(fn, declareRequire, parentFunctions) {
	const fnString = fn.toString().replace(importRe, `${internalImportName}(`).replaceAll(stackBlitzImport, internalImportName).replaceAll(viteSsrDynamicImport, internalImportName);
	return [
		...declareRequire ? ["require"] : [],
		internalImportName,
		"parentFunctions",
		`
${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
return await (${fnString})()
  `
	];
}
var WorkerWithFallback = class {
	/** @internal */
	_disableReal;
	/** @internal */
	_realWorker;
	/** @internal */
	_fakeWorker;
	/** @internal */
	_shouldUseFake;
	constructor(fn, options) {
		this._disableReal = options.max !== void 0 && options.max <= 0;
		this._realWorker = new Worker$1(fn, options);
		this._fakeWorker = new FakeWorker(fn, options);
		this._shouldUseFake = options.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();
	}
};
//#endregion
//#region ../../node_modules/.pnpm/resolve.exports@2.0.3/node_modules/resolve.exports/dist/index.mjs
function e(e, n, r) {
	throw new Error(r ? `No known conditions for "${n}" specifier in "${e}" package` : `Missing "${n}" specifier in "${e}" package`);
}
function n$1(n, i, o, f) {
	let s, u, l = r(n, o), c = function(e) {
		let n = /* @__PURE__ */ new Set(["default", ...e.conditions || []]);
		return e.unsafe || n.add(e.require ? "require" : "import"), e.unsafe || n.add(e.browser ? "browser" : "node"), n;
	}(f || {}), a = i[l];
	if (void 0 === a) {
		let e, n, r, t;
		for (t in i) n && t.length < n.length || ("/" === t[t.length - 1] && l.startsWith(t) ? (u = l.substring(t.length), n = t) : t.length > 1 && (r = t.indexOf("*", 1), ~r && (e = RegExp("^" + t.substring(0, r) + "(.*)" + t.substring(1 + r) + "$").exec(l), e && e[1] && (u = e[1], n = t))));
		a = i[n];
	}
	return a || e(n, l), s = t(a, c), s || e(n, l, 1), u && function(e, n) {
		let r, t = 0, i = e.length, o = /[*]/g, f = /[/]$/;
		for (; t < i; t++) e[t] = o.test(r = e[t]) ? r.replace(o, n) : f.test(r) ? r + n : r;
	}(s, u), s;
}
function r(e, n, r) {
	if (e === n || "." === n) return ".";
	let t = e + "/", i = t.length, o = n.slice(0, i) === t, f = o ? n.slice(i) : n;
	return "#" === f[0] ? f : o || !r ? "./" === f.slice(0, 2) ? f : "./" + f : f;
}
function t(e, n, r) {
	if (e) {
		if ("string" == typeof e) return r && r.add(e), [e];
		let i, o;
		if (Array.isArray(e)) {
			for (o = r || /* @__PURE__ */ new Set(), i = 0; i < e.length; i++) t(e[i], n, o);
			if (!r && o.size) return [...o];
		} else for (i in e) if (n.has(i)) return t(e[i], n, r);
	}
}
function o(e, r, t) {
	let i, o = e.exports;
	if (o) {
		if ("string" == typeof o) o = { ".": o };
		else for (i in o) {
			"." !== i[0] && (o = { ".": o });
			break;
		}
		return n$1(e.name, o, r || ".", t);
	}
}
function f(e, r, t) {
	if (e.imports) return n$1(e.name, e.imports, r, t);
}
(function(A) {
	return A[A.Static = 1] = "Static", A[A.Dynamic = 2] = "Dynamic", A[A.ImportMeta = 3] = "ImportMeta", A[A.StaticSourcePhase = 4] = "StaticSourcePhase", A[A.DynamicSourcePhase = 5] = "DynamicSourcePhase", A[A.StaticDeferPhase = 6] = "StaticDeferPhase", A[A.DynamicDeferPhase = 7] = "DynamicDeferPhase", A;
})({});
const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
function parse$2(g, C = "@") {
	if (!E) return init.then(() => parse$2(g));
	const I = g.length + 1, w = (E.__heap_base.value || E.__heap_base) + 4 * I - E.memory.buffer.byteLength;
	w > 0 && E.memory.grow(Math.ceil(w / 65536));
	const D = E.sa(I - 1);
	if ((A ? B : Q)(g, new Uint16Array(E.memory.buffer, D, I)), !E.parse()) throw Object.assign(/* @__PURE__ */ new Error(`Parse error ${C}:${g.slice(0, E.e()).split("\n").length}:${E.e() - g.lastIndexOf("\n", E.e() - 1)}`), { idx: E.e() });
	const o = [], i = [];
	for (; E.ri();) {
		const A = E.is(), Q = E.ie(), B = E.it(), C = E.ai(), I = E.id(), w = E.ss(), D = E.se();
		let i;
		E.ip() && (i = G(g.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q)));
		let k = null;
		for (k = [], E.rsa(); E.ra();) {
			const A = E.aks(), Q = E.ake(), B = E.avs(), C = E.ave();
			k.push([J(g.slice(A, Q)), J(g.slice(B, C))]);
		}
		0 === k.length && (k = null), o.push({
			n: i,
			t: B,
			s: A,
			e: Q,
			ss: w,
			se: D,
			d: I,
			a: C,
			at: k
		});
	}
	for (; E.re();) {
		const A = E.es(), Q = E.ee(), B = E.els(), C = E.ele(), I = B < 0 ? void 0 : J(g.slice(B, C)), w = J(g.slice(A, Q));
		i.push({
			s: A,
			e: Q,
			ls: B,
			le: C,
			ss: E.ess(),
			n: w,
			ln: I
		});
	}
	function G(A) {
		try {
			return (0, eval)(A);
		} catch (A) {}
	}
	function J(A) {
		if (!A) return A;
		const Q = A[0];
		return ("\"" === Q || "'" === Q) && G(A) || A;
	}
	return [
		o,
		i,
		!!E.f(),
		!!E.ms()
	];
}
function Q(A, Q) {
	const B = A.length;
	let E = 0;
	for (; E < B;) {
		const B = A.charCodeAt(E);
		Q[E++] = (255 & B) << 8 | B >>> 8;
	}
}
function B(A, Q) {
	const B = A.length;
	let E = 0;
	for (; E < B;) Q[E] = A.charCodeAt(E++);
}
let E;
const g = () => {
	return A = " ", "undefined" != typeof Buffer ? Buffer.from(A, "base64") : Uint8Array.from(atob(A), (A) => A.charCodeAt(0));
	var A;
};
const init = WebAssembly.compile(g()).then(WebAssembly.instantiate).then(({ exports: A }) => {
	E = A;
});
//#endregion
//#region src/node/plugins/oxc.ts
const IIFE_BEGIN_RE = /(?:(?:(?:const|var)\s+[^.\s]+|[^.\s]+\.[^.\s]+\.[^.\s]+)\s*=\s*|^|\n)\(?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
const UMD_BEGIN_RE = /\}\)\((?:this,\s*)?function\([^()]*\)\s*\{(?:\s*"use strict";)?/;
const jsxExtensionsRE = /\.(?:j|t)sx\b/;
const validExtensionRE = /\.\w+$/;
function getRollupJsxPresets(preset) {
	switch (preset) {
		case "react": return {
			runtime: "classic",
			pragma: "React.createElement",
			pragmaFrag: "React.Fragment",
			importSource: "react"
		};
		case "react-jsx": return {
			runtime: "automatic",
			pragma: "React.createElement",
			importSource: "react"
		};
	}
}
function joinNewLine(s1, s2) {
	return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
}
function getErrorMessage(e) {
	if (Object.hasOwn(e, "kind")) return e.message;
	let s = "";
	if (e.plugin) s += `[plugin ${e.plugin}]`;
	const id = e.id ?? e.loc?.file;
	if (id) {
		s += " " + id;
		if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
	}
	if (s) s += "\n";
	const message = `${e.name ?? "Error"}: ${e.message}`;
	s += message;
	if (e.frame) s = joinNewLine(s, e.frame);
	if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
	if (e.cause) {
		s = joinNewLine(s, "Caused by:");
		s = joinNewLine(s, getErrorMessage(e.cause).split("\n").map((line) => "  " + line).join("\n"));
	}
	return s;
}
async function transformWithOxc(code, filename, options, inMap, config, watcher) {
	let lang = options?.lang;
	if (!lang) {
		const ext = path.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
		if (ext === "cjs" || ext === "mjs") lang = "js";
		else if (ext === "cts" || ext === "mts") lang = "ts";
		else lang = ext;
	}
	const result = transformSync(filename, code, {
		sourcemap: true,
		...options,
		inputMap: inMap,
		lang
	}, getTSConfigResolutionCache(config));
	if (watcher && config && result.tsconfigFilePaths && result.tsconfigFilePaths.length > 0) for (const tsconfigFile of result.tsconfigFilePaths) ensureWatchedFile(watcher, normalizePath(tsconfigFile), config.root);
	if (result.errors.length > 0) {
		let summary = `Transform failed with ${result.errors.length} error${result.errors.length < 2 ? "" : "s"}:\n`;
		for (let i = 0; i < result.errors.length; i++) {
			summary += "\n";
			if (i >= 5) {
				summary += "...";
				break;
			}
			summary += getErrorMessage(result.errors[i]);
		}
		const wrapper = new Error(summary);
		Object.defineProperty(wrapper, "errors", {
			configurable: true,
			enumerable: true,
			get: () => result.errors,
			set: (value) => Object.defineProperty(wrapper, "errors", {
				configurable: true,
				enumerable: true,
				value
			})
		});
		throw wrapper;
	}
	return result;
}
const warnedMessages = /* @__PURE__ */ new Set();
function shouldSkipWarning(warning) {
	if (warning.code === "UNSUPPORTED_TSCONFIG_OPTION") {
		if (warnedMessages.has(warning.message)) return true;
		warnedMessages.add(warning.message);
	}
	return false;
}
function oxcPlugin(config) {
	const { jsxInject, include, exclude, jsxRefreshInclude, jsxRefreshExclude, ...oxcTransformOptions } = config.oxc;
	const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
	const jsxRefreshFilter = jsxRefreshInclude || jsxRefreshExclude ? createFilter$1(jsxRefreshInclude, jsxRefreshExclude) : void 0;
	const jsxImportSource = typeof oxcTransformOptions.jsx === "object" && oxcTransformOptions.jsx.importSource || "react";
	const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
	const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
	const getModifiedOxcTransformOptions = (oxcTransformOptions, id, code, environment) => {
		const result = {
			...oxcTransformOptions,
			sourcemap: environment.mode !== "build" || !!environment.config.build.sourcemap
		};
		const jsxOptions = result.jsx;
		const [filepath] = id.split("?");
		const isJSX = filepath.endsWith("x");
		if (typeof jsxOptions === "object" && jsxOptions.refresh && (environment.config.consumer === "server" || jsxRefreshFilter && !jsxRefreshFilter(id) || !(isJSX || code.includes(jsxImportRuntime) || code.includes(jsxImportDevRuntime)))) result.jsx = {
			...jsxOptions,
			refresh: false
		};
		if (jsxRefreshFilter?.(id) && !JS_TYPES_RE.test(cleanUrl(id))) result.lang = "js";
		return result;
	};
	let server;
	return {
		name: "vite:oxc",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) {
				const { jsxInject, include = /\.(m?ts|[jt]sx)$/, exclude = /\.js$/, jsxRefreshInclude, jsxRefreshExclude, ..._transformOptions } = environment.config.oxc;
				const transformOptions = _transformOptions;
				transformOptions.sourcemap = environment.config.mode !== "build" || !!environment.config.build.sourcemap;
				return viteTransformPlugin({
					root: environment.config.root,
					include,
					exclude,
					jsxRefreshInclude,
					jsxRefreshExclude,
					isServerConsumer: environment.config.consumer === "server",
					jsxInject,
					transformOptions
				});
			}
			return true;
		},
		configureServer(_server) {
			server = _server;
		},
		async transform(code, id) {
			if (filter(id) || filter(cleanUrl(id)) || jsxRefreshFilter?.(id)) {
				const result = await transformWithOxc(code, id, getModifiedOxcTransformOptions(oxcTransformOptions, id, code, this.environment), void 0, config, server?.watcher);
				if (jsxInject && jsxExtensionsRE.test(id)) result.code = jsxInject + ";" + result.code;
				for (const warning of result.warnings) if (!shouldSkipWarning(warning)) this.warn(warning);
				return {
					code: result.code,
					map: result.map,
					moduleType: "js"
				};
			}
		}
	};
}
function convertEsbuildConfigToOxcConfig(esbuildConfig, logger) {
	const { jsxInject, include, exclude, ...esbuildTransformOptions } = esbuildConfig;
	const oxcOptions = {
		jsxInject,
		include,
		exclude
	};
	if (esbuildTransformOptions.jsx === "preserve") oxcOptions.jsx = "preserve";
	else {
		const jsxOptions = {};
		switch (esbuildTransformOptions.jsx) {
			case "automatic":
				jsxOptions.runtime = "automatic";
				if (esbuildTransformOptions.jsxImportSource) jsxOptions.importSource = esbuildTransformOptions.jsxImportSource;
				break;
			case "transform":
				jsxOptions.runtime = "classic";
				if (esbuildTransformOptions.jsxFactory) jsxOptions.pragma = esbuildTransformOptions.jsxFactory;
				if (esbuildTransformOptions.jsxFragment) jsxOptions.pragmaFrag = esbuildTransformOptions.jsxFragment;
				break;
			default: break;
		}
		if (esbuildTransformOptions.jsxDev !== void 0) jsxOptions.development = esbuildTransformOptions.jsxDev;
		if (esbuildTransformOptions.jsxSideEffects !== void 0) jsxOptions.pure = !esbuildTransformOptions.jsxSideEffects;
		oxcOptions.jsx = jsxOptions;
	}
	if (esbuildTransformOptions.define) oxcOptions.define = esbuildTransformOptions.define;
	if (esbuildTransformOptions.banner) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "banner");
	if (esbuildTransformOptions.footer) warnDeprecatedShouldBeConvertedToPluginOptions(logger, "footer");
	return oxcOptions;
}
function warnDeprecatedShouldBeConvertedToPluginOptions(logger, name) {
	logger.warn(import_picocolors.default.yellow(`\`esbuild.${name}\` option was specified. But this option is deprecated and will be removed in future versions. This option can be achieved by using a plugin with transform hook, please use that instead.`));
}
//#endregion
//#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
var BitSet = class BitSet {
	constructor(arg) {
		this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
	}
	add(n) {
		this.bits[n >> 5] |= 1 << (n & 31);
	}
	has(n) {
		return !!(this.bits[n >> 5] & 1 << (n & 31));
	}
};
var Chunk = class Chunk {
	constructor(start, end, content) {
		this.start = start;
		this.end = end;
		this.original = content;
		this.intro = "";
		this.outro = "";
		this.content = content;
		this.storeName = false;
		this.edited = false;
		this.previous = null;
		this.next = null;
	}
	appendLeft(content) {
		this.outro += content;
	}
	appendRight(content) {
		this.intro = this.intro + content;
	}
	clone() {
		const chunk = new Chunk(this.start, this.end, this.original);
		chunk.intro = this.intro;
		chunk.outro = this.outro;
		chunk.content = this.content;
		chunk.storeName = this.storeName;
		chunk.edited = this.edited;
		return chunk;
	}
	contains(index) {
		return this.start < index && index < this.end;
	}
	eachNext(fn) {
		let chunk = this;
		while (chunk) {
			fn(chunk);
			chunk = chunk.next;
		}
	}
	eachPrevious(fn) {
		let chunk = this;
		while (chunk) {
			fn(chunk);
			chunk = chunk.previous;
		}
	}
	edit(content, storeName, contentOnly) {
		this.content = content;
		if (!contentOnly) {
			this.intro = "";
			this.outro = "";
		}
		this.storeName = storeName;
		this.edited = true;
		return this;
	}
	prependLeft(content) {
		this.outro = content + this.outro;
	}
	prependRight(content) {
		this.intro = content + this.intro;
	}
	reset() {
		this.intro = "";
		this.outro = "";
		if (this.edited) {
			this.content = this.original;
			this.storeName = false;
			this.edited = false;
		}
	}
	split(index) {
		const sliceIndex = index - this.start;
		const originalBefore = this.original.slice(0, sliceIndex);
		const originalAfter = this.original.slice(sliceIndex);
		this.original = originalBefore;
		const newChunk = new Chunk(index, this.end, originalAfter);
		newChunk.outro = this.outro;
		this.outro = "";
		this.end = index;
		if (this.edited) {
			newChunk.edit("", false);
			this.content = "";
		} else this.content = originalBefore;
		newChunk.next = this.next;
		if (newChunk.next) newChunk.next.previous = newChunk;
		newChunk.previous = this;
		this.next = newChunk;
		return newChunk;
	}
	toString() {
		return this.intro + this.content + this.outro;
	}
	trimEnd(rx) {
		this.outro = this.outro.replace(rx, "");
		if (this.outro.length) return true;
		const trimmed = this.content.replace(rx, "");
		if (trimmed.length) {
			if (trimmed !== this.content) {
				this.split(this.start + trimmed.length).edit("", void 0, true);
				if (this.edited) this.edit(trimmed, this.storeName, true);
			}
			return true;
		} else {
			this.edit("", void 0, true);
			this.intro = this.intro.replace(rx, "");
			if (this.intro.length) return true;
		}
	}
	trimStart(rx) {
		this.intro = this.intro.replace(rx, "");
		if (this.intro.length) return true;
		const trimmed = this.content.replace(rx, "");
		if (trimmed.length) {
			if (trimmed !== this.content) {
				const newChunk = this.split(this.end - trimmed.length);
				if (this.edited) newChunk.edit(trimmed, this.storeName, true);
				this.edit("", void 0, true);
			}
			return true;
		} else {
			this.edit("", void 0, true);
			this.outro = this.outro.replace(rx, "");
			if (this.outro.length) return true;
		}
	}
};
function getBtoa() {
	if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
	else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
	else return () => {
		throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
	};
}
const btoa$1 = /*#__PURE__*/ getBtoa();
var SourceMap = class {
	constructor(properties) {
		this.version = 3;
		this.file = properties.file;
		this.sources = properties.sources;
		this.sourcesContent = properties.sourcesContent;
		this.names = properties.names;
		this.mappings = encode$1(properties.mappings);
		if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
		if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
	}
	toString() {
		return JSON.stringify(this);
	}
	toUrl() {
		return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
	}
};
function guessIndent(code) {
	const lines = code.split("\n");
	const tabbed = lines.filter((line) => /^\t+/.test(line));
	const spaced = lines.filter((line) => /^ {2,}/.test(line));
	if (tabbed.length === 0 && spaced.length === 0) return null;
	if (tabbed.length >= spaced.length) return "	";
	const min = spaced.reduce((previous, current) => {
		const numSpaces = /^ +/.exec(current)[0].length;
		return Math.min(numSpaces, previous);
	}, Infinity);
	return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
	const fromParts = from.split(/[/\\]/);
	const toParts = to.split(/[/\\]/);
	fromParts.pop();
	while (fromParts[0] === toParts[0]) {
		fromParts.shift();
		toParts.shift();
	}
	if (fromParts.length) {
		let i = fromParts.length;
		while (i--) fromParts[i] = "..";
	}
	return fromParts.concat(toParts).join("/");
}
const toString = Object.prototype.toString;
function isObject(thing) {
	return toString.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;
		return {
			line,
			column: index - lineOffsets[line]
		};
	};
}
const wordRegex = /\w/;
var Mappings = class {
	constructor(hires) {
		this.hires = hires;
		this.generatedCodeLine = 0;
		this.generatedCodeColumn = 0;
		this.raw = [];
		this.rawSegments = this.raw[this.generatedCodeLine] = [];
		this.pending = null;
	}
	addEdit(sourceIndex, content, loc, nameIndex) {
		if (content.length) {
			const contentLengthMinusOne = content.length - 1;
			let contentLineEnd = content.indexOf("\n", 0);
			let previousContentLineEnd = -1;
			while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
				const segment = [
					this.generatedCodeColumn,
					sourceIndex,
					loc.line,
					loc.column
				];
				if (nameIndex >= 0) segment.push(nameIndex);
				this.rawSegments.push(segment);
				this.generatedCodeLine += 1;
				this.raw[this.generatedCodeLine] = this.rawSegments = [];
				this.generatedCodeColumn = 0;
				previousContentLineEnd = contentLineEnd;
				contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
			}
			const segment = [
				this.generatedCodeColumn,
				sourceIndex,
				loc.line,
				loc.column
			];
			if (nameIndex >= 0) segment.push(nameIndex);
			this.rawSegments.push(segment);
			this.advance(content.slice(previousContentLineEnd + 1));
		} else if (this.pending) {
			this.rawSegments.push(this.pending);
			this.advance(content);
		}
		this.pending = null;
	}
	addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
		let originalCharIndex = chunk.start;
		let first = true;
		let charInHiresBoundary = false;
		while (originalCharIndex < chunk.end) {
			if (original[originalCharIndex] === "\n") {
				loc.line += 1;
				loc.column = 0;
				this.generatedCodeLine += 1;
				this.raw[this.generatedCodeLine] = this.rawSegments = [];
				this.generatedCodeColumn = 0;
				first = true;
				charInHiresBoundary = false;
			} else {
				if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
					const segment = [
						this.generatedCodeColumn,
						sourceIndex,
						loc.line,
						loc.column
					];
					if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
						if (!charInHiresBoundary) {
							this.rawSegments.push(segment);
							charInHiresBoundary = true;
						}
					} else {
						this.rawSegments.push(segment);
						charInHiresBoundary = false;
					}
					else this.rawSegments.push(segment);
				}
				loc.column += 1;
				this.generatedCodeColumn += 1;
				first = false;
			}
			originalCharIndex += 1;
		}
		this.pending = null;
	}
	advance(str) {
		if (!str) return;
		const lines = str.split("\n");
		if (lines.length > 1) {
			for (let i = 0; i < lines.length - 1; i++) {
				this.generatedCodeLine++;
				this.raw[this.generatedCodeLine] = this.rawSegments = [];
			}
			this.generatedCodeColumn = 0;
		}
		this.generatedCodeColumn += lines[lines.length - 1].length;
	}
};
const n = "\n";
const warned = {
	insertLeft: false,
	insertRight: false,
	storeName: false
};
var MagicString = class MagicString {
	constructor(string, options = {}) {
		const chunk = new Chunk(0, string.length, string);
		Object.defineProperties(this, {
			original: {
				writable: true,
				value: string
			},
			outro: {
				writable: true,
				value: ""
			},
			intro: {
				writable: true,
				value: ""
			},
			firstChunk: {
				writable: true,
				value: chunk
			},
			lastChunk: {
				writable: true,
				value: chunk
			},
			lastSearchedChunk: {
				writable: true,
				value: chunk
			},
			byStart: {
				writable: true,
				value: {}
			},
			byEnd: {
				writable: true,
				value: {}
			},
			filename: {
				writable: true,
				value: options.filename
			},
			indentExclusionRanges: {
				writable: true,
				value: options.indentExclusionRanges
			},
			sourcemapLocations: {
				writable: true,
				value: new BitSet()
			},
			storedNames: {
				writable: true,
				value: {}
			},
			indentStr: {
				writable: true,
				value: void 0
			},
			ignoreList: {
				writable: true,
				value: options.ignoreList
			},
			offset: {
				writable: true,
				value: options.offset || 0
			}
		});
		this.byStart[0] = chunk;
		this.byEnd[string.length] = chunk;
	}
	addSourcemapLocation(char) {
		this.sourcemapLocations.add(char);
	}
	append(content) {
		if (typeof content !== "string") throw new TypeError("outro content must be a string");
		this.outro += content;
		return this;
	}
	appendLeft(index, content) {
		index = index + this.offset;
		if (typeof content !== "string") throw new TypeError("inserted content must be a string");
		this._split(index);
		const chunk = this.byEnd[index];
		if (chunk) chunk.appendLeft(content);
		else this.intro += content;
		return this;
	}
	appendRight(index, content) {
		index = index + this.offset;
		if (typeof content !== "string") throw new TypeError("inserted content must be a string");
		this._split(index);
		const chunk = this.byStart[index];
		if (chunk) chunk.appendRight(content);
		else this.outro += content;
		return this;
	}
	clone() {
		const cloned = new MagicString(this.original, {
			filename: this.filename,
			offset: this.offset
		});
		let originalChunk = this.firstChunk;
		let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
		while (originalChunk) {
			cloned.byStart[clonedChunk.start] = clonedChunk;
			cloned.byEnd[clonedChunk.end] = clonedChunk;
			const nextOriginalChunk = originalChunk.next;
			const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
			if (nextClonedChunk) {
				clonedChunk.next = nextClonedChunk;
				nextClonedChunk.previous = clonedChunk;
				clonedChunk = nextClonedChunk;
			}
			originalChunk = nextOriginalChunk;
		}
		cloned.lastChunk = clonedChunk;
		if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
		cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
		cloned.intro = this.intro;
		cloned.outro = this.outro;
		return cloned;
	}
	generateDecodedMap(options) {
		options = options || {};
		const sourceIndex = 0;
		const names = Object.keys(this.storedNames);
		const mappings = new Mappings(options.hires);
		const locate = getLocator(this.original);
		if (this.intro) mappings.advance(this.intro);
		this.firstChunk.eachNext((chunk) => {
			const loc = locate(chunk.start);
			if (chunk.intro.length) mappings.advance(chunk.intro);
			if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
			else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
			if (chunk.outro.length) mappings.advance(chunk.outro);
		});
		if (this.outro) mappings.advance(this.outro);
		return {
			file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
			sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
			sourcesContent: options.includeContent ? [this.original] : void 0,
			names,
			mappings: mappings.raw,
			x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
		};
	}
	generateMap(options) {
		return new SourceMap(this.generateDecodedMap(options));
	}
	_ensureindentStr() {
		if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
	}
	_getRawIndentString() {
		this._ensureindentStr();
		return this.indentStr;
	}
	getIndentString() {
		this._ensureindentStr();
		return this.indentStr === null ? "	" : this.indentStr;
	}
	indent(indentStr, options) {
		const pattern = /^[^\r\n]/gm;
		if (isObject(indentStr)) {
			options = indentStr;
			indentStr = void 0;
		}
		if (indentStr === void 0) {
			this._ensureindentStr();
			indentStr = this.indentStr || "	";
		}
		if (indentStr === "") return this;
		options = options || {};
		const isExcluded = {};
		if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
			for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
		});
		let shouldIndentNextCharacter = options.indentStart !== false;
		const replacer = (match) => {
			if (shouldIndentNextCharacter) return `${indentStr}${match}`;
			shouldIndentNextCharacter = true;
			return match;
		};
		this.intro = this.intro.replace(pattern, replacer);
		let charIndex = 0;
		let chunk = this.firstChunk;
		while (chunk) {
			const end = chunk.end;
			if (chunk.edited) {
				if (!isExcluded[charIndex]) {
					chunk.content = chunk.content.replace(pattern, replacer);
					if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
				}
			} else {
				charIndex = chunk.start;
				while (charIndex < end) {
					if (!isExcluded[charIndex]) {
						const char = this.original[charIndex];
						if (char === "\n") shouldIndentNextCharacter = true;
						else if (char !== "\r" && shouldIndentNextCharacter) {
							shouldIndentNextCharacter = false;
							if (charIndex === chunk.start) chunk.prependRight(indentStr);
							else {
								this._splitChunk(chunk, charIndex);
								chunk = chunk.next;
								chunk.prependRight(indentStr);
							}
						}
					}
					charIndex += 1;
				}
			}
			charIndex = chunk.end;
			chunk = chunk.next;
		}
		this.outro = this.outro.replace(pattern, replacer);
		return this;
	}
	insert() {
		throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
	}
	insertLeft(index, content) {
		if (!warned.insertLeft) {
			console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
			warned.insertLeft = true;
		}
		return this.appendLeft(index, content);
	}
	insertRight(index, content) {
		if (!warned.insertRight) {
			console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
			warned.insertRight = true;
		}
		return this.prependRight(index, content);
	}
	move(start, end, index) {
		start = start + this.offset;
		end = end + this.offset;
		index = index + this.offset;
		if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
		this._split(start);
		this._split(end);
		this._split(index);
		const first = this.byStart[start];
		const last = this.byEnd[end];
		const oldLeft = first.previous;
		const oldRight = last.next;
		const newRight = this.byStart[index];
		if (!newRight && last === this.lastChunk) return this;
		const newLeft = newRight ? newRight.previous : this.lastChunk;
		if (oldLeft) oldLeft.next = oldRight;
		if (oldRight) oldRight.previous = oldLeft;
		if (newLeft) newLeft.next = first;
		if (newRight) newRight.previous = last;
		if (!first.previous) this.firstChunk = last.next;
		if (!last.next) {
			this.lastChunk = first.previous;
			this.lastChunk.next = null;
		}
		first.previous = newLeft;
		last.next = newRight || null;
		if (!newLeft) this.firstChunk = first;
		if (!newRight) this.lastChunk = last;
		return this;
	}
	overwrite(start, end, content, options) {
		options = options || {};
		return this.update(start, end, content, {
			...options,
			overwrite: !options.contentOnly
		});
	}
	update(start, end, content, options) {
		start = start + this.offset;
		end = end + this.offset;
		if (typeof content !== "string") throw new TypeError("replacement content must be a string");
		if (this.original.length !== 0) {
			while (start < 0) start += this.original.length;
			while (end < 0) end += this.original.length;
		}
		if (end > this.original.length) throw new Error("end is out of bounds");
		if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
		this._split(start);
		this._split(end);
		if (options === true) {
			if (!warned.storeName) {
				console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
				warned.storeName = true;
			}
			options = { storeName: true };
		}
		const storeName = options !== void 0 ? options.storeName : false;
		const overwrite = options !== void 0 ? options.overwrite : false;
		if (storeName) {
			const original = this.original.slice(start, end);
			Object.defineProperty(this.storedNames, original, {
				writable: true,
				value: true,
				enumerable: true
			});
		}
		const first = this.byStart[start];
		const last = this.byEnd[end];
		if (first) {
			let chunk = first;
			while (chunk !== last) {
				if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
				chunk = chunk.next;
				chunk.edit("", false);
			}
			first.edit(content, storeName, !overwrite);
		} else {
			const newChunk = new Chunk(start, end, "").edit(content, storeName);
			last.next = newChunk;
			newChunk.previous = last;
		}
		return this;
	}
	prepend(content) {
		if (typeof content !== "string") throw new TypeError("outro content must be a string");
		this.intro = content + this.intro;
		return this;
	}
	prependLeft(index, content) {
		index = index + this.offset;
		if (typeof content !== "string") throw new TypeError("inserted content must be a string");
		this._split(index);
		const chunk = this.byEnd[index];
		if (chunk) chunk.prependLeft(content);
		else this.intro = content + this.intro;
		return this;
	}
	prependRight(index, content) {
		index = index + this.offset;
		if (typeof content !== "string") throw new TypeError("inserted content must be a string");
		this._split(index);
		const chunk = this.byStart[index];
		if (chunk) chunk.prependRight(content);
		else this.outro = content + this.outro;
		return this;
	}
	remove(start, end) {
		start = start + this.offset;
		end = end + this.offset;
		if (this.original.length !== 0) {
			while (start < 0) start += this.original.length;
			while (end < 0) end += this.original.length;
		}
		if (start === end) return this;
		if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
		if (start > end) throw new Error("end must be greater than start");
		this._split(start);
		this._split(end);
		let chunk = this.byStart[start];
		while (chunk) {
			chunk.intro = "";
			chunk.outro = "";
			chunk.edit("");
			chunk = end > chunk.end ? this.byStart[chunk.end] : null;
		}
		return this;
	}
	reset(start, end) {
		start = start + this.offset;
		end = end + this.offset;
		if (this.original.length !== 0) {
			while (start < 0) start += this.original.length;
			while (end < 0) end += this.original.length;
		}
		if (start === end) return this;
		if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
		if (start > end) throw new Error("end must be greater than start");
		this._split(start);
		this._split(end);
		let chunk = this.byStart[start];
		while (chunk) {
			chunk.reset();
			chunk = end > chunk.end ? this.byStart[chunk.end] : null;
		}
		return this;
	}
	lastChar() {
		if (this.outro.length) return this.outro[this.outro.length - 1];
		let chunk = this.lastChunk;
		do {
			if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
			if (chunk.content.length) return chunk.content[chunk.content.length - 1];
			if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
		} while (chunk = chunk.previous);
		if (this.intro.length) return this.intro[this.intro.length - 1];
		return "";
	}
	lastLine() {
		let lineIndex = this.outro.lastIndexOf(n);
		if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
		let lineStr = this.outro;
		let chunk = this.lastChunk;
		do {
			if (chunk.outro.length > 0) {
				lineIndex = chunk.outro.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.outro + lineStr;
			}
			if (chunk.content.length > 0) {
				lineIndex = chunk.content.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.content + lineStr;
			}
			if (chunk.intro.length > 0) {
				lineIndex = chunk.intro.lastIndexOf(n);
				if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
				lineStr = chunk.intro + lineStr;
			}
		} while (chunk = chunk.previous);
		lineIndex = this.intro.lastIndexOf(n);
		if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
		return this.intro + lineStr;
	}
	slice(start = 0, end = this.original.length - this.offset) {
		start = start + this.offset;
		end = end + this.offset;
		if (this.original.length !== 0) {
			while (start < 0) start += this.original.length;
			while (end < 0) end += this.original.length;
		}
		let result = "";
		let chunk = this.firstChunk;
		while (chunk && (chunk.start > start || chunk.end <= start)) {
			if (chunk.start < end && chunk.end >= end) return result;
			chunk = chunk.next;
		}
		if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
		const startChunk = chunk;
		while (chunk) {
			if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
			const containsEnd = chunk.start < end && chunk.end >= end;
			if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
			const sliceStart = startChunk === chunk ? start - chunk.start : 0;
			const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
			result += chunk.content.slice(sliceStart, sliceEnd);
			if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
			if (containsEnd) break;
			chunk = chunk.next;
		}
		return result;
	}
	snip(start, end) {
		const clone = this.clone();
		clone.remove(0, start);
		clone.remove(end, clone.original.length);
		return clone;
	}
	_split(index) {
		if (this.byStart[index] || this.byEnd[index]) return;
		let chunk = this.lastSearchedChunk;
		let previousChunk = chunk;
		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];
			if (chunk === previousChunk) return;
			previousChunk = chunk;
		}
	}
	_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(match, str) {
			if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
				if (i === "$") return "$";
				if (i === "&") return match[0];
				if (+i < match.length) return match[+i];
				return `$${i}`;
			});
			else return replacement(...match, match.index, str, match.groups);
		}
		function matchAll(re, str) {
			let match;
			const matches = [];
			while (match = re.exec(str)) matches.push(match);
			return matches;
		}
		if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
			if (match.index != null) {
				const replacement = getReplacement(match, this.original);
				if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
			}
		});
		else {
			const match = this.original.match(searchValue);
			if (match && match.index != null) {
				const replacement = getReplacement(match, this.original);
				if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
			}
		}
		return this;
	}
	_replaceString(string, replacement) {
		const { original } = this;
		const index = original.indexOf(string);
		if (index !== -1) {
			if (typeof replacement === "function") replacement = replacement(string, index, original);
			if (string !== replacement) this.overwrite(index, index + string.length, replacement);
		}
		return this;
	}
	replace(searchValue, replacement) {
		if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
		return this._replaceRegexp(searchValue, replacement);
	}
	_replaceAllString(string, replacement) {
		const { original } = this;
		const stringLength = string.length;
		for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
			const previous = original.slice(index, index + stringLength);
			let _replacement = replacement;
			if (typeof replacement === "function") _replacement = replacement(previous, index, original);
			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);
	}
};
//#endregion
//#region ../../node_modules/.pnpm/@rollup+plugin-alias@6.0.0_rollup@4.59.0/node_modules/@rollup/plugin-alias/dist/index.js
function matches$1(pattern, importee) {
	if (pattern instanceof RegExp) return pattern.test(importee);
	if (importee.length < pattern.length) return false;
	if (importee === pattern) return true;
	return importee.startsWith(pattern + "/");
}
function getEntries({ entries, customResolver }) {
	if (!entries) return [];
	const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
	if (Array.isArray(entries)) return entries.map((entry) => {
		return {
			find: entry.find,
			replacement: entry.replacement,
			resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
		};
	});
	return Object.entries(entries).map(([key, value]) => {
		return {
			find: key,
			replacement: value,
			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(options = {}) {
	const entries = getEntries(options);
	if (entries.length === 0) return {
		name: "alias",
		resolveId: () => null
	};
	return {
		name: "alias",
		async buildStart(inputOptions) {
			await Promise.all([...Array.isArray(options.entries) ? options.entries : [], options].map(({ customResolver }) => customResolver && getHookFunction(customResolver.buildStart)?.call(this, inputOptions)));
		},
		resolveId(importee, importer, resolveOptions) {
			const matchedEntry = entries.find((entry) => matches$1(entry.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 (!path.isAbsolute(updatedId)) this.warn(`rewrote ${importee} to ${updatedId} but was not an absolute 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 };
			});
		}
	};
}
//#endregion
//#region src/node/plugins/optimizedDeps.ts
const debug$13 = createDebugger("vite:optimize-deps");
function optimizedDepsPlugin() {
	return {
		name: "vite:optimized-deps",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) return false;
			return !isDepOptimizationDisabled(environment.config.optimizeDeps);
		},
		resolveId(id) {
			if (this.environment.depsOptimizer?.isOptimizedDepFile(id)) return id;
		},
		async load(id) {
			const environment = this.environment;
			const depsOptimizer = environment.depsOptimizer;
			if (depsOptimizer?.isOptimizedDepFile(id)) {
				const metadata = depsOptimizer.metadata;
				const file = cleanUrl(id);
				const versionMatch = DEP_VERSION_RE.exec(id);
				const browserHash = versionMatch ? versionMatch[1].split("=")[1] : void 0;
				const info = optimizedDepInfoFromFile(metadata, file);
				if (info) {
					if (browserHash && info.browserHash !== browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) 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?.browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
					}
				}
				debug$13?.(`load ${import_picocolors.default.cyan(file)}`);
				try {
					const [code, map] = await Promise.all([fsp.readFile(file, "utf-8"), fsp.readFile(`${file}.map`, "utf-8").then((map) => JSON.parse(map)).catch(() => null)]);
					if (map) return {
						code,
						map
					};
					return code;
				} catch {
					if (browserHash && !environment.config.optimizeDeps.ignoreOutdatedRequests) throwOutdatedRequest(id);
					throwFileNotFoundInOptimizedDep(id);
				}
			}
		}
	};
}
function throwProcessingError(id) {
	const err = /* @__PURE__ */ new Error(`Something unexpected happened while optimizing "${id}". The current page should have reloaded by now`);
	err.code = ERR_OPTIMIZE_DEPS_PROCESSING_ERROR;
	throw err;
}
function throwOutdatedRequest(id) {
	const err = /* @__PURE__ */ new Error(`There is a new version of the pre-bundle for "${id}", a page reload is going to ask for it.`);
	err.code = ERR_OUTDATED_OPTIMIZED_DEP;
	throw err;
}
function throwFileNotFoundInOptimizedDep(id) {
	const err = /* @__PURE__ */ 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\`.`);
	err.code = ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR;
	throw err;
}
//#endregion
//#region ../../node_modules/.pnpm/ufo@1.6.4/node_modules/ufo/dist/index.mjs
const HASH_RE = /#/g;
const AMPERSAND_RE = /&/g;
const SLASH_RE = /\//g;
const EQUAL_RE = /=/g;
const PLUS_RE = /\+/g;
const ENC_CARET_RE = /%5e/gi;
const ENC_BACKTICK_RE = /%60/gi;
const ENC_PIPE_RE = /%7c/gi;
const 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, value) {
	if (typeof value === "number" || typeof value === "boolean") value = String(value);
	if (!value) return encodeQueryKey(key);
	if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
	return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
}
function stringifyQuery(query) {
	return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
}
new Set(builtinModules);
function clearImports(imports) {
	return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
}
function getImportNames(cleanedImports) {
	const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
	return {
		namespacedImport: topLevelImports.match(/\* as \s*(\S*)/)?.[1],
		defaultImport: topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0
	};
}
/**
* @typedef ErrnoExceptionFields
* @property {number | undefined} [errnode]
* @property {string | undefined} [code]
* @property {string | undefined} [path]
* @property {string | undefined} [syscall]
* @property {string | undefined} [url]
*
* @typedef {Error & ErrnoExceptionFields} ErrnoException
*/
const own$1 = {}.hasOwnProperty;
const classRegExp = /^([A-Z][a-z\d]*)+$/;
const kTypes = /* @__PURE__ */ new Set([
	"string",
	"function",
	"number",
	"object",
	"Function",
	"Object",
	"boolean",
	"bigint",
	"symbol"
]);
const codes = {};
/**
* Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
* We cannot use Intl.ListFormat because it's not available in
* --without-intl builds.
*
* @param {Array<string>} array
*   An array of strings.
* @param {string} [type]
*   The list type to be inserted before the last element.
* @returns {string}
*/
function formatList(array, type = "and") {
	return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
}
/** @type {Map<string, MessageFunction | string>} */
const messages = /* @__PURE__ */ new Map();
const nodeInternalPrefix = "__node_internal_";
/** @type {number} */
let userStackTraceLimit;
codes.ERR_INVALID_ARG_TYPE = createError(
	"ERR_INVALID_ARG_TYPE",
	/**
	* @param {string} name
	* @param {Array<string> | string} expected
	* @param {unknown} actual
	*/
	(name, expected, actual) => {
		assert.ok(typeof name === "string", "'name' must be a string");
		if (!Array.isArray(expected)) expected = [expected];
		let message = "The ";
		if (name.endsWith(" argument")) message += `${name} `;
		else {
			const type = name.includes(".") ? "property" : "argument";
			message += `"${name}" ${type} `;
		}
		message += "must be ";
		/** @type {Array<string>} */
		const types = [];
		/** @type {Array<string>} */
		const instances = [];
		/** @type {Array<string>} */
		const other = [];
		for (const value of expected) {
			assert.ok(typeof value === "string", "All expected entries have to be of type string");
			if (kTypes.has(value)) types.push(value.toLowerCase());
			else if (classRegExp.exec(value) === null) {
				assert.ok(value !== "object", "The value \"object\" should be written as \"Object\"");
				other.push(value);
			} else instances.push(value);
		}
		if (instances.length > 0) {
			const pos = types.indexOf("object");
			if (pos !== -1) {
				types.slice(pos, 1);
				instances.push("Object");
			}
		}
		if (types.length > 0) {
			message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`;
			if (instances.length > 0 || other.length > 0) message += " or ";
		}
		if (instances.length > 0) {
			message += `an instance of ${formatList(instances, "or")}`;
			if (other.length > 0) message += " or ";
		}
		if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`;
		else {
			if (other[0].toLowerCase() !== other[0]) message += "an ";
			message += `${other[0]}`;
		}
		message += `. Received ${determineSpecificType(actual)}`;
		return message;
	},
	TypeError
);
codes.ERR_INVALID_MODULE_SPECIFIER = createError(
	"ERR_INVALID_MODULE_SPECIFIER",
	/**
	* @param {string} request
	* @param {string} reason
	* @param {string} [base]
	*/
	(request, reason, base = void 0) => {
		return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
	},
	TypeError
);
codes.ERR_INVALID_PACKAGE_CONFIG = createError(
	"ERR_INVALID_PACKAGE_CONFIG",
	/**
	* @param {string} path
	* @param {string} [base]
	* @param {string} [message]
	*/
	(path, base, message) => {
		return `Invalid package config ${path}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
	},
	Error
);
codes.ERR_INVALID_PACKAGE_TARGET = createError(
	"ERR_INVALID_PACKAGE_TARGET",
	/**
	* @param {string} packagePath
	* @param {string} key
	* @param {unknown} target
	* @param {boolean} [isImport=false]
	* @param {string} [base]
	*/
	(packagePath, key, target, isImport = false, base = void 0) => {
		const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
		if (key === ".") {
			assert.ok(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
);
codes.ERR_MODULE_NOT_FOUND = createError(
	"ERR_MODULE_NOT_FOUND",
	/**
	* @param {string} path
	* @param {string} base
	* @param {boolean} [exactUrl]
	*/
	(path, base, exactUrl = false) => {
		return `Cannot find ${exactUrl ? "module" : "package"} '${path}' imported from ${base}`;
	},
	Error
);
codes.ERR_NETWORK_IMPORT_DISALLOWED = createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
	"ERR_PACKAGE_IMPORT_NOT_DEFINED",
	/**
	* @param {string} specifier
	* @param {string} packagePath
	* @param {string} base
	*/
	(specifier, packagePath, base) => {
		return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
	},
	TypeError
);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
	"ERR_PACKAGE_PATH_NOT_EXPORTED",
	/**
	* @param {string} packagePath
	* @param {string} subpath
	* @param {string} [base]
	*/
	(packagePath, subpath, base = void 0) => {
		if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
		return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
	},
	Error
);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error);
codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
	"ERR_UNKNOWN_FILE_EXTENSION",
	/**
	* @param {string} extension
	* @param {string} path
	*/
	(extension, path) => {
		return `Unknown file extension "${extension}" for ${path}`;
	},
	TypeError
);
codes.ERR_INVALID_ARG_VALUE = createError(
	"ERR_INVALID_ARG_VALUE",
	/**
	* @param {string} name
	* @param {unknown} value
	* @param {string} [reason='is invalid']
	*/
	(name, value, reason = "is invalid") => {
		let inspected = inspect(value);
		if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
		return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
	},
	TypeError
);
/**
* Utility function for registering the error codes. Only used here. Exported
* *only* to allow for testing.
* @param {string} sym
* @param {MessageFunction | string} value
* @param {ErrorConstructor} constructor
* @returns {new (...parameters: Array<any>) => Error}
*/
function createError(sym, value, constructor) {
	messages.set(sym, value);
	return makeNodeErrorWithCode(constructor, sym);
}
/**
* @param {ErrorConstructor} Base
* @param {string} key
* @returns {ErrorConstructor}
*/
function makeNodeErrorWithCode(Base, key) {
	return NodeError;
	/**
	* @param {Array<unknown>} parameters
	*/
	function NodeError(...parameters) {
		const limit = Error.stackTraceLimit;
		if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
		const error = new Base();
		if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
		const message = getMessage(key, parameters, error);
		Object.defineProperties(error, {
			message: {
				value: message,
				enumerable: false,
				writable: true,
				configurable: true
			},
			toString: {
				/** @this {Error} */
				value() {
					return `${this.name} [${key}]: ${this.message}`;
				},
				enumerable: false,
				writable: true,
				configurable: true
			}
		});
		captureLargerStackTrace(error);
		error.code = key;
		return error;
	}
}
/**
* @returns {boolean}
*/
function isErrorStackTraceLimitWritable() {
	try {
		if (v8.startupSnapshot.isBuildingSnapshot()) return false;
	} catch {}
	const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
	if (desc === void 0) return Object.isExtensible(Error);
	return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
}
/**
* This function removes unnecessary frames from Node.js core errors.
* @template {(...parameters: unknown[]) => unknown} T
* @param {T} wrappedFunction
* @returns {T}
*/
function hideStackFrames(wrappedFunction) {
	const hidden = nodeInternalPrefix + wrappedFunction.name;
	Object.defineProperty(wrappedFunction, "name", { value: hidden });
	return wrappedFunction;
}
const captureLargerStackTrace = hideStackFrames(
	/**
	* @param {Error} error
	* @returns {Error}
	*/
	function(error) {
		const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
		if (stackTraceLimitIsWritable) {
			userStackTraceLimit = Error.stackTraceLimit;
			Error.stackTraceLimit = Number.POSITIVE_INFINITY;
		}
		Error.captureStackTrace(error);
		if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
		return error;
	}
);
/**
* @param {string} key
* @param {Array<unknown>} parameters
* @param {Error} self
* @returns {string}
*/
function getMessage(key, parameters, self) {
	const message = messages.get(key);
	assert.ok(message !== void 0, "expected `message` to be found");
	if (typeof message === "function") {
		assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`);
		return Reflect.apply(message, self, parameters);
	}
	const regex = /%[dfijoOs]/g;
	let expectedLength = 0;
	while (regex.exec(message) !== null) expectedLength++;
	assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`);
	if (parameters.length === 0) return message;
	parameters.unshift(message);
	return Reflect.apply(format, null, parameters);
}
/**
* Determine the specific type of a value for type-mismatch errors.
* @param {unknown} value
* @returns {string}
*/
function determineSpecificType(value) {
	if (value === null || value === void 0) return String(value);
	if (typeof value === "function" && value.name) return `function ${value.name}`;
	if (typeof value === "object") {
		if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`;
		return `${inspect(value, { depth: -1 })}`;
	}
	let inspected = inspect(value, { colors: false });
	if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`;
	return `type ${typeof value} (${inspected})`;
}
const DEFAULT_CONDITIONS = Object.freeze(["node", "import"]);
new Set(DEFAULT_CONDITIONS);
const ESM_STATIC_IMPORT_RE = /(?<=\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;
const TYPE_RE = /^\s*?type\s/;
function parseStaticImport(matched) {
	const cleanedImports = clearImports(matched.imports);
	const namedImports = {};
	const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
	for (const namedImport of _matches) {
		const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
		const source = _match?.[1] || namedImport.trim();
		const importName = _match?.[2] || source;
		if (source && !TYPE_RE.test(source)) namedImports[source] = importName;
	}
	const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
	return {
		...matched,
		defaultImport,
		namespacedImport,
		namedImports
	};
}
//#endregion
//#region src/node/env.ts
var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
	function _resolveEscapeSequences(value) {
		return value.replace(/\\\$/g, "$");
	}
	function expandValue(value, processEnv, runningParsed) {
		const env = {
			...runningParsed,
			...processEnv
		};
		const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
		let result = value;
		let match;
		const seen = /* @__PURE__ */ new Set();
		while ((match = regex.exec(result)) !== null) {
			seen.add(result);
			const [template, bracedExpression, unbracedExpression] = match;
			const expression = bracedExpression || unbracedExpression;
			const opMatch = expression.match(/(:\+|\+|:-|-)/);
			const splitter = opMatch ? opMatch[0] : null;
			const r = expression.split(splitter);
			let defaultValue;
			let value;
			const key = r.shift();
			if ([":+", "+"].includes(splitter)) {
				defaultValue = env[key] ? r.join(splitter) : "";
				value = null;
			} else {
				defaultValue = r.join(splitter);
				value = env[key];
			}
			if (value) if (seen.has(value)) result = result.replace(template, defaultValue);
			else result = result.replace(template, value);
			else result = result.replace(template, defaultValue);
			if (result === runningParsed[key]) break;
			regex.lastIndex = 0;
		}
		return result;
	}
	function expand(options) {
		let processEnv = process.env;
		if (options && options.processEnv != null) processEnv = options.processEnv;
		for (const key in options.parsed) {
			let value = options.parsed[key];
			if (processEnv[key] && processEnv[key] !== value) value = processEnv[key];
			else value = expandValue(value, processEnv, options.parsed);
			options.parsed[key] = _resolveEscapeSequences(value);
		}
		for (const processKey in options.parsed) processEnv[processKey] = options.parsed[processKey];
		return options;
	}
	module.exports.expand = expand;
})))();
const debug$12 = createDebugger("vite:env");
function getEnvFilesForMode(mode, envDir) {
	if (envDir !== false) return [
		`.env`,
		`.env.local`,
		`.env.${mode}`,
		`.env.${mode}.local`
	].map((file) => normalizePath(path.join(envDir, file)));
	return [];
}
/**
* Load `.env` files within the `envDir` and merge them with the matching
* variables already present in `process.env`.
*/
function loadEnv(mode, envDir, prefixes = "VITE_") {
	const start = performance.now();
	const getTime = () => `${(performance.now() - start).toFixed(2)}ms`;
	if (mode === "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 env = {};
	const envFiles = getEnvFilesForMode(mode, envDir);
	debug$12?.(`loading env files: %O`, envFiles);
	const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
		const stat = tryStatSync(filePath);
		if (!stat || !stat.isFile() && !stat.isFIFO()) return [];
		const parsedEnv = parseEnv(fs.readFileSync(filePath, "utf-8"));
		return Object.entries(parsedEnv);
	}));
	debug$12?.(`env files loaded in ${getTime()}`);
	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;
	(0, import_main.expand)({
		parsed,
		processEnv: { ...process.env }
	});
	for (const [key, value] of Object.entries(parsed)) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = value;
	for (const prefix of prefixes) Object.assign(env, getEnvs({ prefix }));
	for (const key in process.env) if (prefixes.some((prefix) => key.startsWith(prefix))) env[key] = process.env[key];
	debug$12?.(`using resolved env: %O`, env);
	return env;
}
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.`);
	if (envPrefix.some((prefix) => /\s/.test(prefix))) console.warn(import_picocolors.default.yellow(`[vite] Warning: envPrefix option contains values with whitespace, which does not work in practice.`));
	return envPrefix;
}
//#endregion
//#region src/node/deprecations.ts
const docsURL = "https://vite.dev";
const deprecationCode = {
	removePluginHookSsrArgument: "this-environment-in-hooks",
	removePluginHookHandleHotUpdate: "hotupdate-hook",
	removeServerModuleGraph: "per-environment-apis",
	removeServerReloadModule: "per-environment-apis",
	removeServerPluginContainer: "per-environment-apis",
	removeServerHot: "per-environment-apis",
	removeServerTransformRequest: "per-environment-apis",
	removeServerWarmupRequest: "per-environment-apis",
	removeSsrLoadModule: "ssr-using-modulerunner"
};
const deprecationMessages = {
	removePluginHookSsrArgument: "Plugin hook `options.ssr` is replaced with `this.environment.config.consumer === 'server'`.",
	removePluginHookHandleHotUpdate: "Plugin hook `handleHotUpdate()` is replaced with `hotUpdate()`.",
	removeServerModuleGraph: "The `server.moduleGraph` is replaced with `this.environment.moduleGraph`.",
	removeServerReloadModule: "The `server.reloadModule` is replaced with `environment.reloadModule`.",
	removeServerPluginContainer: "The `server.pluginContainer` is replaced with `this.environment.pluginContainer`.",
	removeServerHot: "The `server.hot` is replaced with `this.environment.hot`.",
	removeServerTransformRequest: "The `server.transformRequest` is replaced with `this.environment.transformRequest`.",
	removeServerWarmupRequest: "The `server.warmupRequest` is replaced with `this.environment.warmupRequest`.",
	removeSsrLoadModule: "The `server.ssrLoadModule` is replaced with Environment Runner."
};
let _ignoreDeprecationWarnings = false;
function isFutureDeprecationEnabled(config, type) {
	return !!config.future?.[type];
}
/**
* Warn about future deprecations.
*/
function warnFutureDeprecation(config, type, extraMessage, stacktrace = true) {
	if (_ignoreDeprecationWarnings || !config.future || config.future[type] !== "warn") return;
	let msg = `[vite future] ${deprecationMessages[type]}`;
	if (extraMessage) msg += ` ${extraMessage}`;
	msg = import_picocolors.default.yellow(msg);
	const docs = `${docsURL}/changes/${deprecationCode[type].toLowerCase()}`;
	msg += import_picocolors.default.gray(`\n  ${stacktrace ? "├" : "└"}─── `) + import_picocolors.default.underline(docs) + "\n";
	if (stacktrace) {
		const stack = (/* @__PURE__ */ new Error()).stack;
		if (stack) {
			let stacks = stack.split("\n").slice(3).filter((i) => !i.includes("/node_modules/vite/dist/"));
			if (stacks.length === 0) stacks.push("No stack trace found.");
			stacks = stacks.map((i, idx) => `  ${idx === stacks.length - 1 ? "└" : "│"} ${i.trim()}`);
			msg += import_picocolors.default.dim(stacks.join("\n")) + "\n";
		}
	}
	config.logger.warnOnce(msg);
}
function ignoreDeprecationWarnings(fn) {
	const before = _ignoreDeprecationWarnings;
	_ignoreDeprecationWarnings = true;
	const ret = fn();
	_ignoreDeprecationWarnings = before;
	return ret;
}
//#endregion
//#region src/node/server/middlewares/error.ts
function prepareError(err) {
	return {
		message: stripVTControlCharacters(err.message),
		stack: stripVTControlCharacters(cleanStack(err.stack || "")),
		id: err.id,
		frame: stripVTControlCharacters(err.frame || ""),
		plugin: err.plugin,
		pluginCode: err.pluginCode?.toString(),
		loc: err.loc
	};
}
function buildErrorMessage(err, args = [], includeStack = true) {
	if (err.plugin) args.push(`  Plugin: ${import_picocolors.default.magenta(err.plugin)}`);
	const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : "";
	if (err.id) args.push(`  File: ${import_picocolors.default.cyan(err.id)}${loc}`);
	if (err.frame) args.push(import_picocolors.default.yellow(pad(err.frame)));
	if (includeStack && err.stack) args.push(pad(cleanStack(err.stack)));
	return args.join("\n");
}
function cleanStack(stack) {
	return stack.split(/\n/).filter((l) => /^\s*at/.test(l)).join("\n");
}
function logError(server, err) {
	const msg = buildErrorMessage(err, [import_picocolors.default.red(`Internal server error: ${err.message}`)]);
	server.config.logger.error(msg, {
		clear: true,
		timestamp: true,
		error: err
	});
	server.environments.client.hot.send({
		type: "error",
		err: prepareError(err)
	});
}
function errorMiddleware(server, allowNext = false) {
	return function viteErrorMiddleware(err, _req, res, next) {
		logError(server, err);
		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(err)).replace(/</g, "\\u003c")}
              try {
                const { ErrorOverlay } = await import(${JSON.stringify(path.posix.join(server.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>
      `);
		}
	};
}
//#endregion
//#region ../../node_modules/.pnpm/encodeurl@1.0.2/node_modules/encodeurl/index.js
/*!
* encodeurl
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
var require_encodeurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	* @public
	*/
	module.exports = encodeUrl;
	/**
	* RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
	* and including invalid escape sequences.
	* @private
	*/
	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;
	/**
	* RegExp to match unmatched surrogate pair.
	* @private
	*/
	var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;
	/**
	* String to replace unmatched surrogate pair with.
	* @private
	*/
	var UNMATCHED_SURROGATE_PAIR_REPLACE = "$1�$2";
	/**
	* Encode a URL to a percent-encoded form, excluding already-encoded sequences.
	*
	* This function will take an already-encoded URL and encode all the non-URL
	* code points. This function will not encode the "%" character unless it is
	* not part of a valid sequence (`%20` will be left as-is, but `%foo` will
	* be encoded as `%25foo`).
	*
	* This encode is meant to be "safe" and does not throw errors. It will try as
	* hard as it can to properly encode the given URL, including replacing any raw,
	* unpaired surrogate pairs with the Unicode replacement character prior to
	* encoding.
	*
	* @param {string} url
	* @return {string}
	* @public
	*/
	function encodeUrl(url) {
		return String(url).replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP, encodeURI);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js
/*!
* escape-html
* Copyright(c) 2012-2013 TJ Holowaychuk
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
*/
var require_escape_html = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module variables.
	* @private
	*/
	var matchHtmlRegExp = /["'&<>]/;
	/**
	* Module exports.
	* @public
	*/
	module.exports = escapeHtml;
	/**
	* Escape special characters in the given string of html.
	*
	* @param  {string} string The string to escape for inserting into HTML
	* @return {string}
	* @public
	*/
	function escapeHtml(string) {
		var str = "" + string;
		var match = matchHtmlRegExp.exec(str);
		if (!match) return str;
		var escape;
		var html = "";
		var index = 0;
		var lastIndex = 0;
		for (index = match.index; index < str.length; index++) {
			switch (str.charCodeAt(index)) {
				case 34:
					escape = "&quot;";
					break;
				case 38:
					escape = "&amp;";
					break;
				case 39:
					escape = "&#39;";
					break;
				case 60:
					escape = "&lt;";
					break;
				case 62:
					escape = "&gt;";
					break;
				default: continue;
			}
			if (lastIndex !== index) html += str.substring(lastIndex, index);
			lastIndex = index + 1;
			html += escape;
		}
		return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/ee-first@1.1.1/node_modules/ee-first/index.js
/*!
* ee-first
* Copyright(c) 2014 Jonathan Ong
* MIT Licensed
*/
var require_ee_first = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	* @public
	*/
	module.exports = first;
	/**
	* Get the first event in a set of event emitters and event pairs.
	*
	* @param {array} stuff
	* @param {function} done
	* @public
	*/
	function first(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 i = 0; i < cleanups.length; i++) {
				x = cleanups[i];
				x.ee.removeListener(x.event, x.fn);
			}
		}
		function thunk(fn) {
			done = fn;
		}
		thunk.cancel = cleanup;
		return thunk;
	}
	/**
	* Create the event listener.
	* @private
	*/
	function listener(event, done) {
		return function onevent(arg1) {
			var args = new Array(arguments.length);
			var ee = this;
			var err = event === "error" ? arg1 : null;
			for (var i = 0; i < args.length; i++) args[i] = arguments[i];
			done(err, ee, event, args);
		};
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/on-finished@2.3.0/node_modules/on-finished/index.js
/*!
* on-finished
* Copyright(c) 2013 Jonathan Ong
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
var require_on_finished = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	* @public
	*/
	module.exports = onFinished;
	module.exports.isFinished = isFinished;
	/**
	* Module dependencies.
	* @private
	*/
	var first = require_ee_first();
	/**
	* Variables.
	* @private
	*/
	/* istanbul ignore next */
	var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
		process.nextTick(fn.bind.apply(fn, arguments));
	};
	/**
	* Invoke callback when the response has finished, useful for
	* cleaning up resources afterwards.
	*
	* @param {object} msg
	* @param {function} listener
	* @return {object}
	* @public
	*/
	function onFinished(msg, listener) {
		if (isFinished(msg) !== false) {
			defer(listener, null, msg);
			return msg;
		}
		attachListener(msg, listener);
		return msg;
	}
	/**
	* Determine if message is already finished.
	*
	* @param {object} msg
	* @return {boolean}
	* @public
	*/
	function isFinished(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);
	}
	/**
	* Attach a finished listener to the message.
	*
	* @param {object} msg
	* @param {function} callback
	* @private
	*/
	function attachFinishedListener(msg, callback) {
		var eeMsg;
		var eeSocket;
		var finished = false;
		function onFinish(error) {
			eeMsg.cancel();
			eeSocket.cancel();
			finished = true;
			callback(error);
		}
		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);
	}
	/**
	* Attach the listener to the message.
	*
	* @param {object} msg
	* @return {function}
	* @private
	*/
	function attachListener(msg, listener) {
		var attached = msg.__onFinished;
		if (!attached || !attached.queue) {
			attached = msg.__onFinished = createListener(msg);
			attachFinishedListener(msg, attached);
		}
		attached.queue.push(listener);
	}
	/**
	* Create listener on message.
	*
	* @param {object} msg
	* @return {function}
	* @private
	*/
	function createListener(msg) {
		function listener(err) {
			if (msg.__onFinished === listener) msg.__onFinished = null;
			if (!listener.queue) return;
			var queue = listener.queue;
			listener.queue = null;
			for (var i = 0; i < queue.length; i++) queue[i](err, msg);
		}
		listener.queue = [];
		return listener;
	}
	/**
	* Patch ServerResponse.prototype.assignSocket for node.js 0.8.
	*
	* @param {ServerResponse} res
	* @param {function} callback
	* @private
	*/
	function patchAssignSocket(res, callback) {
		var assignSocket = res.assignSocket;
		if (typeof assignSocket !== "function") return;
		res.assignSocket = function _assignSocket(socket) {
			assignSocket.call(this, socket);
			callback(socket);
		};
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/parseurl@1.3.3/node_modules/parseurl/index.js
/*!
* parseurl
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
var require_parseurl = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module dependencies.
	* @private
	*/
	var url$2 = __require("url");
	var parse = url$2.parse;
	var Url = url$2.Url;
	/**
	* Module exports.
	* @public
	*/
	module.exports = parseurl;
	module.exports.original = originalurl;
	/**
	* Parse the `req` url with memoization.
	*
	* @param {ServerRequest} req
	* @return {Object}
	* @public
	*/
	function parseurl(req) {
		var url = req.url;
		if (url === void 0) return;
		var parsed = req._parsedUrl;
		if (fresh(url, parsed)) return parsed;
		parsed = fastparse(url);
		parsed._raw = url;
		return req._parsedUrl = parsed;
	}
	/**
	* Parse the `req` original url with fallback and memoization.
	*
	* @param {ServerRequest} req
	* @return {Object}
	* @public
	*/
	function originalurl(req) {
		var url = req.originalUrl;
		if (typeof url !== "string") return parseurl(req);
		var parsed = req._parsedOriginalUrl;
		if (fresh(url, parsed)) return parsed;
		parsed = fastparse(url);
		parsed._raw = url;
		return req._parsedOriginalUrl = parsed;
	}
	/**
	* Parse the `str` url with fast-path short-cut.
	*
	* @param {string} str
	* @return {Object}
	* @private
	*/
	function fastparse(str) {
		if (typeof str !== "string" || str.charCodeAt(0) !== 47) return parse(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(str);
		}
		var url = Url !== void 0 ? new Url() : {};
		url.path = str;
		url.href = str;
		url.pathname = pathname;
		if (search !== null) {
			url.query = query;
			url.search = search;
		}
		return url;
	}
	/**
	* Determine if parsed is still fresh for url.
	*
	* @param {string} url
	* @param {object} parsedUrl
	* @return {boolean}
	* @private
	*/
	function fresh(url, parsedUrl) {
		return typeof parsedUrl === "object" && parsedUrl !== null && (Url === void 0 || parsedUrl instanceof Url) && parsedUrl._raw === url;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/codes.json
var require_codes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		"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"
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/statuses@1.5.0/node_modules/statuses/index.js
/*!
* statuses
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
var require_statuses = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module dependencies.
	* @private
	*/
	var codes = require_codes();
	/**
	* Module exports.
	* @public
	*/
	module.exports = 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
	};
	/**
	* Populate the statuses map for given codes.
	* @private
	*/
	function populateStatusesMap(statuses, codes) {
		var arr = [];
		Object.keys(codes).forEach(function forEachCode(code) {
			var message = codes[code];
			var status = Number(code);
			statuses[status] = message;
			statuses[message] = status;
			statuses[message.toLowerCase()] = status;
			arr.push(status);
		});
		return arr;
	}
	/**
	* Get the status code.
	*
	* Given a number, this will throw if it is not a known status
	* code, otherwise the code will be returned. Given a string,
	* the string will be parsed for a number and return the code
	* if valid, otherwise will lookup the code assuming this is
	* the status message.
	*
	* @param {string|number} code
	* @returns {number}
	* @public
	*/
	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 n = parseInt(code, 10);
		if (!isNaN(n)) {
			if (!status[n]) throw new Error("invalid status code: " + n);
			return n;
		}
		n = status[code.toLowerCase()];
		if (!n) throw new Error("invalid status message: \"" + code + "\"");
		return n;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/unpipe@1.0.0/node_modules/unpipe/index.js
/*!
* unpipe
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
var require_unpipe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	* @public
	*/
	module.exports = unpipe;
	/**
	* Determine if there are Node.js pipe-like data listeners.
	* @private
	*/
	function hasPipeDataListeners(stream) {
		var listeners = stream.listeners("data");
		for (var i = 0; i < listeners.length; i++) if (listeners[i].name === "ondata") return true;
		return false;
	}
	/**
	* Unpipe a stream from all destinations.
	*
	* @param {object} stream
	* @public
	*/
	function unpipe(stream) {
		if (!stream) throw new TypeError("argument stream is required");
		if (typeof stream.unpipe === "function") {
			stream.unpipe();
			return;
		}
		if (!hasPipeDataListeners(stream)) return;
		var listener;
		var listeners = stream.listeners("close");
		for (var i = 0; i < listeners.length; i++) {
			listener = listeners[i];
			if (listener.name !== "cleanup" && listener.name !== "onclose") continue;
			listener.call(stream);
		}
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/finalhandler@1.1.2_ms@2.1.3/node_modules/finalhandler/index.js
/*!
* finalhandler
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
var require_finalhandler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module dependencies.
	* @private
	*/
	var debug = (init_node(), __toCommonJS(node_exports))("finalhandler");
	var encodeUrl = require_encodeurl();
	var escapeHtml = require_escape_html();
	var onFinished = require_on_finished();
	var parseUrl = require_parseurl();
	var statuses = require_statuses();
	var unpipe = require_unpipe();
	/**
	* Module variables.
	* @private
	*/
	var DOUBLE_SPACE_REGEXP = /\x20{2}/g;
	var NEWLINE_REGEXP = /\n/g;
	/* istanbul ignore next */
	var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
		process.nextTick(fn.bind.apply(fn, arguments));
	};
	var isFinished = onFinished.isFinished;
	/**
	* Create a minimal HTML document.
	*
	* @param {string} message
	* @private
	*/
	function createHtmlDocument(message) {
		return "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>" + escapeHtml(message).replace(NEWLINE_REGEXP, "<br>").replace(DOUBLE_SPACE_REGEXP, " &nbsp;") + "</pre>\n</body>\n</html>\n";
	}
	/**
	* Module exports.
	* @public
	*/
	module.exports = finalhandler;
	/**
	* Create a function to handle the final response.
	*
	* @param {Request} req
	* @param {Response} res
	* @param {Object} [options]
	* @return {Function}
	* @public
	*/
	function finalhandler(req, res, options) {
		var opts = options || {};
		var env = opts.env || process.env.NODE_ENV || "development";
		var onerror = opts.onerror;
		return function(err) {
			var headers;
			var msg;
			var status;
			if (!err && headersSent(res)) {
				debug("cannot 404 after headers sent");
				return;
			}
			if (err) {
				status = getErrorStatusCode(err);
				if (status === void 0) status = getResponseStatusCode(res);
				else headers = getErrorHeaders(err);
				msg = getErrorMessage(err, status, env);
			} else {
				status = 404;
				msg = "Cannot " + req.method + " " + encodeUrl(getResourceName(req));
			}
			debug("default %s", status);
			if (err && onerror) defer(onerror, err, req, res);
			if (headersSent(res)) {
				debug("cannot %d after headers sent", status);
				req.socket.destroy();
				return;
			}
			send(req, res, status, headers, msg);
		};
	}
	/**
	* Get headers from Error object.
	*
	* @param {Error} err
	* @return {object}
	* @private
	*/
	function getErrorHeaders(err) {
		if (!err.headers || typeof err.headers !== "object") return;
		var headers = Object.create(null);
		var keys = Object.keys(err.headers);
		for (var i = 0; i < keys.length; i++) {
			var key = keys[i];
			headers[key] = err.headers[key];
		}
		return headers;
	}
	/**
	* Get message from Error object, fallback to status message.
	*
	* @param {Error} err
	* @param {number} status
	* @param {string} env
	* @return {string}
	* @private
	*/
	function getErrorMessage(err, status, env) {
		var msg;
		if (env !== "production") {
			msg = err.stack;
			if (!msg && typeof err.toString === "function") msg = err.toString();
		}
		return msg || statuses[status];
	}
	/**
	* Get status code from Error object.
	*
	* @param {Error} err
	* @return {number}
	* @private
	*/
	function getErrorStatusCode(err) {
		if (typeof err.status === "number" && err.status >= 400 && err.status < 600) return err.status;
		if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 600) return err.statusCode;
	}
	/**
	* Get resource name for the request.
	*
	* This is typically just the original pathname of the request
	* but will fallback to "resource" is that cannot be determined.
	*
	* @param {IncomingMessage} req
	* @return {string}
	* @private
	*/
	function getResourceName(req) {
		try {
			return parseUrl.original(req).pathname;
		} catch (e) {
			return "resource";
		}
	}
	/**
	* Get status code from response.
	*
	* @param {OutgoingMessage} res
	* @return {number}
	* @private
	*/
	function getResponseStatusCode(res) {
		var status = res.statusCode;
		if (typeof status !== "number" || status < 400 || status > 599) status = 500;
		return status;
	}
	/**
	* Determine if the response headers have been sent.
	*
	* @param {object} res
	* @returns {boolean}
	* @private
	*/
	function headersSent(res) {
		return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
	}
	/**
	* Send response.
	*
	* @param {IncomingMessage} req
	* @param {OutgoingMessage} res
	* @param {number} status
	* @param {object} headers
	* @param {string} message
	* @private
	*/
	function send(req, res, status, headers, message) {
		function write() {
			var body = createHtmlDocument(message);
			res.statusCode = status;
			res.statusMessage = statuses[status];
			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 (req.method === "HEAD") {
				res.end();
				return;
			}
			res.end(body, "utf8");
		}
		if (isFinished(req)) {
			write();
			return;
		}
		unpipe(req);
		onFinished(req, write);
		req.resume();
	}
	/**
	* Set response headers from an object.
	*
	* @param {OutgoingMessage} res
	* @param {object} headers
	* @private
	*/
	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]);
		}
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/utils-merge@1.0.1/node_modules/utils-merge/index.js
var require_utils_merge = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Merge object b with object a.
	*
	*     var a = { foo: 'bar' }
	*       , b = { bar: 'baz' };
	*
	*     merge(a, b);
	*     // => { foo: 'bar', bar: 'baz' }
	*
	* @param {Object} a
	* @param {Object} b
	* @return {Object}
	* @api public
	*/
	exports = module.exports = function(a, b) {
		if (a && b) for (var key in b) a[key] = b[key];
		return a;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/connect@3.7.0_ms@2.1.3/node_modules/connect/index.js
/*!
* connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
var require_connect = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module dependencies.
	* @private
	*/
	var debug = (init_node(), __toCommonJS(node_exports))("connect:dispatcher");
	var EventEmitter$4 = __require("events").EventEmitter;
	var finalhandler = require_finalhandler();
	var http$6 = __require("http");
	var merge = require_utils_merge();
	var parseUrl = require_parseurl();
	/**
	* Module exports.
	* @public
	*/
	module.exports = createServer;
	/**
	* Module variables.
	* @private
	*/
	var env = process.env.NODE_ENV || "development";
	var proto = {};
	/* istanbul ignore next */
	var defer = typeof setImmediate === "function" ? setImmediate : function(fn) {
		process.nextTick(fn.bind.apply(fn, arguments));
	};
	/**
	* Create a new connect server.
	*
	* @return {function}
	* @public
	*/
	function createServer() {
		function app(req, res, next) {
			app.handle(req, res, next);
		}
		merge(app, proto);
		merge(app, EventEmitter$4.prototype);
		app.route = "/";
		app.stack = [];
		return app;
	}
	/**
	* Utilize the given middleware `handle` to the given `route`,
	* defaulting to _/_. This "route" is the mount-point for the
	* middleware, when given a value other than _/_ the middleware
	* is only effective when that segment is present in the request's
	* pathname.
	*
	* For example if we were to mount a function at _/admin_, it would
	* be invoked on _/admin_, and _/admin/settings_, however it would
	* not be invoked for _/_, or _/posts_.
	*
	* @param {String|Function|Server} route, callback or server
	* @param {Function|Server} callback or server
	* @return {Server} for chaining
	* @public
	*/
	proto.use = function use(route, fn) {
		var handle = fn;
		var path = route;
		if (typeof route !== "string") {
			handle = route;
			path = "/";
		}
		if (typeof handle.handle === "function") {
			var server = handle;
			server.route = path;
			handle = function(req, res, next) {
				server.handle(req, res, next);
			};
		}
		if (handle instanceof http$6.Server) handle = handle.listeners("request")[0];
		if (path[path.length - 1] === "/") path = path.slice(0, -1);
		debug("use %s %s", path || "/", handle.name || "anonymous");
		this.stack.push({
			route: path,
			handle
		});
		return this;
	};
	/**
	* Handle server requests, punting them down
	* the middleware stack.
	*
	* @private
	*/
	proto.handle = function handle(req, res, out) {
		var index = 0;
		var protohost = getProtohost(req.url) || "";
		var removed = "";
		var slashAdded = false;
		var stack = this.stack;
		var done = out || finalhandler(req, res, {
			env,
			onerror: logerror
		});
		req.originalUrl = req.originalUrl || req.url;
		function next(err) {
			if (slashAdded) {
				req.url = req.url.substr(1);
				slashAdded = false;
			}
			if (removed.length !== 0) {
				req.url = protohost + removed + req.url.substr(protohost.length);
				removed = "";
			}
			var layer = stack[index++];
			if (!layer) {
				defer(done, err);
				return;
			}
			var path = parseUrl(req).pathname || "/";
			var route = layer.route;
			if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) return next(err);
			var c = path.length > route.length && path[route.length];
			if (c && c !== "/" && c !== ".") return next(err);
			if (route.length !== 0 && route !== "/") {
				removed = route;
				req.url = protohost + req.url.substr(protohost.length + removed.length);
				if (!protohost && req.url[0] !== "/") {
					req.url = "/" + req.url;
					slashAdded = true;
				}
			}
			call(layer.handle, route, err, req, res, next);
		}
		next();
	};
	/**
	* Listen for connections.
	*
	* This method takes the same arguments
	* as node's `http.Server#listen()`.
	*
	* HTTP and HTTPS:
	*
	* If you run your application both as HTTP
	* and HTTPS you may wrap them individually,
	* since your Connect "server" is really just
	* a JavaScript `Function`.
	*
	*      var connect = require('connect')
	*        , http = require('http')
	*        , https = require('https');
	*
	*      var app = connect();
	*
	*      http.createServer(app).listen(80);
	*      https.createServer(options, app).listen(443);
	*
	* @return {http.Server}
	* @api public
	*/
	proto.listen = function listen() {
		var server = http$6.createServer(this);
		return server.listen.apply(server, arguments);
	};
	/**
	* Invoke a route handle.
	* @private
	*/
	function call(handle, route, err, req, res, next) {
		var arity = handle.length;
		var error = err;
		var hasError = Boolean(err);
		debug("%s %s : %s", handle.name || "<anonymous>", route, req.originalUrl);
		try {
			if (hasError && arity === 4) {
				handle(err, req, res, next);
				return;
			} else if (!hasError && arity < 4) {
				handle(req, res, next);
				return;
			}
		} catch (e) {
			error = e;
		}
		next(error);
	}
	/**
	* Log error using console.error.
	*
	* @param {Error} err
	* @private
	*/
	function logerror(err) {
		if (env !== "test") console.error(err.stack || err.toString());
	}
	/**
	* Get get protocol + host for a URL.
	*
	* @param {string} url
	* @private
	*/
	function getProtohost(url) {
		if (url.length === 0 || url[0] === "/") return;
		var fqdnIndex = url.indexOf("://");
		return fqdnIndex !== -1 && url.lastIndexOf("?", fqdnIndex) === -1 ? url.substr(0, url.indexOf("/", 3 + fqdnIndex)) : void 0;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/object-assign@4.1.1/node_modules/object-assign/index.js
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var require_object_assign = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	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 = /* @__PURE__ */ 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;
			if (Object.getOwnPropertyNames(test2).map(function(n) {
				return test2[n];
			}).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 (err) {
			return false;
		}
	}
	module.exports = 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;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
/*!
* vary
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
var require_vary = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	*/
	module.exports = vary;
	module.exports.append = append;
	/**
	* RegExp to match field-name in RFC 7230 sec 3.2
	*
	* field-name    = token
	* token         = 1*tchar
	* tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
	*               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
	*               / DIGIT / ALPHA
	*               ; any VCHAR, except delimiters
	*/
	var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
	/**
	* Append a field to a vary header.
	*
	* @param {String} header
	* @param {String|Array} field
	* @return {String}
	* @public
	*/
	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(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(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;
	}
	/**
	* Parse a vary header into an array.
	*
	* @param {String} header
	* @return {Array}
	* @private
	*/
	function parse(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;
	}
	/**
	* Mark that a request is varied on a header field.
	*
	* @param {Object} res
	* @param {String|Array} field
	* @public
	*/
	function vary(res, field) {
		if (!res || !res.getHeader || !res.setHeader) throw new TypeError("res argument is required");
		var val = res.getHeader("Vary") || "";
		if (val = append(Array.isArray(val) ? val.join(", ") : String(val), field)) res.setHeader("Vary", val);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js
var require_lib$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function() {
		"use strict";
		var assign = require_object_assign();
		var vary = require_vary();
		var defaults = {
			origin: "*",
			methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
			preflightContinue: false,
			optionsSuccessStatus: 204
		};
		function isString(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 (isString(allowedOrigin)) return origin === allowedOrigin;
			else if (allowedOrigin instanceof RegExp) return allowedOrigin.test(origin);
			else return !!allowedOrigin;
		}
		function configureOrigin(options, req) {
			var requestOrigin = req.headers.origin, headers = [], isAllowed;
			if (!options.origin || options.origin === "*") headers.push([{
				key: "Access-Control-Allow-Origin",
				value: "*"
			}]);
			else if (isString(options.origin)) {
				headers.push([{
					key: "Access-Control-Allow-Origin",
					value: options.origin
				}]);
				headers.push([{
					key: "Vary",
					value: "Origin"
				}]);
			} else {
				isAllowed = isOriginAllowed(requestOrigin, options.origin);
				headers.push([{
					key: "Access-Control-Allow-Origin",
					value: isAllowed ? requestOrigin : false
				}]);
				headers.push([{
					key: "Vary",
					value: "Origin"
				}]);
			}
			return headers;
		}
		function configureMethods(options) {
			var methods = options.methods;
			if (methods.join) methods = options.methods.join(",");
			return {
				key: "Access-Control-Allow-Methods",
				value: methods
			};
		}
		function configureCredentials(options) {
			if (options.credentials === true) return {
				key: "Access-Control-Allow-Credentials",
				value: "true"
			};
			return null;
		}
		function configureAllowedHeaders(options, req) {
			var allowedHeaders = options.allowedHeaders || options.headers;
			var headers = [];
			if (!allowedHeaders) {
				allowedHeaders = req.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(options) {
			var headers = options.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(options) {
			var maxAge = (typeof options.maxAge === "number" || options.maxAge) && options.maxAge.toString();
			if (maxAge && maxAge.length) return {
				key: "Access-Control-Max-Age",
				value: maxAge
			};
			return null;
		}
		function applyHeaders(headers, res) {
			for (var i = 0, n = headers.length; i < n; i++) {
				var header = headers[i];
				if (header) {
					if (Array.isArray(header)) applyHeaders(header, res);
					else if (header.key === "Vary" && header.value) vary(res, header.value);
					else if (header.value) res.setHeader(header.key, header.value);
				}
			}
		}
		function cors(options, req, res, next) {
			var headers = [];
			if ((req.method && req.method.toUpperCase && req.method.toUpperCase()) === "OPTIONS") {
				headers.push(configureOrigin(options, req));
				headers.push(configureCredentials(options));
				headers.push(configureMethods(options));
				headers.push(configureAllowedHeaders(options, req));
				headers.push(configureMaxAge(options));
				headers.push(configureExposedHeaders(options));
				applyHeaders(headers, res);
				if (options.preflightContinue) next();
				else {
					res.statusCode = options.optionsSuccessStatus;
					res.setHeader("Content-Length", "0");
					res.end();
				}
			} else {
				headers.push(configureOrigin(options, req));
				headers.push(configureCredentials(options));
				headers.push(configureExposedHeaders(options));
				applyHeaders(headers, res);
				next();
			}
		}
		function middlewareWrapper(o) {
			var optionsCallback = null;
			if (typeof o === "function") optionsCallback = o;
			else optionsCallback = function(req, cb) {
				cb(null, o);
			};
			return function corsMiddleware(req, res, next) {
				optionsCallback(req, function(err, options) {
					if (err) next(err);
					else {
						var corsOptions = assign({}, defaults, options);
						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(req.headers.origin, function(err2, origin) {
							if (err2 || !origin) next(err2);
							else {
								corsOptions.origin = origin;
								cors(corsOptions, req, res, next);
							}
						});
						else next();
					}
				});
			};
		}
		module.exports = middlewareWrapper;
	})();
}));
//#endregion
//#region ../../node_modules/.pnpm/readdirp@3.6.0/node_modules/readdirp/index.js
var require_readdirp = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fs$10 = __require("fs");
	const { Readable: Readable$1 } = __require("stream");
	const sysPath$3 = __require("path");
	const { promisify: promisify$4 } = __require("util");
	const picomatch$1 = __require("picomatch");
	const readdir = promisify$4(fs$10.readdir);
	const stat = promisify$4(fs$10.stat);
	const lstat = promisify$4(fs$10.lstat);
	const realpath = promisify$4(fs$10.realpath);
	/**
	* @typedef {Object} EntryInfo
	* @property {String} path
	* @property {String} fullPath
	* @property {fs.Stats=} stats
	* @property {fs.Dirent=} dirent
	* @property {String} basename
	*/
	const BANG = "!";
	const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
	const NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set([
		"ENOENT",
		"EPERM",
		"EACCES",
		"ELOOP",
		RECURSIVE_ERROR_CODE
	]);
	const FILE_TYPE = "files";
	const DIR_TYPE = "directories";
	const FILE_DIR_TYPE = "files_directories";
	const EVERYTHING_TYPE = "all";
	const ALL_TYPES = [
		FILE_TYPE,
		DIR_TYPE,
		FILE_DIR_TYPE,
		EVERYTHING_TYPE
	];
	const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
	const [maj, min] = process.versions.node.split(".").slice(0, 2).map((n) => Number.parseInt(n, 10));
	const wantBigintFsStats = process.platform === "win32" && (maj > 10 || maj === 10 && min >= 5);
	const normalizeFilter = (filter) => {
		if (filter === void 0) return;
		if (typeof filter === "function") return filter;
		if (typeof filter === "string") {
			const glob = picomatch$1(filter.trim());
			return (entry) => glob(entry.basename);
		}
		if (Array.isArray(filter)) {
			const positive = [];
			const negative = [];
			for (const item of filter) {
				const trimmed = item.trim();
				if (trimmed.charAt(0) === BANG) negative.push(picomatch$1(trimmed.slice(1)));
				else positive.push(picomatch$1(trimmed));
			}
			if (negative.length > 0) {
				if (positive.length > 0) return (entry) => positive.some((f) => f(entry.basename)) && !negative.some((f) => f(entry.basename));
				return (entry) => !negative.some((f) => f(entry.basename));
			}
			return (entry) => positive.some((f) => f(entry.basename));
		}
	};
	var ReaddirpStream = class ReaddirpStream extends Readable$1 {
		static get defaultOptions() {
			return {
				root: ".",
				fileFilter: (path) => true,
				directoryFilter: (path) => true,
				type: FILE_TYPE,
				lstat: false,
				depth: 2147483648,
				alwaysStat: false
			};
		}
		constructor(options = {}) {
			super({
				objectMode: true,
				autoDestroy: true,
				highWaterMark: options.highWaterMark || 4096
			});
			const opts = {
				...ReaddirpStream.defaultOptions,
				...options
			};
			const { root, type } = opts;
			this._fileFilter = normalizeFilter(opts.fileFilter);
			this._directoryFilter = normalizeFilter(opts.directoryFilter);
			const statMethod = opts.lstat ? lstat : stat;
			if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
			else this._stat = statMethod;
			this._maxDepth = opts.depth;
			this._wantsDir = [
				DIR_TYPE,
				FILE_DIR_TYPE,
				EVERYTHING_TYPE
			].includes(type);
			this._wantsFile = [
				FILE_TYPE,
				FILE_DIR_TYPE,
				EVERYTHING_TYPE
			].includes(type);
			this._wantsEverything = type === EVERYTHING_TYPE;
			this._root = sysPath$3.resolve(root);
			this._isDirent = "Dirent" in fs$10 && !opts.alwaysStat;
			this._statsProp = this._isDirent ? "dirent" : "stats";
			this._rdOptions = {
				encoding: "utf8",
				withFileTypes: this._isDirent
			};
			this.parents = [this._exploreDir(root, 1)];
			this.reading = false;
			this.parent = void 0;
		}
		async _read(batch) {
			if (this.reading) return;
			this.reading = true;
			try {
				while (!this.destroyed && batch > 0) {
					const { path, depth, files = [] } = this.parent || {};
					if (files.length > 0) {
						const slice = files.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
						for (const entry of await Promise.all(slice)) {
							if (this.destroyed) return;
							const entryType = await this._getEntryType(entry);
							if (entryType === "directory" && this._directoryFilter(entry)) {
								if (depth <= this._maxDepth) this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
								if (this._wantsDir) {
									this.push(entry);
									batch--;
								}
							} else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
								if (this._wantsFile) {
									this.push(entry);
									batch--;
								}
							}
						}
					} else {
						const parent = this.parents.pop();
						if (!parent) {
							this.push(null);
							break;
						}
						this.parent = await parent;
						if (this.destroyed) return;
					}
				}
			} catch (error) {
				this.destroy(error);
			} finally {
				this.reading = false;
			}
		}
		async _exploreDir(path, depth) {
			let files;
			try {
				files = await readdir(path, this._rdOptions);
			} catch (error) {
				this._onError(error);
			}
			return {
				files,
				depth,
				path
			};
		}
		async _formatEntry(dirent, path) {
			let entry;
			try {
				const basename = this._isDirent ? dirent.name : dirent;
				const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
				entry = {
					path: sysPath$3.relative(this._root, fullPath),
					fullPath,
					basename
				};
				entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
			} catch (err) {
				this._onError(err);
			}
			return entry;
		}
		_onError(err) {
			if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
			else this.destroy(err);
		}
		async _getEntryType(entry) {
			const stats = entry && entry[this._statsProp];
			if (!stats) return;
			if (stats.isFile()) return "file";
			if (stats.isDirectory()) return "directory";
			if (stats && stats.isSymbolicLink()) {
				const full = entry.fullPath;
				try {
					const entryRealPath = await realpath(full);
					const entryRealPathStats = await lstat(entryRealPath);
					if (entryRealPathStats.isFile()) return "file";
					if (entryRealPathStats.isDirectory()) {
						const len = entryRealPath.length;
						if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
							const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
							recursiveError.code = RECURSIVE_ERROR_CODE;
							return this._onError(recursiveError);
						}
						return "directory";
					}
				} catch (error) {
					this._onError(error);
				}
			}
		}
		_includeAsFile(entry) {
			const stats = entry && entry[this._statsProp];
			return stats && this._wantsEverything && !stats.isDirectory();
		}
	};
	/**
	* @typedef {Object} ReaddirpArguments
	* @property {Function=} fileFilter
	* @property {Function=} directoryFilter
	* @property {String=} type
	* @property {Number=} depth
	* @property {String=} root
	* @property {Boolean=} lstat
	* @property {Boolean=} bigint
	*/
	/**
	* Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
	* @param {String} root Root directory
	* @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
	*/
	const readdirp = (root, options = {}) => {
		let type = options.entryType || options.type;
		if (type === "both") type = FILE_DIR_TYPE;
		if (type) options.type = type;
		if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
		else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
		else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
		options.root = root;
		return new ReaddirpStream(options);
	};
	const readdirpPromise = (root, options = {}) => {
		return new Promise((resolve, reject) => {
			const files = [];
			readdirp(root, options).on("data", (entry) => files.push(entry)).on("end", () => resolve(files)).on("error", (error) => reject(error));
		});
	};
	readdirp.promise = readdirpPromise;
	readdirp.ReaddirpStream = ReaddirpStream;
	readdirp.default = readdirp;
	module.exports = readdirp;
}));
//#endregion
//#region ../../node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js
var require_normalize_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/*!
	* normalize-path <https://github.com/jonschlinkert/normalize-path>
	*
	* Copyright (c) 2014-2018, Jon Schlinkert.
	* Released under the MIT License.
	*/
	module.exports = function(path, stripTrailing) {
		if (typeof path !== "string") throw new TypeError("expected path to be a string");
		if (path === "\\" || path === "/") return "/";
		var len = path.length;
		if (len <= 1) return path;
		var prefix = "";
		if (len > 4 && path[3] === "\\") {
			var ch = path[2];
			if ((ch === "?" || ch === ".") && path.slice(0, 2) === "\\\\") {
				path = path.slice(2);
				prefix = "//";
			}
		}
		var segs = path.split(/[/\\]+/);
		if (stripTrailing !== false && segs[segs.length - 1] === "") segs.pop();
		return prefix + segs.join("/");
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/anymatch@3.1.3/node_modules/anymatch/index.js
var require_anymatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const picomatch = __require("picomatch");
	const normalizePath = require_normalize_path();
	/**
	* @typedef {(testString: string) => boolean} AnymatchFn
	* @typedef {string|RegExp|AnymatchFn} AnymatchPattern
	* @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
	*/
	const BANG = "!";
	const DEFAULT_OPTIONS = { returnIndex: false };
	const arrify = (item) => Array.isArray(item) ? item : [item];
	/**
	* @param {AnymatchPattern} matcher
	* @param {object} options
	* @returns {AnymatchFn}
	*/
	const createPattern = (matcher, options) => {
		if (typeof matcher === "function") return matcher;
		if (typeof matcher === "string") {
			const glob = picomatch(matcher, options);
			return (string) => matcher === string || glob(string);
		}
		if (matcher instanceof RegExp) return (string) => matcher.test(string);
		return (string) => false;
	};
	/**
	* @param {Array<Function>} patterns
	* @param {Array<Function>} negPatterns
	* @param {String|Array} args
	* @param {Boolean} returnIndex
	* @returns {boolean|number}
	*/
	const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
		const isList = Array.isArray(args);
		const _path = isList ? args[0] : args;
		if (!isList && typeof _path !== "string") throw new TypeError("anymatch: second argument must be a string: got " + Object.prototype.toString.call(_path));
		const path = normalizePath(_path, false);
		for (let index = 0; index < negPatterns.length; index++) {
			const nglob = negPatterns[index];
			if (nglob(path)) return returnIndex ? -1 : false;
		}
		const applied = isList && [path].concat(args.slice(1));
		for (let index = 0; index < patterns.length; index++) {
			const pattern = patterns[index];
			if (isList ? pattern(...applied) : pattern(path)) return returnIndex ? index : true;
		}
		return returnIndex ? -1 : false;
	};
	/**
	* @param {AnymatchMatcher} matchers
	* @param {Array|string} testString
	* @param {object} options
	* @returns {boolean|number|Function}
	*/
	const anymatch = (matchers, testString, options = DEFAULT_OPTIONS) => {
		if (matchers == null) throw new TypeError("anymatch: specify first argument");
		const opts = typeof options === "boolean" ? { returnIndex: options } : options;
		const returnIndex = opts.returnIndex || false;
		const mtchers = arrify(matchers);
		const negatedGlobs = mtchers.filter((item) => typeof item === "string" && item.charAt(0) === BANG).map((item) => item.slice(1)).map((item) => picomatch(item, opts));
		const patterns = mtchers.filter((item) => typeof item !== "string" || typeof item === "string" && item.charAt(0) !== BANG).map((matcher) => createPattern(matcher, opts));
		if (testString == null) return (testString, ri = false) => {
			return matchPatterns(patterns, negatedGlobs, testString, typeof ri === "boolean" ? ri : false);
		};
		return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
	};
	anymatch.default = anymatch;
	module.exports = anymatch;
}));
//#endregion
//#region ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js
var require_is_extglob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/*!
	* is-extglob <https://github.com/jonschlinkert/is-extglob>
	*
	* Copyright (c) 2014-2016, Jon Schlinkert.
	* Licensed under the MIT License.
	*/
	module.exports = function isExtglob(str) {
		if (typeof str !== "string" || str === "") return false;
		var match;
		while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
			if (match[2]) return true;
			str = str.slice(match.index + match[0].length);
		}
		return false;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js
var require_is_glob = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/*!
	* is-glob <https://github.com/jonschlinkert/is-glob>
	*
	* Copyright (c) 2014-2017, Jon Schlinkert.
	* Released under the MIT License.
	*/
	var isExtglob = require_is_extglob();
	var chars = {
		"{": "}",
		"(": ")",
		"[": "]"
	};
	var strictCheck = function(str) {
		if (str[0] === "!") return true;
		var index = 0;
		var pipeIndex = -2;
		var closeSquareIndex = -2;
		var closeCurlyIndex = -2;
		var closeParenIndex = -2;
		var backSlashIndex = -2;
		while (index < str.length) {
			if (str[index] === "*") return true;
			if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) return true;
			if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
				if (closeSquareIndex < index) closeSquareIndex = str.indexOf("]", index);
				if (closeSquareIndex > index) {
					if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
					backSlashIndex = str.indexOf("\\", index);
					if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) return true;
				}
			}
			if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
				closeCurlyIndex = str.indexOf("}", index);
				if (closeCurlyIndex > index) {
					backSlashIndex = str.indexOf("\\", index);
					if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) return true;
				}
			}
			if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
				closeParenIndex = str.indexOf(")", index);
				if (closeParenIndex > index) {
					backSlashIndex = str.indexOf("\\", index);
					if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
				}
			}
			if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
				if (pipeIndex < index) pipeIndex = str.indexOf("|", index);
				if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
					closeParenIndex = str.indexOf(")", pipeIndex);
					if (closeParenIndex > pipeIndex) {
						backSlashIndex = str.indexOf("\\", pipeIndex);
						if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) return true;
					}
				}
			}
			if (str[index] === "\\") {
				var open = str[index + 1];
				index += 2;
				var close = chars[open];
				if (close) {
					var n = str.indexOf(close, index);
					if (n !== -1) index = n + 1;
				}
				if (str[index] === "!") return true;
			} else index++;
		}
		return false;
	};
	var relaxedCheck = function(str) {
		if (str[0] === "!") return true;
		var index = 0;
		while (index < str.length) {
			if (/[*?{}()[\]]/.test(str[index])) return true;
			if (str[index] === "\\") {
				var open = str[index + 1];
				index += 2;
				var close = chars[open];
				if (close) {
					var n = str.indexOf(close, index);
					if (n !== -1) index = n + 1;
				}
				if (str[index] === "!") return true;
			} else index++;
		}
		return false;
	};
	module.exports = function isGlob(str, options) {
		if (typeof str !== "string" || str === "") return false;
		if (isExtglob(str)) return true;
		var check = strictCheck;
		if (options && options.strict === false) check = relaxedCheck;
		return check(str);
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js
var require_glob_parent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var isGlob = require_is_glob();
	var pathPosixDirname = __require("path").posix.dirname;
	var isWin32 = __require("os").platform() === "win32";
	var slash = "/";
	var backslash = /\\/g;
	var enclosure = /[\{\[].*[\}\]]$/;
	var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
	var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
	/**
	* @param {string} str
	* @param {Object} opts
	* @param {boolean} [opts.flipBackslashes=true]
	* @returns {string}
	*/
	module.exports = function globParent(str, opts) {
		if (Object.assign({ flipBackslashes: true }, opts).flipBackslashes && isWin32 && str.indexOf(slash) < 0) str = str.replace(backslash, slash);
		if (enclosure.test(str)) str += slash;
		str += "a";
		do
			str = pathPosixDirname(str);
		while (isGlob(str) || globby.test(str));
		return str.replace(escaped, "$1");
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js
var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
	exports.isInteger = (num) => {
		if (typeof num === "number") return Number.isInteger(num);
		if (typeof num === "string" && num.trim() !== "") return Number.isInteger(Number(num));
		return false;
	};
	/**
	* Find a node of the given type
	*/
	exports.find = (node, type) => node.nodes.find((node) => node.type === type);
	/**
	* Find a node of the given type
	*/
	exports.exceedsLimit = (min, max, step = 1, limit) => {
		if (limit === false) return false;
		if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
		return (Number(max) - Number(min)) / Number(step) >= limit;
	};
	/**
	* Escape the given node with '\\' before node.value
	*/
	exports.escapeNode = (block, n = 0, type) => {
		const node = block.nodes[n];
		if (!node) return;
		if (type && node.type === type || node.type === "open" || node.type === "close") {
			if (node.escaped !== true) {
				node.value = "\\" + node.value;
				node.escaped = true;
			}
		}
	};
	/**
	* Returns true if the given brace node should be enclosed in literal braces
	*/
	exports.encloseBrace = (node) => {
		if (node.type !== "brace") return false;
		if (node.commas >> 0 + node.ranges >> 0 === 0) {
			node.invalid = true;
			return true;
		}
		return false;
	};
	/**
	* Returns true if a brace node is invalid.
	*/
	exports.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;
	};
	/**
	* Returns true if a node is an open or close node
	*/
	exports.isOpenOrClose = (node) => {
		if (node.type === "open" || node.type === "close") return true;
		return node.open === true || node.close === true;
	};
	/**
	* Reduce an array of text nodes.
	*/
	exports.reduce = (nodes) => nodes.reduce((acc, node) => {
		if (node.type === "text") acc.push(node.value);
		if (node.type === "range") node.type = "text";
		return acc;
	}, []);
	/**
	* Flatten an array
	*/
	exports.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;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js
var require_stringify = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const utils = require_utils();
	module.exports = (ast, options = {}) => {
		const stringify = (node, parent = {}) => {
			const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
			const invalidNode = node.invalid === true && options.escapeInvalid === true;
			let output = "";
			if (node.value) {
				if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) return "\\" + node.value;
				return node.value;
			}
			if (node.value) return node.value;
			if (node.nodes) for (const child of node.nodes) output += stringify(child);
			return output;
		};
		return stringify(ast);
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js
/*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Released under the MIT License.
*/
var require_is_number = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = function(num) {
		if (typeof num === "number") return num - num === 0;
		if (typeof num === "string" && num.trim() !== "") return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
		return false;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js
/*!
* to-regex-range <https://github.com/micromatch/to-regex-range>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*/
var require_to_regex_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const isNumber = require_is_number();
	const toRegexRange = (min, max, options) => {
		if (isNumber(min) === false) throw new TypeError("toRegexRange: expected the first argument to be a number");
		if (max === void 0 || min === max) return String(min);
		if (isNumber(max) === false) throw new TypeError("toRegexRange: expected the second argument to be a number.");
		let opts = {
			relaxZeros: true,
			...options
		};
		if (typeof opts.strictZeros === "boolean") opts.relaxZeros = opts.strictZeros === false;
		let relax = String(opts.relaxZeros);
		let shorthand = String(opts.shorthand);
		let capture = String(opts.capture);
		let wrap = String(opts.wrap);
		let cacheKey = min + ":" + max + "=" + relax + shorthand + capture + wrap;
		if (toRegexRange.cache.hasOwnProperty(cacheKey)) return toRegexRange.cache[cacheKey].result;
		let a = Math.min(min, max);
		let b = Math.max(min, max);
		if (Math.abs(a - b) === 1) {
			let result = min + "|" + max;
			if (opts.capture) return `(${result})`;
			if (opts.wrap === false) return result;
			return `(?:${result})`;
		}
		let isPadded = hasPadding(min) || hasPadding(max);
		let state = {
			min,
			max,
			a,
			b
		};
		let positives = [];
		let negatives = [];
		if (isPadded) {
			state.isPadded = isPadded;
			state.maxLen = String(state.max).length;
		}
		if (a < 0) {
			negatives = splitToPatterns(b < 0 ? Math.abs(b) : 1, Math.abs(a), state, opts);
			a = state.a = 0;
		}
		if (b >= 0) positives = splitToPatterns(a, b, state, opts);
		state.negatives = negatives;
		state.positives = positives;
		state.result = collatePatterns(negatives, positives, opts);
		if (opts.capture === true) state.result = `(${state.result})`;
		else if (opts.wrap !== false && positives.length + negatives.length > 1) state.result = `(?:${state.result})`;
		toRegexRange.cache[cacheKey] = state;
		return state.result;
	};
	function collatePatterns(neg, pos, options) {
		let onlyNegative = filterPatterns(neg, pos, "-", false, options) || [];
		let onlyPositive = filterPatterns(pos, neg, "", false, options) || [];
		let intersected = filterPatterns(neg, pos, "-?", true, options) || [];
		return onlyNegative.concat(intersected).concat(onlyPositive).join("|");
	}
	function splitToRanges(min, max) {
		let nines = 1;
		let zeros = 1;
		let stop = countNines(min, nines);
		let stops = /* @__PURE__ */ new Set([max]);
		while (min <= stop && stop <= max) {
			stops.add(stop);
			nines += 1;
			stop = countNines(min, nines);
		}
		stop = countZeros(max + 1, zeros) - 1;
		while (min < stop && stop <= max) {
			stops.add(stop);
			zeros += 1;
			stop = countZeros(max + 1, zeros) - 1;
		}
		stops = [...stops];
		stops.sort(compare);
		return stops;
	}
	/**
	* Convert a range to a regex pattern
	* @param {Number} `start`
	* @param {Number} `stop`
	* @return {String}
	*/
	function rangeToPattern(start, stop, options) {
		if (start === stop) return {
			pattern: start,
			count: [],
			digits: 0
		};
		let zipped = zip(start, stop);
		let digits = zipped.length;
		let pattern = "";
		let count = 0;
		for (let i = 0; i < digits; i++) {
			let [startDigit, stopDigit] = zipped[i];
			if (startDigit === stopDigit) pattern += startDigit;
			else if (startDigit !== "0" || stopDigit !== "9") pattern += toCharacterClass(startDigit, stopDigit, options);
			else count++;
		}
		if (count) pattern += options.shorthand === true ? "\\d" : "[0-9]";
		return {
			pattern,
			count: [count],
			digits
		};
	}
	function splitToPatterns(min, max, tok, options) {
		let ranges = splitToRanges(min, max);
		let tokens = [];
		let start = min;
		let prev;
		for (let i = 0; i < ranges.length; i++) {
			let max = ranges[i];
			let obj = rangeToPattern(String(start), String(max), options);
			let zeros = "";
			if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
				if (prev.count.length > 1) prev.count.pop();
				prev.count.push(obj.count[0]);
				prev.string = prev.pattern + toQuantifier(prev.count);
				start = max + 1;
				continue;
			}
			if (tok.isPadded) zeros = padZeros(max, tok, options);
			obj.string = zeros + obj.pattern + toQuantifier(obj.count);
			tokens.push(obj);
			start = max + 1;
			prev = obj;
		}
		return tokens;
	}
	function filterPatterns(arr, comparison, prefix, intersection, options) {
		let result = [];
		for (let ele of arr) {
			let { string } = ele;
			if (!intersection && !contains(comparison, "string", string)) result.push(prefix + string);
			if (intersection && contains(comparison, "string", string)) result.push(prefix + string);
		}
		return result;
	}
	/**
	* Zip strings
	*/
	function zip(a, b) {
		let arr = [];
		for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
		return arr;
	}
	function compare(a, b) {
		return a > b ? 1 : b > a ? -1 : 0;
	}
	function contains(arr, key, val) {
		return arr.some((ele) => ele[key] === val);
	}
	function countNines(min, len) {
		return Number(String(min).slice(0, -len) + "9".repeat(len));
	}
	function countZeros(integer, zeros) {
		return integer - integer % Math.pow(10, zeros);
	}
	function toQuantifier(digits) {
		let [start = 0, stop = ""] = digits;
		if (stop || start > 1) return `{${start + (stop ? "," + stop : "")}}`;
		return "";
	}
	function toCharacterClass(a, b, options) {
		return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
	}
	function hasPadding(str) {
		return /^-?(0+)\d/.test(str);
	}
	function padZeros(value, tok, options) {
		if (!tok.isPadded) return value;
		let diff = Math.abs(tok.maxLen - String(value).length);
		let relax = options.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}}`;
		}
	}
	/**
	* Cache
	*/
	toRegexRange.cache = {};
	toRegexRange.clearCache = () => toRegexRange.cache = {};
	/**
	* Expose `toRegexRange`
	*/
	module.exports = toRegexRange;
}));
//#endregion
//#region ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js
/*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Licensed under the MIT License.
*/
var require_fill_range = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const util = __require("util");
	const toRegexRange = require_to_regex_range();
	const isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
	const transform = (toNumber) => {
		return (value) => toNumber === true ? Number(value) : String(value);
	};
	const isValidValue = (value) => {
		return typeof value === "number" || typeof value === "string" && value !== "";
	};
	const isNumber = (num) => Number.isInteger(+num);
	const zeros = (input) => {
		let value = `${input}`;
		let index = -1;
		if (value[0] === "-") value = value.slice(1);
		if (value === "0") return false;
		while (value[++index] === "0");
		return index > 0;
	};
	const stringify = (start, end, options) => {
		if (typeof start === "string" || typeof end === "string") return true;
		return options.stringify === true;
	};
	const 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;
	};
	const 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;
	};
	const toSequence = (parts, options, maxLen) => {
		parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
		parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
		let prefix = options.capture ? "" : "?:";
		let positives = "";
		let negatives = "";
		let result;
		if (parts.positives.length) positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
		if (parts.negatives.length) negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
		if (positives && negatives) result = `${positives}|${negatives}`;
		else result = positives || negatives;
		if (options.wrap) return `(${prefix}${result})`;
		return result;
	};
	const toRange = (a, b, isNumbers, options) => {
		if (isNumbers) return toRegexRange(a, b, {
			wrap: false,
			...options
		});
		let start = String.fromCharCode(a);
		if (a === b) return start;
		return `[${start}-${String.fromCharCode(b)}]`;
	};
	const toRegex = (start, end, options) => {
		if (Array.isArray(start)) return options.wrap === true ? `(${options.capture ? "" : "?:"}${start.join("|")})` : start.join("|");
		return toRegexRange(start, end, options);
	};
	const rangeError = (...args) => {
		return /* @__PURE__ */ new RangeError("Invalid range arguments: " + util.inspect(...args));
	};
	const invalidRange = (start, end, options) => {
		if (options.strictRanges === true) throw rangeError([start, end]);
		return [];
	};
	const invalidStep = (step, options) => {
		if (options.strictRanges === true) throw new TypeError(`Expected step "${step}" to be a number`);
		return [];
	};
	const fillNumbers = (start, end, step = 1, options = {}) => {
		let a = Number(start);
		let b = Number(end);
		if (!Number.isInteger(a) || !Number.isInteger(b)) {
			if (options.strictRanges === true) throw rangeError([start, end]);
			return [];
		}
		if (a === 0) a = 0;
		if (b === 0) b = 0;
		let descending = a > b;
		let startString = String(start);
		let endString = String(end);
		let stepString = String(step);
		step = Math.max(Math.abs(step), 1);
		let padded = zeros(startString) || zeros(endString) || zeros(stepString);
		let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
		let toNumber = padded === false && stringify(start, end, options) === false;
		let format = options.transform || transform(toNumber);
		if (options.toRegex && step === 1) return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
		let parts = {
			negatives: [],
			positives: []
		};
		let push = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
		let range = [];
		let index = 0;
		while (descending ? a >= b : a <= b) {
			if (options.toRegex === true && step > 1) push(a);
			else range.push(pad(format(a, index), maxLen, toNumber));
			a = descending ? a - step : a + step;
			index++;
		}
		if (options.toRegex === true) return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, {
			wrap: false,
			...options
		});
		return range;
	};
	const fillLetters = (start, end, step = 1, options = {}) => {
		if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) return invalidRange(start, end, options);
		let format = options.transform || ((val) => String.fromCharCode(val));
		let a = `${start}`.charCodeAt(0);
		let b = `${end}`.charCodeAt(0);
		let descending = a > b;
		let min = Math.min(a, b);
		let max = Math.max(a, b);
		if (options.toRegex && step === 1) return toRange(min, max, false, options);
		let range = [];
		let index = 0;
		while (descending ? a >= b : a <= b) {
			range.push(format(a, index));
			a = descending ? a - step : a + step;
			index++;
		}
		if (options.toRegex === true) return toRegex(range, null, {
			wrap: false,
			options
		});
		return range;
	};
	const fill = (start, end, step, options = {}) => {
		if (end == null && isValidValue(start)) return [start];
		if (!isValidValue(start) || !isValidValue(end)) return invalidRange(start, end, options);
		if (typeof step === "function") return fill(start, end, 1, { transform: step });
		if (isObject(step)) return fill(start, end, 0, step);
		let opts = { ...options };
		if (opts.capture === true) opts.wrap = true;
		step = step || opts.step || 1;
		if (!isNumber(step)) {
			if (step != null && !isObject(step)) return invalidStep(step, opts);
			return fill(start, end, 1, step);
		}
		if (isNumber(start) && isNumber(end)) return fillNumbers(start, end, step, opts);
		return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
	};
	module.exports = fill;
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js
var require_compile = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fill = require_fill_range();
	const utils = require_utils();
	const compile = (ast, options = {}) => {
		const walk = (node, parent = {}) => {
			const invalid = utils.isInvalidBrace(parent) === true || (node.invalid === true && options.escapeInvalid === true) === true;
			const prefix = options.escapeInvalid === true ? "\\" : "";
			let output = "";
			if (node.isOpen === true) return prefix + node.value;
			if (node.isClose === true) {
				console.log("node.isClose", prefix, node.value);
				return prefix + node.value;
			}
			if (node.type === "open") return invalid ? prefix + node.value : "(";
			if (node.type === "close") return invalid ? prefix + node.value : ")";
			if (node.type === "comma") return node.prev.type === "comma" ? "" : invalid ? node.value : "|";
			if (node.value) return node.value;
			if (node.nodes && node.ranges > 0) {
				const args = utils.reduce(node.nodes);
				const range = fill(...args, {
					...options,
					wrap: false,
					toRegex: true,
					strictZeros: true
				});
				if (range.length !== 0) return args.length > 1 && range.length > 1 ? `(${range})` : range;
			}
			if (node.nodes) for (const child of node.nodes) output += walk(child, node);
			return output;
		};
		return walk(ast);
	};
	module.exports = compile;
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js
var require_expand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fill = require_fill_range();
	const stringify = require_stringify();
	const utils = require_utils();
	const append = (queue = "", stash = "", enclose = false) => {
		const result = [];
		queue = [].concat(queue);
		stash = [].concat(stash);
		if (!stash.length) return queue;
		if (!queue.length) return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash;
		for (const item of queue) if (Array.isArray(item)) for (const value of item) result.push(append(value, stash, enclose));
		else for (let ele of stash) {
			if (enclose === true && typeof ele === "string") ele = `{${ele}}`;
			result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
		}
		return utils.flatten(result);
	};
	const expand = (ast, options = {}) => {
		const rangeLimit = options.rangeLimit === void 0 ? 1e3 : options.rangeLimit;
		const walk = (node, parent = {}) => {
			node.queue = [];
			let p = parent;
			let q = parent.queue;
			while (p.type !== "brace" && p.type !== "root" && p.parent) {
				p = p.parent;
				q = p.queue;
			}
			if (node.invalid || node.dollar) {
				q.push(append(q.pop(), stringify(node, options)));
				return;
			}
			if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) {
				q.push(append(q.pop(), ["{}"]));
				return;
			}
			if (node.nodes && node.ranges > 0) {
				const args = utils.reduce(node.nodes);
				if (utils.exceedsLimit(...args, options.step, rangeLimit)) throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
				let range = fill(...args, options);
				if (range.length === 0) range = stringify(node, options);
				q.push(append(q.pop(), range));
				node.nodes = [];
				return;
			}
			const enclose = utils.encloseBrace(node);
			let queue = node.queue;
			let block = node;
			while (block.type !== "brace" && block.type !== "root" && block.parent) {
				block = block.parent;
				queue = block.queue;
			}
			for (let i = 0; i < node.nodes.length; i++) {
				const child = node.nodes[i];
				if (child.type === "comma" && node.type === "brace") {
					if (i === 1) queue.push("");
					queue.push("");
					continue;
				}
				if (child.type === "close") {
					q.push(append(q.pop(), queue, enclose));
					continue;
				}
				if (child.value && child.type !== "open") {
					queue.push(append(queue.pop(), child.value));
					continue;
				}
				if (child.nodes) walk(child, node);
			}
			return queue;
		};
		return utils.flatten(walk(ast));
	};
	module.exports = expand;
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js
var require_constants$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		MAX_LENGTH: 1e4,
		CHAR_0: "0",
		CHAR_9: "9",
		CHAR_UPPERCASE_A: "A",
		CHAR_LOWERCASE_A: "a",
		CHAR_UPPERCASE_Z: "Z",
		CHAR_LOWERCASE_Z: "z",
		CHAR_LEFT_PARENTHESES: "(",
		CHAR_RIGHT_PARENTHESES: ")",
		CHAR_ASTERISK: "*",
		CHAR_AMPERSAND: "&",
		CHAR_AT: "@",
		CHAR_BACKSLASH: "\\",
		CHAR_BACKTICK: "`",
		CHAR_CARRIAGE_RETURN: "\r",
		CHAR_CIRCUMFLEX_ACCENT: "^",
		CHAR_COLON: ":",
		CHAR_COMMA: ",",
		CHAR_DOLLAR: "$",
		CHAR_DOT: ".",
		CHAR_DOUBLE_QUOTE: "\"",
		CHAR_EQUAL: "=",
		CHAR_EXCLAMATION_MARK: "!",
		CHAR_FORM_FEED: "\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",
		CHAR_NO_BREAK_SPACE: "\xA0",
		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: "	",
		CHAR_UNDERSCORE: "_",
		CHAR_VERTICAL_LINE: "|",
		CHAR_ZERO_WIDTH_NOBREAK_SPACE: "﻿"
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js
var require_parse$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const stringify = require_stringify();
	/**
	* Constants
	*/
	const { MAX_LENGTH, CHAR_BACKSLASH, CHAR_BACKTICK, CHAR_COMMA, CHAR_DOT, CHAR_LEFT_PARENTHESES, CHAR_RIGHT_PARENTHESES, CHAR_LEFT_CURLY_BRACE, CHAR_RIGHT_CURLY_BRACE, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_DOUBLE_QUOTE, CHAR_SINGLE_QUOTE, CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = require_constants$2();
	/**
	* parse
	*/
	const parse = (input, options = {}) => {
		if (typeof input !== "string") throw new TypeError("Expected a string");
		const opts = options || {};
		const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
		if (input.length > max) throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
		const ast = {
			type: "root",
			input,
			nodes: []
		};
		const stack = [ast];
		let block = ast;
		let prev = ast;
		let brackets = 0;
		const length = input.length;
		let index = 0;
		let depth = 0;
		let value;
		/**
		* Helpers
		*/
		const advance = () => input[index++];
		const push = (node) => {
			if (node.type === "text" && prev.type === "dot") prev.type = "text";
			if (prev && prev.type === "text" && node.type === "text") {
				prev.value += node.value;
				return;
			}
			block.nodes.push(node);
			node.parent = block;
			node.prev = prev;
			prev = node;
			return node;
		};
		push({ type: "bos" });
		while (index < length) {
			block = stack[stack.length - 1];
			value = advance();
			/**
			* Invalid chars
			*/
			if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) continue;
			/**
			* Escaped chars
			*/
			if (value === CHAR_BACKSLASH) {
				push({
					type: "text",
					value: (options.keepEscaping ? value : "") + advance()
				});
				continue;
			}
			/**
			* Right square bracket (literal): ']'
			*/
			if (value === CHAR_RIGHT_SQUARE_BRACKET) {
				push({
					type: "text",
					value: "\\" + value
				});
				continue;
			}
			/**
			* Left square bracket: '['
			*/
			if (value === CHAR_LEFT_SQUARE_BRACKET) {
				brackets++;
				let next;
				while (index < length && (next = advance())) {
					value += next;
					if (next === CHAR_LEFT_SQUARE_BRACKET) {
						brackets++;
						continue;
					}
					if (next === CHAR_BACKSLASH) {
						value += advance();
						continue;
					}
					if (next === CHAR_RIGHT_SQUARE_BRACKET) {
						brackets--;
						if (brackets === 0) break;
					}
				}
				push({
					type: "text",
					value
				});
				continue;
			}
			/**
			* Parentheses
			*/
			if (value === CHAR_LEFT_PARENTHESES) {
				block = push({
					type: "paren",
					nodes: []
				});
				stack.push(block);
				push({
					type: "text",
					value
				});
				continue;
			}
			if (value === CHAR_RIGHT_PARENTHESES) {
				if (block.type !== "paren") {
					push({
						type: "text",
						value
					});
					continue;
				}
				block = stack.pop();
				push({
					type: "text",
					value
				});
				block = stack[stack.length - 1];
				continue;
			}
			/**
			* Quotes: '|"|`
			*/
			if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
				const open = value;
				let next;
				if (options.keepQuotes !== true) value = "";
				while (index < length && (next = advance())) {
					if (next === CHAR_BACKSLASH) {
						value += next + advance();
						continue;
					}
					if (next === open) {
						if (options.keepQuotes === true) value += next;
						break;
					}
					value += next;
				}
				push({
					type: "text",
					value
				});
				continue;
			}
			/**
			* Left curly brace: '{'
			*/
			if (value === CHAR_LEFT_CURLY_BRACE) {
				depth++;
				block = push({
					type: "brace",
					open: true,
					close: false,
					dollar: prev.value && prev.value.slice(-1) === "$" || block.dollar === true,
					depth,
					commas: 0,
					ranges: 0,
					nodes: []
				});
				stack.push(block);
				push({
					type: "open",
					value
				});
				continue;
			}
			/**
			* Right curly brace: '}'
			*/
			if (value === CHAR_RIGHT_CURLY_BRACE) {
				if (block.type !== "brace") {
					push({
						type: "text",
						value
					});
					continue;
				}
				const type = "close";
				block = stack.pop();
				block.close = true;
				push({
					type,
					value
				});
				depth--;
				block = stack[stack.length - 1];
				continue;
			}
			/**
			* Comma: ','
			*/
			if (value === CHAR_COMMA && depth > 0) {
				if (block.ranges > 0) {
					block.ranges = 0;
					const open = block.nodes.shift();
					block.nodes = [open, {
						type: "text",
						value: stringify(block)
					}];
				}
				push({
					type: "comma",
					value
				});
				block.commas++;
				continue;
			}
			/**
			* Dot: '.'
			*/
			if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
				const siblings = block.nodes;
				if (depth === 0 || siblings.length === 0) {
					push({
						type: "text",
						value
					});
					continue;
				}
				if (prev.type === "dot") {
					block.range = [];
					prev.value += value;
					prev.type = "range";
					if (block.nodes.length !== 3 && block.nodes.length !== 5) {
						block.invalid = true;
						block.ranges = 0;
						prev.type = "text";
						continue;
					}
					block.ranges++;
					block.args = [];
					continue;
				}
				if (prev.type === "range") {
					siblings.pop();
					const before = siblings[siblings.length - 1];
					before.value += prev.value + value;
					prev = before;
					block.ranges--;
					continue;
				}
				push({
					type: "dot",
					value
				});
				continue;
			}
			/**
			* Text
			*/
			push({
				type: "text",
				value
			});
		}
		do {
			block = stack.pop();
			if (block.type !== "root") {
				block.nodes.forEach((node) => {
					if (!node.nodes) {
						if (node.type === "open") node.isOpen = true;
						if (node.type === "close") node.isClose = true;
						if (!node.nodes) node.type = "text";
						node.invalid = true;
					}
				});
				const parent = stack[stack.length - 1];
				const index = parent.nodes.indexOf(block);
				parent.nodes.splice(index, 1, ...block.nodes);
			}
		} while (stack.length > 0);
		push({ type: "eos" });
		return ast;
	};
	module.exports = parse;
}));
//#endregion
//#region ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js
var require_braces = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const stringify = require_stringify();
	const compile = require_compile();
	const expand = require_expand();
	const parse = require_parse$2();
	/**
	* Expand the given pattern or create a regex-compatible string.
	*
	* ```js
	* const braces = require('braces');
	* console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
	* console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
	* ```
	* @param {String} `str`
	* @param {Object} `options`
	* @return {String}
	* @api public
	*/
	const braces = (input, options = {}) => {
		let output = [];
		if (Array.isArray(input)) for (const pattern of input) {
			const result = braces.create(pattern, options);
			if (Array.isArray(result)) output.push(...result);
			else output.push(result);
		}
		else output = [].concat(braces.create(input, options));
		if (options && options.expand === true && options.nodupes === true) output = [...new Set(output)];
		return output;
	};
	/**
	* Parse the given `str` with the given `options`.
	*
	* ```js
	* // braces.parse(pattern, [, options]);
	* const ast = braces.parse('a/{b,c}/d');
	* console.log(ast);
	* ```
	* @param {String} pattern Brace pattern to parse
	* @param {Object} options
	* @return {Object} Returns an AST
	* @api public
	*/
	braces.parse = (input, options = {}) => parse(input, options);
	/**
	* Creates a braces string from an AST, or an AST node.
	*
	* ```js
	* const braces = require('braces');
	* let ast = braces.parse('foo/{a,b}/bar');
	* console.log(stringify(ast.nodes[2])); //=> '{a,b}'
	* ```
	* @param {String} `input` Brace pattern or AST.
	* @param {Object} `options`
	* @return {Array} Returns an array of expanded values.
	* @api public
	*/
	braces.stringify = (input, options = {}) => {
		if (typeof input === "string") return stringify(braces.parse(input, options), options);
		return stringify(input, options);
	};
	/**
	* Compiles a brace pattern into a regex-compatible, optimized string.
	* This method is called by the main [braces](#braces) function by default.
	*
	* ```js
	* const braces = require('braces');
	* console.log(braces.compile('a/{b,c}/d'));
	* //=> ['a/(b|c)/d']
	* ```
	* @param {String} `input` Brace pattern or AST.
	* @param {Object} `options`
	* @return {Array} Returns an array of expanded values.
	* @api public
	*/
	braces.compile = (input, options = {}) => {
		if (typeof input === "string") input = braces.parse(input, options);
		return compile(input, options);
	};
	/**
	* Expands a brace pattern into an array. This method is called by the
	* main [braces](#braces) function when `options.expand` is true. Before
	* using this method it's recommended that you read the [performance notes](#performance))
	* and advantages of using [.compile](#compile) instead.
	*
	* ```js
	* const braces = require('braces');
	* console.log(braces.expand('a/{b,c}/d'));
	* //=> ['a/b/d', 'a/c/d'];
	* ```
	* @param {String} `pattern` Brace pattern
	* @param {Object} `options`
	* @return {Array} Returns an array of expanded values.
	* @api public
	*/
	braces.expand = (input, options = {}) => {
		if (typeof input === "string") input = braces.parse(input, options);
		let result = expand(input, options);
		if (options.noempty === true) result = result.filter(Boolean);
		if (options.nodupes === true) result = [...new Set(result)];
		return result;
	};
	/**
	* Processes a brace pattern and returns either an expanded array
	* (if `options.expand` is true), a highly optimized regex-compatible string.
	* This method is called by the main [braces](#braces) function.
	*
	* ```js
	* const braces = require('braces');
	* console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
	* //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
	* ```
	* @param {String} `pattern` Brace pattern
	* @param {Object} `options`
	* @return {Array} Returns an array of expanded values.
	* @api public
	*/
	braces.create = (input, options = {}) => {
		if (input === "" || input.length < 3) return [input];
		return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
	};
	/**
	* Expose "braces"
	*/
	module.exports = braces;
}));
//#endregion
//#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/binary-extensions.json
var require_binary_extensions$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = [
		"3dm",
		"3ds",
		"3g2",
		"3gp",
		"7z",
		"a",
		"aac",
		"adp",
		"afdesign",
		"afphoto",
		"afpub",
		"ai",
		"aif",
		"aiff",
		"alz",
		"ape",
		"apk",
		"appimage",
		"ar",
		"arj",
		"asf",
		"au",
		"avi",
		"bak",
		"baml",
		"bh",
		"bin",
		"bk",
		"bmp",
		"btif",
		"bz2",
		"bzip2",
		"cab",
		"caf",
		"cgm",
		"class",
		"cmx",
		"cpio",
		"cr2",
		"cur",
		"dat",
		"dcm",
		"deb",
		"dex",
		"djvu",
		"dll",
		"dmg",
		"dng",
		"doc",
		"docm",
		"docx",
		"dot",
		"dotm",
		"dra",
		"DS_Store",
		"dsk",
		"dts",
		"dtshd",
		"dvb",
		"dwg",
		"dxf",
		"ecelp4800",
		"ecelp7470",
		"ecelp9600",
		"egg",
		"eol",
		"eot",
		"epub",
		"exe",
		"f4v",
		"fbs",
		"fh",
		"fla",
		"flac",
		"flatpak",
		"fli",
		"flv",
		"fpx",
		"fst",
		"fvt",
		"g3",
		"gh",
		"gif",
		"graffle",
		"gz",
		"gzip",
		"h261",
		"h263",
		"h264",
		"icns",
		"ico",
		"ief",
		"img",
		"ipa",
		"iso",
		"jar",
		"jpeg",
		"jpg",
		"jpgv",
		"jpm",
		"jxr",
		"key",
		"ktx",
		"lha",
		"lib",
		"lvp",
		"lz",
		"lzh",
		"lzma",
		"lzo",
		"m3u",
		"m4a",
		"m4v",
		"mar",
		"mdi",
		"mht",
		"mid",
		"midi",
		"mj2",
		"mka",
		"mkv",
		"mmr",
		"mng",
		"mobi",
		"mov",
		"movie",
		"mp3",
		"mp4",
		"mp4a",
		"mpeg",
		"mpg",
		"mpga",
		"mxu",
		"nef",
		"npx",
		"numbers",
		"nupkg",
		"o",
		"odp",
		"ods",
		"odt",
		"oga",
		"ogg",
		"ogv",
		"otf",
		"ott",
		"pages",
		"pbm",
		"pcx",
		"pdb",
		"pdf",
		"pea",
		"pgm",
		"pic",
		"png",
		"pnm",
		"pot",
		"potm",
		"potx",
		"ppa",
		"ppam",
		"ppm",
		"pps",
		"ppsm",
		"ppsx",
		"ppt",
		"pptm",
		"pptx",
		"psd",
		"pya",
		"pyc",
		"pyo",
		"pyv",
		"qt",
		"rar",
		"ras",
		"raw",
		"resources",
		"rgb",
		"rip",
		"rlc",
		"rmf",
		"rmvb",
		"rpm",
		"rtf",
		"rz",
		"s3m",
		"s7z",
		"scpt",
		"sgi",
		"shar",
		"snap",
		"sil",
		"sketch",
		"slk",
		"smv",
		"snk",
		"so",
		"stl",
		"suo",
		"sub",
		"swf",
		"tar",
		"tbz",
		"tbz2",
		"tga",
		"tgz",
		"thmx",
		"tif",
		"tiff",
		"tlz",
		"ttc",
		"ttf",
		"txz",
		"udf",
		"uvh",
		"uvi",
		"uvm",
		"uvp",
		"uvs",
		"uvu",
		"viv",
		"vob",
		"war",
		"wav",
		"wax",
		"wbmp",
		"wdp",
		"weba",
		"webm",
		"webp",
		"whl",
		"wim",
		"wm",
		"wma",
		"wmv",
		"wmx",
		"woff",
		"woff2",
		"wrm",
		"wvx",
		"xbm",
		"xif",
		"xla",
		"xlam",
		"xls",
		"xlsb",
		"xlsm",
		"xlsx",
		"xlt",
		"xltm",
		"xltx",
		"xm",
		"xmind",
		"xpi",
		"xpm",
		"xwd",
		"xz",
		"z",
		"zip",
		"zipx"
	];
}));
//#endregion
//#region ../../node_modules/.pnpm/binary-extensions@2.3.0/node_modules/binary-extensions/index.js
var require_binary_extensions = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = require_binary_extensions$1();
}));
//#endregion
//#region ../../node_modules/.pnpm/is-binary-path@2.1.0/node_modules/is-binary-path/index.js
var require_is_binary_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$10 = __require("path");
	const binaryExtensions = require_binary_extensions();
	const extensions = new Set(binaryExtensions);
	module.exports = (filePath) => extensions.has(path$10.extname(filePath).slice(1).toLowerCase());
}));
//#endregion
//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/constants.js
var require_constants$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	const { sep: sep$1 } = __require("path");
	const { platform } = process;
	const os$3 = __require("os");
	exports.EV_ALL = "all";
	exports.EV_READY = "ready";
	exports.EV_ADD = "add";
	exports.EV_CHANGE = "change";
	exports.EV_ADD_DIR = "addDir";
	exports.EV_UNLINK = "unlink";
	exports.EV_UNLINK_DIR = "unlinkDir";
	exports.EV_RAW = "raw";
	exports.EV_ERROR = "error";
	exports.STR_DATA = "data";
	exports.STR_END = "end";
	exports.STR_CLOSE = "close";
	exports.FSEVENT_CREATED = "created";
	exports.FSEVENT_MODIFIED = "modified";
	exports.FSEVENT_DELETED = "deleted";
	exports.FSEVENT_MOVED = "moved";
	exports.FSEVENT_CLONED = "cloned";
	exports.FSEVENT_UNKNOWN = "unknown";
	exports.FSEVENT_FLAG_MUST_SCAN_SUBDIRS = 1;
	exports.FSEVENT_TYPE_FILE = "file";
	exports.FSEVENT_TYPE_DIRECTORY = "directory";
	exports.FSEVENT_TYPE_SYMLINK = "symlink";
	exports.KEY_LISTENERS = "listeners";
	exports.KEY_ERR = "errHandlers";
	exports.KEY_RAW = "rawEmitters";
	exports.HANDLER_KEYS = [
		exports.KEY_LISTENERS,
		exports.KEY_ERR,
		exports.KEY_RAW
	];
	exports.DOT_SLASH = `.${sep$1}`;
	exports.BACK_SLASH_RE = /\\/g;
	exports.DOUBLE_SLASH_RE = /\/\//;
	exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
	exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
	exports.REPLACER_RE = /^\.[/\\]/;
	exports.SLASH = "/";
	exports.SLASH_SLASH = "//";
	exports.BRACE_START = "{";
	exports.BANG = "!";
	exports.ONE_DOT = ".";
	exports.TWO_DOTS = "..";
	exports.STAR = "*";
	exports.GLOBSTAR = "**";
	exports.ROOT_GLOBSTAR = "/**/*";
	exports.SLASH_GLOBSTAR = "/**";
	exports.DIR_SUFFIX = "Dir";
	exports.ANYMATCH_OPTS = { dot: true };
	exports.STRING_TYPE = "string";
	exports.FUNCTION_TYPE = "function";
	exports.EMPTY_STR = "";
	exports.EMPTY_FN = () => {};
	exports.IDENTITY_FN = (val) => val;
	exports.isWindows = platform === "win32";
	exports.isMacos = platform === "darwin";
	exports.isLinux = platform === "linux";
	exports.isIBMi = os$3.type() === "OS400";
}));
//#endregion
//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/nodefs-handler.js
var require_nodefs_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fs$9 = __require("fs");
	const sysPath$2 = __require("path");
	const { promisify: promisify$3 } = __require("util");
	const isBinaryPath = require_is_binary_path();
	const { isWindows, isLinux, EMPTY_FN, EMPTY_STR, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, EV_CHANGE, EV_ADD, EV_ADD_DIR, EV_ERROR, STR_DATA, STR_END, BRACE_START, STAR } = require_constants$1();
	const THROTTLE_MODE_WATCH = "watch";
	const open = promisify$3(fs$9.open);
	const stat = promisify$3(fs$9.stat);
	const lstat = promisify$3(fs$9.lstat);
	const close = promisify$3(fs$9.close);
	const fsrealpath = promisify$3(fs$9.realpath);
	const statMethods = {
		lstat,
		stat
	};
	const foreach = (val, fn) => {
		if (val instanceof Set) val.forEach(fn);
		else fn(val);
	};
	const addAndConvert = (main, prop, item) => {
		let container = main[prop];
		if (!(container instanceof Set)) main[prop] = container = /* @__PURE__ */ new Set([container]);
		container.add(item);
	};
	const clearItem = (cont) => (key) => {
		const set = cont[key];
		if (set instanceof Set) set.clear();
		else delete cont[key];
	};
	const delFromSet = (main, prop, item) => {
		const container = main[prop];
		if (container instanceof Set) container.delete(item);
		else if (container === item) delete main[prop];
	};
	const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
	/**
	* @typedef {String} Path
	*/
	/**
	* @typedef {Object} FsWatchContainer
	* @property {Set} listeners
	* @property {Set} errHandlers
	* @property {Set} rawEmitters
	* @property {fs.FSWatcher=} watcher
	* @property {Boolean=} watcherUnusable
	*/
	/**
	* @type {Map<String,FsWatchContainer>}
	*/
	const FsWatchInstances = /* @__PURE__ */ new Map();
	/**
	* Instantiates the fs_watch interface
	* @param {String} path to be watched
	* @param {Object} options to be passed to fs_watch
	* @param {Function} listener main event handler
	* @param {Function} errHandler emits info about errors
	* @param {Function} emitRaw emits raw event data
	* @returns {fs.FSWatcher} new fsevents instance
	*/
	function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
		const handleEvent = (rawEvent, evPath) => {
			listener(path);
			emitRaw(rawEvent, evPath, { watchedPath: path });
			if (evPath && path !== evPath) fsWatchBroadcast(sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath));
		};
		try {
			return fs$9.watch(path, options, handleEvent);
		} catch (error) {
			errHandler(error);
		}
	}
	/**
	* Helper for passing fs_watch event data to a collection of listeners
	* @param {Path} fullPath absolute path bound to fs_watch instance
	* @param {String} type listener type
	* @param {*=} val1 arguments to be passed to listeners
	* @param {*=} val2
	* @param {*=} val3
	*/
	const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
		const cont = FsWatchInstances.get(fullPath);
		if (!cont) return;
		foreach(cont[type], (listener) => {
			listener(val1, val2, val3);
		});
	};
	/**
	* Instantiates the fs_watch interface or binds listeners
	* to an existing one covering the same file system entry
	* @param {String} path
	* @param {String} fullPath absolute path
	* @param {Object} options to be passed to fs_watch
	* @param {Object} handlers container for event listener functions
	*/
	const setFsWatchListener = (path, fullPath, options, handlers) => {
		const { listener, errHandler, rawEmitter } = handlers;
		let cont = FsWatchInstances.get(fullPath);
		/** @type {fs.FSWatcher=} */
		let watcher;
		if (!options.persistent) {
			watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
			return watcher.close.bind(watcher);
		}
		if (cont) {
			addAndConvert(cont, KEY_LISTENERS, listener);
			addAndConvert(cont, KEY_ERR, errHandler);
			addAndConvert(cont, KEY_RAW, rawEmitter);
		} else {
			watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
			if (!watcher) return;
			watcher.on(EV_ERROR, async (error) => {
				const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
				cont.watcherUnusable = true;
				if (isWindows && error.code === "EPERM") try {
					await close(await open(path, "r"));
					broadcastErr(error);
				} catch (err) {}
				else broadcastErr(error);
			});
			cont = {
				listeners: listener,
				errHandlers: errHandler,
				rawEmitters: rawEmitter,
				watcher
			};
			FsWatchInstances.set(fullPath, cont);
		}
		return () => {
			delFromSet(cont, KEY_LISTENERS, listener);
			delFromSet(cont, KEY_ERR, errHandler);
			delFromSet(cont, KEY_RAW, rawEmitter);
			if (isEmptySet(cont.listeners)) {
				cont.watcher.close();
				FsWatchInstances.delete(fullPath);
				HANDLER_KEYS.forEach(clearItem(cont));
				cont.watcher = void 0;
				Object.freeze(cont);
			}
		};
	};
	const FsWatchFileInstances = /* @__PURE__ */ new Map();
	/**
	* Instantiates the fs_watchFile interface or binds listeners
	* to an existing one covering the same file system entry
	* @param {String} path to be watched
	* @param {String} fullPath absolute path
	* @param {Object} options options to be passed to fs_watchFile
	* @param {Object} handlers container for event listener functions
	* @returns {Function} closer
	*/
	const setFsWatchFileListener = (path, fullPath, options, handlers) => {
		const { listener, rawEmitter } = handlers;
		let cont = FsWatchFileInstances.get(fullPath);
		const copts = cont && cont.options;
		if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
			fs$9.unwatchFile(fullPath);
			cont = void 0;
		}
		if (cont) {
			addAndConvert(cont, KEY_LISTENERS, listener);
			addAndConvert(cont, KEY_RAW, rawEmitter);
		} else {
			cont = {
				listeners: listener,
				rawEmitters: rawEmitter,
				options,
				watcher: fs$9.watchFile(fullPath, options, (curr, prev) => {
					foreach(cont.rawEmitters, (rawEmitter) => {
						rawEmitter(EV_CHANGE, fullPath, {
							curr,
							prev
						});
					});
					const currmtime = curr.mtimeMs;
					if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
				})
			};
			FsWatchFileInstances.set(fullPath, cont);
		}
		return () => {
			delFromSet(cont, KEY_LISTENERS, listener);
			delFromSet(cont, KEY_RAW, rawEmitter);
			if (isEmptySet(cont.listeners)) {
				FsWatchFileInstances.delete(fullPath);
				fs$9.unwatchFile(fullPath);
				cont.options = cont.watcher = void 0;
				Object.freeze(cont);
			}
		};
	};
	/**
	* @mixin
	*/
	var NodeFsHandler = class {
		/**
		* @param {import("../index").FSWatcher} fsW
		*/
		constructor(fsW) {
			this.fsw = fsW;
			this._boundHandleError = (error) => fsW._handleError(error);
		}
		/**
		* Watch file for changes with fs_watchFile or fs_watch.
		* @param {String} path to file or dir
		* @param {Function} listener on fs change
		* @returns {Function} closer for the watcher instance
		*/
		_watchWithNodeFs(path, listener) {
			const opts = this.fsw.options;
			const directory = sysPath$2.dirname(path);
			const basename = sysPath$2.basename(path);
			this.fsw._getWatchedDir(directory).add(basename);
			const absolutePath = sysPath$2.resolve(path);
			const options = { persistent: opts.persistent };
			if (!listener) listener = EMPTY_FN;
			let closer;
			if (opts.usePolling) {
				options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
				closer = setFsWatchFileListener(path, absolutePath, options, {
					listener,
					rawEmitter: this.fsw._emitRaw
				});
			} else closer = setFsWatchListener(path, absolutePath, options, {
				listener,
				errHandler: this._boundHandleError,
				rawEmitter: this.fsw._emitRaw
			});
			return closer;
		}
		/**
		* Watch a file and emit add event if warranted.
		* @param {Path} file Path
		* @param {fs.Stats} stats result of fs_stat
		* @param {Boolean} initialAdd was the file added at watch instantiation?
		* @returns {Function} closer for the watcher instance
		*/
		_handleFile(file, stats, initialAdd) {
			if (this.fsw.closed) return;
			const dirname = sysPath$2.dirname(file);
			const basename = sysPath$2.basename(file);
			const parent = this.fsw._getWatchedDir(dirname);
			let prevStats = stats;
			if (parent.has(basename)) return;
			const listener = async (path, newStats) => {
				if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
				if (!newStats || newStats.mtimeMs === 0) try {
					const newStats = await stat(file);
					if (this.fsw.closed) return;
					const at = newStats.atimeMs;
					const mt = newStats.mtimeMs;
					if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
					if (isLinux && prevStats.ino !== newStats.ino) {
						this.fsw._closeFile(path);
						prevStats = newStats;
						this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
					} else prevStats = newStats;
				} catch (error) {
					this.fsw._remove(dirname, basename);
				}
				else if (parent.has(basename)) {
					const at = newStats.atimeMs;
					const mt = newStats.mtimeMs;
					if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV_CHANGE, file, newStats);
					prevStats = newStats;
				}
			};
			const closer = this._watchWithNodeFs(file, listener);
			if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
				if (!this.fsw._throttle(EV_ADD, file, 0)) return;
				this.fsw._emit(EV_ADD, file, stats);
			}
			return closer;
		}
		/**
		* Handle symlinks encountered while reading a dir.
		* @param {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(entry, directory, path, item) {
			if (this.fsw.closed) return;
			const full = entry.fullPath;
			const dir = this.fsw._getWatchedDir(directory);
			if (!this.fsw.options.followSymlinks) {
				this.fsw._incrReadyCount();
				let linkPath;
				try {
					linkPath = await fsrealpath(path);
				} catch (e) {
					this.fsw._emitReady();
					return true;
				}
				if (this.fsw.closed) return;
				if (dir.has(item)) {
					if (this.fsw._symlinkPaths.get(full) !== linkPath) {
						this.fsw._symlinkPaths.set(full, linkPath);
						this.fsw._emit(EV_CHANGE, path, entry.stats);
					}
				} else {
					dir.add(item);
					this.fsw._symlinkPaths.set(full, linkPath);
					this.fsw._emit(EV_ADD, path, entry.stats);
				}
				this.fsw._emitReady();
				return true;
			}
			if (this.fsw._symlinkPaths.has(full)) return true;
			this.fsw._symlinkPaths.set(full, true);
		}
		_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
			directory = sysPath$2.join(directory, EMPTY_STR);
			if (!wh.hasGlob) {
				throttler = this.fsw._throttle("readdir", directory, 1e3);
				if (!throttler) return;
			}
			const previous = this.fsw._getWatchedDir(wh.path);
			const current = /* @__PURE__ */ new Set();
			let stream = this.fsw._readdirp(directory, {
				fileFilter: (entry) => wh.filterPath(entry),
				directoryFilter: (entry) => wh.filterDir(entry),
				depth: 0
			}).on(STR_DATA, async (entry) => {
				if (this.fsw.closed) {
					stream = void 0;
					return;
				}
				const item = entry.path;
				let path = sysPath$2.join(directory, item);
				current.add(item);
				if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
				if (this.fsw.closed) {
					stream = void 0;
					return;
				}
				if (item === target || !target && !previous.has(item)) {
					this.fsw._incrReadyCount();
					path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
					this._addToNodeFs(path, initialAdd, wh, depth + 1);
				}
			}).on(EV_ERROR, this._boundHandleError);
			return new Promise((resolve) => stream.once(STR_END, () => {
				if (this.fsw.closed) {
					stream = void 0;
					return;
				}
				const wasThrottled = throttler ? throttler.clear() : false;
				resolve();
				previous.getChildren().filter((item) => {
					return item !== directory && !current.has(item) && (!wh.hasGlob || wh.filterPath({ fullPath: sysPath$2.resolve(directory, item) }));
				}).forEach((item) => {
					this.fsw._remove(directory, item);
				});
				stream = void 0;
				if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
			}));
		}
		/**
		* Read directory to add / remove files from `@watched` list and re-read it on change.
		* @param {String} dir fs path
		* @param {fs.Stats} stats
		* @param {Boolean} initialAdd
		* @param {Number} depth relative to user-supplied path
		* @param {String} target child path targeted for watch
		* @param {Object} wh Common watch helpers for this path
		* @param {String} realpath
		* @returns {Promise<Function>} closer for the watcher instance.
		*/
		async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
			const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
			const tracked = parentDir.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, dir, stats);
			}
			parentDir.add(sysPath$2.basename(dir));
			this.fsw._getWatchedDir(dir);
			let throttler;
			let closer;
			const oDepth = this.fsw.options.depth;
			if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
				if (!target) {
					await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
					if (this.fsw.closed) return;
				}
				closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
					if (stats && stats.mtimeMs === 0) return;
					this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
				});
			}
			return closer;
		}
		/**
		* Handle added file, directory, or glob pattern.
		* Delegates call to _handleFile / _handleDir after checks.
		* @param {String} path to file or ir
		* @param {Boolean} initialAdd was the file added at watch instantiation?
		* @param {Object} priorWh depth relative to user-supplied path
		* @param {Number} depth Child path actually targeted for watch
		* @param {String=} target Child path actually targeted for watch
		* @returns {Promise}
		*/
		async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
			const ready = this.fsw._emitReady;
			if (this.fsw._isIgnored(path) || this.fsw.closed) {
				ready();
				return false;
			}
			const wh = this.fsw._getWatchHelpers(path, depth);
			if (!wh.hasGlob && priorWh) {
				wh.hasGlob = priorWh.hasGlob;
				wh.globFilter = priorWh.globFilter;
				wh.filterPath = (entry) => priorWh.filterPath(entry);
				wh.filterDir = (entry) => priorWh.filterDir(entry);
			}
			try {
				const stats = await statMethods[wh.statMethod](wh.watchPath);
				if (this.fsw.closed) return;
				if (this.fsw._isIgnored(wh.watchPath, stats)) {
					ready();
					return false;
				}
				const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
				let closer;
				if (stats.isDirectory()) {
					const absPath = sysPath$2.resolve(path);
					const targetPath = follow ? await fsrealpath(path) : path;
					if (this.fsw.closed) return;
					closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
					if (this.fsw.closed) return;
					if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
				} else if (stats.isSymbolicLink()) {
					const targetPath = follow ? await fsrealpath(path) : path;
					if (this.fsw.closed) return;
					const parent = sysPath$2.dirname(wh.watchPath);
					this.fsw._getWatchedDir(parent).add(wh.watchPath);
					this.fsw._emit(EV_ADD, wh.watchPath, stats);
					closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
					if (this.fsw.closed) return;
					if (targetPath !== void 0) this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
				} else closer = this._handleFile(wh.watchPath, stats, initialAdd);
				ready();
				this.fsw._addPathCloser(path, closer);
				return false;
			} catch (error) {
				if (this.fsw._handleError(error)) {
					ready();
					return path;
				}
			}
		}
	};
	module.exports = NodeFsHandler;
}));
//#endregion
//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/lib/fsevents-handler.js
var require_fsevents_handler = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fs$8 = __require("fs");
	const sysPath$1 = __require("path");
	const { promisify: promisify$2 } = __require("util");
	let fsevents;
	try {
		fsevents = __require("fsevents");
	} catch (error) {
		if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
	}
	if (fsevents) {
		const mtch = process.version.match(/v(\d+)\.(\d+)/);
		if (mtch && mtch[1] && mtch[2]) {
			if (Number.parseInt(mtch[1], 10) === 8 && Number.parseInt(mtch[2], 10) < 16) fsevents = void 0;
		}
	}
	const { EV_ADD, EV_CHANGE, EV_ADD_DIR, EV_UNLINK, EV_ERROR, STR_DATA, STR_END, FSEVENT_CREATED, FSEVENT_MODIFIED, FSEVENT_DELETED, FSEVENT_MOVED, FSEVENT_UNKNOWN, FSEVENT_FLAG_MUST_SCAN_SUBDIRS, FSEVENT_TYPE_FILE, FSEVENT_TYPE_DIRECTORY, FSEVENT_TYPE_SYMLINK, ROOT_GLOBSTAR, DIR_SUFFIX, DOT_SLASH, FUNCTION_TYPE, EMPTY_FN, IDENTITY_FN } = require_constants$1();
	const Depth = (value) => isNaN(value) ? {} : { depth: value };
	const stat = promisify$2(fs$8.stat);
	const lstat = promisify$2(fs$8.lstat);
	const realpath = promisify$2(fs$8.realpath);
	const statMethods = {
		stat,
		lstat
	};
	/**
	* @typedef {String} Path
	*/
	/**
	* @typedef {Object} FsEventsWatchContainer
	* @property {Set<Function>} listeners
	* @property {Function} rawEmitter
	* @property {{stop: Function}} watcher
	*/
	/**
	* Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
	* @type {Map<Path,FsEventsWatchContainer>}
	*/
	const FSEventsWatchers = /* @__PURE__ */ new Map();
	const consolidateThreshhold = 10;
	const wrongEventFlags = /* @__PURE__ */ new Set([
		69888,
		70400,
		71424,
		72704,
		73472,
		131328,
		131840,
		262912
	]);
	/**
	* Instantiates the fsevents interface
	* @param {Path} path path to be watched
	* @param {Function} callback called when fsevents is bound and ready
	* @returns {{stop: Function}} new fsevents instance
	*/
	const createFSEventsInstance = (path, callback) => {
		return { stop: fsevents.watch(path, callback) };
	};
	/**
	* Instantiates the fsevents interface or binds listeners to an existing one covering
	* the same file tree.
	* @param {Path} path           - to be watched
	* @param {Path} realPath       - real path for symlinks
	* @param {Function} listener   - called when fsevents emits events
	* @param {Function} rawEmitter - passes data to listeners of the 'raw' event
	* @returns {Function} closer
	*/
	function setFSEventsListener(path, realPath, listener, 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(path);
		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)) listener(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);
				});
			}
		};
	}
	const couldConsolidate = (path) => {
		let count = 0;
		for (const watchPath of FSEventsWatchers.keys()) if (watchPath.indexOf(path) === 0) {
			count++;
			if (count >= consolidateThreshhold) return true;
		}
		return false;
	};
	const canUse = () => fsevents && FSEventsWatchers.size < 128;
	const calcDepth = (path, root) => {
		let i = 0;
		while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
		return i;
	};
	const sameTypes = (info, stats) => info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() || info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() || info.type === FSEVENT_TYPE_FILE && stats.isFile();
	/**
	* @mixin
	*/
	var FsEventsHandler = class {
		/**
		* @param {import('../index').FSWatcher} fsw
		*/
		constructor(fsw) {
			this.fsw = fsw;
		}
		checkIgnored(path, stats) {
			const ipaths = this.fsw._ignoredPaths;
			if (this.fsw._isIgnored(path, stats)) {
				ipaths.add(path);
				if (stats && stats.isDirectory()) ipaths.add(path + ROOT_GLOBSTAR);
				return true;
			}
			ipaths.delete(path);
			ipaths.delete(path + ROOT_GLOBSTAR);
		}
		addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
			const event = watchedDir.has(item) ? EV_CHANGE : EV_ADD;
			this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
		}
		async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
			try {
				const stats = await stat(path);
				if (this.fsw.closed) return;
				if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
				else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
			} catch (error) {
				if (error.code === "EACCES") this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
				else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
			}
		}
		handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
			if (this.fsw.closed || this.checkIgnored(path)) return;
			if (event === EV_UNLINK) {
				const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
				if (isDirectory || watchedDir.has(item)) this.fsw._remove(parent, item, isDirectory);
			} else {
				if (event === EV_ADD) {
					if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
					if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
						const curDepth = opts.depth === void 0 ? void 0 : calcDepth(fullPath, realPath) + 1;
						return this._addToFsEvents(path, false, true, curDepth);
					}
					this.fsw._getWatchedDir(parent).add(item);
				}
				/**
				* @type {'add'|'addDir'|'unlink'|'unlinkDir'}
				*/
				const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
				this.fsw._emit(eventName, path);
				if (eventName === EV_ADD_DIR) this._addToFsEvents(path, false, true);
			}
		}
		/**
		* Handle symlinks encountered during directory scan
		* @param {String} watchPath  - file/dir path to be watched with fsevents
		* @param {String} realPath   - real path (in case of symlinks)
		* @param {Function} transform  - path transformer
		* @param {Function} globFilter - path filter in case a glob pattern was provided
		* @returns {Function} closer for the watcher instance
		*/
		_watchWithFsEvents(watchPath, realPath, transform, 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 path = transform(sysPath$1.join(watchPath, sysPath$1.relative(watchPath, fullPath)));
				if (globFilter && !globFilter(path)) return;
				const parent = sysPath$1.dirname(path);
				const item = sysPath$1.basename(path);
				const watchedDir = this.fsw._getWatchedDir(info.type === FSEVENT_TYPE_DIRECTORY ? path : parent);
				if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) if (typeof opts.ignored === FUNCTION_TYPE) {
					let stats;
					try {
						stats = await stat(path);
					} catch (error) {}
					if (this.fsw.closed) return;
					if (this.checkIgnored(path, stats)) return;
					if (sameTypes(info, stats)) this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
					else this.handleEvent(EV_UNLINK, path, fullPath, realPath, parent, watchedDir, item, info, opts);
				} else this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
				else switch (info.event) {
					case FSEVENT_CREATED:
					case FSEVENT_MODIFIED: return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
					case FSEVENT_DELETED:
					case FSEVENT_MOVED: return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
				}
			};
			const closer = setFSEventsListener(watchPath, realPath, watchCallback, this.fsw._emitRaw);
			this.fsw._emitReady();
			return closer;
		}
		/**
		* Handle symlinks encountered during directory scan
		* @param {String} linkPath path to symlink
		* @param {String} fullPath absolute path to the symlink
		* @param {Function} transform pre-existing path transformer
		* @param {Number} curDepth level of subdirectories traversed to where symlink is
		* @returns {Promise<void>}
		*/
		async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
			if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
			this.fsw._symlinkPaths.set(fullPath, true);
			this.fsw._incrReadyCount();
			try {
				const linkTarget = await realpath(linkPath);
				if (this.fsw.closed) return;
				if (this.fsw._isIgnored(linkTarget)) return this.fsw._emitReady();
				this.fsw._incrReadyCount();
				this._addToFsEvents(linkTarget || linkPath, (path) => {
					let aliasedPath = linkPath;
					if (linkTarget && linkTarget !== DOT_SLASH) aliasedPath = path.replace(linkTarget, linkPath);
					else if (path !== DOT_SLASH) aliasedPath = sysPath$1.join(linkPath, path);
					return transform(aliasedPath);
				}, false, curDepth);
			} catch (error) {
				if (this.fsw._handleError(error)) 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 : EV_ADD, pp, stats);
		}
		initWatch(realPath, path, 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(path, closer);
		}
		/**
		* Handle added path with fsevents
		* @param {String} path file/dir path or glob pattern
		* @param {Function|Boolean=} transform converts working path to what the user expects
		* @param {Boolean=} forceAdd ensure add is emitted
		* @param {Number=} priorDepth Level of subdirectories already traversed.
		* @returns {Promise<void>}
		*/
		async _addToFsEvents(path, transform, forceAdd, priorDepth) {
			if (this.fsw.closed) return;
			const opts = this.fsw.options;
			const processPath = typeof transform === FUNCTION_TYPE ? transform : IDENTITY_FN;
			const wh = this.fsw._getWatchHelpers(path);
			try {
				const stats = await statMethods[wh.statMethod](wh.watchPath);
				if (this.fsw.closed) return;
				if (this.fsw._isIgnored(wh.watchPath, stats)) throw null;
				if (stats.isDirectory()) {
					if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
					if (priorDepth && priorDepth > opts.depth) return;
					this.fsw._readdirp(wh.watchPath, {
						fileFilter: (entry) => wh.filterPath(entry),
						directoryFilter: (entry) => wh.filterDir(entry),
						...Depth(opts.depth - (priorDepth || 0))
					}).on(STR_DATA, (entry) => {
						if (this.fsw.closed) return;
						if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
						const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
						const { fullPath } = entry;
						if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
							const curDepth = opts.depth === void 0 ? void 0 : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
							this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
						} else this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
					}).on(EV_ERROR, EMPTY_FN).on(STR_END, () => {
						this.fsw._emitReady();
					});
				} else {
					this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
					this.fsw._emitReady();
				}
			} catch (error) {
				if (!error || this.fsw._handleError(error)) {
					this.fsw._emitReady();
					this.fsw._emitReady();
				}
			}
			if (opts.persistent && forceAdd !== true) if (typeof transform === FUNCTION_TYPE) this.initWatch(void 0, path, wh, processPath);
			else {
				let realPath;
				try {
					realPath = await realpath(wh.watchPath);
				} catch (e) {}
				this.initWatch(realPath, path, wh, processPath);
			}
		}
	};
	module.exports = FsEventsHandler;
	module.exports.canUse = canUse;
}));
//#endregion
//#region ../../node_modules/.pnpm/chokidar@3.6.0_patch_hash=8a4f9e2b397e6034b91a0508faae3cecb97f222313faa129d7cb0eb71e9d0e84/node_modules/chokidar/index.js
var require_chokidar = /* @__PURE__ */ __commonJSMin(((exports) => {
	const { EventEmitter: EventEmitter$3 } = __require("events");
	const fs$7 = __require("fs");
	const sysPath = __require("path");
	const { promisify: promisify$1 } = __require("util");
	const readdirp = require_readdirp();
	const anymatch = require_anymatch().default;
	const globParent = require_glob_parent();
	const isGlob = require_is_glob();
	const braces = require_braces();
	const normalizePath = require_normalize_path();
	const NodeFsHandler = require_nodefs_handler();
	const FsEventsHandler = require_fsevents_handler();
	const { EV_ALL, EV_READY, EV_ADD, EV_CHANGE, EV_UNLINK, EV_ADD_DIR, EV_UNLINK_DIR, EV_RAW, EV_ERROR, STR_CLOSE, STR_END, BACK_SLASH_RE, DOUBLE_SLASH_RE, SLASH_OR_BACK_SLASH_RE, DOT_RE, REPLACER_RE, SLASH, SLASH_SLASH, BRACE_START, BANG, ONE_DOT, TWO_DOTS, GLOBSTAR, SLASH_GLOBSTAR, ANYMATCH_OPTS, STRING_TYPE, FUNCTION_TYPE, EMPTY_STR, EMPTY_FN, isWindows, isMacos, isIBMi } = require_constants$1();
	const stat = promisify$1(fs$7.stat);
	const readdir = promisify$1(fs$7.readdir);
	/**
	* @typedef {String} Path
	* @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
	* @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
	*/
	/**
	*
	* @typedef {Object} WatchHelpers
	* @property {Boolean} followSymlinks
	* @property {'stat'|'lstat'} statMethod
	* @property {Path} path
	* @property {Path} watchPath
	* @property {Function} entryPath
	* @property {Boolean} hasGlob
	* @property {Object} globFilter
	* @property {Function} filterPath
	* @property {Function} filterDir
	*/
	const arrify = (value = []) => Array.isArray(value) ? value : [value];
	const flatten = (list, result = []) => {
		list.forEach((item) => {
			if (Array.isArray(item)) flatten(item, result);
			else result.push(item);
		});
		return result;
	};
	const unifyPaths = (paths_) => {
		/**
		* @type {Array<String>}
		*/
		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);
	};
	const toUnix = (string) => {
		let str = string.replace(BACK_SLASH_RE, SLASH);
		let prepend = false;
		if (str.startsWith(SLASH_SLASH)) prepend = true;
		while (str.match(DOUBLE_SLASH_RE)) str = str.replace(DOUBLE_SLASH_RE, SLASH);
		if (prepend) str = SLASH + str;
		return str;
	};
	const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
	const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
		if (typeof path !== STRING_TYPE) return path;
		return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
	};
	const getAbsolutePath = (path, cwd) => {
		if (sysPath.isAbsolute(path)) return path;
		if (path.startsWith(BANG)) return BANG + sysPath.join(cwd, path.slice(1));
		return sysPath.join(cwd, path);
	};
	const undef = (opts, key) => opts[key] === void 0;
	/**
	* Directory entry.
	* @property {Path} path
	* @property {Set<Path>} items
	*/
	var DirEntry = class {
		/**
		* @param {Path} dir
		* @param {Function} removeWatcher
		*/
		constructor(dir, removeWatcher) {
			this.path = dir;
			this._removeWatcher = removeWatcher;
			/** @type {Set<Path>} */
			this.items = /* @__PURE__ */ new Set();
		}
		add(item) {
			const { items } = this;
			if (!items) return;
			if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
		}
		async remove(item) {
			const { items } = this;
			if (!items) return;
			items.delete(item);
			if (items.size > 0) return;
			const dir = this.path;
			try {
				await readdir(dir);
			} catch (err) {
				if (this._removeWatcher) this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
			}
		}
		has(item) {
			const { items } = this;
			if (!items) return;
			return items.has(item);
		}
		/**
		* @returns {Array<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);
		}
	};
	const STAT_METHOD_F = "stat";
	const STAT_METHOD_L = "lstat";
	var WatchHelper = class {
		constructor(path, watchPath, follow, fsw) {
			this.fsw = fsw;
			this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
			this.watchPath = watchPath;
			this.fullWatchPath = sysPath.resolve(watchPath);
			this.hasGlob = watchPath !== path;
			/** @type {object|boolean} */
			if (path === EMPTY_STR) this.hasGlob = false;
			this.globSymlink = this.hasGlob && follow ? void 0 : false;
			this.globFilter = this.hasGlob ? anymatch(path, void 0, ANYMATCH_OPTS) : false;
			this.dirParts = this.getDirParts(path);
			this.dirParts.forEach((parts) => {
				if (parts.length > 1) parts.pop();
			});
			this.followSymlinks = follow;
			this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
		}
		checkGlobSymlink(entry) {
			if (this.globSymlink === void 0) this.globSymlink = entry.fullParentDir === this.fullWatchPath ? false : {
				realPath: entry.fullParentDir,
				linkPath: this.fullWatchPath
			};
			if (this.globSymlink) return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
			return entry.fullPath;
		}
		entryPath(entry) {
			return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, this.checkGlobSymlink(entry)));
		}
		filterPath(entry) {
			const { stats } = entry;
			if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
			const resolvedPath = this.entryPath(entry);
			return (this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ? this.globFilter(resolvedPath) : true) && this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
		}
		getDirParts(path) {
			if (!this.hasGlob) return [];
			const parts = [];
			(path.includes(BRACE_START) ? braces.expand(path) : [path]).forEach((path) => {
				parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
			});
			return parts;
		}
		filterDir(entry) {
			if (this.hasGlob) {
				const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
				let globstar = false;
				this.unmatchedGlob = !this.dirParts.some((parts) => {
					return parts.every((part, i) => {
						if (part === GLOBSTAR) globstar = true;
						return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
					});
				});
			}
			return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
		}
	};
	/**
	* Watches files & directories for changes. Emitted events:
	* `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
	*
	*     new FSWatcher()
	*       .add(directories)
	*       .on('add', path => log('File', path, 'was added'))
	*/
	var FSWatcher = class extends EventEmitter$3 {
		constructor(_opts) {
			super();
			const opts = {};
			if (_opts) Object.assign(opts, _opts);
			/** @type {Map<String, DirEntry>} */
			this._watched = /* @__PURE__ */ new Map();
			/** @type {Map<String, Array>} */
			this._closers = /* @__PURE__ */ new Map();
			/** @type {Set<String>} */
			this._ignoredPaths = /* @__PURE__ */ new Set();
			/** @type {Map<ThrottleType, Map>} */
			this._throttled = /* @__PURE__ */ new Map();
			/** @type {Map<Path, String|Boolean>} */
			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;
			if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
			if (undef(opts, "usePolling") && !opts.useFsEvents) opts.usePolling = isMacos;
			if (isIBMi) opts.usePolling = true;
			const envPoll = process.env.CHOKIDAR_USEPOLLING;
			if (envPoll !== void 0) {
				const envLower = envPoll.toLowerCase();
				if (envLower === "false" || envLower === "0") opts.usePolling = false;
				else if (envLower === "true" || envLower === "1") opts.usePolling = true;
				else opts.usePolling = !!envLower;
			}
			const envInterval = process.env.CHOKIDAR_INTERVAL;
			if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
			if (undef(opts, "atomic")) opts.atomic = !opts.usePolling && !opts.useFsEvents;
			if (opts.atomic) this._pendingUnlinks = /* @__PURE__ */ new Map();
			if (undef(opts, "followSymlinks")) opts.followSymlinks = true;
			if (undef(opts, "awaitWriteFinish")) opts.awaitWriteFinish = false;
			if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
			const awf = opts.awaitWriteFinish;
			if (awf) {
				if (!awf.stabilityThreshold) awf.stabilityThreshold = 2e3;
				if (!awf.pollInterval) awf.pollInterval = 100;
				this._pendingWrites = /* @__PURE__ */ new Map();
			}
			if (opts.ignored) opts.ignored = arrify(opts.ignored);
			let readyCalls = 0;
			this._emitReady = () => {
				readyCalls++;
				if (readyCalls >= this._readyCount) {
					this._emitReady = EMPTY_FN;
					this._readyEmitted = true;
					process.nextTick(() => this.emit(EV_READY));
				}
			};
			this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
			this._readyEmitted = false;
			this.options = opts;
			if (opts.useFsEvents) this._fsEventsHandler = new FsEventsHandler(this);
			else this._nodeFsHandler = new NodeFsHandler(this);
			Object.freeze(opts);
		}
		/**
		* 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((path) => {
				const absPath = getAbsolutePath(path, cwd);
				if (disableGlobbing || !isGlob(path)) return absPath;
				return normalizePath(absPath);
			});
			paths = paths.filter((path) => {
				if (path.startsWith(BANG)) {
					this._ignoredPaths.add(path.slice(1));
					return false;
				}
				this._ignoredPaths.delete(path);
				this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
				this._userIgnored = void 0;
				return true;
			});
			if (this.options.useFsEvents && this._fsEventsHandler) {
				if (!this._readyCount) this._readyCount = paths.length;
				if (this.options.persistent) this._readyCount += paths.length;
				paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
			} else {
				if (!this._readyCount) this._readyCount = 0;
				this._readyCount += paths.length;
				Promise.all(paths.map(async (path) => {
					const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
					if (res) this._emitReady();
					return res;
				})).then((results) => {
					if (this.closed) return;
					results.filter((item) => item).forEach((item) => {
						this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
					});
				});
			}
			return this;
		}
		/**
		* Close watchers or start ignoring events from specified paths.
		* @param {Path|Array<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((path) => {
				if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
					if (cwd) path = sysPath.join(cwd, path);
					path = sysPath.resolve(path);
				}
				this._closePath(path);
				this._ignoredPaths.add(path);
				if (this._watched.has(path)) this._ignoredPaths.add(path + SLASH_GLOBSTAR);
				this._userIgnored = void 0;
			});
			return this;
		}
		/**
		* Close watchers and remove all listeners from watched paths.
		* @returns {Promise<void>}.
		*/
		close() {
			if (this.closed) return this._closePromise;
			this.closed = true;
			this.removeAllListeners();
			const closers = [];
			this._closers.forEach((closerList) => closerList.forEach((closer) => {
				const promise = closer();
				if (promise instanceof Promise) closers.push(promise);
			}));
			this._streams.forEach((stream) => stream.destroy());
			this._userIgnored = void 0;
			this._readyCount = 0;
			this._readyEmitted = false;
			this._watched.forEach((dirent) => dirent.dispose());
			[
				"closers",
				"watched",
				"streams",
				"symlinkPaths",
				"throttled"
			].forEach((key) => {
				this[`_${key}`].clear();
			});
			this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
			return this._closePromise;
		}
		/**
		* Expose list of watched paths
		* @returns {Object} for chaining
		*/
		getWatched() {
			const watchList = {};
			this._watched.forEach((entry, dir) => {
				const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
				watchList[key || ONE_DOT] = entry.getChildren().sort();
			});
			return watchList;
		}
		emitWithAll(event, args) {
			this.emit(...args);
			if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
		}
		/**
		* Normalize and emit events.
		* Calling _emit DOES NOT MEAN emit() would be called!
		* @param {EventName} event Type of event
		* @param {Path} path File or directory path
		* @param {*=} val1 arguments to be passed with event
		* @param {*=} val2
		* @param {*=} val3
		* @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
		*/
		async _emit(event, path, val1, val2, val3) {
			if (this.closed) return;
			const opts = this.options;
			if (isWindows) path = sysPath.normalize(path);
			if (opts.cwd) path = sysPath.relative(opts.cwd, path);
			/** @type Array<any> */
			const args = [event, path];
			if (val3 !== void 0) args.push(val1, val2, val3);
			else if (val2 !== void 0) args.push(val1, val2);
			else if (val1 !== void 0) args.push(val1);
			const awf = opts.awaitWriteFinish;
			let pw;
			if (awf && (pw = this._pendingWrites.get(path))) {
				pw.lastChange = /* @__PURE__ */ new Date();
				return this;
			}
			if (opts.atomic) {
				if (event === EV_UNLINK) {
					this._pendingUnlinks.set(path, args);
					setTimeout(() => {
						this._pendingUnlinks.forEach((entry, path) => {
							this.emit(...entry);
							this.emit(EV_ALL, ...entry);
							this._pendingUnlinks.delete(path);
						});
					}, typeof opts.atomic === "number" ? opts.atomic : 100);
					return this;
				}
				if (event === EV_ADD && this._pendingUnlinks.has(path)) {
					event = args[0] = EV_CHANGE;
					this._pendingUnlinks.delete(path);
				}
			}
			if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
				const awfEmit = (err, stats) => {
					if (err) {
						event = args[0] = EV_ERROR;
						args[1] = err;
						this.emitWithAll(event, args);
					} else if (stats) {
						if (args.length > 2) args[2] = stats;
						else args.push(stats);
						this.emitWithAll(event, args);
					}
				};
				this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
				return this;
			}
			if (event === EV_CHANGE) {
				if (!this._throttle(EV_CHANGE, path, 50)) return this;
			}
			if (opts.alwaysStat && val1 === void 0 && (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)) {
				const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
				let stats;
				try {
					stats = await stat(fullPath);
				} catch (err) {}
				if (!stats || this.closed) return;
				args.push(stats);
			}
			this.emitWithAll(event, args);
			return this;
		}
		/**
		* Common handler for errors
		* @param {Error} error
		* @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
		*/
		_handleError(error) {
			const code = error && error.code;
			if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EV_ERROR, error);
			return error || this.closed;
		}
		/**
		* Helper utility for throttling
		* @param {ThrottleType} actionType type being throttled
		* @param {Path} path being acted upon
		* @param {Number} timeout duration of time to suppress duplicate actions
		* @returns {Object|false} tracking object or false if action should be suppressed
		*/
		_throttle(actionType, path, timeout) {
			if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
			/** @type {Map<Path, Object>} */
			const action = this._throttled.get(actionType);
			/** @type {Object} */
			const actionPath = action.get(path);
			if (actionPath) {
				actionPath.count++;
				return false;
			}
			let timeoutObject;
			const clear = () => {
				const item = action.get(path);
				const count = item ? item.count : 0;
				action.delete(path);
				clearTimeout(timeoutObject);
				if (item) clearTimeout(item.timeoutObject);
				return count;
			};
			timeoutObject = setTimeout(clear, timeout);
			const thr = {
				timeoutObject,
				clear,
				count: 0
			};
			action.set(path, thr);
			return thr;
		}
		_incrReadyCount() {
			return this._readyCount++;
		}
		/**
		* Awaits write operation to finish.
		* Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
		* @param {Path} path being acted upon
		* @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
		* @param {EventName} event
		* @param {Function} awfEmit Callback to be called when ready for event to be emitted.
		*/
		_awaitWriteFinish(path, threshold, event, awfEmit) {
			let timeoutHandler;
			let fullPath = path;
			if (this.options.cwd && !sysPath.isAbsolute(path)) fullPath = sysPath.join(this.options.cwd, path);
			const now = /* @__PURE__ */ new Date();
			const awaitWriteFinish = (prevStat) => {
				fs$7.stat(fullPath, (err, curStat) => {
					if (err || !this._pendingWrites.has(path)) {
						if (err && err.code !== "ENOENT") awfEmit(err);
						return;
					}
					const now = Number(/* @__PURE__ */ new Date());
					if (prevStat && curStat.size !== prevStat.size) this._pendingWrites.get(path).lastChange = now;
					if (now - this._pendingWrites.get(path).lastChange >= threshold) {
						this._pendingWrites.delete(path);
						awfEmit(void 0, curStat);
					} else timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval, curStat);
				});
			};
			if (!this._pendingWrites.has(path)) {
				this._pendingWrites.set(path, {
					lastChange: now,
					cancelWait: () => {
						this._pendingWrites.delete(path);
						clearTimeout(timeoutHandler);
						return event;
					}
				});
				timeoutHandler = setTimeout(awaitWriteFinish, this.options.awaitWriteFinish.pollInterval);
			}
		}
		_getGlobIgnored() {
			return [...this._ignoredPaths.values()];
		}
		/**
		* Determines whether user has asked to ignore this path.
		* @param {Path} path filepath or dir
		* @param {fs.Stats=} stats result of fs.stat
		* @returns {Boolean}
		*/
		_isIgnored(path, stats) {
			if (this.options.atomic && DOT_RE.test(path)) return true;
			if (!this._userIgnored) {
				const { cwd } = this.options;
				const ign = this.options.ignored;
				const ignored = ign && ign.map(normalizeIgnored(cwd));
				const paths = arrify(ignored).filter((path) => typeof path === STRING_TYPE && !isGlob(path)).map((path) => path + SLASH_GLOBSTAR);
				const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
				this._userIgnored = anymatch(list, void 0, ANYMATCH_OPTS);
			}
			return this._userIgnored([path, stats]);
		}
		_isntIgnored(path, stat) {
			return !this._isIgnored(path, stat);
		}
		/**
		* Provides a set of common helpers and properties relating to symlink and glob handling.
		* @param {Path} path file, directory, or glob pattern being watched
		* @param {Number=} depth at any depth > 0, this isn't a glob
		* @returns {WatchHelper} object containing helpers for this path
		*/
		_getWatchHelpers(path, depth) {
			const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
			const follow = this.options.followSymlinks;
			return new WatchHelper(path, watchPath, follow, this);
		}
		/**
		* 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);
		}
		/**
		* 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 st = (stats && Number.parseInt(stats.mode, 10)) & 511;
			const it = Number.parseInt(st.toString(8)[0], 10);
			return Boolean(4 & it);
		}
		/**
		* Handles emitting unlink events for
		* files and directories, and via recursion, for
		* files and directories within directories that are unlinked
		* @param {String} directory within which the following item is located
		* @param {String} item      base path of item/directory
		* @returns {void}
		*/
		_remove(directory, item, isDirectory) {
			const path = sysPath.join(directory, item);
			const fullPath = sysPath.resolve(path);
			isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
			if (!this._throttle("remove", path, 100)) return;
			if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) this.add(directory, item, true);
			this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
			const parent = this._getWatchedDir(directory);
			const wasTracked = parent.has(item);
			parent.remove(item);
			if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
			let relPath = path;
			if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
			if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
				if (this._pendingWrites.get(relPath).cancelWait() === EV_ADD) return;
			}
			this._watched.delete(path);
			this._watched.delete(fullPath);
			const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
			if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
			if (!this.options.useFsEvents) this._closePath(path);
		}
		/**
		* Closes all watchers for a path
		* @param {Path} path
		*/
		_closePath(path) {
			this._closeFile(path);
			const dir = sysPath.dirname(path);
			this._getWatchedDir(dir).remove(sysPath.basename(path));
		}
		/**
		* Closes only file-specific watchers
		* @param {Path} path
		*/
		_closeFile(path) {
			const closers = this._closers.get(path);
			if (!closers) return;
			closers.forEach((closer) => closer());
			this._closers.delete(path);
		}
		/**
		*
		* @param {Path} path
		* @param {Function} closer
		*/
		_addPathCloser(path, closer) {
			if (!closer) return;
			let list = this._closers.get(path);
			if (!list) {
				list = [];
				this._closers.set(path, list);
			}
			list.push(closer);
		}
		_readdirp(root, opts) {
			if (this.closed) return;
			let stream = readdirp(root, {
				type: EV_ALL,
				alwaysStat: true,
				lstat: true,
				...opts
			});
			this._streams.add(stream);
			stream.once(STR_CLOSE, () => {
				stream = void 0;
			});
			stream.once(STR_END, () => {
				if (stream) {
					this._streams.delete(stream);
					stream = void 0;
				}
			});
			return stream;
		}
	};
	/**
	* Instantiates watcher with paths to be tracked.
	* @param {String|Array<String>} paths file/directory paths and/or globs
	* @param {Object=} options chokidar opts
	* @returns an instance of FSWatcher for chaining.
	*/
	const watch = (paths, options) => {
		const watcher = new FSWatcher(options);
		watcher.add(paths);
		return watcher;
	};
	exports.watch = watch;
}));
//#endregion
//#region ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/quote.js
var require_quote = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var OPS = [
		"||",
		"&&",
		";;",
		"|&",
		"<(",
		"<<<",
		">>",
		">&",
		"<&",
		"&",
		";",
		"(",
		")",
		"|",
		"<",
		">"
	];
	var LINE_TERMINATORS = /[\n\r\u2028\u2029]/;
	var GLOB_SHELL_SPECIAL = /[\s#!"$&'():;<=>@\\^`|]/g;
	module.exports = function quote(xs) {
		return xs.map(function(s) {
			if (s === "") return "''";
			if (s && typeof s === "object") {
				if (s.op === "glob") {
					if (typeof s.pattern !== "string") throw new TypeError("glob token requires a string `pattern`");
					if (LINE_TERMINATORS.test(s.pattern)) throw new TypeError("glob `pattern` must not contain line terminators");
					return s.pattern.replace(GLOB_SHELL_SPECIAL, "\\$&");
				}
				if (typeof s.op === "string") {
					if (OPS.indexOf(s.op) < 0) throw new TypeError("invalid `op` value: " + JSON.stringify(s.op));
					return s.op.replace(/[\s\S]/g, "\\$&");
				}
				if (typeof s.comment === "string") {
					if (LINE_TERMINATORS.test(s.comment)) throw new TypeError("`comment` must not contain line terminators");
					return "#" + s.comment;
				}
				throw new TypeError("unrecognized object token shape");
			}
			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(" ");
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/parse.js
var require_parse$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	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 (var i = 0; i < 4; i++) TOKEN += (mult * Math.random()).toString(16);
	var startsWithToken = new RegExp("^" + TOKEN);
	function matchAll(s, r) {
		var origIndex = r.lastIndex;
		var matches = [];
		var matchObj;
		while (matchObj = r.exec(s)) {
			matches.push(matchObj);
			if (r.lastIndex === matchObj.index) r.lastIndex += 1;
		}
		r.lastIndex = origIndex;
		return matches;
	}
	function getVar(env, pre, key) {
		var r = typeof env === "function" ? env(key) : env[key];
		if (typeof r === "undefined" && key != "") r = "";
		else if (typeof r === "undefined") r = "$";
		if (typeof r === "object") return pre + TOKEN + JSON.stringify(r) + TOKEN;
		return pre + r;
	}
	function parseInternal(string, env, opts) {
		if (!opts) opts = {};
		var BS = opts.escape || "\\";
		var BAREWORD = "(\\" + BS + "['\"" + META + "]|[^\\s'\"" + META + "])+";
		var matches = matchAll(string, new RegExp(["(" + CONTROL + ")", "(" + BAREWORD + "|" + SINGLE_QUOTE + "|" + DOUBLE_QUOTE + ")+"].join("|"), "g"));
		if (matches.length === 0) return [];
		if (!env) env = {};
		var commented = false;
		return matches.map(function(match) {
			var s = match[0];
			if (!s || commented) return;
			if (controlRE.test(s)) return { op: s };
			var quote = false;
			var esc = false;
			var out = "";
			var isGlob = 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(env, "", varname);
			}
			for (i = 0; i < s.length; i++) {
				var c = s.charAt(i);
				isGlob = isGlob || !quote && (c === "*" || c === "?");
				if (esc) {
					out += c;
					esc = false;
				} else if (quote) if (c === quote) quote = false;
				else if (quote == SQ) out += c;
				else if (c === BS) {
					i += 1;
					c = s.charAt(i);
					if (c === DQ || c === BS || c === DS) out += c;
					else out += BS + c;
				} else if (c === DS) out += parseEnvVar();
				else out += c;
				else if (c === DQ || c === SQ) quote = c;
				else if (controlRE.test(c)) return { op: s };
				else if (hash.test(c)) {
					commented = true;
					var commentObj = { comment: string.slice(match.index + i + 1) };
					if (out.length) return [out, commentObj];
					return [commentObj];
				} else if (c === BS) esc = true;
				else if (c === DS) out += parseEnvVar();
				else out += c;
			}
			if (isGlob) return {
				op: "glob",
				pattern: out
			};
			return out;
		}).reduce(function(prev, arg) {
			return typeof arg === "undefined" ? prev : prev.concat(arg);
		}, []);
	}
	module.exports = function parse(s, env, opts) {
		var mapped = parseInternal(s, env, opts);
		if (typeof env !== "function") return mapped;
		return mapped.reduce(function(acc, s) {
			if (typeof s === "object") return acc.concat(s);
			var xs = s.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;
			}));
		}, []);
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/shell-quote@1.8.4/node_modules/shell-quote/index.js
var require_shell_quote = /* @__PURE__ */ __commonJSMin(((exports) => {
	exports.quote = require_quote();
	exports.parse = require_parse$1();
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/editor-info/macos.js
var require_macos = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		"/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/Code": "code",
		"/Applications/Visual Studio Code.app/Contents/MacOS/Electron": "code",
		"/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Code - Insiders": "code-insiders",
		"/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/Trae.app/Contents/MacOS/Electron": "trae",
		"/Applications/Antigravity.app/Contents/MacOS/Electron": "antigravity",
		"/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"
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/editor-info/linux.js
var require_linux = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		atom: "atom",
		Brackets: "brackets",
		"code-insiders": "code-insiders",
		code: "code",
		vscodium: "vscodium",
		codium: "codium",
		cursor: "cursor",
		trae: "trae",
		antigravity: "antigravity",
		emacs: "emacs",
		gvim: "gvim",
		idea: "idea",
		"idea.sh": "idea",
		phpstorm: "phpstorm",
		"phpstorm.sh": "phpstorm",
		pycharm: "pycharm",
		"pycharm.sh": "pycharm",
		rubymine: "rubymine",
		"rubymine.sh": "rubymine",
		sublime_text: "subl",
		vim: "vim",
		webstorm: "webstorm",
		"webstorm.sh": "webstorm",
		goland: "goland",
		"goland.sh": "goland",
		rider: "rider",
		"rider.sh": "rider",
		zed: "zed"
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/editor-info/windows.js
var require_windows$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = [
		"Brackets.exe",
		"Code.exe",
		"Code - Insiders.exe",
		"VSCodium.exe",
		"Cursor.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",
		"Trae.exe",
		"zed.exe",
		"Antigravity.exe"
	];
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/guess.js
var require_guess = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$9 = __require("path");
	const shellQuote = require_shell_quote();
	const childProcess$2 = __require("child_process");
	const COMMON_EDITORS_MACOS = require_macos();
	const COMMON_EDITORS_LINUX = require_linux();
	const COMMON_EDITORS_WIN = require_windows$1();
	function getEditorFromMacProcesses(output) {
		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;
			}
		}
	}
	function getEditorFromWindowsProcesses(output) {
		const runningProcesses = output.split("\r\n");
		for (let i = 0; i < runningProcesses.length; i++) {
			const fullProcessPath = runningProcesses[i].trim();
			const shortProcessName = path$9.win32.basename(fullProcessPath);
			if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) return fullProcessPath;
		}
	}
	function getEditorFromLinuxProcesses(output) {
		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];
		}
	}
	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 editor = getEditorFromMacProcesses(childProcess$2.execSync("ps x -o comm=", { stdio: [
					"pipe",
					"pipe",
					"ignore"
				] }).toString());
				if (editor !== void 0) return [editor];
			} else if (process.platform === "win32") {
				const editor = getEditorFromWindowsProcesses(childProcess$2.execSync("powershell -NoProfile -Command \"[Console]::OutputEncoding=[Text.Encoding]::UTF8;Get-CimInstance -Query \\\"select executablepath from win32_process where executablepath is not null\\\" | % { $_.ExecutablePath }\"", { stdio: [
					"pipe",
					"pipe",
					"ignore"
				] }).toString());
				if (editor !== void 0) return [editor];
			} else if (process.platform === "linux") {
				const editor = getEditorFromLinuxProcesses(childProcess$2.execSync("ps x --no-heading -o comm --sort=comm", { stdio: [
					"pipe",
					"pipe",
					"ignore"
				] }).toString());
				if (editor !== void 0) return [editor];
			}
		} catch (ignoreError) {}
		if (process.env.VISUAL) return [process.env.VISUAL];
		else if (process.env.EDITOR) return [process.env.EDITOR];
		return [null];
	}
	module.exports = guessEditor;
	module.exports.getEditorFromMacProcesses = getEditorFromMacProcesses;
	module.exports.getEditorFromWindowsProcesses = getEditorFromWindowsProcesses;
	module.exports.getEditorFromLinuxProcesses = getEditorFromLinuxProcesses;
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/get-args.js
var require_get_args = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$8 = __require("path");
	module.exports = function getArgumentsForPosition(editor, fileName, lineNumber, columnNumber = 1) {
		switch (path$8.basename(editor).replace(/\.(exe|cmd|bat)$/i, "")) {
			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 "trae":
			case "antigravity":
			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];
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor@2.14.1/node_modules/launch-editor/index.js
var require_launch_editor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Copyright (c) 2015-present, Facebook, Inc.
	*
	* This source code is licensed under the MIT license found in the
	* LICENSE file at
	* https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
	*
	* Modified by Yuxi Evan You
	*/
	const fs$6 = __require("fs");
	const os$2 = __require("os");
	const path$7 = __require("path");
	const colors = require_picocolors();
	const childProcess$1 = __require("child_process");
	const guessEditor = require_guess();
	const getArgumentsForPosition = require_get_args();
	function wrapErrorCallback(cb) {
		return (fileName, errorMessage) => {
			console.log();
			console.log(colors.red("Could not open " + path$7.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;
	}
	const positionRE = /:(\d+)(:(\d+))?$/;
	function parseFile(file) {
		if (file.startsWith("file://")) file = __require("url").fileURLToPath(file);
		const fileName = file.replace(positionRE, "");
		const match = file.match(positionRE);
		return {
			fileName,
			lineNumber: match && match[1],
			columnNumber: match && match[3]
		};
	}
	let currentChildProcess = null;
	function launchEditor(file, specifiedEditor, onErrorCallback) {
		const parsed = parseFile(file);
		let { fileName } = parsed;
		const { lineNumber, columnNumber } = parsed;
		if (process.platform === "win32" && path$7.resolve(fileName).startsWith("\\\\")) return onErrorCallback(fileName, "UNC paths are not supported on Windows to avoid security issues. See https://github.com/vitejs/launch-editor/tree/main/packages/launch-editor#unc-paths-on-windows for details.");
		if (!fs$6.existsSync(fileName)) return;
		if (typeof specifiedEditor === "function") {
			onErrorCallback = specifiedEditor;
			specifiedEditor = void 0;
		}
		onErrorCallback = wrapErrorCallback(onErrorCallback);
		const [editor, ...args] = guessEditor(specifiedEditor);
		if (!editor) {
			onErrorCallback(fileName, null);
			return;
		}
		if (process.platform === "linux" && fileName.startsWith("/mnt/") && /Microsoft/i.test(os$2.release())) fileName = path$7.relative("", fileName);
		if (lineNumber) {
			const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber);
			args.push.apply(args, extraArgs);
		} else args.push(fileName);
		if (currentChildProcess && isTerminalEditor(editor)) currentChildProcess.kill("SIGKILL");
		if (process.platform === "win32") {
			function escapeCmdArgs(cmdArgs) {
				return cmdArgs.replace(/([&|<>,;=^])/g, "^$1");
			}
			function doubleQuoteIfNeeded(str) {
				if (str.includes("^")) return `^"${str}^"`;
				else if (str.includes(" ")) return `"${str}"`;
				return str;
			}
			const launchCommand = [editor, ...args.map(escapeCmdArgs)].map(doubleQuoteIfNeeded).join(" ");
			currentChildProcess = childProcess$1.exec(launchCommand, {
				stdio: "inherit",
				shell: true
			});
		} else currentChildProcess = childProcess$1.spawn(editor, args, { stdio: "inherit" });
		currentChildProcess.on("exit", function(errorCode) {
			currentChildProcess = null;
			if (errorCode) onErrorCallback(fileName, "(code " + errorCode + ")");
		});
		currentChildProcess.on("error", function(error) {
			let { code, message } = error;
			if ("ENOENT" === code) message = `${message} ('${editor}' command does not exist in 'PATH')`;
			onErrorCallback(fileName, message);
		});
	}
	module.exports = launchEditor;
}));
//#endregion
//#region ../../node_modules/.pnpm/launch-editor-middleware@2.14.1/node_modules/launch-editor-middleware/index.js
var require_launch_editor_middleware = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$6 = __require("path");
	const launch = require_launch_editor();
	module.exports = (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 launchEditorMiddleware(req, res) {
			let url;
			try {
				const fullUrl = req.url.startsWith("http") ? req.url : `http://localhost${req.url}`;
				url = new URL(fullUrl);
			} catch (_err) {
				res.statusCode = 500;
				res.end(`launch-editor-middleware: invalid URL.`);
				return;
			}
			const file = url.searchParams.get("file");
			if (!file) {
				res.statusCode = 500;
				res.end(`launch-editor-middleware: required query param "file" is missing.`);
			} else {
				launch(file.startsWith("file://") ? file : path$6.resolve(srcRoot, file), specifiedEditor, onErrorCallback);
				res.end();
			}
		};
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/@vercel+detect-agent@1.2.3/node_modules/@vercel/detect-agent/dist/index.js
var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var __defProp = Object.defineProperty;
	var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
	var __getOwnPropNames = Object.getOwnPropertyNames;
	var __hasOwnProp = Object.prototype.hasOwnProperty;
	var __export = (target, all) => {
		for (var name in all) __defProp(target, name, {
			get: all[name],
			enumerable: true
		});
	};
	var __copyProps = (to, from, except, desc) => {
		if (from && typeof from === "object" || typeof from === "function") {
			for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
				get: () => from[key],
				enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
			});
		}
		return to;
	};
	var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
	var src_exports = {};
	__export(src_exports, {
		KNOWN_AGENTS: () => KNOWN_AGENTS,
		determineAgent: () => determineAgent
	});
	module.exports = __toCommonJS(src_exports);
	var import_promises = __require("node:fs/promises");
	var import_node_fs = __require("node:fs");
	const DEVIN_LOCAL_PATH = "/opt/.devin";
	const CURSOR = "cursor";
	const CURSOR_CLI = "cursor-cli";
	const CLAUDE = "claude";
	const COWORK = "cowork";
	const DEVIN = "devin";
	const REPLIT = "replit";
	const GEMINI = "gemini";
	const CODEX = "codex";
	const ANTIGRAVITY = "antigravity";
	const AUGMENT_CLI = "augment-cli";
	const OPENCODE = "opencode";
	const GITHUB_COPILOT = "github-copilot";
	const GITHUB_COPILOT_CLI = "github-copilot-cli";
	const V0 = "v0";
	const KNOWN_AGENTS = {
		CURSOR,
		CURSOR_CLI,
		CLAUDE,
		COWORK,
		DEVIN,
		REPLIT,
		GEMINI,
		CODEX,
		ANTIGRAVITY,
		AUGMENT_CLI,
		OPENCODE,
		GITHUB_COPILOT,
		V0
	};
	async function determineAgent() {
		if (process.env.AI_AGENT) {
			const name = process.env.AI_AGENT.trim();
			if (name) {
				if (name === GITHUB_COPILOT || name === GITHUB_COPILOT_CLI) return {
					isAgent: true,
					agent: { name: GITHUB_COPILOT }
				};
				if (name === V0) return {
					isAgent: true,
					agent: { name: V0 }
				};
				return {
					isAgent: true,
					agent: { name }
				};
			}
		}
		if (process.env.CURSOR_TRACE_ID) return {
			isAgent: true,
			agent: { name: CURSOR }
		};
		if (process.env.CURSOR_AGENT || process.env.CURSOR_EXTENSION_HOST_ROLE === "agent-exec") return {
			isAgent: true,
			agent: { name: CURSOR_CLI }
		};
		if (process.env.GEMINI_CLI) return {
			isAgent: true,
			agent: { name: GEMINI }
		};
		if (process.env.CODEX_SANDBOX || process.env.CODEX_CI || process.env.CODEX_THREAD_ID) return {
			isAgent: true,
			agent: { name: CODEX }
		};
		if (process.env.ANTIGRAVITY_AGENT) return {
			isAgent: true,
			agent: { name: ANTIGRAVITY }
		};
		if (process.env.AUGMENT_AGENT) return {
			isAgent: true,
			agent: { name: AUGMENT_CLI }
		};
		if (process.env.OPENCODE_CLIENT) return {
			isAgent: true,
			agent: { name: OPENCODE }
		};
		if (process.env.CLAUDECODE || process.env.CLAUDE_CODE) {
			if (process.env.CLAUDE_CODE_IS_COWORK) return {
				isAgent: true,
				agent: { name: COWORK }
			};
			return {
				isAgent: true,
				agent: { name: CLAUDE }
			};
		}
		if (process.env.REPL_ID) return {
			isAgent: true,
			agent: { name: REPLIT }
		};
		if (process.env.COPILOT_MODEL || process.env.COPILOT_ALLOW_ALL || process.env.COPILOT_GITHUB_TOKEN) return {
			isAgent: true,
			agent: { name: GITHUB_COPILOT }
		};
		try {
			await (0, import_promises.access)(DEVIN_LOCAL_PATH, import_node_fs.constants.F_OK);
			return {
				isAgent: true,
				agent: { name: DEVIN }
			};
		} catch (_error) {}
		return {
			isAgent: false,
			agent: void 0
		};
	}
	0 && (module.exports = {
		KNOWN_AGENTS,
		determineAgent
	});
}));
//#endregion
//#region src/node/http.ts
async function resolveHttpServer(app, httpsOptions) {
	if (!httpsOptions) {
		const { createServer } = await import("node:http");
		return createServer(app);
	}
	const { createSecureServer } = await import("node:http2");
	return createSecureServer({
		maxSessionMemory: 1e3,
		streamResetBurst: 1e5,
		streamResetRate: 33,
		...httpsOptions,
		allowHTTP1: true
	}, app);
}
async function resolveHttpsConfig(https) {
	if (!https) return void 0;
	const [ca, cert, key, pfx] = await Promise.all([
		readFileIfExists(https.ca),
		readFileIfExists(https.cert),
		readFileIfExists(https.key),
		readFileIfExists(https.pfx)
	]);
	return {
		...https,
		ca,
		cert,
		key,
		pfx
	};
}
async function readFileIfExists(value) {
	if (typeof value === "string") return fsp.readFile(path.resolve(value)).catch(() => value);
	return value;
}
async function isPortAvailable(port) {
	for (const host of wildcardHosts) if (!await tryListen(port, host).catch(() => true)) return false;
	return true;
}
function tryListen(port, host) {
	return new Promise((resolve) => {
		const server = net.createServer();
		server.once("error", (e) => {
			server.close(() => resolve(e.code !== "EADDRINUSE"));
		});
		server.once("listening", () => {
			server.close(() => resolve(true));
		});
		server.listen(port, host);
	});
}
async function tryBindServer(httpServer, port, host) {
	return new Promise((resolve) => {
		const onError = (e) => {
			httpServer.off("error", onError);
			httpServer.off("listening", onListening);
			resolve({
				success: false,
				error: e
			});
		};
		const onListening = () => {
			httpServer.off("error", onError);
			httpServer.off("listening", onListening);
			resolve({ success: true });
		};
		httpServer.on("error", onError);
		httpServer.on("listening", onListening);
		httpServer.listen(port, host);
	});
}
const MAX_PORT = 65535;
async function httpServerStart(httpServer, serverOptions) {
	const { port: startPort, strictPort, host, logger } = serverOptions;
	for (let port = startPort; port <= MAX_PORT; port++) {
		const portAvailableOnWildcard = await isPortAvailable(port);
		if (strictPort) {
			const result = await tryBindServer(httpServer, port, host);
			if (result.success) {
				if (!portAvailableOnWildcard) logger.warn(import_picocolors.default.yellow(`Port ${port} is in use on a wildcard address, but ${host ?? "localhost"}:${port} is available. There may be another server running on a wildcard IP on port ${port}.`));
				return port;
			}
			if (result.error.code !== "EADDRINUSE") throw result.error;
			throw new Error(`Port ${port} is already in use`);
		}
		if (portAvailableOnWildcard) {
			const result = await tryBindServer(httpServer, port, host);
			if (result.success) return port;
			if (result.error.code !== "EADDRINUSE") throw result.error;
		}
		logger.info(`Port ${port} is in use, trying another one...`);
	}
	throw new Error(`No available ports found between ${startPort} and ${MAX_PORT}`);
}
function setClientErrorHandler(server, logger) {
	server.on("clientError", (err, socket) => {
		let msg;
		switch (err.code) {
			case "HPE_HEADER_OVERFLOW":
				msg = "431 Request Header Fields Too Large";
				logger.warn(import_picocolors.default.yellow("Server responded with status code 431. See https://vite.dev/guide/troubleshooting.html#_431-request-header-fields-too-large."));
				break;
			case "HPE_CHUNK_EXTENSIONS_OVERFLOW":
				msg = "413 Payload Too Large";
				break;
			case "ERR_HTTP_REQUEST_TIMEOUT":
				msg = "408 Request Timeout";
				break;
			default:
				msg = "400 Bad Request";
				break;
		}
		if (err.code === "ECONNRESET" || !socket.writable) return;
		socket.end(`HTTP/1.1 ${msg}\r\nConnection: close\r\n\r\n`);
	});
}
//#endregion
//#region src/node/ssr/ssrStacktrace.ts
let offset;
function calculateOffsetOnce() {
	if (offset !== void 0) return;
	try {
		new Function("\"use strict\";\nthrow new Error(1)")();
	} catch (e) {
		const match = /:(\d+):\d+\)$/.exec(e.stack.split("\n")[1]);
		offset = match ? +match[1] - 1 : 0;
	}
}
function ssrRewriteStacktrace(stack, moduleGraph) {
	calculateOffsetOnce();
	let alreadyRewritten = false;
	return {
		result: stack.split("\n").map((line) => {
			return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, originalLine, originalColumn) => {
				if (!id) return input;
				const rawSourceMap = moduleGraph.getModuleById(id)?.transformResult?.map;
				if (!rawSourceMap) return input;
				const traced = new TraceMap(rawSourceMap);
				const line = Number(originalLine) - offset;
				const column = Number(originalColumn) - 1;
				if (line <= 0 || column < 0) {
					alreadyRewritten = true;
					return input;
				}
				const pos = originalPositionFor$2(traced, {
					line,
					column
				});
				if (!pos.source) return input;
				const trimmedVarName = varName?.trim();
				const source = `${path.resolve(path.dirname(id), pos.source)}:${pos.line}:${pos.column + 1}`;
				if (!trimmedVarName || trimmedVarName === "eval") return `    at ${source}`;
				else return `    at ${trimmedVarName} (${source})`;
			});
		}).join("\n"),
		alreadyRewritten
	};
}
function rebindErrorStacktrace(e, stacktrace) {
	const { configurable, writable } = Object.getOwnPropertyDescriptor(e, "stack");
	if (configurable) Object.defineProperty(e, "stack", {
		value: stacktrace,
		enumerable: true,
		configurable: true,
		writable: true
	});
	else if (writable) e.stack = stacktrace;
}
const rewroteStacktraces = /* @__PURE__ */ new WeakSet();
function ssrFixStacktrace(e, moduleGraph) {
	if (!e.stack) return;
	if (rewroteStacktraces.has(e)) return;
	const { result: stacktrace, alreadyRewritten } = ssrRewriteStacktrace(e.stack, moduleGraph);
	rebindErrorStacktrace(e, stacktrace);
	if (alreadyRewritten) e.message += " (The stacktrace appears to be already rewritten by something else, but was passed to vite.ssrFixStacktrace. This may cause incorrect stacktraces.)";
	rewroteStacktraces.add(e);
}
//#endregion
//#region src/node/ssr/runtime/serverModuleRunner.ts
function createHMROptions(environment, options) {
	if (environment.config.server.hmr === false || options.hmr === false) return false;
	if (!("api" in environment.hot)) return false;
	return { logger: options.hmr?.logger ?? {
		debug: (...msg) => environment.logger.info(msg.join(" "), { timestamp: true }),
		error: (err) => environment.logger.error(err instanceof Error ? err.message : String(err), { timestamp: true })
	} };
}
const prepareStackTrace = { retrieveFile(id) {
	if (existsSync(id)) return readFileSync(id, "utf-8");
} };
function resolveSourceMapOptions(options) {
	if (options.sourcemapInterceptor != null) {
		if (options.sourcemapInterceptor === "prepareStackTrace") return prepareStackTrace;
		if (typeof options.sourcemapInterceptor === "object") return {
			...prepareStackTrace,
			...options.sourcemapInterceptor
		};
		return options.sourcemapInterceptor;
	}
	if (typeof process !== "undefined" && "setSourceMapsEnabled" in process) return "node";
	return prepareStackTrace;
}
const createServerModuleRunnerTransport = (options) => {
	const hmrClient = { send: (payload) => {
		if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the client to the server.");
		options.channel.send(payload);
	} };
	let handler;
	return {
		connect({ onMessage }) {
			options.channel.api.outsideEmitter.on("send", onMessage);
			options.channel.api.innerEmitter.emit("vite:client:connect", void 0, hmrClient);
			onMessage({ type: "connected" });
			handler = onMessage;
		},
		disconnect() {
			if (handler) options.channel.api.outsideEmitter.off("send", handler);
			options.channel.api.innerEmitter.emit("vite:client:disconnect", void 0, hmrClient);
		},
		send(payload) {
			if (payload.type !== "custom") throw new Error("Cannot send non-custom events from the server to the client.");
			options.channel.api.innerEmitter.emit(payload.event, payload.data, hmrClient);
		}
	};
};
/**
* Create an instance of the Vite SSR runtime that support HMR.
* @experimental
*/
function createServerModuleRunner(environment, options = {}) {
	const hmr = createHMROptions(environment, options);
	return new ModuleRunner({
		...options,
		transport: createServerModuleRunnerTransport({ channel: environment.hot }),
		hmr,
		createImportMeta: createNodeImportMeta,
		sourcemapInterceptor: resolveSourceMapOptions(options)
	}, options.evaluator);
}
//#endregion
//#region src/node/ssr/ssrModuleLoader.ts
async function ssrLoadModule(url, server, fixStacktrace) {
	const environment = server.environments.ssr;
	if (!isRunnableDevEnvironment(environment)) throw new Error(`ssrLoadModule requires the 'ssr' environment to be a runnable environment.`);
	server._ssrCompatModuleRunner ||= new SSRCompatModuleRunner(environment);
	url = unwrapId(url);
	return instantiateModule(url, server._ssrCompatModuleRunner, environment, fixStacktrace);
}
async function instantiateModule(url, runner, environment, fixStacktrace) {
	const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
	if (mod.ssrError) throw mod.ssrError;
	try {
		return await runner.import(url);
	} catch (e) {
		if (e.stack && fixStacktrace) ssrFixStacktrace(e, environment.moduleGraph);
		environment.logger.error(buildErrorMessage(e, [import_picocolors.default.red(`Error when evaluating SSR module ${url}: ${e.message}`)]), {
			timestamp: true,
			clear: environment.config.clearScreen,
			error: e
		});
		throw e;
	}
}
var SSRCompatModuleRunner = class extends ModuleRunner {
	environment;
	constructor(environment) {
		super({
			transport: createServerModuleRunnerTransport({ channel: environment.hot }),
			createImportMeta: createNodeImportMeta,
			sourcemapInterceptor: false,
			hmr: false
		}, new ESModulesEvaluator());
		this.environment = environment;
	}
	async directRequest(url, mod, callstack) {
		const id = mod.meta && "id" in mod.meta && mod.meta.id;
		if (!id) return super.directRequest(url, mod, callstack);
		const viteMod = this.environment.moduleGraph.getModuleById(id);
		if (!viteMod) return super.directRequest(id, mod, callstack);
		try {
			const exports = await super.directRequest(id, mod, callstack);
			viteMod.ssrModule = exports;
			return exports;
		} catch (err) {
			viteMod.ssrError = err;
			throw err;
		}
	}
};
//#endregion
//#region ../../node_modules/.pnpm/periscopic@4.0.3/node_modules/periscopic/src/index.js
/**
* @param {import('estree').Node} param
* @returns {string[]}
*/
function extract_names(param) {
	return extract_identifiers(param).map((node) => node.name);
}
/**
* @param {import('estree').Node} param
* @param {import('estree').Identifier[]} nodes
* @returns {import('estree').Identifier[]}
*/
function extract_identifiers(param, nodes = []) {
	switch (param.type) {
		case "Identifier":
			nodes.push(param);
			break;
		case "MemberExpression":
			let object = param;
			while (object.type === "MemberExpression") object = object.object;
			nodes.push(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;
}
//#endregion
//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
/**
* @typedef { import('estree').Node} Node
* @typedef {{
*   skip: () => void;
*   remove: () => void;
*   replace: (node: Node) => void;
* }} WalkerContext
*/
var WalkerBase = class {
	constructor() {
		/** @type {boolean} */
		this.should_skip = false;
		/** @type {boolean} */
		this.should_remove = false;
		/** @type {Node | null} */
		this.replacement = null;
		/** @type {WalkerContext} */
		this.context = {
			skip: () => this.should_skip = true,
			remove: () => this.should_remove = true,
			replace: (node) => this.replacement = node
		};
	}
	/**
	* @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, node) {
		if (parent && prop) if (index != null)
 /** @type {Array<Node>} */ parent[prop][index] = node;
		else
 /** @type {Node} */ parent[prop] = node;
	}
	/**
	* @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)
 /** @type {Array<Node>} */ parent[prop].splice(index, 1);
		else delete parent[prop];
	}
};
//#endregion
//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
/**
* @typedef { import('estree').Node} Node
* @typedef { import('./walker.js').WalkerContext} WalkerContext
* @typedef {(
*    this: WalkerContext,
*    node: Node,
*    parent: Node | null,
*    key: string | number | symbol | null | undefined,
*    index: number | null | undefined
* ) => void} SyncHandler
*/
var SyncWalker = class extends WalkerBase {
	/**
	*
	* @param {SyncHandler} [enter]
	* @param {SyncHandler} [leave]
	*/
	constructor(enter, leave) {
		super();
		/** @type {boolean} */
		this.should_skip = false;
		/** @type {boolean} */
		this.should_remove = false;
		/** @type {Node | null} */
		this.replacement = null;
		/** @type {WalkerContext} */
		this.context = {
			skip: () => this.should_skip = true,
			remove: () => this.should_remove = true,
			replace: (node) => this.replacement = node
		};
		/** @type {SyncHandler | undefined} */
		this.enter = enter;
		/** @type {SyncHandler | undefined} */
		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(node, parent, prop, index) {
		if (node) {
			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, node, parent, prop, index);
				if (this.replacement) {
					node = this.replacement;
					this.replace(parent, prop, index, node);
				}
				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 node;
				if (removed) return null;
			}
			/** @type {keyof Node} */
			let key;
			for (key in node) {
				/** @type {unknown} */
				const value = node[key];
				if (value && typeof value === "object") {
					if (Array.isArray(value)) {
						const nodes = value;
						for (let i = 0; i < nodes.length; i += 1) {
							const item = nodes[i];
							if (isNode(item)) {
								if (!this.visit(item, node, key, i)) i--;
							}
						}
					} else if (isNode(value)) this.visit(value, node, 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, node, parent, prop, index);
				if (this.replacement) {
					node = this.replacement;
					this.replace(parent, prop, index, node);
				}
				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 node;
	}
};
/**
* Ducktype a node.
*
* @param {unknown} value
* @returns {value is Node}
*/
function isNode(value) {
	return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
//#endregion
//#region ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
/**
* @typedef {import('estree').Node} Node
* @typedef {import('./sync.js').SyncHandler} SyncHandler
* @typedef {import('./async.js').AsyncHandler} AsyncHandler
*/
/**
* @param {Node} ast
* @param {{
*   enter?: SyncHandler
*   leave?: SyncHandler
* }} walker
* @returns {Node | null}
*/
function walk$1(ast, { enter, leave }) {
	return new SyncWalker(enter, leave).visit(ast, null);
}
//#endregion
//#region src/node/plugins/json.ts
const jsonLangRE = new RegExp(`\\.(?:json|json5)(?:$|\\?)`);
const isJSONRequest = (request) => jsonLangRE.test(request);
//#endregion
//#region src/node/ssr/ssrTransform.ts
const ssrModuleExportsKey = `__vite_ssr_exports__`;
const ssrImportKey = `__vite_ssr_import__`;
const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
const ssrExportAllKey = `__vite_ssr_exportAll__`;
const ssrExportNameKey = `__vite_ssr_exportName__`;
const ssrImportMetaKey = `__vite_ssr_import_meta__`;
async function ssrTransform(code, inMap, url, originalCode, options) {
	if (options?.json?.stringify && isJSONRequest(url)) return ssrTransformJSON(code, inMap);
	return ssrTransformScript(code, inMap, url, originalCode);
}
function ssrTransformJSON(code, inMap) {
	return {
		code: code.replace("export default", `${ssrModuleExportsKey}.default =`),
		map: inMap,
		deps: [],
		dynamicDeps: [],
		ssr: true
	};
}
async function ssrTransformScript(code, inMap, url, originalCode) {
	const s = new MagicString(code);
	let ast;
	try {
		ast = await parseAstAsync(code);
	} catch (err) {
		if (err.code === "PARSE_ERROR") {
			err.message = `Parse failure: ${err.message}\n`;
			err.id = url;
			if (typeof err.pos === "number") {
				err.loc = numberToPos(code, err.pos);
				err.loc.file = url;
				err.frame = generateCodeFrame(code, err.pos);
				err.message += `At file: ${url}:${err.loc.line}:${err.loc.column}`;
			} else err.message += `At file: ${url}`;
		}
		throw err;
	}
	let uid = 0;
	const deps = /* @__PURE__ */ new Set();
	const dynamicDeps = /* @__PURE__ */ new Set();
	const idToImportMap = /* @__PURE__ */ new Map();
	const declaredConst = /* @__PURE__ */ new Set();
	const fileStartIndex = getFileStartIndex(code);
	let hoistIndex = fileStartIndex;
	function defineImport(index, importNode, metadata) {
		const source = importNode.source.value;
		deps.add(source);
		const metadataArg = (metadata?.importedNames?.length ?? 0) > 0 ? `, ${JSON.stringify(metadata)}` : "";
		const importId = `__vite_ssr_import_${uid++}__`;
		const transformedImport = `const ${importId} = await ${ssrImportKey}(${JSON.stringify(source)}${metadataArg});\n`;
		s.update(importNode.start, importNode.end, transformedImport);
		if (importNode.start === index) hoistIndex = importNode.end;
		else s.move(importNode.start, importNode.end, index);
		return importId;
	}
	function defineExport(name, local = name) {
		s.appendLeft(fileStartIndex, `${ssrExportNameKey}(${JSON.stringify(name)}, () => { try { return ${local} } catch {} });\n`);
	}
	const imports = [];
	const exports = [];
	const reExportImportIdMap = /* @__PURE__ */ new Map();
	for (const node of ast.body) if (node.type === "ImportDeclaration") imports.push(node);
	else if (node.type === "ExportDefaultDeclaration") exports.push(node);
	else if (node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") {
		imports.push(node);
		exports.push(node);
	}
	for (const node of imports) {
		if (node.type === "ExportNamedDeclaration") {
			if (node.source) {
				const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => getIdentifierNameOrLiteralValue$1(s.local)) });
				reExportImportIdMap.set(node, importId);
			}
			continue;
		}
		if (node.type === "ExportAllDeclaration") {
			if (node.source) {
				const importId = defineImport(hoistIndex, node);
				reExportImportIdMap.set(node, importId);
			}
			continue;
		}
		const importId = defineImport(hoistIndex, node, { importedNames: node.specifiers.map((s) => {
			if (s.type === "ImportSpecifier") return getIdentifierNameOrLiteralValue$1(s.imported);
			else if (s.type === "ImportDefaultSpecifier") return "default";
		}).filter(isDefined) });
		for (const spec of node.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}[${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 node of exports) {
		if (node.type === "ExportNamedDeclaration") if (node.declaration) {
			if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") defineExport(node.declaration.id.name);
			else {
				const declaration = node.declaration;
				for (const decl of declaration.declarations) {
					const names = extract_names(decl.id);
					for (const name of names) defineExport(name);
				}
			}
			s.remove(node.start, node.declaration.start);
		} else if (node.source) {
			const importId = reExportImportIdMap.get(node);
			for (const spec of node.specifiers) {
				const exportedAs = getIdentifierNameOrLiteralValue$1(spec.exported);
				if (spec.local.type === "Identifier") defineExport(exportedAs, `${importId}.${spec.local.name}`);
				else defineExport(exportedAs, `${importId}[${JSON.stringify(spec.local.value)}]`);
			}
		} else {
			s.remove(node.start, node.end);
			for (const spec of node.specifiers) {
				const local = spec.local.name;
				const binding = idToImportMap.get(local);
				defineExport(getIdentifierNameOrLiteralValue$1(spec.exported), binding || local);
			}
		}
		if (node.type === "ExportDefaultDeclaration") if ("id" in node.declaration && node.declaration.id && !["FunctionExpression", "ClassExpression"].includes(node.declaration.type)) {
			const { name } = node.declaration.id;
			s.remove(node.start, node.start + 15);
			defineExport("default", name);
		} else {
			const name = `__vite_ssr_export_default__`;
			s.update(node.start, node.start + 14, `const ${name} =`);
			defineExport("default", name);
		}
		if (node.type === "ExportAllDeclaration") {
			const importId = reExportImportIdMap.get(node);
			if (node.exported) defineExport(getIdentifierNameOrLiteralValue$1(node.exported), `${importId}`);
			else s.appendLeft(node.end, `${ssrExportAllKey}(${importId});\n`);
		}
	}
	walk(ast, {
		onStatements(statements) {
			for (let i = 0; i < statements.length - 1; i++) {
				const stmt = statements[i];
				if (code[stmt.end - 1] !== ";" && stmt.type !== "FunctionDeclaration" && stmt.type !== "ClassDeclaration" && stmt.type !== "BlockStatement" && stmt.type !== "ImportDeclaration") s.appendLeft(stmt.end, ";");
			}
		},
		onIdentifier(id, parent, parentStack) {
			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 === "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};\n`);
				}
			} else if (parent.type === "CallExpression") {
				s.update(id.start, id.end, binding);
				s.prependRight(id.start, `(0,`);
				s.appendLeft(id.end, `)`);
			} else if (!(parent.type === "ClassExpression" && id === parent.id)) s.update(id.start, id.end, binding);
		},
		onImportMeta(node) {
			s.update(node.start, node.end, ssrImportMetaKey);
		},
		onDynamicImport(node) {
			s.update(node.start, node.start + 6, ssrDynamicImportKey);
			if (node.type === "ImportExpression" && node.source.type === "Literal") dynamicDeps.add(node.source.value);
		}
	});
	let map;
	if (inMap?.mappings === "") map = inMap;
	else {
		map = s.generateMap({ hires: "boundary" });
		map.sources = [path.basename(url)];
		map.sourcesContent = [originalCode];
		if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) map = combineSourcemaps(url, [map, inMap]);
	}
	return {
		code: s.toString(),
		map,
		ssr: true,
		deps: [...deps],
		dynamicDeps: [...dynamicDeps]
	};
}
function getIdentifierNameOrLiteralValue$1(node) {
	return node.type === "Identifier" ? node.name : node.value;
}
const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet();
const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node);
const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node);
/**
* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
* Except this is using acorn AST
*/
function walk(root, { onIdentifier, onImportMeta, onDynamicImport, onStatements }) {
	const parentStack = [];
	const varKindStack = [];
	const scopeMap = /* @__PURE__ */ new WeakMap();
	const identifiers = [];
	const setScope = (node, name) => {
		let scopeIds = scopeMap.get(node);
		if (scopeIds && scopeIds.has(name)) return;
		if (!scopeIds) {
			scopeIds = /* @__PURE__ */ new Set();
			scopeMap.set(node, scopeIds);
		}
		scopeIds.add(name);
	};
	function isInScope(name, parents) {
		return parents.some((node) => scopeMap.get(node)?.has(name));
	}
	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(node, parent) {
			if (node.type === "ImportDeclaration") return this.skip();
			if (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock") onStatements(node.body);
			else if (node.type === "SwitchCase") onStatements(node.consequent);
			if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.unshift(parent);
			if (node.type === "VariableDeclaration") varKindStack.unshift(node.kind);
			if (node.type === "MetaProperty" && node.meta.name === "import") onImportMeta(node);
			else if (node.type === "ImportExpression") onDynamicImport(node);
			if (node.type === "Identifier") {
				if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) identifiers.push([node, parentStack.slice(0)]);
			} else if (isFunction(node)) {
				if (node.type === "FunctionDeclaration") {
					const parentScope = findParentScope(parentStack);
					if (parentScope) setScope(parentScope, node.id.name);
				}
				if (node.type === "FunctionExpression" && node.id) setScope(node, node.id.name);
				node.params.forEach((p) => {
					if (p.type === "ObjectPattern" || p.type === "ArrayPattern") {
						handlePattern(p, node);
						return;
					}
					walk$1(p.type === "AssignmentPattern" ? p.left : p, { enter(child, parent) {
						if (parent?.type === "AssignmentPattern" && parent.right === child) return this.skip();
						if (child.type !== "Identifier") return;
						if (isStaticPropertyKey(child, parent)) return;
						if (parent?.type === "TemplateLiteral" && parent.expressions.includes(child) || parent?.type === "CallExpression" && parent.callee === child) return;
						setScope(node, child.name);
					} });
				});
			} else if (node.type === "ClassDeclaration") {
				const parentScope = findParentScope(parentStack);
				if (parentScope) setScope(parentScope, node.id.name);
			} else if (node.type === "ClassExpression" && node.id) setScope(node, node.id.name);
			else if (node.type === "Property" && parent.type === "ObjectPattern") setIsNodeInPattern(node);
			else if (node.type === "VariableDeclarator") {
				const parentFunction = findParentScope(parentStack, varKindStack[0] === "var");
				if (parentFunction) handlePattern(node.id, parentFunction);
			} else if (node.type === "CatchClause" && node.param) handlePattern(node.param, node);
		},
		leave(node, parent) {
			if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) parentStack.shift();
			if (node.type === "VariableDeclaration") varKindStack.shift();
		}
	});
	identifiers.forEach(([node, stack]) => {
		if (!isInScope(node.name, stack)) onIdentifier(node, 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(parent)) {
		if (parent.id === id) return false;
		if (parent.params.includes(id)) return false;
	}
	if (parent.type === "MethodDefinition" && !parent.computed) return false;
	if (parent.type === "PropertyDefinition" && !parent.computed) return parent.value === id;
	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 === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") && parent.label === id) return false;
	if (parent.type === "MetaProperty") return false;
	if (parent.type === "ExportSpecifier" || parent.type === "ExportAllDeclaration") return false;
	if (id.name === "arguments") return false;
	return true;
}
const isStaticProperty = (node) => node.type === "Property" && !node.computed;
const isStaticPropertyKey = (node, parent) => parent && isStaticProperty(parent) && parent.key === node;
const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/;
function isFunction(node) {
	return functionNodeTypeRE.test(node.type);
}
const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/;
function isBlock(node) {
	return blockNodeTypeRE.test(node.type);
}
function findParentScope(parentStack, isVar = false) {
	return parentStack.find(isVar ? isFunction : isBlock);
}
function isInDestructuringAssignment(parent, parentStack) {
	if (parent.type === "Property" || parent.type === "ArrayPattern") return parentStack.some((i) => i.type === "AssignmentExpression");
	return false;
}
//#endregion
//#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
let isDockerCached;
function hasDockerEnv() {
	try {
		fs.statSync("/.dockerenv");
		return true;
	} catch {
		return false;
	}
}
function hasDockerCGroup() {
	try {
		return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
	} catch {
		return false;
	}
}
function isDocker() {
	if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
	return isDockerCached;
}
//#endregion
//#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
let cachedResult;
const hasContainerEnv = () => {
	try {
		fs.statSync("/run/.containerenv");
		return true;
	} catch {
		return false;
	}
};
function isInsideContainer() {
	if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
	return cachedResult;
}
//#endregion
//#region ../../node_modules/.pnpm/is-wsl@3.1.0/node_modules/is-wsl/index.js
const isWsl = () => {
	if (process$1.platform !== "linux") return false;
	if (os.release().toLowerCase().includes("microsoft")) {
		if (isInsideContainer()) return false;
		return true;
	}
	try {
		return fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
	} catch {
		return false;
	}
};
var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
//#endregion
//#region ../../node_modules/.pnpm/wsl-utils@0.1.0/node_modules/wsl-utils/index.js
const wslDrivesMountPoint = (() => {
	const defaultMountPoint = "/mnt/";
	let mountPoint;
	return async function() {
		if (mountPoint) return mountPoint;
		const configFilePath = "/etc/wsl.conf";
		let isConfigFileExists = false;
		try {
			await fsp.access(configFilePath, constants.F_OK);
			isConfigFileExists = true;
		} catch {}
		if (!isConfigFileExists) return defaultMountPoint;
		const configContent = await fsp.readFile(configFilePath, { encoding: "utf8" });
		const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
		if (!configMountPoint) return defaultMountPoint;
		mountPoint = configMountPoint.groups.mountPoint.trim();
		mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
		return mountPoint;
	};
})();
const powerShellPathFromWsl = async () => {
	return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
};
const powerShellPath = async () => {
	if (is_wsl_default) return powerShellPathFromWsl();
	return `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
};
//#endregion
//#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
function defineLazyProperty(object, propertyName, valueGetter) {
	const define = (value) => Object.defineProperty(object, propertyName, {
		value,
		enumerable: true,
		writable: true
	});
	Object.defineProperty(object, propertyName, {
		configurable: true,
		enumerable: true,
		get() {
			const result = valueGetter();
			define(result);
			return result;
		},
		set(value) {
			define(value);
		}
	});
	return object;
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
const execFileAsync$3 = promisify(execFile);
async function defaultBrowserId() {
	if (process$1.platform !== "darwin") throw new Error("macOS only");
	const { stdout } = await execFileAsync$3("defaults", [
		"read",
		"com.apple.LaunchServices/com.apple.launchservices.secure",
		"LSHandlers"
	]);
	const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
	if (browserId === "com.apple.safari") return "com.apple.Safari";
	return browserId;
}
//#endregion
//#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
const execFileAsync$2 = promisify(execFile);
async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
	if (process$1.platform !== "darwin") throw new Error("macOS only");
	const outputArguments = humanReadableOutput ? [] : ["-ss"];
	const execOptions = {};
	if (signal) execOptions.signal = signal;
	const { stdout } = await execFileAsync$2("osascript", [
		"-e",
		script,
		outputArguments
	], execOptions);
	return stdout.trim();
}
//#endregion
//#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
async function bundleName(bundleId) {
	return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
const execFileAsync$1 = promisify(execFile);
const windowsBrowserProgIds = {
	MSEdgeHTM: {
		name: "Edge",
		id: "com.microsoft.edge"
	},
	MSEdgeBHTML: {
		name: "Edge Beta",
		id: "com.microsoft.edge.beta"
	},
	MSEdgeDHTML: {
		name: "Edge Dev",
		id: "com.microsoft.edge.dev"
	},
	AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
		name: "Edge",
		id: "com.microsoft.edge.old"
	},
	ChromeHTML: {
		name: "Chrome",
		id: "com.google.chrome"
	},
	ChromeBHTML: {
		name: "Chrome Beta",
		id: "com.google.chrome.beta"
	},
	ChromeDHTML: {
		name: "Chrome Dev",
		id: "com.google.chrome.dev"
	},
	ChromiumHTM: {
		name: "Chromium",
		id: "org.chromium.Chromium"
	},
	BraveHTML: {
		name: "Brave",
		id: "com.brave.Browser"
	},
	BraveBHTML: {
		name: "Brave Beta",
		id: "com.brave.Browser.beta"
	},
	BraveDHTML: {
		name: "Brave Dev",
		id: "com.brave.Browser.dev"
	},
	BraveSSHTM: {
		name: "Brave Nightly",
		id: "com.brave.Browser.nightly"
	},
	FirefoxURL: {
		name: "Firefox",
		id: "org.mozilla.firefox"
	},
	OperaStable: {
		name: "Opera",
		id: "com.operasoftware.Opera"
	},
	VivaldiHTM: {
		name: "Vivaldi",
		id: "com.vivaldi.Vivaldi"
	},
	"IE.HTTP": {
		name: "Internet Explorer",
		id: "com.microsoft.ie"
	}
};
new Map(Object.entries(windowsBrowserProgIds));
var UnknownBrowserError = class extends Error {};
async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
	const { stdout } = await _execFileAsync("reg", [
		"QUERY",
		" HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
		"/v",
		"ProgId"
	]);
	const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
	if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
	const { id } = match.groups;
	const dotIndex = id.lastIndexOf(".");
	const hyphenIndex = id.lastIndexOf("-");
	const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
	const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
	return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
		name: id,
		id
	};
}
//#endregion
//#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
const execFileAsync = promisify(execFile);
const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
async function defaultBrowser() {
	if (process$1.platform === "darwin") {
		const id = await defaultBrowserId();
		return {
			name: await bundleName(id),
			id
		};
	}
	if (process$1.platform === "linux") {
		const { stdout } = await execFileAsync("xdg-mime", [
			"query",
			"default",
			"x-scheme-handler/http"
		]);
		const id = stdout.trim();
		return {
			name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
			id
		};
	}
	if (process$1.platform === "win32") return defaultBrowser$1();
	throw new Error("Only macOS, Linux, and Windows are supported");
}
//#endregion
//#region ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
const execFile$1 = promisify(childProcess.execFile);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const localXdgOpenPath = path.join(__dirname, "xdg-open");
const { platform, arch } = process$1;
/**
Get the default browser name in Windows from WSL.

@returns {Promise<string>} Browser name.
*/
async function getWindowsDefaultBrowserFromWsl() {
	const powershellPath = await powerShellPath();
	const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
	const { stdout } = await execFile$1(powershellPath, [
		"-NoProfile",
		"-NonInteractive",
		"-ExecutionPolicy",
		"Bypass",
		"-EncodedCommand",
		Buffer$1.from(rawCommand, "utf16le").toString("base64")
	], { encoding: "utf8" });
	const progId = stdout.trim();
	const browserMap = {
		ChromeHTML: "com.google.chrome",
		BraveHTML: "com.brave.Browser",
		MSEdgeHTM: "com.microsoft.edge",
		FirefoxURL: "org.mozilla.firefox"
	};
	return browserMap[progId] ? { id: browserMap[progId] } : {};
}
const pTryEach = async (array, mapper) => {
	let latestError;
	for (const item of array) try {
		return await mapper(item);
	} catch (error) {
		latestError = error;
	}
	throw latestError;
};
const baseOpen = async (options) => {
	options = {
		wait: false,
		background: false,
		newInstance: false,
		allowNonzeroExitCode: false,
		...options
	};
	if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
		...options,
		app: singleApp
	}));
	let { name: app, arguments: appArguments = [] } = options.app ?? {};
	appArguments = [...appArguments];
	if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
		...options,
		app: {
			name: appName,
			arguments: appArguments
		}
	}));
	if (app === "browser" || app === "browserPrivate") {
		const ids = {
			"com.google.chrome": "chrome",
			"google-chrome.desktop": "chrome",
			"com.brave.Browser": "brave",
			"org.mozilla.firefox": "firefox",
			"firefox.desktop": "firefox",
			"com.microsoft.msedge": "edge",
			"com.microsoft.edge": "edge",
			"com.microsoft.edgemac": "edge",
			"microsoft-edge.desktop": "edge"
		};
		const flags = {
			chrome: "--incognito",
			brave: "--incognito",
			firefox: "--private-window",
			edge: "--inPrivate"
		};
		const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
		if (browser.id in ids) {
			const browserName = ids[browser.id];
			if (app === "browserPrivate") appArguments.push(flags[browserName]);
			return baseOpen({
				...options,
				app: {
					name: apps[browserName],
					arguments: appArguments
				}
			});
		}
		throw new Error(`${browser.name} is not supported as a default browser`);
	}
	let command;
	const cliArguments = [];
	const childProcessOptions = {};
	if (platform === "darwin") {
		command = "open";
		if (options.wait) cliArguments.push("--wait-apps");
		if (options.background) cliArguments.push("--background");
		if (options.newInstance) cliArguments.push("--new");
		if (app) cliArguments.push("-a", app);
	} else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
		command = await powerShellPath();
		cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
		if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
		const encodedArguments = ["Start"];
		if (options.wait) encodedArguments.push("-Wait");
		if (app) {
			encodedArguments.push(`"\`"${app}\`""`);
			if (options.target) appArguments.push(options.target);
		} else if (options.target) encodedArguments.push(`"${options.target}"`);
		if (appArguments.length > 0) {
			appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
			encodedArguments.push("-ArgumentList", appArguments.join(","));
		}
		options.target = Buffer$1.from(encodedArguments.join(" "), "utf16le").toString("base64");
	} else {
		if (app) command = app;
		else {
			const isBundled = !__dirname || __dirname === "/";
			let exeLocalXdgOpen = false;
			try {
				await fsp.access(localXdgOpenPath, constants.X_OK);
				exeLocalXdgOpen = true;
			} catch {}
			command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
		}
		if (appArguments.length > 0) cliArguments.push(...appArguments);
		if (!options.wait) {
			childProcessOptions.stdio = "ignore";
			childProcessOptions.detached = true;
		}
	}
	if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
	if (options.target) cliArguments.push(options.target);
	const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
	if (options.wait) return new Promise((resolve, reject) => {
		subprocess.once("error", reject);
		subprocess.once("close", (exitCode) => {
			if (!options.allowNonzeroExitCode && exitCode > 0) {
				reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
				return;
			}
			resolve(subprocess);
		});
	});
	subprocess.unref();
	return subprocess;
};
const open = (target, options) => {
	if (typeof target !== "string") throw new TypeError("Expected a `target`");
	return baseOpen({
		...options,
		target
	});
};
function detectArchBinary(binary) {
	if (typeof binary === "string" || Array.isArray(binary)) return binary;
	const { [arch]: archBinary } = binary;
	if (!archBinary) throw new Error(`${arch} is not supported`);
	return archBinary;
}
function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
	if (wsl && is_wsl_default) return detectArchBinary(wsl);
	if (!platformBinary) throw new Error(`${platform} is not supported`);
	return detectArchBinary(platformBinary);
}
const 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, "brave", () => detectPlatformBinary({
	darwin: "brave browser",
	win32: "brave",
	linux: ["brave-browser", "brave"]
}, { wsl: {
	ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
	x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
} }));
defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
	darwin: "firefox",
	win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
	linux: "firefox"
}, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
defineLazyProperty(apps, "edge", () => detectPlatformBinary({
	darwin: "microsoft edge",
	win32: "msedge",
	linux: ["microsoft-edge", "microsoft-edge-dev"]
}, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
defineLazyProperty(apps, "browser", () => "browser");
defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
//#endregion
//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = isexe;
	isexe.sync = sync;
	var fs$5 = __require("fs");
	function checkPathExt(path, options) {
		var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
		if (!pathext) return true;
		pathext = pathext.split(";");
		if (pathext.indexOf("") !== -1) return true;
		for (var i = 0; i < pathext.length; i++) {
			var p = pathext[i].toLowerCase();
			if (p && path.substr(-p.length).toLowerCase() === p) return true;
		}
		return false;
	}
	function checkStat(stat, path, options) {
		if (!stat.isSymbolicLink() && !stat.isFile()) return false;
		return checkPathExt(path, options);
	}
	function isexe(path, options, cb) {
		fs$5.stat(path, function(er, stat) {
			cb(er, er ? false : checkStat(stat, path, options));
		});
	}
	function sync(path, options) {
		return checkStat(fs$5.statSync(path), path, options);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = isexe;
	isexe.sync = sync;
	var fs$4 = __require("fs");
	function isexe(path, options, cb) {
		fs$4.stat(path, function(er, stat) {
			cb(er, er ? false : checkStat(stat, options));
		});
	}
	function sync(path, options) {
		return checkStat(fs$4.statSync(path), options);
	}
	function checkStat(stat, options) {
		return stat.isFile() && checkMode(stat, options);
	}
	function checkMode(stat, options) {
		var mod = stat.mode;
		var uid = stat.uid;
		var gid = stat.gid;
		var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
		var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
		var u = parseInt("100", 8);
		var g = parseInt("010", 8);
		var o = parseInt("001", 8);
		var ug = u | g;
		return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	__require("fs");
	var core;
	if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
	else core = require_mode();
	module.exports = isexe;
	isexe.sync = sync;
	function isexe(path, options, cb) {
		if (typeof options === "function") {
			cb = options;
			options = {};
		}
		if (!cb) {
			if (typeof Promise !== "function") throw new TypeError("callback not provided");
			return new Promise(function(resolve, reject) {
				isexe(path, options || {}, function(er, is) {
					if (er) reject(er);
					else resolve(is);
				});
			});
		}
		core(path, options || {}, function(er, is) {
			if (er) {
				if (er.code === "EACCES" || options && options.ignoreErrors) {
					er = null;
					is = false;
				}
			}
			cb(er, is);
		});
	}
	function sync(path, options) {
		try {
			return core.sync(path, options || {});
		} catch (er) {
			if (options && options.ignoreErrors || er.code === "EACCES") return false;
			else throw er;
		}
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
	const path$5 = __require("path");
	const COLON = isWindows ? ";" : ":";
	const isexe = require_isexe();
	const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
	const getPathInfo = (cmd, opt) => {
		const colon = opt.colon || COLON;
		const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH || "").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
		};
	};
	const which = (cmd, opt, cb) => {
		if (typeof opt === "function") {
			cb = opt;
			opt = {};
		}
		if (!opt) opt = {};
		const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
		const found = [];
		const step = (i) => new Promise((resolve, reject) => {
			if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
			const ppRaw = pathEnv[i];
			const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
			const pCmd = path$5.join(pathPart, cmd);
			resolve(subStep(!pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd, i, 0));
		});
		const subStep = (p, i, ii) => new Promise((resolve, reject) => {
			if (ii === pathExt.length) return resolve(step(i + 1));
			const ext = pathExt[ii];
			isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
				if (!er && is) if (opt.all) found.push(p + ext);
				else return resolve(p + ext);
				return resolve(subStep(p, i, ii + 1));
			});
		});
		return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
	};
	const whichSync = (cmd, opt) => {
		opt = opt || {};
		const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
		const found = [];
		for (let i = 0; i < pathEnv.length; i++) {
			const ppRaw = pathEnv[i];
			const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
			const pCmd = path$5.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 {
					if (isexe.sync(cur, { pathExt: pathExtExe })) if (opt.all) found.push(cur);
					else return cur;
				} catch (ex) {}
			}
		}
		if (opt.all && found.length) return found;
		if (opt.nothrow) return null;
		throw getNotFoundError(cmd);
	};
	module.exports = which;
	which.sync = whichSync;
}));
//#endregion
//#region ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const pathKey = (options = {}) => {
		const environment = options.env || process.env;
		if ((options.platform || process.platform) !== "win32") return "PATH";
		return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
	};
	module.exports = pathKey;
	module.exports.default = pathKey;
}));
//#endregion
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$4 = __require("path");
	const which = require_which();
	const getPathKey = require_path_key();
	function resolveCommandAttempt(parsed, withoutPathExt) {
		const env = parsed.options.env || process.env;
		const cwd = process.cwd();
		const hasCustomCwd = parsed.options.cwd != null;
		const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
		if (shouldSwitchCwd) try {
			process.chdir(parsed.options.cwd);
		} catch (err) {}
		let resolved;
		try {
			resolved = which.sync(parsed.command, {
				path: env[getPathKey({ env })],
				pathExt: withoutPathExt ? path$4.delimiter : void 0
			});
		} catch (e) {} finally {
			if (shouldSwitchCwd) process.chdir(cwd);
		}
		if (resolved) resolved = path$4.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
		return resolved;
	}
	function resolveCommand(parsed) {
		return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
	}
	module.exports = resolveCommand;
}));
//#endregion
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
	function escapeCommand(arg) {
		arg = arg.replace(metaCharsRegExp, "^$1");
		return arg;
	}
	function escapeArgument(arg, doubleEscapeMetaChars) {
		arg = `${arg}`;
		arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
		arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
		arg = `"${arg}"`;
		arg = arg.replace(metaCharsRegExp, "^$1");
		if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
		return arg;
	}
	module.exports.command = escapeCommand;
	module.exports.argument = escapeArgument;
}));
//#endregion
//#region ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = /^#!(.*)/;
}));
//#endregion
//#region ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const shebangRegex = require_shebang_regex();
	module.exports = (string = "") => {
		const match = string.match(shebangRegex);
		if (!match) return null;
		const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
		const binary = path.split("/").pop();
		if (binary === "env") return argument;
		return argument ? `${binary} ${argument}` : binary;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const fs$3 = __require("fs");
	const shebangCommand = require_shebang_command();
	function readShebang(command) {
		const size = 150;
		const buffer = Buffer.alloc(size);
		let fd;
		try {
			fd = fs$3.openSync(command, "r");
			fs$3.readSync(fd, buffer, 0, size, 0);
			fs$3.closeSync(fd);
		} catch (e) {}
		return shebangCommand(buffer.toString());
	}
	module.exports = readShebang;
}));
//#endregion
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$3 = __require("path");
	const resolveCommand = require_resolveCommand();
	const escape = require_escape();
	const readShebang = require_readShebang();
	const isWin = process.platform === "win32";
	const isExecutableRegExp = /\.(?:com|exe)$/i;
	const 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) return parsed;
		const commandFile = detectShebang(parsed);
		const needsShell = !isExecutableRegExp.test(commandFile);
		if (parsed.options.forceShell || needsShell) {
			const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
			parsed.command = path$3.normalize(parsed.command);
			parsed.command = escape.command(parsed.command);
			parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
			parsed.args = [
				"/d",
				"/s",
				"/c",
				`"${[parsed.command].concat(parsed.args).join(" ")}"`
			];
			parsed.command = process.env.comspec || "cmd.exe";
			parsed.options.windowsVerbatimArguments = true;
		}
		return parsed;
	}
	function parse(command, args, options) {
		if (args && !Array.isArray(args)) {
			options = args;
			args = null;
		}
		args = args ? args.slice(0) : [];
		options = Object.assign({}, options);
		const parsed = {
			command,
			args,
			options,
			file: void 0,
			original: {
				command,
				args
			}
		};
		return options.shell ? parsed : parseNonShell(parsed);
	}
	module.exports = parse;
}));
//#endregion
//#region ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const isWin = process.platform === "win32";
	function notFoundError(original, syscall) {
		return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
			code: "ENOENT",
			errno: "ENOENT",
			syscall: `${syscall} ${original.command}`,
			path: original.command,
			spawnargs: original.args
		});
	}
	function hookChildProcess(cp, parsed) {
		if (!isWin) return;
		const originalEmit = cp.emit;
		cp.emit = function(name, arg1) {
			if (name === "exit") {
				const err = verifyENOENT(arg1, parsed);
				if (err) return originalEmit.call(cp, "error", err);
			}
			return originalEmit.apply(cp, arguments);
		};
	}
	function verifyENOENT(status, parsed) {
		if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
		return null;
	}
	function verifyENOENTSync(status, parsed) {
		if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
		return null;
	}
	module.exports = {
		hookChildProcess,
		verifyENOENT,
		verifyENOENTSync,
		notFoundError
	};
}));
//#endregion
//#region src/node/server/openBrowser.ts
/**
* The following is modified based on source found in
* https://github.com/react/create-react-app
*
* MIT Licensed
* Copyright (c) 2015-present, Facebook, Inc.
* https://github.com/react/create-react-app/blob/main/LICENSE
*
*/
var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	const cp = __require("child_process");
	const parse = require_parse();
	const enoent = require_enoent();
	function spawn(command, args, options) {
		const parsed = parse(command, args, options);
		const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
		enoent.hookChildProcess(spawned, parsed);
		return spawned;
	}
	function spawnSync(command, args, options) {
		const parsed = parse(command, args, options);
		const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
		result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
		return result;
	}
	module.exports = spawn;
	module.exports.spawn = spawn;
	module.exports.sync = spawnSync;
	module.exports._parse = parse;
	module.exports._enoent = enoent;
})))(), 1);
/**
* Reads the BROWSER environment variable and decides what to do with it.
*/
function openBrowser(url, opt, logger) {
	const browser = typeof opt === "string" ? opt : process.env.BROWSER || "";
	if (browser.toLowerCase().endsWith(".js")) executeNodeScript(browser, url, logger);
	else if (browser.toLowerCase() !== "none") startBrowserProcess(browser, process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : [], url, logger);
}
function executeNodeScript(scriptPath, url, logger) {
	const extraArgs = process.argv.slice(2);
	(0, import_cross_spawn.default)(process.execPath, [
		scriptPath,
		...extraArgs,
		url
	], { stdio: "inherit" }).on("close", (code) => {
		if (code !== 0) logger.error(import_picocolors.default.red(`\nThe script specified as BROWSER environment variable failed.\n\n${import_picocolors.default.cyan(scriptPath)} exited with code ${code}.`), { error: null });
	});
}
const supportedChromiumBrowsers = [
	"Google Chrome Canary",
	"Google Chrome Dev",
	"Google Chrome Beta",
	"Google Chrome",
	"Microsoft Edge",
	"Brave Browser",
	"Vivaldi",
	"Chromium"
];
async function startBrowserProcess(browser, browserArgs, url, logger) {
	const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser;
	if (process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser))) 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.js "${url}" "${openedBrowser}"`, { cwd: join(VITE_PACKAGE_DIR, "bin") });
			return true;
		}
	} catch {}
	if (process.platform === "darwin" && browser === "open") browser = void 0;
	try {
		const options = browser ? { app: {
			name: browser,
			arguments: browserArgs
		} } : {};
		new Promise((_, reject) => {
			open(url, options).then((subprocess) => {
				subprocess.on("error", reject);
			}).catch(reject);
		}).catch((err) => {
			logger.error(err.stack || err.message);
		});
		return true;
	} catch {
		return false;
	}
}
function execAsync(command, options) {
	return new Promise((resolve, reject) => {
		exec(command, options, (error, stdout) => {
			if (error) reject(error);
			else resolve(stdout.toString());
		});
	});
}
//#endregion
//#region src/node/shortcuts.ts
function bindCLIShortcuts(server, opts, enabled = process.stdin.isTTY && !process.env.CI) {
	if (!server.httpServer || !enabled) return;
	const isDev = isDevServer(server);
	const previousShortcuts = server._shortcutsState?.options.customShortcuts ?? [];
	const newShortcuts = opts?.customShortcuts ?? [];
	const previousKeys = new Set(previousShortcuts.map((s) => s.key));
	const customShortcuts = [...newShortcuts.filter((s) => !previousKeys.has(s.key)), ...previousShortcuts.map((s) => newShortcuts.find((n) => n.key === s.key) ?? s)];
	const newOptions = {
		...opts,
		customShortcuts
	};
	if (opts?.print) server.config.logger.info(import_picocolors.default.dim(import_picocolors.default.green("  ➜")) + import_picocolors.default.dim("  press ") + import_picocolors.default.bold("h + enter") + import_picocolors.default.dim(" to show help"));
	const shortcuts = customShortcuts.concat(isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS);
	let actionRunning = false;
	const onInput = async (input) => {
		if (actionRunning) return;
		input = input.trim().toLocaleLowerCase();
		if (input === "h") {
			const loggedKeys = /* @__PURE__ */ new Set();
			server.config.logger.info("\n  Shortcuts");
			for (const shortcut of shortcuts) {
				if (loggedKeys.has(shortcut.key)) continue;
				loggedKeys.add(shortcut.key);
				if (shortcut.action == null) continue;
				server.config.logger.info(import_picocolors.default.dim("  press ") + import_picocolors.default.bold(`${shortcut.key} + enter`) + import_picocolors.default.dim(` to ${shortcut.description}`));
			}
			return;
		}
		const shortcut = shortcuts.find((shortcut) => shortcut.key === input);
		if (!shortcut || shortcut.action == null) return;
		actionRunning = true;
		await shortcut.action(server);
		actionRunning = false;
	};
	if (!server._shortcutsState) {
		server._shortcutsState = {
			rl: readline.createInterface({ input: process.stdin }),
			options: newOptions
		};
		server.httpServer.on("close", () => {
			if (server._shortcutsState) server._shortcutsState.rl.close();
		});
	} else {
		server._shortcutsState.rl.removeAllListeners("line");
		server._shortcutsState.options = newOptions;
	}
	server._shortcutsState.rl.on("line", onInput);
}
const BASE_DEV_SHORTCUTS = [
	{
		key: "r",
		description: "restart the server",
		async action(server) {
			await restartServerWithUrls(server);
		}
	},
	{
		key: "u",
		description: "show server url",
		action(server) {
			server.config.logger.info("");
			server.printUrls();
		}
	},
	{
		key: "o",
		description: "open in browser",
		action(server) {
			server.openBrowser();
		}
	},
	{
		key: "c",
		description: "clear console",
		action(server) {
			server.config.logger.clearScreen("error");
		}
	},
	{
		key: "q",
		description: "quit",
		async action(server) {
			try {
				await server.close();
			} finally {
				process.exit();
			}
		}
	}
];
const BASE_PREVIEW_SHORTCUTS = [{
	key: "o",
	description: "open in browser",
	action(server) {
		const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0];
		if (url) openBrowser(url, true, server.config.logger);
		else server.config.logger.warn("No URL available to open in browser");
	}
}, {
	key: "q",
	description: "quit",
	async action(server) {
		try {
			await server.close();
		} finally {
			process.exit();
		}
	}
}];
//#endregion
//#region src/node/watch.ts
function getResolvedOutDirs(root, outDir, outputOptions) {
	const resolvedOutDir = path.resolve(root, outDir);
	if (!outputOptions) return /* @__PURE__ */ new Set([resolvedOutDir]);
	return new Set(arraify(outputOptions).map(({ dir }) => dir ? path.resolve(root, dir) : resolvedOutDir));
}
function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) {
	if (emptyOutDir != null) return emptyOutDir;
	for (const outDir of outDirs) if (!normalizePath(outDir).startsWith(withTrailingSlash(root))) {
		logger?.warn(import_picocolors.default.yellow(`\n${import_picocolors.default.bold(`(!)`)} outDir ${import_picocolors.default.white(import_picocolors.default.dim(outDir))} is not inside project root and will not be emptied.\nUse --emptyOutDir to override.\n`));
		return false;
	}
	return true;
}
function resolveChokidarOptions(options, resolvedOutDirs, emptyOutDir, cacheDir) {
	const { ignored: ignoredList, ...otherOptions } = options ?? {};
	const ignored = [
		"**/.git/**",
		"**/node_modules/**",
		"**/test-results/**",
		escapePath(cacheDir) + "/**",
		...arraify(ignoredList || [])
	];
	if (emptyOutDir) ignored.push(...[...resolvedOutDirs].map((outDir) => escapePath(outDir) + "/**"));
	return {
		ignored,
		ignoreInitial: true,
		ignorePermissionErrors: true,
		...otherOptions
	};
}
function convertToWatcherOptions(options) {
	if (!options) return;
	return {
		usePolling: options.usePolling,
		pollInterval: options.interval
	};
}
var NoopWatcher = class extends EventEmitter {
	options;
	constructor(options) {
		super();
		this.options = options;
	}
	add() {
		return this;
	}
	unwatch() {
		return this;
	}
	getWatched() {
		return {};
	}
	ref() {
		return this;
	}
	unref() {
		return this;
	}
	async close() {}
};
function createNoopWatcher(options) {
	return new NoopWatcher(options);
}
//#endregion
//#region src/node/publicDir.ts
const publicFilesMap = /* @__PURE__ */ new WeakMap();
async function initPublicFiles(config) {
	let fileNames;
	try {
		fileNames = await recursiveReaddir(config.publicDir);
	} catch (e) {
		if (e.code === "ERR_SYMLINK_IN_RECURSIVE_READDIR") return;
		throw e;
	}
	const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length)));
	publicFilesMap.set(config, publicFiles);
	return publicFiles;
}
function getPublicFiles(config) {
	return publicFilesMap.get(config);
}
function checkPublicFile(url, config) {
	const { publicDir } = config;
	if (!publicDir || url[0] !== "/") return;
	const fileName = cleanUrl(url);
	const publicFiles = getPublicFiles(config);
	if (publicFiles) return publicFiles.has(fileName) ? normalizePath(path.join(publicDir, fileName)) : void 0;
	const publicFile = normalizePath(path.join(publicDir, fileName));
	if (!publicFile.startsWith(withTrailingSlash(publicDir))) return;
	return tryStatSync(publicFile)?.isFile() ? publicFile : void 0;
}
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js
var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const BINARY_TYPES = [
		"nodebuffer",
		"arraybuffer",
		"fragments"
	];
	const hasBlob = typeof Blob !== "undefined";
	if (hasBlob) BINARY_TYPES.push("blob");
	module.exports = {
		BINARY_TYPES,
		CLOSE_TIMEOUT: 3e4,
		EMPTY_BUFFER: Buffer.alloc(0),
		GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
		hasBlob,
		kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
		kListener: Symbol("kListener"),
		kStatusCode: Symbol("status-code"),
		kWebSocket: Symbol("websocket"),
		NOOP: () => {}
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js
var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { EMPTY_BUFFER } = require_constants();
	const FastBuffer = Buffer[Symbol.species];
	/**
	* Merges an array of buffers into a new buffer.
	*
	* @param {Buffer[]} list The array of buffers to concat
	* @param {Number} totalLength The total length of buffers in the list
	* @return {Buffer} The resulting buffer
	* @public
	*/
	function concat(list, totalLength) {
		if (list.length === 0) return EMPTY_BUFFER;
		if (list.length === 1) return list[0];
		const target = Buffer.allocUnsafe(totalLength);
		let offset = 0;
		for (let i = 0; i < list.length; i++) {
			const buf = list[i];
			target.set(buf, offset);
			offset += buf.length;
		}
		if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
		return target;
	}
	/**
	* Masks a buffer using the given mask.
	*
	* @param {Buffer} source The buffer to mask
	* @param {Buffer} mask The mask to use
	* @param {Buffer} output The buffer where to store the result
	* @param {Number} offset The offset at which to start writing
	* @param {Number} length The number of bytes to mask.
	* @public
	*/
	function _mask(source, mask, output, offset, length) {
		for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
	}
	/**
	* Unmasks a buffer using the given mask.
	*
	* @param {Buffer} buffer The buffer to unmask
	* @param {Buffer} mask The mask to use
	* @public
	*/
	function _unmask(buffer, mask) {
		for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
	}
	/**
	* Converts a buffer to an `ArrayBuffer`.
	*
	* @param {Buffer} buf The buffer to convert
	* @return {ArrayBuffer} Converted buffer
	* @public
	*/
	function toArrayBuffer(buf) {
		if (buf.length === buf.buffer.byteLength) return buf.buffer;
		return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
	}
	/**
	* Converts `data` to a `Buffer`.
	*
	* @param {*} data The data to convert
	* @return {Buffer} The buffer
	* @throws {TypeError}
	* @public
	*/
	function toBuffer(data) {
		toBuffer.readOnly = true;
		if (Buffer.isBuffer(data)) return data;
		let buf;
		if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
		else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
		else {
			buf = Buffer.from(data);
			toBuffer.readOnly = false;
		}
		return buf;
	}
	module.exports = {
		concat,
		mask: _mask,
		toArrayBuffer,
		toBuffer,
		unmask: _unmask
	};
	/* istanbul ignore else  */
	if (!process.env.WS_NO_BUFFER_UTIL) try {
		const bufferUtil = __require("bufferutil");
		module.exports.mask = function(source, mask, output, offset, length) {
			if (length < 48) _mask(source, mask, output, offset, length);
			else bufferUtil.mask(source, mask, output, offset, length);
		};
		module.exports.unmask = function(buffer, mask) {
			if (buffer.length < 32) _unmask(buffer, mask);
			else bufferUtil.unmask(buffer, mask);
		};
	} catch (e) {}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js
var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const kDone = Symbol("kDone");
	const kRun = Symbol("kRun");
	/**
	* A very simple job queue with adjustable concurrency. Adapted from
	* https://github.com/STRML/async-limiter
	*/
	var Limiter = class {
		/**
		* Creates a new `Limiter`.
		*
		* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
		*     to run concurrently
		*/
		constructor(concurrency) {
			this[kDone] = () => {
				this.pending--;
				this[kRun]();
			};
			this.concurrency = concurrency || Infinity;
			this.jobs = [];
			this.pending = 0;
		}
		/**
		* Adds a job to the queue.
		*
		* @param {Function} job The job to run
		* @public
		*/
		add(job) {
			this.jobs.push(job);
			this[kRun]();
		}
		/**
		* Removes a job from the queue and runs it if possible.
		*
		* @private
		*/
		[kRun]() {
			if (this.pending === this.concurrency) return;
			if (this.jobs.length) {
				const job = this.jobs.shift();
				this.pending++;
				job(this[kDone]);
			}
		}
	};
	module.exports = Limiter;
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const zlib$1 = __require("zlib");
	const bufferUtil = require_buffer_util();
	const Limiter = require_limiter();
	const { kStatusCode } = require_constants();
	const FastBuffer = Buffer[Symbol.species];
	const TRAILER = Buffer.from([
		0,
		0,
		255,
		255
	]);
	const kPerMessageDeflate = Symbol("permessage-deflate");
	const kTotalLength = Symbol("total-length");
	const kCallback = Symbol("callback");
	const kBuffers = Symbol("buffers");
	const kError = Symbol("error");
	let zlibLimiter;
	/**
	* permessage-deflate implementation.
	*/
	var PerMessageDeflate = class {
		/**
		* Creates a PerMessageDeflate instance.
		*
		* @param {Object} [options] Configuration options
		* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
		*     for, or request, a custom client window size
		* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
		*     acknowledge disabling of client context takeover
		* @param {Number} [options.concurrencyLimit=10] The number of concurrent
		*     calls to zlib
		* @param {Boolean} [options.isServer=false] Create the instance in either
		*     server or client mode
		* @param {Number} [options.maxPayload=0] The maximum allowed message length
		* @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
		*/
		constructor(options) {
			this._options = options || {};
			this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
			this._maxPayload = this._options.maxPayload | 0;
			this._isServer = !!this._options.isServer;
			this._deflate = null;
			this._inflate = null;
			this.params = null;
			if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
		}
		/**
		* @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(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
			}
		}
		/**
		*  Accept an extension negotiation offer.
		*
		* @param {Array} offers The extension negotiation offers
		* @return {Object} Accepted configuration
		* @private
		*/
		acceptAsServer(offers) {
			const opts = this._options;
			const accepted = offers.find((params) => {
				if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
				return true;
			});
			if (!accepted) throw new Error("None of the extension offers can be accepted");
			if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
			if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
			if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
			if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
			else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
			return accepted;
		}
		/**
		* Accept the extension negotiation response.
		*
		* @param {Array} response The extension negotiation response
		* @return {Object} Accepted configuration
		* @private
		*/
		acceptAsClient(response) {
			const params = response[0];
			if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
			if (!params.client_max_window_bits) {
				if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
			} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
			return params;
		}
		/**
		* Normalize parameters.
		*
		* @param {Array} configurations The extension negotiation offers/reponse
		* @return {Array} The offers/response with normalized parameters
		* @private
		*/
		normalizeParams(configurations) {
			configurations.forEach((params) => {
				Object.keys(params).forEach((key) => {
					let value = params[key];
					if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
					value = value[0];
					if (key === "client_max_window_bits") {
						if (value !== true) {
							const num = +value;
							if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
							value = num;
						} else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
					} else if (key === "server_max_window_bits") {
						const num = +value;
						if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
						value = num;
					} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
						if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
					} else throw new Error(`Unknown parameter "${key}"`);
					params[key] = value;
				});
			});
			return configurations;
		}
		/**
		* Decompress data. Concurrency limited.
		*
		* @param {Buffer} data Compressed data
		* @param {Boolean} fin Specifies whether or not this is the last fragment
		* @param {Function} callback Callback
		* @public
		*/
		decompress(data, fin, callback) {
			zlibLimiter.add((done) => {
				this._decompress(data, fin, (err, result) => {
					done();
					callback(err, result);
				});
			});
		}
		/**
		* Compress data. Concurrency limited.
		*
		* @param {(Buffer|String)} data Data to compress
		* @param {Boolean} fin Specifies whether or not this is the last fragment
		* @param {Function} callback Callback
		* @public
		*/
		compress(data, fin, callback) {
			zlibLimiter.add((done) => {
				this._compress(data, fin, (err, result) => {
					done();
					callback(err, result);
				});
			});
		}
		/**
		* Decompress data.
		*
		* @param {Buffer} data Compressed data
		* @param {Boolean} fin Specifies whether or not this is the last fragment
		* @param {Function} callback Callback
		* @private
		*/
		_decompress(data, fin, callback) {
			const endpoint = this._isServer ? "client" : "server";
			if (!this._inflate) {
				const key = `${endpoint}_max_window_bits`;
				const windowBits = typeof this.params[key] !== "number" ? zlib$1.Z_DEFAULT_WINDOWBITS : this.params[key];
				this._inflate = zlib$1.createInflateRaw({
					...this._options.zlibInflateOptions,
					windowBits
				});
				this._inflate[kPerMessageDeflate] = this;
				this._inflate[kTotalLength] = 0;
				this._inflate[kBuffers] = [];
				this._inflate.on("error", inflateOnError);
				this._inflate.on("data", inflateOnData);
			}
			this._inflate[kCallback] = callback;
			this._inflate.write(data);
			if (fin) this._inflate.write(TRAILER);
			this._inflate.flush(() => {
				const err = this._inflate[kError];
				if (err) {
					this._inflate.close();
					this._inflate = null;
					callback(err);
					return;
				}
				const data = 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, data);
			});
		}
		/**
		* 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$1.Z_DEFAULT_WINDOWBITS : this.params[key];
				this._deflate = zlib$1.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$1.Z_SYNC_FLUSH, () => {
				if (!this._deflate) return;
				let data = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
				if (fin) data = new FastBuffer(data.buffer, data.byteOffset, data.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, data);
			});
		}
	};
	module.exports = PerMessageDeflate;
	/**
	* The listener of the `zlib.DeflateRaw` stream `'data'` event.
	*
	* @param {Buffer} chunk A chunk of data
	* @private
	*/
	function deflateOnData(chunk) {
		this[kBuffers].push(chunk);
		this[kTotalLength] += chunk.length;
	}
	/**
	* The listener of the `zlib.InflateRaw` stream `'data'` event.
	*
	* @param {Buffer} chunk A chunk of data
	* @private
	*/
	function inflateOnData(chunk) {
		this[kTotalLength] += chunk.length;
		if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
			this[kBuffers].push(chunk);
			return;
		}
		this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
		this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
		this[kError][kStatusCode] = 1009;
		this.removeListener("data", inflateOnData);
		this.reset();
	}
	/**
	* The listener of the `zlib.InflateRaw` stream `'error'` event.
	*
	* @param {Error} err The emitted error
	* @private
	*/
	function inflateOnError(err) {
		this[kPerMessageDeflate]._inflate = null;
		if (this[kError]) {
			this[kCallback](this[kError]);
			return;
		}
		err[kStatusCode] = 1007;
		this[kCallback](err);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js
var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { isUtf8 } = __require("buffer");
	const { hasBlob } = require_constants();
	const tokenChars = [
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		1,
		0,
		1,
		1,
		1,
		1,
		1,
		0,
		0,
		1,
		1,
		0,
		1,
		1,
		0,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		0,
		0,
		0,
		0,
		0,
		0,
		0,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		0,
		0,
		0,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		1,
		0,
		1,
		0,
		1,
		0
	];
	/**
	* Checks if a status code is allowed in a close frame.
	*
	* @param {Number} code The status code
	* @return {Boolean} `true` if the status code is valid, else `false`
	* @public
	*/
	function isValidStatusCode(code) {
		return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
	}
	/**
	* Checks if a given buffer contains only correct UTF-8.
	* Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
	* Markus Kuhn.
	*
	* @param {Buffer} buf The buffer to check
	* @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
	* @public
	*/
	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 || 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 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
			i += 4;
		} else return false;
		return true;
	}
	/**
	* Determines whether a value is a `Blob`.
	*
	* @param {*} value The value to be tested
	* @return {Boolean} `true` if `value` is a `Blob`, else `false`
	* @private
	*/
	function isBlob(value) {
		return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
	}
	module.exports = {
		isBlob,
		isValidStatusCode,
		isValidUTF8: _isValidUTF8,
		tokenChars
	};
	if (isUtf8) module.exports.isValidUTF8 = function(buf) {
		return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
	};
	else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
		const isValidUTF8 = __require("utf-8-validate");
		module.exports.isValidUTF8 = function(buf) {
			return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
		};
	} catch (e) {}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js
var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { Writable: Writable$1 } = __require("stream");
	const PerMessageDeflate = require_permessage_deflate();
	const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
	const { concat, toArrayBuffer, unmask } = require_buffer_util();
	const { isValidStatusCode, isValidUTF8 } = require_validation();
	const FastBuffer = Buffer[Symbol.species];
	const GET_INFO = 0;
	const GET_PAYLOAD_LENGTH_16 = 1;
	const GET_PAYLOAD_LENGTH_64 = 2;
	const GET_MASK = 3;
	const GET_DATA = 4;
	const INFLATING = 5;
	const DEFER_EVENT = 6;
	/**
	* HyBi Receiver implementation.
	*
	* @extends Writable
	*/
	var Receiver = class 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.maxBufferedChunks=0] The maximum number of
		*     buffered data chunks
		* @param {Number} [options.maxFragments=0] The maximum number of message
		*     fragments
		* @param {Number} [options.maxPayload=0] The maximum allowed message length
		* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
		*     not to skip UTF-8 validation for text and close messages
		*/
		constructor(options = {}) {
			super();
			this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
			this._binaryType = options.binaryType || BINARY_TYPES[0];
			this._extensions = options.extensions || {};
			this._isServer = !!options.isServer;
			this._maxBufferedChunks = options.maxBufferedChunks | 0;
			this._maxFragments = options.maxFragments | 0;
			this._maxPayload = options.maxPayload | 0;
			this._skipUTF8Validation = !!options.skipUTF8Validation;
			this[kWebSocket] = void 0;
			this._bufferedBytes = 0;
			this._buffers = [];
			this._compressed = false;
			this._payloadLength = 0;
			this._mask = void 0;
			this._fragmented = 0;
			this._masked = false;
			this._fin = false;
			this._opcode = 0;
			this._totalPayloadLength = 0;
			this._messageLength = 0;
			this._fragments = [];
			this._errored = false;
			this._loop = false;
			this._state = GET_INFO;
		}
		/**
		* Implements `Writable.prototype._write()`.
		*
		* @param {Buffer} chunk The chunk of data to write
		* @param {String} encoding The character encoding of `chunk`
		* @param {Function} cb Callback
		* @private
		*/
		_write(chunk, encoding, cb) {
			if (this._opcode === 8 && this._state == GET_INFO) return cb();
			if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
				cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
				return;
			}
			this._bufferedBytes += chunk.length;
			this._buffers.push(chunk);
			this.startLoop(cb);
		}
		/**
		* Consumes `n` bytes from the buffered data.
		*
		* @param {Number} n The number of bytes to consume
		* @return {Buffer} The consumed bytes
		* @private
		*/
		consume(n) {
			this._bufferedBytes -= n;
			if (n === this._buffers[0].length) return this._buffers.shift();
			if (n < this._buffers[0].length) {
				const buf = this._buffers[0];
				this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
				return new FastBuffer(buf.buffer, buf.byteOffset, n);
			}
			const dst = Buffer.allocUnsafe(n);
			do {
				const buf = this._buffers[0];
				const offset = dst.length - n;
				if (n >= buf.length) dst.set(this._buffers.shift(), offset);
				else {
					dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
					this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
				}
				n -= buf.length;
			} while (n > 0);
			return dst;
		}
		/**
		* Starts the parsing loop.
		*
		* @param {Function} cb Callback
		* @private
		*/
		startLoop(cb) {
			this._loop = true;
			do
				switch (this._state) {
					case GET_INFO:
						this.getInfo(cb);
						break;
					case GET_PAYLOAD_LENGTH_16:
						this.getPayloadLength16(cb);
						break;
					case GET_PAYLOAD_LENGTH_64:
						this.getPayloadLength64(cb);
						break;
					case GET_MASK:
						this.getMask();
						break;
					case GET_DATA:
						this.getData(cb);
						break;
					case INFLATING:
					case DEFER_EVENT:
						this._loop = false;
						return;
				}
			while (this._loop);
			if (!this._errored) cb();
		}
		/**
		* Reads the first two bytes of a frame.
		*
		* @param {Function} cb Callback
		* @private
		*/
		getInfo(cb) {
			if (this._bufferedBytes < 2) {
				this._loop = false;
				return;
			}
			const buf = this.consume(2);
			if ((buf[0] & 48) !== 0) {
				cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
				return;
			}
			const compressed = (buf[0] & 64) === 64;
			if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
				cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
				return;
			}
			this._fin = (buf[0] & 128) === 128;
			this._opcode = buf[0] & 15;
			this._payloadLength = buf[1] & 127;
			if (this._opcode === 0) {
				if (compressed) {
					cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
					return;
				}
				if (!this._fragmented) {
					cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
					return;
				}
				this._opcode = this._fragmented;
			} else if (this._opcode === 1 || this._opcode === 2) {
				if (this._fragmented) {
					cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
					return;
				}
				this._compressed = compressed;
			} else if (this._opcode > 7 && this._opcode < 11) {
				if (!this._fin) {
					cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
					return;
				}
				if (compressed) {
					cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
					return;
				}
				if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
					cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
					return;
				}
			} else {
				cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
				return;
			}
			if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
			this._masked = (buf[1] & 128) === 128;
			if (this._isServer) {
				if (!this._masked) {
					cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
					return;
				}
			} else if (this._masked) {
				cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
				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, 21) - 1) {
				cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
				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) {
					cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
					return;
				}
			}
			if (this._masked) this._state = GET_MASK;
			else this._state = GET_DATA;
		}
		/**
		* Reads mask bytes.
		*
		* @private
		*/
		getMask() {
			if (this._bufferedBytes < 4) {
				this._loop = false;
				return;
			}
			this._mask = this.consume(4);
			this._state = GET_DATA;
		}
		/**
		* Reads data bytes.
		*
		* @param {Function} cb Callback
		* @private
		*/
		getData(cb) {
			let data = EMPTY_BUFFER;
			if (this._payloadLength) {
				if (this._bufferedBytes < this._payloadLength) {
					this._loop = false;
					return;
				}
				data = this.consume(this._payloadLength);
				if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
			}
			if (this._opcode > 7) {
				this.controlMessage(data, cb);
				return;
			}
			if (this._compressed) {
				this._state = INFLATING;
				this.decompress(data, cb);
				return;
			}
			if (data.length) {
				if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
					cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
					return;
				}
				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) {
			this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
				if (err) return cb(err);
				if (buf.length) {
					this._messageLength += buf.length;
					if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
						cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
						return;
					}
					if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
						cb(this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"));
						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)) {
					cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
					return;
				}
				if (this._state === INFLATING || this._allowSynchronousEvents) {
					this.emit("message", buf, false);
					this._state = GET_INFO;
				} else {
					this._state = DEFER_EVENT;
					setImmediate(() => {
						this.emit("message", buf, false);
						this._state = GET_INFO;
						this.startLoop(cb);
					});
				}
			}
		}
		/**
		* Handles a control message.
		*
		* @param {Buffer} data Data to handle
		* @return {(Error|RangeError|undefined)} A possible error
		* @private
		*/
		controlMessage(data, cb) {
			if (this._opcode === 8) {
				if (data.length === 0) {
					this._loop = false;
					this.emit("conclude", 1005, EMPTY_BUFFER);
					this.end();
				} else {
					const code = data.readUInt16BE(0);
					if (!isValidStatusCode(code)) {
						cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
						return;
					}
					const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
					if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
						cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
						return;
					}
					this._loop = false;
					this.emit("conclude", code, buf);
					this.end();
				}
				this._state = GET_INFO;
				return;
			}
			if (this._allowSynchronousEvents) {
				this.emit(this._opcode === 9 ? "ping" : "pong", data);
				this._state = GET_INFO;
			} else {
				this._state = DEFER_EVENT;
				setImmediate(() => {
					this.emit(this._opcode === 9 ? "ping" : "pong", data);
					this._state = GET_INFO;
					this.startLoop(cb);
				});
			}
		}
		/**
		* Builds an error object.
		*
		* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
		* @param {String} message The error message
		* @param {Boolean} prefix Specifies whether or not to add a default prefix to
		*     `message`
		* @param {Number} statusCode The status code
		* @param {String} errorCode The exposed error code
		* @return {(Error|RangeError)} The error
		* @private
		*/
		createError(ErrorCtor, message, prefix, statusCode, errorCode) {
			this._loop = false;
			this._errored = true;
			const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
			Error.captureStackTrace(err, this.createError);
			err.code = errorCode;
			err[kStatusCode] = statusCode;
			return err;
		}
	};
	module.exports = Receiver;
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js
var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { Duplex: Duplex$3 } = __require("stream");
	const { randomFillSync } = __require("crypto");
	const { types: { isUint8Array } } = __require("util");
	const PerMessageDeflate = require_permessage_deflate();
	const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
	const { isBlob, isValidStatusCode } = require_validation();
	const { mask: applyMask, toBuffer } = require_buffer_util();
	const kByteLength = Symbol("kByteLength");
	const maskBuffer = Buffer.alloc(4);
	const RANDOM_POOL_SIZE = 8 * 1024;
	let randomPool;
	let randomPoolPointer = RANDOM_POOL_SIZE;
	const DEFAULT = 0;
	const DEFLATING = 1;
	const GET_BLOB_DATA = 2;
	module.exports = class Sender {
		/**
		* Creates a Sender instance.
		*
		* @param {Duplex} socket The connection socket
		* @param {Object} [extensions] An object containing the negotiated extensions
		* @param {Function} [generateMask] The function used to generate the masking
		*     key
		*/
		constructor(socket, extensions, generateMask) {
			this._extensions = extensions || {};
			if (generateMask) {
				this._generateMask = generateMask;
				this._maskBuffer = Buffer.alloc(4);
			}
			this._socket = socket;
			this._firstFragment = true;
			this._compress = false;
			this._bufferedBytes = 0;
			this._queue = [];
			this._state = DEFAULT;
			this.onerror = NOOP;
			this[kWebSocket] = void 0;
		}
		/**
		* Frames a piece of data according to the HyBi WebSocket protocol.
		*
		* @param {(Buffer|String)} data The data to frame
		* @param {Object} options Options object
		* @param {Boolean} [options.fin=false] Specifies whether or not to set the
		*     FIN bit
		* @param {Function} [options.generateMask] The function used to generate the
		*     masking key
		* @param {Boolean} [options.mask=false] Specifies whether or not to mask
		*     `data`
		* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
		*     key
		* @param {Number} options.opcode The opcode
		* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
		*     modified
		* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
		*     RSV1 bit
		* @return {(Buffer|String)[]} The framed data
		* @public
		*/
		static frame(data, options) {
			let mask;
			let merge = false;
			let offset = 2;
			let skipMasking = false;
			if (options.mask) {
				mask = options.maskBuffer || maskBuffer;
				if (options.generateMask) options.generateMask(mask);
				else {
					if (randomPoolPointer === RANDOM_POOL_SIZE) {
						/* istanbul ignore else  */
						if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
						randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
						randomPoolPointer = 0;
					}
					mask[0] = randomPool[randomPoolPointer++];
					mask[1] = randomPool[randomPoolPointer++];
					mask[2] = randomPool[randomPoolPointer++];
					mask[3] = randomPool[randomPoolPointer++];
				}
				skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
				offset = 6;
			}
			let dataLength;
			if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
			else {
				data = Buffer.from(data);
				dataLength = data.length;
			}
			else {
				dataLength = data.length;
				merge = options.mask && options.readOnly && !skipMasking;
			}
			let payloadLength = dataLength;
			if (dataLength >= 65536) {
				offset += 8;
				payloadLength = 127;
			} else if (dataLength > 125) {
				offset += 2;
				payloadLength = 126;
			}
			const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
			target[0] = options.fin ? options.opcode | 128 : options.opcode;
			if (options.rsv1) target[0] |= 64;
			target[1] = payloadLength;
			if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
			else if (payloadLength === 127) {
				target[2] = target[3] = 0;
				target.writeUIntBE(dataLength, 4, 6);
			}
			if (!options.mask) return [target, data];
			target[1] |= 128;
			target[offset - 4] = mask[0];
			target[offset - 3] = mask[1];
			target[offset - 2] = mask[2];
			target[offset - 1] = mask[3];
			if (skipMasking) return [target, data];
			if (merge) {
				applyMask(data, mask, target, offset, dataLength);
				return [target];
			}
			applyMask(data, mask, data, 0, dataLength);
			return [target, data];
		}
		/**
		* Sends a close message to the other peer.
		*
		* @param {Number} [code] The status code component of the body
		* @param {(String|Buffer)} [data] The message component of the body
		* @param {Boolean} [mask=false] Specifies whether or not to mask the message
		* @param {Function} [cb] Callback
		* @public
		*/
		close(code, data, mask, cb) {
			let buf;
			if (code === void 0) buf = EMPTY_BUFFER;
			else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
			else if (data === void 0 || !data.length) {
				buf = Buffer.allocUnsafe(2);
				buf.writeUInt16BE(code, 0);
			} else {
				const length = Buffer.byteLength(data);
				if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
				buf = Buffer.allocUnsafe(2 + length);
				buf.writeUInt16BE(code, 0);
				if (typeof data === "string") buf.write(data, 2);
				else if (isUint8Array(data)) buf.set(data, 2);
				else throw new TypeError("Second argument must be a string or a Uint8Array");
			}
			const options = {
				[kByteLength]: buf.length,
				fin: true,
				generateMask: this._generateMask,
				mask,
				maskBuffer: this._maskBuffer,
				opcode: 8,
				readOnly: false,
				rsv1: false
			};
			if (this._state !== DEFAULT) this.enqueue([
				this.dispatch,
				buf,
				false,
				options,
				cb
			]);
			else this.sendFrame(Sender.frame(buf, options), cb);
		}
		/**
		* Sends a ping message to the other peer.
		*
		* @param {*} data The message to send
		* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
		* @param {Function} [cb] Callback
		* @public
		*/
		ping(data, mask, cb) {
			let byteLength;
			let readOnly;
			if (typeof data === "string") {
				byteLength = Buffer.byteLength(data);
				readOnly = false;
			} else if (isBlob(data)) {
				byteLength = data.size;
				readOnly = false;
			} else {
				data = toBuffer(data);
				byteLength = data.length;
				readOnly = toBuffer.readOnly;
			}
			if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
			const options = {
				[kByteLength]: byteLength,
				fin: true,
				generateMask: this._generateMask,
				mask,
				maskBuffer: this._maskBuffer,
				opcode: 9,
				readOnly,
				rsv1: false
			};
			if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
				this.getBlobData,
				data,
				false,
				options,
				cb
			]);
			else this.getBlobData(data, false, options, cb);
			else if (this._state !== DEFAULT) this.enqueue([
				this.dispatch,
				data,
				false,
				options,
				cb
			]);
			else this.sendFrame(Sender.frame(data, options), cb);
		}
		/**
		* Sends a pong message to the other peer.
		*
		* @param {*} data The message to send
		* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
		* @param {Function} [cb] Callback
		* @public
		*/
		pong(data, mask, cb) {
			let byteLength;
			let readOnly;
			if (typeof data === "string") {
				byteLength = Buffer.byteLength(data);
				readOnly = false;
			} else if (isBlob(data)) {
				byteLength = data.size;
				readOnly = false;
			} else {
				data = toBuffer(data);
				byteLength = data.length;
				readOnly = toBuffer.readOnly;
			}
			if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
			const options = {
				[kByteLength]: byteLength,
				fin: true,
				generateMask: this._generateMask,
				mask,
				maskBuffer: this._maskBuffer,
				opcode: 10,
				readOnly,
				rsv1: false
			};
			if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
				this.getBlobData,
				data,
				false,
				options,
				cb
			]);
			else this.getBlobData(data, false, options, cb);
			else if (this._state !== DEFAULT) this.enqueue([
				this.dispatch,
				data,
				false,
				options,
				cb
			]);
			else this.sendFrame(Sender.frame(data, options), cb);
		}
		/**
		* Sends a data message to the other peer.
		*
		* @param {*} data The message to send
		* @param {Object} options Options object
		* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
		*     or text
		* @param {Boolean} [options.compress=false] Specifies whether or not to
		*     compress `data`
		* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
		*     last one
		* @param {Boolean} [options.mask=false] Specifies whether or not to mask
		*     `data`
		* @param {Function} [cb] Callback
		* @public
		*/
		send(data, options, cb) {
			const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
			let opcode = options.binary ? 2 : 1;
			let rsv1 = options.compress;
			let byteLength;
			let readOnly;
			if (typeof data === "string") {
				byteLength = Buffer.byteLength(data);
				readOnly = false;
			} else if (isBlob(data)) {
				byteLength = data.size;
				readOnly = false;
			} else {
				data = toBuffer(data);
				byteLength = data.length;
				readOnly = toBuffer.readOnly;
			}
			if (this._firstFragment) {
				this._firstFragment = false;
				if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
				this._compress = rsv1;
			} else {
				rsv1 = false;
				opcode = 0;
			}
			if (options.fin) this._firstFragment = true;
			const opts = {
				[kByteLength]: byteLength,
				fin: options.fin,
				generateMask: this._generateMask,
				mask: options.mask,
				maskBuffer: this._maskBuffer,
				opcode,
				readOnly,
				rsv1
			};
			if (isBlob(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, options, cb) {
			this._bufferedBytes += options[kByteLength];
			this._state = GET_BLOB_DATA;
			blob.arrayBuffer().then((arrayBuffer) => {
				if (this._socket.destroyed) {
					const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
					process.nextTick(callCallbacks, this, err, cb);
					return;
				}
				this._bufferedBytes -= options[kByteLength];
				const data = toBuffer(arrayBuffer);
				if (!compress) {
					this._state = DEFAULT;
					this.sendFrame(Sender.frame(data, options), cb);
					this.dequeue();
				} else this.dispatch(data, compress, options, cb);
			}).catch((err) => {
				process.nextTick(onError, this, err, cb);
			});
		}
		/**
		* Dispatches a message.
		*
		* @param {(Buffer|String)} data The message to send
		* @param {Boolean} [compress=false] Specifies whether or not to compress
		*     `data`
		* @param {Object} options Options object
		* @param {Boolean} [options.fin=false] Specifies whether or not to set the
		*     FIN bit
		* @param {Function} [options.generateMask] The function used to generate the
		*     masking key
		* @param {Boolean} [options.mask=false] Specifies whether or not to mask
		*     `data`
		* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
		*     key
		* @param {Number} options.opcode The opcode
		* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
		*     modified
		* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
		*     RSV1 bit
		* @param {Function} [cb] Callback
		* @private
		*/
		dispatch(data, compress, options, cb) {
			if (!compress) {
				this.sendFrame(Sender.frame(data, options), cb);
				return;
			}
			const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
			this._bufferedBytes += options[kByteLength];
			this._state = DEFLATING;
			perMessageDeflate.compress(data, options.fin, (_, buf) => {
				if (this._socket.destroyed) {
					const err = /* @__PURE__ */ new Error("The socket was closed while data was being compressed");
					callCallbacks(this, err, cb);
					return;
				}
				this._bufferedBytes -= options[kByteLength];
				this._state = DEFAULT;
				options.readOnly = false;
				this.sendFrame(Sender.frame(buf, options), 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 | String)[]} 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);
		}
	};
	/**
	* Calls queued callbacks with an error.
	*
	* @param {Sender} sender The `Sender` instance
	* @param {Error} err The error to call the callbacks with
	* @param {Function} [cb] The first callback
	* @private
	*/
	function callCallbacks(sender, err, cb) {
		if (typeof cb === "function") cb(err);
		for (let i = 0; i < sender._queue.length; i++) {
			const params = sender._queue[i];
			const callback = params[params.length - 1];
			if (typeof callback === "function") callback(err);
		}
	}
	/**
	* Handles a `Sender` error.
	*
	* @param {Sender} sender The `Sender` instance
	* @param {Error} err The error
	* @param {Function} [cb] The first pending callback
	* @private
	*/
	function onError(sender, err, cb) {
		callCallbacks(sender, err, cb);
		sender.onerror(err);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js
var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { kForOnEventAttribute, kListener } = require_constants();
	const kCode = Symbol("kCode");
	const kData = Symbol("kData");
	const kError = Symbol("kError");
	const kMessage = Symbol("kMessage");
	const kReason = Symbol("kReason");
	const kTarget = Symbol("kTarget");
	const kType = Symbol("kType");
	const kWasClean = Symbol("kWasClean");
	/**
	* Class representing an event.
	*/
	var Event = class {
		/**
		* Create a new `Event`.
		*
		* @param {String} type The name of the event
		* @throws {TypeError} If the `type` argument is not specified
		*/
		constructor(type) {
			this[kTarget] = null;
			this[kType] = type;
		}
		/**
		* @type {*}
		*/
		get target() {
			return this[kTarget];
		}
		/**
		* @type {String}
		*/
		get type() {
			return this[kType];
		}
	};
	Object.defineProperty(Event.prototype, "target", { enumerable: true });
	Object.defineProperty(Event.prototype, "type", { enumerable: true });
	/**
	* Class representing a close event.
	*
	* @extends Event
	*/
	var CloseEvent = class extends Event {
		/**
		* Create a new `CloseEvent`.
		*
		* @param {String} type The name of the event
		* @param {Object} [options] A dictionary object that allows for setting
		*     attributes via object members of the same name
		* @param {Number} [options.code=0] The status code explaining why the
		*     connection was closed
		* @param {String} [options.reason=''] A human-readable string explaining why
		*     the connection was closed
		* @param {Boolean} [options.wasClean=false] Indicates whether or not the
		*     connection was cleanly closed
		*/
		constructor(type, options = {}) {
			super(type);
			this[kCode] = options.code === void 0 ? 0 : options.code;
			this[kReason] = options.reason === void 0 ? "" : options.reason;
			this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
		}
		/**
		* @type {Number}
		*/
		get code() {
			return this[kCode];
		}
		/**
		* @type {String}
		*/
		get reason() {
			return this[kReason];
		}
		/**
		* @type {Boolean}
		*/
		get wasClean() {
			return this[kWasClean];
		}
	};
	Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
	Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
	Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
	/**
	* Class representing an error event.
	*
	* @extends Event
	*/
	var ErrorEvent = class extends Event {
		/**
		* Create a new `ErrorEvent`.
		*
		* @param {String} type The name of the event
		* @param {Object} [options] A dictionary object that allows for setting
		*     attributes via object members of the same name
		* @param {*} [options.error=null] The error that generated this event
		* @param {String} [options.message=''] The error message
		*/
		constructor(type, options = {}) {
			super(type);
			this[kError] = options.error === void 0 ? null : options.error;
			this[kMessage] = options.message === void 0 ? "" : options.message;
		}
		/**
		* @type {*}
		*/
		get error() {
			return this[kError];
		}
		/**
		* @type {String}
		*/
		get message() {
			return this[kMessage];
		}
	};
	Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
	Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
	/**
	* Class representing a message event.
	*
	* @extends Event
	*/
	var MessageEvent = class extends Event {
		/**
		* Create a new `MessageEvent`.
		*
		* @param {String} type The name of the event
		* @param {Object} [options] A dictionary object that allows for setting
		*     attributes via object members of the same name
		* @param {*} [options.data=null] The message content
		*/
		constructor(type, options = {}) {
			super(type);
			this[kData] = options.data === void 0 ? null : options.data;
		}
		/**
		* @type {*}
		*/
		get data() {
			return this[kData];
		}
	};
	Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
	module.exports = {
		CloseEvent,
		ErrorEvent,
		Event,
		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, options = {}) {
				for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
				let wrapper;
				if (type === "message") wrapper = function onMessage(data, isBinary) {
					const event = new 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 onError(error) {
					const event = new ErrorEvent("error", {
						error,
						message: error.message
					});
					event[kTarget] = this;
					callListener(handler, this, event);
				};
				else if (type === "open") wrapper = function onOpen() {
					const event = new Event("open");
					event[kTarget] = this;
					callListener(handler, this, event);
				};
				else return;
				wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
				wrapper[kListener] = handler;
				if (options.once) this.once(type, wrapper);
				else this.on(type, wrapper);
			},
			/**
			* Remove an event listener.
			*
			* @param {String} type A string representing the event type to remove
			* @param {(Function|Object)} handler The listener to remove
			* @public
			*/
			removeEventListener(type, handler) {
				for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
					this.removeListener(type, listener);
					break;
				}
			}
		},
		MessageEvent
	};
	/**
	* Call an event listener
	*
	* @param {(Function|Object)} listener The listener to call
	* @param {*} thisArg The value to use as `this`` when calling the listener
	* @param {Event} event The event to pass to the listener
	* @private
	*/
	function callListener(listener, thisArg, event) {
		if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
		else listener.call(thisArg, event);
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js
var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { tokenChars } = require_validation();
	/**
	* Adds an offer to the map of extension offers or a parameter to the map of
	* parameters.
	*
	* @param {Object} dest The map of extension offers or parameters
	* @param {String} name The extension or parameter name
	* @param {(Object|Boolean|String)} elem The extension parameters or the
	*     parameter value
	* @private
	*/
	function push(dest, name, elem) {
		if (dest[name] === void 0) dest[name] = [elem];
		else dest[name].push(elem);
	}
	/**
	* Parses the `Sec-WebSocket-Extensions` header into an object.
	*
	* @param {String} header The field value of the header
	* @return {Object} The parsed object
	* @public
	*/
	function parse(header) {
		const offers = Object.create(null);
		let params = Object.create(null);
		let mustUnescape = false;
		let isEscaping = false;
		let inQuotes = false;
		let extensionName;
		let paramName;
		let start = -1;
		let code = -1;
		let end = -1;
		let i = 0;
		for (; i < header.length; i++) {
			code = header.charCodeAt(i);
			if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
				if (start === -1) start = i;
			} else if (i !== 0 && (code === 32 || code === 9)) {
				if (end === -1 && start !== -1) end = i;
			} else if (code === 59 || code === 44) {
				if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
				if (end === -1) end = i;
				const name = header.slice(start, end);
				if (code === 44) {
					push(offers, name, params);
					params = Object.create(null);
				} else extensionName = name;
				start = end = -1;
			} else throw new SyntaxError(`Unexpected character at index ${i}`);
			else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
				if (start === -1) start = i;
			} else if (code === 32 || code === 9) {
				if (end === -1 && start !== -1) end = i;
			} else if (code === 59 || code === 44) {
				if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
				if (end === -1) end = i;
				push(params, header.slice(start, end), true);
				if (code === 44) {
					push(offers, extensionName, params);
					params = Object.create(null);
					extensionName = void 0;
				}
				start = end = -1;
			} else if (code === 61 && start !== -1 && end === -1) {
				paramName = header.slice(start, i);
				start = end = -1;
			} else throw new SyntaxError(`Unexpected character at index ${i}`);
			else if (isEscaping) {
				if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
				if (start === -1) start = i;
				else if (!mustUnescape) mustUnescape = true;
				isEscaping = false;
			} else if (inQuotes) if (tokenChars[code] === 1) {
				if (start === -1) start = i;
			} else if (code === 34 && start !== -1) {
				inQuotes = false;
				end = i;
			} else if (code === 92) isEscaping = true;
			else throw new SyntaxError(`Unexpected character at index ${i}`);
			else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
			else if (end === -1 && tokenChars[code] === 1) {
				if (start === -1) start = i;
			} else if (start !== -1 && (code === 32 || code === 9)) {
				if (end === -1) end = i;
			} else if (code === 59 || code === 44) {
				if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
				if (end === -1) end = i;
				let value = header.slice(start, end);
				if (mustUnescape) {
					value = value.replace(/\\/g, "");
					mustUnescape = false;
				}
				push(params, paramName, value);
				if (code === 44) {
					push(offers, extensionName, params);
					params = 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;
	}
	/**
	* Builds the `Sec-WebSocket-Extensions` header field value.
	*
	* @param {Object} extensions The map of extensions and parameters to format
	* @return {String} A string representing the given object
	* @public
	*/
	function format(extensions) {
		return Object.keys(extensions).map((extension) => {
			let configurations = extensions[extension];
			if (!Array.isArray(configurations)) configurations = [configurations];
			return configurations.map((params) => {
				return [extension].concat(Object.keys(params).map((k) => {
					let values = params[k];
					if (!Array.isArray(values)) values = [values];
					return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
				})).join("; ");
			}).join(", ");
		}).join(", ");
	}
	module.exports = {
		format,
		parse
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js
var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const EventEmitter$2 = __require("events");
	const https$3 = __require("https");
	const http$5 = __require("http");
	const net$1 = __require("net");
	const tls = __require("tls");
	const { randomBytes, createHash: createHash$1 } = __require("crypto");
	const { Duplex: Duplex$2, Readable } = __require("stream");
	const { URL: URL$2 } = __require("url");
	const PerMessageDeflate = require_permessage_deflate();
	const Receiver = require_receiver();
	const Sender = require_sender();
	const { isBlob } = require_validation();
	const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
	const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
	const { format, parse } = require_extension();
	const { toBuffer } = require_buffer_util();
	const kAborted = Symbol("kAborted");
	const protocolVersions = [8, 13];
	const readyStates = [
		"CONNECTING",
		"OPEN",
		"CLOSING",
		"CLOSED"
	];
	const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
	/**
	* Class representing a WebSocket.
	*
	* @extends EventEmitter
	*/
	var WebSocket = class WebSocket extends EventEmitter$2 {
		/**
		* Create a new `WebSocket`.
		*
		* @param {(String|URL)} address The URL to which to connect
		* @param {(String|String[])} [protocols] The subprotocols
		* @param {Object} [options] Connection options
		*/
		constructor(address, protocols, options) {
			super();
			this._binaryType = BINARY_TYPES[0];
			this._closeCode = 1006;
			this._closeFrameReceived = false;
			this._closeFrameSent = false;
			this._closeMessage = EMPTY_BUFFER;
			this._closeTimer = null;
			this._errorEmitted = false;
			this._extensions = {};
			this._paused = false;
			this._protocol = "";
			this._readyState = WebSocket.CONNECTING;
			this._receiver = null;
			this._sender = null;
			this._socket = null;
			if (address !== null) {
				this._bufferedAmount = 0;
				this._isServer = false;
				this._redirects = 0;
				if (protocols === void 0) protocols = [];
				else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
					options = protocols;
					protocols = [];
				} else protocols = [protocols];
				initAsClient(this, address, protocols, options);
			} else {
				this._autoPong = options.autoPong;
				this._closeTimeout = options.closeTimeout;
				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.maxBufferedChunks=0] The maximum number of
		*     buffered data chunks
		* @param {Number} [options.maxFragments=0] The maximum number of message
		*     fragments
		* @param {Number} [options.maxPayload=0] The maximum allowed message size
		* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
		*     not to skip UTF-8 validation for text and close messages
		* @private
		*/
		setSocket(socket, head, options) {
			const receiver = new Receiver({
				allowSynchronousEvents: options.allowSynchronousEvents,
				binaryType: this.binaryType,
				extensions: this._extensions,
				isServer: this._isServer,
				maxBufferedChunks: options.maxBufferedChunks,
				maxFragments: options.maxFragments,
				maxPayload: options.maxPayload,
				skipUTF8Validation: options.skipUTF8Validation
			});
			const sender = new Sender(socket, this._extensions, options.generateMask);
			this._receiver = receiver;
			this._sender = sender;
			this._socket = socket;
			receiver[kWebSocket] = this;
			sender[kWebSocket] = this;
			socket[kWebSocket] = this;
			receiver.on("conclude", receiverOnConclude);
			receiver.on("drain", receiverOnDrain);
			receiver.on("error", receiverOnError);
			receiver.on("message", receiverOnMessage);
			receiver.on("ping", receiverOnPing);
			receiver.on("pong", receiverOnPong);
			sender.onerror = senderOnError;
			if (socket.setTimeout) socket.setTimeout(0);
			if (socket.setNoDelay) socket.setNoDelay();
			if (head.length > 0) socket.unshift(head);
			socket.on("close", socketOnClose);
			socket.on("data", socketOnData);
			socket.on("end", socketOnEnd);
			socket.on("error", socketOnError);
			this._readyState = WebSocket.OPEN;
			this.emit("open");
		}
		/**
		* Emit the `'close'` event.
		*
		* @private
		*/
		emitClose() {
			if (!this._socket) {
				this._readyState = WebSocket.CLOSED;
				this.emit("close", this._closeCode, this._closeMessage);
				return;
			}
			if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
			this._receiver.removeAllListeners();
			this._readyState = WebSocket.CLOSED;
			this.emit("close", this._closeCode, this._closeMessage);
		}
		/**
		* Start a closing handshake.
		*
		*          +----------+   +-----------+   +----------+
		*     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
		*    |     +----------+   +-----------+   +----------+     |
		*          +----------+   +-----------+         |
		* CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING
		*          +----------+   +-----------+   |
		*    |           |                        |   +---+        |
		*                +------------------------+-->|fin| - - - -
		*    |         +---+                      |   +---+
		*     - - - - -|fin|<---------------------+
		*              +---+
		*
		* @param {Number} [code] Status code explaining why the connection is closing
		* @param {(String|Buffer)} [data] The reason why the connection is
		*     closing
		* @public
		*/
		close(code, data) {
			if (this.readyState === WebSocket.CLOSED) return;
			if (this.readyState === WebSocket.CONNECTING) {
				abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
				return;
			}
			if (this.readyState === WebSocket.CLOSING) {
				if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
				return;
			}
			this._readyState = WebSocket.CLOSING;
			this._sender.close(code, data, !this._isServer, (err) => {
				if (err) return;
				this._closeFrameSent = true;
				if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
			});
			setCloseTimer(this);
		}
		/**
		* Pause the socket.
		*
		* @public
		*/
		pause() {
			if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
			this._paused = true;
			this._socket.pause();
		}
		/**
		* Send a ping.
		*
		* @param {*} [data] The data to send
		* @param {Boolean} [mask] Indicates whether or not to mask `data`
		* @param {Function} [cb] Callback which is executed when the ping is sent
		* @public
		*/
		ping(data, mask, cb) {
			if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
			if (typeof data === "function") {
				cb = data;
				data = mask = void 0;
			} else if (typeof mask === "function") {
				cb = mask;
				mask = void 0;
			}
			if (typeof data === "number") data = data.toString();
			if (this.readyState !== WebSocket.OPEN) {
				sendAfterClose(this, data, cb);
				return;
			}
			if (mask === void 0) mask = !this._isServer;
			this._sender.ping(data || EMPTY_BUFFER, mask, cb);
		}
		/**
		* Send a pong.
		*
		* @param {*} [data] The data to send
		* @param {Boolean} [mask] Indicates whether or not to mask `data`
		* @param {Function} [cb] Callback which is executed when the pong is sent
		* @public
		*/
		pong(data, mask, cb) {
			if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
			if (typeof data === "function") {
				cb = data;
				data = mask = void 0;
			} else if (typeof mask === "function") {
				cb = mask;
				mask = void 0;
			}
			if (typeof data === "number") data = data.toString();
			if (this.readyState !== WebSocket.OPEN) {
				sendAfterClose(this, data, cb);
				return;
			}
			if (mask === void 0) mask = !this._isServer;
			this._sender.pong(data || EMPTY_BUFFER, mask, cb);
		}
		/**
		* Resume the socket.
		*
		* @public
		*/
		resume() {
			if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
			this._paused = false;
			if (!this._receiver._writableState.needDrain) this._socket.resume();
		}
		/**
		* Send a data message.
		*
		* @param {*} data The message to send
		* @param {Object} [options] Options object
		* @param {Boolean} [options.binary] Specifies whether `data` is binary or
		*     text
		* @param {Boolean} [options.compress] Specifies whether or not to compress
		*     `data`
		* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
		*     last one
		* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
		* @param {Function} [cb] Callback which is executed when data is written out
		* @public
		*/
		send(data, options, cb) {
			if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
			if (typeof options === "function") {
				cb = options;
				options = {};
			}
			if (typeof data === "number") data = data.toString();
			if (this.readyState !== WebSocket.OPEN) {
				sendAfterClose(this, data, cb);
				return;
			}
			const opts = {
				binary: typeof data !== "string",
				mask: !this._isServer,
				compress: true,
				fin: true,
				...options
			};
			if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
			this._sender.send(data || EMPTY_BUFFER, opts, cb);
		}
		/**
		* Forcibly close the connection.
		*
		* @public
		*/
		terminate() {
			if (this.readyState === WebSocket.CLOSED) return;
			if (this.readyState === WebSocket.CONNECTING) {
				abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
				return;
			}
			if (this._socket) {
				this._readyState = WebSocket.CLOSING;
				this._socket.destroy();
			}
		}
	};
	/**
	* @constant {Number} CONNECTING
	* @memberof WebSocket
	*/
	Object.defineProperty(WebSocket, "CONNECTING", {
		enumerable: true,
		value: readyStates.indexOf("CONNECTING")
	});
	/**
	* @constant {Number} CONNECTING
	* @memberof WebSocket.prototype
	*/
	Object.defineProperty(WebSocket.prototype, "CONNECTING", {
		enumerable: true,
		value: readyStates.indexOf("CONNECTING")
	});
	/**
	* @constant {Number} OPEN
	* @memberof WebSocket
	*/
	Object.defineProperty(WebSocket, "OPEN", {
		enumerable: true,
		value: readyStates.indexOf("OPEN")
	});
	/**
	* @constant {Number} OPEN
	* @memberof WebSocket.prototype
	*/
	Object.defineProperty(WebSocket.prototype, "OPEN", {
		enumerable: true,
		value: readyStates.indexOf("OPEN")
	});
	/**
	* @constant {Number} CLOSING
	* @memberof WebSocket
	*/
	Object.defineProperty(WebSocket, "CLOSING", {
		enumerable: true,
		value: readyStates.indexOf("CLOSING")
	});
	/**
	* @constant {Number} CLOSING
	* @memberof WebSocket.prototype
	*/
	Object.defineProperty(WebSocket.prototype, "CLOSING", {
		enumerable: true,
		value: readyStates.indexOf("CLOSING")
	});
	/**
	* @constant {Number} CLOSED
	* @memberof WebSocket
	*/
	Object.defineProperty(WebSocket, "CLOSED", {
		enumerable: true,
		value: readyStates.indexOf("CLOSED")
	});
	/**
	* @constant {Number} CLOSED
	* @memberof WebSocket.prototype
	*/
	Object.defineProperty(WebSocket.prototype, "CLOSED", {
		enumerable: true,
		value: readyStates.indexOf("CLOSED")
	});
	[
		"binaryType",
		"bufferedAmount",
		"extensions",
		"isPaused",
		"protocol",
		"readyState",
		"url"
	].forEach((property) => {
		Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
	});
	[
		"open",
		"error",
		"close",
		"message"
	].forEach((method) => {
		Object.defineProperty(WebSocket.prototype, `on${method}`, {
			enumerable: true,
			get() {
				for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
				return null;
			},
			set(handler) {
				for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
					this.removeListener(method, listener);
					break;
				}
				if (typeof handler !== "function") return;
				this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
			}
		});
	});
	WebSocket.prototype.addEventListener = addEventListener;
	WebSocket.prototype.removeEventListener = removeEventListener;
	module.exports = WebSocket;
	/**
	* Initialize a WebSocket client.
	*
	* @param {WebSocket} websocket The client to initialize
	* @param {(String|URL)} address The URL to which to connect
	* @param {Array} protocols The subprotocols
	* @param {Object} [options] Connection 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.closeTimeout=30000] Duration in milliseconds to wait
	*     for the closing handshake to finish after `websocket.close()` is called
	* @param {Function} [options.finishRequest] A function which can be used to
	*     customize the headers of each http request before it is sent
	* @param {Boolean} [options.followRedirects=false] Whether or not to follow
	*     redirects
	* @param {Function} [options.generateMask] The function used to generate the
	*     masking key
	* @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
	*     handshake request
	* @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
	*     buffered data chunks
	* @param {Number} [options.maxFragments=131072] The maximum number of message
	*     fragments
	* @param {Number} [options.maxPayload=104857600] The maximum allowed message
	*     size
	* @param {Number} [options.maxRedirects=10] The maximum number of redirects
	*     allowed
	* @param {String} [options.origin] Value of the `Origin` or
	*     `Sec-WebSocket-Origin` header
	* @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
	*     permessage-deflate
	* @param {Number} [options.protocolVersion=13] Value of the
	*     `Sec-WebSocket-Version` header
	* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
	*     not to skip UTF-8 validation for text and close messages
	* @private
	*/
	function initAsClient(websocket, address, protocols, options) {
		const opts = {
			allowSynchronousEvents: true,
			autoPong: true,
			closeTimeout: CLOSE_TIMEOUT,
			protocolVersion: protocolVersions[1],
			maxBufferedChunks: 1024 * 1024,
			maxFragments: 128 * 1024,
			maxPayload: 100 * 1024 * 1024,
			skipUTF8Validation: false,
			perMessageDeflate: true,
			followRedirects: false,
			maxRedirects: 10,
			...options,
			socketPath: void 0,
			hostname: void 0,
			protocol: void 0,
			timeout: void 0,
			method: "GET",
			host: void 0,
			path: void 0,
			port: void 0
		};
		websocket._autoPong = opts.autoPong;
		websocket._closeTimeout = opts.closeTimeout;
		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 {
			throw new SyntaxError(`Invalid URL: ${address}`);
		}
		if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
		else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
		websocket._url = parsedUrl.href;
		const isSecure = parsedUrl.protocol === "wss:";
		const isIpcUrl = parsedUrl.protocol === "ws+unix:";
		let invalidUrlMessage;
		if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
		else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
		else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
		if (invalidUrlMessage) {
			const err = new SyntaxError(invalidUrlMessage);
			if (websocket._redirects === 0) throw err;
			else {
				emitErrorAndClose(websocket, err);
				return;
			}
		}
		const defaultPort = isSecure ? 443 : 80;
		const key = randomBytes(16).toString("base64");
		const request = isSecure ? https$3.request : http$5.request;
		const protocolSet = /* @__PURE__ */ new Set();
		let perMessageDeflate;
		opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
		opts.defaultPort = opts.defaultPort || defaultPort;
		opts.port = parsedUrl.port || defaultPort;
		opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
		opts.headers = {
			...opts.headers,
			"Sec-WebSocket-Version": opts.protocolVersion,
			"Sec-WebSocket-Key": key,
			Connection: "Upgrade",
			Upgrade: "websocket"
		};
		opts.path = parsedUrl.pathname + parsedUrl.search;
		opts.timeout = opts.handshakeTimeout;
		if (opts.perMessageDeflate) {
			perMessageDeflate = new PerMessageDeflate({
				...opts.perMessageDeflate,
				isServer: false,
				maxPayload: opts.maxPayload
			});
			opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
		}
		if (protocols.length) {
			for (const protocol of protocols) {
				if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
				protocolSet.add(protocol);
			}
			opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
		}
		if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
		else opts.headers.Origin = opts.origin;
		if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
		if (isIpcUrl) {
			const parts = opts.path.split(":");
			opts.socketPath = parts[0];
			opts.path = parts[1];
		}
		let req;
		if (opts.followRedirects) {
			if (websocket._redirects === 0) {
				websocket._originalIpc = isIpcUrl;
				websocket._originalSecure = isSecure;
				websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
				const headers = options && options.headers;
				options = {
					...options,
					headers: {}
				};
				if (headers) for (const [key, value] of Object.entries(headers)) options.headers[key.toLowerCase()] = value;
			} else if (websocket.listenerCount("redirect") === 0) {
				const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
				if (!isSameHost || websocket._originalSecure && !isSecure) {
					delete opts.headers.authorization;
					delete opts.headers.cookie;
					if (!isSameHost) delete opts.headers.host;
					opts.auth = void 0;
				}
			}
			if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
			req = websocket._req = request(opts);
			if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
		} else req = websocket._req = request(opts);
		if (opts.timeout) req.on("timeout", () => {
			abortHandshake(websocket, req, "Opening handshake has timed out");
		});
		req.on("error", (err) => {
			if (req === null || req[kAborted]) return;
			req = websocket._req = null;
			emitErrorAndClose(websocket, err);
		});
		req.on("response", (res) => {
			const location = res.headers.location;
			const statusCode = res.statusCode;
			if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
				if (++websocket._redirects > opts.maxRedirects) {
					abortHandshake(websocket, req, "Maximum redirects exceeded");
					return;
				}
				req.abort();
				let addr;
				try {
					addr = new URL$2(location, address);
				} catch (e) {
					emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
					return;
				}
				initAsClient(websocket, addr, protocols, options);
			} else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
		});
		req.on("upgrade", (res, socket, head) => {
			websocket.emit("upgrade", res);
			if (websocket.readyState !== WebSocket.CONNECTING) return;
			req = websocket._req = null;
			const upgrade = res.headers.upgrade;
			if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
				abortHandshake(websocket, socket, "Invalid Upgrade header");
				return;
			}
			const digest = createHash$1("sha1").update(key + GUID).digest("base64");
			if (res.headers["sec-websocket-accept"] !== digest) {
				abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
				return;
			}
			const serverProt = res.headers["sec-websocket-protocol"];
			let protError;
			if (serverProt !== void 0) {
				if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
				else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
			} else if (protocolSet.size) protError = "Server sent no subprotocol";
			if (protError) {
				abortHandshake(websocket, socket, protError);
				return;
			}
			if (serverProt) websocket._protocol = serverProt;
			const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
			if (secWebSocketExtensions !== void 0) {
				if (!perMessageDeflate) {
					abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
					return;
				}
				let extensions;
				try {
					extensions = parse(secWebSocketExtensions);
				} catch (err) {
					abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
					return;
				}
				const extensionNames = Object.keys(extensions);
				if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
					abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
					return;
				}
				try {
					perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
				} catch (err) {
					abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
					return;
				}
				websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
			}
			websocket.setSocket(socket, head, {
				allowSynchronousEvents: opts.allowSynchronousEvents,
				generateMask: opts.generateMask,
				maxBufferedChunks: opts.maxBufferedChunks,
				maxFragments: opts.maxFragments,
				maxPayload: opts.maxPayload,
				skipUTF8Validation: opts.skipUTF8Validation
			});
		});
		if (opts.finishRequest) opts.finishRequest(req, websocket);
		else req.end();
	}
	/**
	* Emit the `'error'` and `'close'` events.
	*
	* @param {WebSocket} websocket The WebSocket instance
	* @param {Error} The error to emit
	* @private
	*/
	function emitErrorAndClose(websocket, err) {
		websocket._readyState = WebSocket.CLOSING;
		websocket._errorEmitted = true;
		websocket.emit("error", err);
		websocket.emitClose();
	}
	/**
	* Create a `net.Socket` and initiate a connection.
	*
	* @param {Object} options Connection options
	* @return {net.Socket} The newly created socket used to start the connection
	* @private
	*/
	function netConnect(options) {
		options.path = options.socketPath;
		return net$1.connect(options);
	}
	/**
	* Create a `tls.TLSSocket` and initiate a connection.
	*
	* @param {Object} options Connection options
	* @return {tls.TLSSocket} The newly created socket used to start the connection
	* @private
	*/
	function tlsConnect(options) {
		options.path = void 0;
		if (!options.servername && options.servername !== "") options.servername = net$1.isIP(options.host) ? "" : options.host;
		return tls.connect(options);
	}
	/**
	* Abort the handshake and emit an error.
	*
	* @param {WebSocket} websocket The WebSocket instance
	* @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
	*     abort or the socket to destroy
	* @param {String} message The error message
	* @private
	*/
	function abortHandshake(websocket, stream, message) {
		websocket._readyState = WebSocket.CLOSING;
		const err = new Error(message);
		Error.captureStackTrace(err, abortHandshake);
		if (stream.setHeader) {
			stream[kAborted] = true;
			stream.abort();
			if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
			process.nextTick(emitErrorAndClose, websocket, err);
		} else {
			stream.destroy(err);
			stream.once("error", websocket.emit.bind(websocket, "error"));
			stream.once("close", websocket.emitClose.bind(websocket));
		}
	}
	/**
	* Handle cases where the `ping()`, `pong()`, or `send()` methods are called
	* when the `readyState` attribute is `CLOSING` or `CLOSED`.
	*
	* @param {WebSocket} websocket The WebSocket instance
	* @param {*} [data] The data to send
	* @param {Function} [cb] Callback
	* @private
	*/
	function sendAfterClose(websocket, data, cb) {
		if (data) {
			const length = isBlob(data) ? data.size : toBuffer(data).length;
			if (websocket._socket) websocket._sender._bufferedBytes += length;
			else websocket._bufferedAmount += length;
		}
		if (cb) {
			const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
			process.nextTick(cb, err);
		}
	}
	/**
	* The listener of the `Receiver` `'conclude'` event.
	*
	* @param {Number} code The status code
	* @param {Buffer} reason The reason for closing
	* @private
	*/
	function receiverOnConclude(code, reason) {
		const websocket = this[kWebSocket];
		websocket._closeFrameReceived = true;
		websocket._closeMessage = reason;
		websocket._closeCode = code;
		if (websocket._socket[kWebSocket] === void 0) return;
		websocket._socket.removeListener("data", socketOnData);
		process.nextTick(resume, websocket._socket);
		if (code === 1005) websocket.close();
		else websocket.close(code, reason);
	}
	/**
	* The listener of the `Receiver` `'drain'` event.
	*
	* @private
	*/
	function receiverOnDrain() {
		const websocket = this[kWebSocket];
		if (!websocket.isPaused) websocket._socket.resume();
	}
	/**
	* The listener of the `Receiver` `'error'` event.
	*
	* @param {(RangeError|Error)} err The emitted error
	* @private
	*/
	function receiverOnError(err) {
		const websocket = this[kWebSocket];
		if (websocket._socket[kWebSocket] !== void 0) {
			websocket._socket.removeListener("data", socketOnData);
			process.nextTick(resume, websocket._socket);
			websocket.close(err[kStatusCode]);
		}
		if (!websocket._errorEmitted) {
			websocket._errorEmitted = true;
			websocket.emit("error", err);
		}
	}
	/**
	* The listener of the `Receiver` `'finish'` event.
	*
	* @private
	*/
	function receiverOnFinish() {
		this[kWebSocket].emitClose();
	}
	/**
	* The listener of the `Receiver` `'message'` event.
	*
	* @param {Buffer|ArrayBuffer|Buffer[])} data The message
	* @param {Boolean} isBinary Specifies whether the message is binary or not
	* @private
	*/
	function receiverOnMessage(data, isBinary) {
		this[kWebSocket].emit("message", data, isBinary);
	}
	/**
	* The listener of the `Receiver` `'ping'` event.
	*
	* @param {Buffer} data The data included in the ping frame
	* @private
	*/
	function receiverOnPing(data) {
		const websocket = this[kWebSocket];
		if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
		websocket.emit("ping", data);
	}
	/**
	* The listener of the `Receiver` `'pong'` event.
	*
	* @param {Buffer} data The data included in the pong frame
	* @private
	*/
	function receiverOnPong(data) {
		this[kWebSocket].emit("pong", data);
	}
	/**
	* Resume a readable stream
	*
	* @param {Readable} stream The readable stream
	* @private
	*/
	function resume(stream) {
		stream.resume();
	}
	/**
	* The `Sender` error event handler.
	*
	* @param {Error} The error
	* @private
	*/
	function senderOnError(err) {
		const websocket = this[kWebSocket];
		if (websocket.readyState === WebSocket.CLOSED) return;
		if (websocket.readyState === WebSocket.OPEN) {
			websocket._readyState = WebSocket.CLOSING;
			setCloseTimer(websocket);
		}
		this._socket.end();
		if (!websocket._errorEmitted) {
			websocket._errorEmitted = true;
			websocket.emit("error", err);
		}
	}
	/**
	* Set a timer to destroy the underlying raw socket of a WebSocket.
	*
	* @param {WebSocket} websocket The WebSocket instance
	* @private
	*/
	function setCloseTimer(websocket) {
		websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
	}
	/**
	* The listener of the socket `'close'` event.
	*
	* @private
	*/
	function socketOnClose() {
		const websocket = this[kWebSocket];
		this.removeListener("close", socketOnClose);
		this.removeListener("data", socketOnData);
		this.removeListener("end", socketOnEnd);
		websocket._readyState = WebSocket.CLOSING;
		if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
			const chunk = this.read(this._readableState.length);
			websocket._receiver.write(chunk);
		}
		websocket._receiver.end();
		this[kWebSocket] = void 0;
		clearTimeout(websocket._closeTimer);
		if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
		else {
			websocket._receiver.on("error", receiverOnFinish);
			websocket._receiver.on("finish", receiverOnFinish);
		}
	}
	/**
	* The listener of the socket `'data'` event.
	*
	* @param {Buffer} chunk A chunk of data
	* @private
	*/
	function socketOnData(chunk) {
		if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
	}
	/**
	* The listener of the socket `'end'` event.
	*
	* @private
	*/
	function socketOnEnd() {
		const websocket = this[kWebSocket];
		websocket._readyState = WebSocket.CLOSING;
		websocket._receiver.end();
		this.end();
	}
	/**
	* The listener of the socket `'error'` event.
	*
	* @private
	*/
	function socketOnError() {
		const websocket = this[kWebSocket];
		this.removeListener("error", socketOnError);
		this.on("error", NOOP);
		if (websocket) {
			websocket._readyState = WebSocket.CLOSING;
			this.destroy();
		}
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js
var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	require_websocket();
	const { Duplex: Duplex$1 } = __require("stream");
	/**
	* Emits the `'close'` event on a stream.
	*
	* @param {Duplex} stream The stream.
	* @private
	*/
	function emitClose(stream) {
		stream.emit("close");
	}
	/**
	* The listener of the `'end'` event.
	*
	* @private
	*/
	function duplexOnEnd() {
		if (!this.destroyed && this._writableState.finished) this.destroy();
	}
	/**
	* The listener of the `'error'` event.
	*
	* @param {Error} err The error
	* @private
	*/
	function duplexOnError(err) {
		this.removeListener("error", duplexOnError);
		this.destroy();
		if (this.listenerCount("error") === 0) this.emit("error", err);
	}
	/**
	* Wraps a `WebSocket` in a duplex stream.
	*
	* @param {WebSocket} ws The `WebSocket` to wrap
	* @param {Object} [options] The options for the `Duplex` constructor
	* @return {Duplex} The duplex stream
	* @public
	*/
	function createWebSocketStream(ws, options) {
		let terminateOnDestroy = true;
		const duplex = new Duplex$1({
			...options,
			autoDestroy: false,
			emitClose: false,
			objectMode: false,
			writableObjectMode: false
		});
		ws.on("message", function message(msg, isBinary) {
			const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
			if (!duplex.push(data)) ws.pause();
		});
		ws.once("error", function error(err) {
			if (duplex.destroyed) return;
			terminateOnDestroy = false;
			duplex.destroy(err);
		});
		ws.once("close", function close() {
			if (duplex.destroyed) return;
			duplex.push(null);
		});
		duplex._destroy = function(err, callback) {
			if (ws.readyState === ws.CLOSED) {
				callback(err);
				process.nextTick(emitClose, duplex);
				return;
			}
			let called = false;
			ws.once("error", function error(err) {
				called = true;
				callback(err);
			});
			ws.once("close", function close() {
				if (!called) callback(err);
				process.nextTick(emitClose, duplex);
			});
			if (terminateOnDestroy) ws.terminate();
		};
		duplex._final = function(callback) {
			if (ws.readyState === ws.CONNECTING) {
				ws.once("open", function open() {
					duplex._final(callback);
				});
				return;
			}
			if (ws._socket === null) return;
			if (ws._socket._writableState.finished) {
				callback();
				if (duplex._readableState.endEmitted) duplex.destroy();
			} else {
				ws._socket.once("finish", function finish() {
					callback();
				});
				ws.close();
			}
		};
		duplex._read = function() {
			if (ws.isPaused) ws.resume();
		};
		duplex._write = function(chunk, encoding, callback) {
			if (ws.readyState === ws.CONNECTING) {
				ws.once("open", function open() {
					duplex._write(chunk, encoding, callback);
				});
				return;
			}
			ws.send(chunk, callback);
		};
		duplex.on("end", duplexOnEnd);
		duplex.on("error", duplexOnError);
		return duplex;
	}
	module.exports = createWebSocketStream;
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js
var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { tokenChars } = require_validation();
	/**
	* Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
	*
	* @param {String} header The field value of the header
	* @return {Set} The subprotocol names
	* @public
	*/
	function parse(header) {
		const protocols = /* @__PURE__ */ new Set();
		let start = -1;
		let end = -1;
		let i = 0;
		for (; 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 protocol = header.slice(start, end);
				if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
				protocols.add(protocol);
				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;
	}
	module.exports = { parse };
}));
//#endregion
//#region ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js
var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const EventEmitter$1 = __require("events");
	const http$4 = __require("http");
	const { Duplex } = __require("stream");
	const { createHash } = __require("crypto");
	const extension = require_extension();
	const PerMessageDeflate = require_permessage_deflate();
	const subprotocol = require_subprotocol();
	const WebSocket = require_websocket();
	const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
	const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
	const RUNNING = 0;
	const CLOSING = 1;
	const CLOSED = 2;
	/**
	* Class representing a WebSocket server.
	*
	* @extends EventEmitter
	*/
	var WebSocketServer = class extends EventEmitter$1 {
		/**
		* 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 {Number} [options.closeTimeout=30000] Duration in milliseconds to
		*     wait for the closing handshake to finish after `websocket.close()` is
		*     called
		* @param {Function} [options.handleProtocols] A hook to handle protocols
		* @param {String} [options.host] The hostname where to bind the server
		* @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
		*     buffered data chunks
		* @param {Number} [options.maxFragments=131072] The maximum number of message
		*     fragments
		* @param {Number} [options.maxPayload=104857600] The maximum allowed message
		*     size
		* @param {Boolean} [options.noServer=false] Enable no server mode
		* @param {String} [options.path] Accept only connections matching this path
		* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
		*     permessage-deflate
		* @param {Number} [options.port] The port where to bind the server
		* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
		*     server to use
		* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
		*     not to skip UTF-8 validation for text and close messages
		* @param {Function} [options.verifyClient] A hook to reject connections
		* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
		*     class to use. It must be the `WebSocket` class or class that extends it
		* @param {Function} [callback] A listener for the `listening` event
		*/
		constructor(options, callback) {
			super();
			options = {
				allowSynchronousEvents: true,
				autoPong: true,
				maxBufferedChunks: 1024 * 1024,
				maxFragments: 128 * 1024,
				maxPayload: 100 * 1024 * 1024,
				skipUTF8Validation: false,
				perMessageDeflate: false,
				handleProtocols: null,
				clientTracking: true,
				closeTimeout: CLOSE_TIMEOUT,
				verifyClient: null,
				noServer: false,
				backlog: null,
				server: null,
				host: null,
				path: null,
				port: null,
				WebSocket,
				...options
			};
			if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
			if (options.port != null) {
				this._server = http$4.createServer((req, res) => {
					const body = http$4.STATUS_CODES[426];
					res.writeHead(426, {
						"Content-Length": body.length,
						"Content-Type": "text/plain"
					});
					res.end(body);
				});
				this._server.listen(options.port, options.host, options.backlog, callback);
			} else if (options.server) this._server = options.server;
			if (this._server) {
				const emitConnection = this.emit.bind(this, "connection");
				this._removeListeners = addListeners(this._server, {
					listening: this.emit.bind(this, "listening"),
					error: this.emit.bind(this, "error"),
					upgrade: (req, socket, head) => {
						this.handleUpgrade(req, socket, head, emitConnection);
					}
				});
			}
			if (options.perMessageDeflate === true) options.perMessageDeflate = {};
			if (options.clientTracking) {
				this.clients = /* @__PURE__ */ new Set();
				this._shouldEmitClose = false;
			}
			this.options = options;
			this._state = RUNNING;
		}
		/**
		* Returns the bound address, the address family name, and port of the server
		* as reported by the operating system if listening on an IP socket.
		* If the server is listening on a pipe or UNIX domain socket, the name is
		* returned as a string.
		*
		* @return {(Object|String|null)} The address of the server
		* @public
		*/
		address() {
			if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
			if (!this._server) return null;
			return this._server.address();
		}
		/**
		* Stop the server from accepting new connections and emit the `'close'` event
		* when all existing connections are closed.
		*
		* @param {Function} [cb] A one-time listener for the `'close'` event
		* @public
		*/
		close(cb) {
			if (this._state === CLOSED) {
				if (cb) this.once("close", () => {
					cb(/* @__PURE__ */ new Error("The server is not running"));
				});
				process.nextTick(emitClose, this);
				return;
			}
			if (cb) this.once("close", cb);
			if (this._state === CLOSING) return;
			this._state = CLOSING;
			if (this.options.noServer || this.options.server) {
				if (this._server) {
					this._removeListeners();
					this._removeListeners = this._server = null;
				}
				if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
				else this._shouldEmitClose = true;
				else process.nextTick(emitClose, this);
			} else {
				const server = this._server;
				this._removeListeners();
				this._removeListeners = this._server = null;
				server.close(() => {
					emitClose(this);
				});
			}
		}
		/**
		* See if a given request should be handled by this server instance.
		*
		* @param {http.IncomingMessage} req Request object to inspect
		* @return {Boolean} `true` if the request is valid, else `false`
		* @public
		*/
		shouldHandle(req) {
			if (this.options.path) {
				const index = req.url.indexOf("?");
				if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
			}
			return true;
		}
		/**
		* Handle a HTTP Upgrade request.
		*
		* @param {http.IncomingMessage} req The request object
		* @param {Duplex} socket The network socket between the server and client
		* @param {Buffer} head The first packet of the upgraded stream
		* @param {Function} cb Callback
		* @public
		*/
		handleUpgrade(req, socket, head, cb) {
			socket.on("error", socketOnError);
			const key = req.headers["sec-websocket-key"];
			const upgrade = req.headers.upgrade;
			const version = +req.headers["sec-websocket-version"];
			if (req.method !== "GET") {
				abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
				return;
			}
			if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
				abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
				return;
			}
			if (key === void 0 || !keyRegex.test(key)) {
				abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
				return;
			}
			if (version !== 13 && version !== 8) {
				abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
				return;
			}
			if (!this.shouldHandle(req)) {
				abortHandshake(socket, 400);
				return;
			}
			const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
			let protocols = /* @__PURE__ */ new Set();
			if (secWebSocketProtocol !== void 0) try {
				protocols = subprotocol.parse(secWebSocketProtocol);
			} catch (err) {
				abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
				return;
			}
			const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
			const extensions = {};
			if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
				const perMessageDeflate = new PerMessageDeflate({
					...this.options.perMessageDeflate,
					isServer: true,
					maxPayload: this.options.maxPayload
				});
				try {
					const offers = extension.parse(secWebSocketExtensions);
					if (offers[PerMessageDeflate.extensionName]) {
						perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
						extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
					}
				} catch (err) {
					abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
					return;
				}
			}
			if (this.options.verifyClient) {
				const info = {
					origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
					secure: !!(req.socket.authorized || req.socket.encrypted),
					req
				};
				if (this.options.verifyClient.length === 2) {
					this.options.verifyClient(info, (verified, code, message, headers) => {
						if (!verified) return abortHandshake(socket, code || 401, message, headers);
						this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
					});
					return;
				}
				if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
			}
			this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
		}
		/**
		* Upgrade the connection to WebSocket.
		*
		* @param {Object} extensions The accepted extensions
		* @param {String} key The value of the `Sec-WebSocket-Key` header
		* @param {Set} protocols The subprotocols
		* @param {http.IncomingMessage} req The request object
		* @param {Duplex} socket The network socket between the server and client
		* @param {Buffer} head The first packet of the upgraded stream
		* @param {Function} cb Callback
		* @throws {Error} If called more than once with the same socket
		* @private
		*/
		completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
			if (!socket.readable || !socket.writable) return socket.destroy();
			if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
			if (this._state > RUNNING) return abortHandshake(socket, 503);
			const headers = [
				"HTTP/1.1 101 Switching Protocols",
				"Upgrade: websocket",
				"Connection: Upgrade",
				`Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
			];
			const ws = new this.options.WebSocket(null, void 0, this.options);
			if (protocols.size) {
				const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
				if (protocol) {
					headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
					ws._protocol = protocol;
				}
			}
			if (extensions[PerMessageDeflate.extensionName]) {
				const params = extensions[PerMessageDeflate.extensionName].params;
				const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
				headers.push(`Sec-WebSocket-Extensions: ${value}`);
				ws._extensions = extensions;
			}
			this.emit("headers", headers, req);
			socket.write(headers.concat("\r\n").join("\r\n"));
			socket.removeListener("error", socketOnError);
			ws.setSocket(socket, head, {
				allowSynchronousEvents: this.options.allowSynchronousEvents,
				maxBufferedChunks: this.options.maxBufferedChunks,
				maxFragments: this.options.maxFragments,
				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, req);
		}
	};
	module.exports = WebSocketServer;
	/**
	* Add event listeners on an `EventEmitter` using a map of <event, listener>
	* pairs.
	*
	* @param {EventEmitter} server The event emitter
	* @param {Object.<String, Function>} map The listeners to add
	* @return {Function} A function that will remove the added listeners when
	*     called
	* @private
	*/
	function addListeners(server, map) {
		for (const event of Object.keys(map)) server.on(event, map[event]);
		return function removeListeners() {
			for (const event of Object.keys(map)) server.removeListener(event, map[event]);
		};
	}
	/**
	* Emit a `'close'` event on an `EventEmitter`.
	*
	* @param {EventEmitter} server The event emitter
	* @private
	*/
	function emitClose(server) {
		server._state = CLOSED;
		server.emit("close");
	}
	/**
	* Handle socket errors.
	*
	* @private
	*/
	function socketOnError() {
		this.destroy();
	}
	/**
	* Close the connection when preconditions are not fulfilled.
	*
	* @param {Duplex} socket The socket of the upgrade request
	* @param {Number} code The HTTP response status code
	* @param {String} [message] The HTTP response body
	* @param {Object} [headers] Additional HTTP response headers
	* @private
	*/
	function abortHandshake(socket, code, message, headers) {
		message = message || http$4.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$4.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
	}
	/**
	* Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
	* one listener for it, otherwise call `abortHandshake()`.
	*
	* @param {WebSocketServer} server The WebSocket server
	* @param {http.IncomingMessage} req The request object
	* @param {Duplex} socket The socket of the upgrade request
	* @param {Number} code The HTTP response status code
	* @param {String} message The HTTP response body
	* @param {Object} [headers] The HTTP response headers
	* @private
	*/
	function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
		if (server.listenerCount("wsClientError")) {
			const err = new Error(message);
			Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
			server.emit("wsClientError", err, socket, req);
		} else abortHandshake(socket, code, message, headers);
	}
}));
require_stream();
require_extension();
require_permessage_deflate();
require_receiver();
require_sender();
require_subprotocol();
require_websocket();
var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
//#endregion
//#region ../../node_modules/.pnpm/host-validation-middleware@0.1.4/node_modules/host-validation-middleware/dist/index.js
/**
* This function assumes that the input is not malformed.
* This is because we only care about browser requests.
* Non-browser clients can send any value they want anyway.
*/
function extractHostNameFromHostHeader(hostHeader) {
	const trimmedHost = hostHeader.trim();
	if (trimmedHost[0] === "[") {
		const endIpv6 = trimmedHost.indexOf("]");
		if (endIpv6 < 0) return { type: "invalid" };
		return net.isIP(trimmedHost.slice(1, endIpv6)) === 6 ? { type: "ipv6" } : { type: "invalid" };
	}
	const colonPos = trimmedHost.indexOf(":");
	const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos);
	if (net.isIP(hostname) === 4) return { type: "ipv4" };
	return {
		type: "hostname",
		value: hostname
	};
}
const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i;
function isHostAllowedInternal(hostHeader, allowedHosts) {
	if (isFileOrExtensionProtocolRE.test(hostHeader)) return true;
	const extracted = extractHostNameFromHostHeader(hostHeader);
	if (extracted.type === "invalid") return false;
	if (extracted.type === "ipv4" || extracted.type === "ipv6") return true;
	const hostname = extracted.value;
	if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
	for (const allowedHost of allowedHosts) {
		if (allowedHost === hostname) return true;
		if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) return true;
	}
	return false;
}
const cache = /* @__PURE__ */ new WeakMap();
/**
* Check if the host contained in the host header is allowed.
*
* This function will cache the result if the `allowedHosts` array is frozen.
*
* @param hostHeader - The value of host header. See [RFC 9110 7.2](https://datatracker.ietf.org/doc/html/rfc9110#name-host-and-authority).
* @param allowedHosts - The allowed host patterns. See the README for more details.
*/
function isHostAllowed(hostHeader, allowedHosts) {
	if (hostHeader === void 0) return true;
	let cachedAllowedHosts;
	if (Object.isFrozen(allowedHosts)) {
		if (!cache.has(allowedHosts)) cache.set(allowedHosts, /* @__PURE__ */ new Set());
		cachedAllowedHosts = cache.get(allowedHosts);
		if (cachedAllowedHosts.has(hostHeader)) return true;
	}
	const result = isHostAllowedInternal(hostHeader, allowedHosts);
	if (cachedAllowedHosts && result) cachedAllowedHosts.add(hostHeader);
	return result;
}
/**
* Middleware to validate the host header of incoming requests.
*
* If the host header is not in the allowed hosts list, a 403 Forbidden response
* is sent.
*/
function hostValidationMiddleware$1(options) {
	return async function hostValidationMiddleware(req, res, next) {
		const hostHeader = req.headers.host;
		if (!isHostAllowed(hostHeader, options.allowedHosts)) {
			const hostname = hostHeader?.replace(/:\d+$/, "") ?? "";
			const errorMessage = options.generateErrorMessage?.(hostname) ?? generateDefaultErrorMessage(hostname);
			res.writeHead(403, { "Content-Type": options.errorResponseContentType ?? "text/plain" });
			res.end(errorMessage);
			return;
		}
		next();
	};
}
function generateDefaultErrorMessage(hostname) {
	return `Blocked request. This host (${JSON.stringify(hostname)}) is not allowed.`;
}
//#endregion
//#region src/node/server/ws.ts
const WebSocketServerRaw = process.versions.bun ? import.meta.require("ws").WebSocketServer : import_websocket_server.default;
const isWebSocketServer = Symbol("isWebSocketServer");
const wsServerEvents = [
	"connection",
	"error",
	"headers",
	"listening",
	"message"
];
function noop$1() {}
function hasValidToken(config, url) {
	const token = url.searchParams.get("token");
	if (!token) return false;
	try {
		return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(config.webSocketToken));
	} catch {}
	return false;
}
function createWebSocketServer(server, config, httpsOptions) {
	if (config.server.ws === false) return {
		[isWebSocketServer]: true,
		get clients() {
			return /* @__PURE__ */ new Set();
		},
		async close() {},
		on: noop$1,
		off: noop$1,
		setInvokeHandler: noop$1,
		handleInvoke: async () => ({ error: {
			name: "TransportError",
			message: "handleInvoke not implemented",
			stack: (/* @__PURE__ */ new Error()).stack
		} }),
		listen: noop$1,
		send: noop$1
	};
	let wsHttpServer = void 0;
	const wsOptions = isObject$1(config.server.ws) ? config.server.ws : void 0;
	const wsCustomServer = wsOptions?.server;
	const wsPort = wsOptions?.port;
	const wsServer = wsCustomServer || (!wsPort || wsPort === config.server.port) && server;
	let hmrServerWsListener;
	const customListeners = /* @__PURE__ */ new Map();
	const clientsMap = /* @__PURE__ */ new WeakMap();
	const port = wsPort || 24678;
	const host = wsOptions?.host || void 0;
	const allowedHosts = config.server.allowedHosts === true ? config.server.allowedHosts : Object.freeze([...config.server.allowedHosts]);
	const shouldHandle = (req) => {
		if (req.headers["sec-websocket-protocol"] === "vite-ping") return true;
		if (allowedHosts !== true && !isHostAllowed(req.headers.host, allowedHosts)) return false;
		if (config.legacy?.skipWebSocketTokenCheck) return true;
		if (req.headers.origin) return hasValidToken(config, new URL(`http://example.com${req.url}`));
		return true;
	};
	const handleUpgrade = (req, socket, head, isPing) => {
		wss.handleUpgrade(req, socket, head, (ws) => {
			if (isPing) {
				ws.close(1e3);
				return;
			}
			wss.emit("connection", ws, req);
		});
	};
	const wss = new WebSocketServerRaw({ noServer: true });
	wss.shouldHandle = shouldHandle;
	if (wsServer) {
		let hmrBase = config.base;
		const wsPath = wsOptions?.path;
		if (wsPath) hmrBase = path.posix.join(hmrBase, wsPath);
		hmrServerWsListener = (req, socket, head) => {
			const protocol = req.headers["sec-websocket-protocol"];
			const parsedUrl = new URL(`http://example.com${req.url}`);
			if (["vite-hmr", "vite-ping"].includes(protocol) && parsedUrl.pathname === hmrBase) handleUpgrade(req, socket, head, protocol === "vite-ping");
		};
		wsServer.on("upgrade", hmrServerWsListener);
	} else {
		const route = ((_, res) => {
			const statusCode = 426;
			const body = 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 = createServer$1(httpsOptions, route);
		else wsHttpServer = createServer(route);
		wsHttpServer.on("upgrade", (req, socket, head) => {
			const protocol = req.headers["sec-websocket-protocol"];
			if (protocol === "vite-ping" && server && !server.listening) {
				req.destroy();
				return;
			}
			handleUpgrade(req, socket, head, protocol === "vite-ping");
		});
		wsHttpServer.on("error", (e) => {
			if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
			else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
		});
	}
	const emitCustomEvent = (event, data, socket) => {
		const listeners = customListeners.get(event);
		if (!listeners?.size) return;
		const client = getSocketClient(socket);
		for (const listener of listeners) listener(data, client);
	};
	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;
			emitCustomEvent(parsed.event, parsed.data, socket);
		});
		socket.on("error", (err) => {
			config.logger.error(`${import_picocolors.default.red(`ws error:`)}\n${err.stack}`, {
				timestamp: true,
				error: err
			});
		});
		socket.on("close", () => {
			emitCustomEvent("vite:client:disconnect", void 0, socket);
		});
		emitCustomEvent("vite:client:connect", void 0, socket);
		socket.send(JSON.stringify({ type: "connected" }));
		if (bufferedMessage) {
			socket.send(JSON.stringify(bufferedMessage));
			bufferedMessage = null;
		}
	});
	wss.on("error", (e) => {
		if (e.code === "EADDRINUSE") config.logger.error(import_picocolors.default.red(`WebSocket server error: Port ${e.port} is already in use`), { error: e });
		else config.logger.error(import_picocolors.default.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e });
	});
	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 bufferedMessage = null;
	const normalizedHotChannel = normalizeHotChannel({
		send(payload) {
			if ((payload.type === "error" || payload.type === "full-reload") && !wss.clients.size) {
				bufferedMessage = payload;
				return;
			}
			const stringified = JSON.stringify(payload);
			wss.clients.forEach((client) => {
				if (client.readyState === 1) client.send(stringified);
			});
		},
		on(event, fn) {
			if (!customListeners.has(event)) customListeners.set(event, /* @__PURE__ */ new Set());
			customListeners.get(event).add(fn);
		},
		off(event, fn) {
			customListeners.get(event)?.delete(fn);
		},
		listen() {
			wsHttpServer?.listen(port, host);
		},
		close() {
			if (hmrServerWsListener && wsServer) wsServer.off("upgrade", hmrServerWsListener);
			return new Promise((resolve, reject) => {
				wss.clients.forEach((client) => {
					client.terminate();
				});
				wss.close((err) => {
					if (err) reject(err);
					else if (wsHttpServer) wsHttpServer.close((err) => {
						if (err) reject(err);
						else resolve();
					});
					else resolve();
				});
			});
		}
	}, config.server.hmr !== false, false);
	return {
		...normalizedHotChannel,
		on: ((event, fn) => {
			if (wsServerEvents.includes(event)) {
				wss.on(event, fn);
				return;
			}
			normalizedHotChannel.on(event, fn);
		}),
		off: ((event, fn) => {
			if (wsServerEvents.includes(event)) {
				wss.off(event, fn);
				return;
			}
			normalizedHotChannel.off(event, fn);
		}),
		async close() {
			await normalizedHotChannel.close();
		},
		[isWebSocketServer]: true,
		get clients() {
			return new Set(Array.from(wss.clients).map(getSocketClient));
		}
	};
}
//#endregion
//#region src/node/server/middlewares/base.ts
function baseMiddleware(rawBase, middlewareMode) {
	return function viteBaseMiddleware(req, res, next) {
		const url = req.url;
		const pathname = cleanUrl(url);
		const base = rawBase;
		if (pathname.startsWith(base)) {
			req.url = stripBase(url, base);
			return next();
		}
		if (middlewareMode) return next();
		if (pathname === "/" || pathname === "/index.html") {
			res.writeHead(302, { Location: base + url.slice(pathname.length) });
			res.end();
			return;
		}
		const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
		if (req.headers.accept?.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;
		}
	};
}
//#endregion
//#region ../../node_modules/.pnpm/follow-redirects@1.16.0_obug@1.0.2/node_modules/follow-redirects/debug.js
var require_debug = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var debug;
	module.exports = function() {
		if (!debug) {
			try {
				debug = (init_node(), __toCommonJS(node_exports))("follow-redirects");
			} catch (error) {}
			if (typeof debug !== "function") debug = function() {};
		}
		debug.apply(null, arguments);
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/follow-redirects@1.16.0_obug@1.0.2/node_modules/follow-redirects/index.js
var require_follow_redirects = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var url$1 = __require("url");
	var URL = url$1.URL;
	var http$3 = __require("http");
	var https$2 = __require("https");
	var Writable = __require("stream").Writable;
	var assert$1 = __require("assert");
	var debug = require_debug();
	// istanbul ignore next
	(function detectUnsupportedEnvironment() {
		var looksLikeNode = typeof process !== "undefined";
		var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
		var looksLikeV8 = isFunction(Error.captureStackTrace);
		if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) console.warn("The follow-redirects package should be excluded from browser builds.");
	})();
	var useNativeURL = false;
	try {
		assert$1(new URL(""));
	} catch (error) {
		useNativeURL = error.code === "ERR_INVALID_URL";
	}
	var sensitiveHeaders = [
		"Authorization",
		"Proxy-Authorization",
		"Cookie"
	];
	var preservedUrlFields = [
		"auth",
		"host",
		"hostname",
		"href",
		"path",
		"pathname",
		"port",
		"protocol",
		"query",
		"search",
		"hash"
	];
	var events = [
		"abort",
		"aborted",
		"connect",
		"error",
		"socket",
		"timeout"
	];
	var eventHandlers = 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");
	// istanbul ignore next
	var destroy = Writable.prototype.destroy || noop;
	function RedirectableRequest(options, responseCallback) {
		Writable.call(this);
		this._sanitizeOptions(options);
		this._options = options;
		this._ended = false;
		this._ending = false;
		this._redirectCount = 0;
		this._redirects = [];
		this._requestBodyLength = 0;
		this._requestBodyBuffers = [];
		if (responseCallback) this.on("response", responseCallback);
		var self = this;
		this._onNativeResponse = function(response) {
			try {
				self._processResponse(response);
			} catch (cause) {
				self.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
			}
		};
		this._headerFilter = new RegExp("^(?:" + sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|") + ")$", "i");
		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(error) {
		destroyRequest(this._currentRequest, error);
		destroy.call(this, error);
		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 self = this;
			var currentRequest = this._currentRequest;
			this.write(data, encoding, function() {
				self._ended = true;
				currentRequest.end(null, null, callback);
			});
			this._ending = true;
		}
	};
	RedirectableRequest.prototype.setHeader = function(name, value) {
		this._options.headers[name] = value;
		this._currentRequest.setHeader(name, value);
	};
	RedirectableRequest.prototype.removeHeader = function(name) {
		delete this._options.headers[name];
		this._currentRequest.removeHeader(name);
	};
	RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
		var self = this;
		function destroyOnTimeout(socket) {
			socket.setTimeout(msecs);
			socket.removeListener("timeout", socket.destroy);
			socket.addListener("timeout", socket.destroy);
		}
		function startTimer(socket) {
			if (self._timeout) clearTimeout(self._timeout);
			self._timeout = setTimeout(function() {
				self.emit("timeout");
				clearTimer();
			}, msecs);
			destroyOnTimeout(socket);
		}
		function clearTimer() {
			if (self._timeout) {
				clearTimeout(self._timeout);
				self._timeout = null;
			}
			self.removeListener("abort", clearTimer);
			self.removeListener("error", clearTimer);
			self.removeListener("response", clearTimer);
			self.removeListener("close", clearTimer);
			if (callback) self.removeListener("timeout", callback);
			if (!self.socket) self._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(options) {
		if (!options.headers) options.headers = {};
		if (!isArray(options.sensitiveHeaders)) options.sensitiveHeaders = [];
		if (options.host) {
			if (!options.hostname) options.hostname = options.host;
			delete options.host;
		}
		if (!options.pathname && options.path) {
			var searchPos = options.path.indexOf("?");
			if (searchPos < 0) options.pathname = options.path;
			else {
				options.pathname = options.path.substring(0, searchPos);
				options.search = options.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$1.format(this._options) : this._options.path;
		if (this._isRedirect) {
			var i = 0;
			var self = this;
			var buffers = this._requestBodyBuffers;
			(function writeNext(error) {
				// istanbul ignore else
				if (request === self._currentRequest) {
					// istanbul ignore if
					if (error) self.emit("error", error);
					else if (i < buffers.length) {
						var buffer = buffers[i++];
						// istanbul ignore else
						if (!request.finished) request.write(buffer.data, buffer.encoding, writeNext);
					} else if (self._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 location = response.headers.location;
		if (!location || 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({ Host: response.req.getHeader("host") }, this._options.headers);
		var method = this._options.method;
		if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || 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(location) ? this._currentUrl : url$1.format(Object.assign(currentUrlParts, { host: currentHost }));
		var redirectUrl = resolveUrl(location, currentUrl);
		debug("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(this._headerFilter, 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 exports$1 = {
			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 = exports$1[scheme] = Object.create(nativeProtocol);
			function request(input, options, callback) {
				if (isURL(input)) input = spreadUrlObject(input);
				else if (isString(input)) input = spreadUrlObject(parseUrl(input));
				else {
					callback = options;
					options = validateUrl(input);
					input = { protocol };
				}
				if (isFunction(options)) {
					callback = options;
					options = null;
				}
				options = Object.assign({
					maxRedirects: exports$1.maxRedirects,
					maxBodyLength: exports$1.maxBodyLength
				}, input, options);
				options.nativeProtocols = nativeProtocols;
				if (!isString(options.host) && !isString(options.hostname)) options.hostname = "::1";
				assert$1.equal(options.protocol, protocol, "protocol mismatch");
				debug("options", options);
				return new RedirectableRequest(options, callback);
			}
			function get(input, options, callback) {
				var wrappedRequest = wrappedProtocol.request(input, options, callback);
				wrappedRequest.end();
				return wrappedRequest;
			}
			Object.defineProperties(wrappedProtocol, {
				request: {
					value: request,
					configurable: true,
					enumerable: true,
					writable: true
				},
				get: {
					value: get,
					configurable: true,
					enumerable: true,
					writable: true
				}
			});
		});
		return exports$1;
	}
	function noop() {}
	function parseUrl(input) {
		var parsed;
		// istanbul ignore else
		if (useNativeURL) parsed = new URL(input);
		else {
			parsed = validateUrl(url$1.parse(input));
			if (!isString(parsed.protocol)) throw new InvalidUrlError({ input });
		}
		return parsed;
	}
	function resolveUrl(relative, base) {
		// istanbul ignore next
		return useNativeURL ? new URL(relative, base) : parseUrl(url$1.resolve(base, relative));
	}
	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(regex, headers) {
		var lastValue;
		for (var header in headers) if (regex.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) {
			// istanbul ignore else
			if (isFunction(Error.captureStackTrace)) 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, error) {
		for (var event of events) request.removeListener(event, eventHandlers[event]);
		request.on("error", noop);
		request.destroy(error);
	}
	function isSubdomain(subdomain, domain) {
		assert$1(isString(subdomain) && isString(domain));
		var dot = subdomain.length - domain.length - 1;
		return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
	}
	function isArray(value) {
		return value instanceof Array;
	}
	function isString(value) {
		return typeof value === "string" || value instanceof String;
	}
	function isFunction(value) {
		return typeof value === "function";
	}
	function isBuffer(value) {
		return typeof value === "object" && "length" in value;
	}
	function isURL(value) {
		return URL && value instanceof URL;
	}
	function escapeRegex(regex) {
		return regex.replace(/[\]\\/()*+?.$]/g, "\\$&");
	}
	module.exports = wrap({
		http: http$3,
		https: https$2
	});
	module.exports.wrap = wrap;
}));
//#endregion
//#region ../../node_modules/.pnpm/http-proxy-3@1.23.3_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/common.js
var require_common = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.isSSL = void 0;
	exports.setupOutgoing = setupOutgoing;
	exports.setupSocket = setupSocket;
	exports.getPort = getPort;
	exports.hasEncryptedConnection = hasEncryptedConnection;
	exports.urlJoin = urlJoin;
	exports.rewriteCookieProperty = rewriteCookieProperty;
	exports.toURL = toURL;
	const node_tls_1 = __require("node:tls");
	const upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i;
	exports.isSSL = /^https|wss/;
	const HEADER_BLACKLIST = "trailer";
	const HTTP2_HEADER_BLACKLIST = [
		":method",
		":path",
		":scheme",
		":authority",
		"connection",
		"keep-alive"
	];
	function setupOutgoing(outgoing, options, req, forward) {
		const target = options[forward || "target"];
		outgoing.port = +(target.port ?? (target.protocol !== void 0 && exports.isSSL.test(target.protocol) ? 443 : 80));
		for (const e of [
			"host",
			"hostname",
			"socketPath",
			"pfx",
			"key",
			"passphrase",
			"cert",
			"ca",
			"ciphers",
			"secureProtocol"
		]) outgoing[e] = target[e];
		if (outgoing.hostname?.startsWith("[") && outgoing.hostname.endsWith("]")) outgoing.hostname = outgoing.hostname.slice(1, -1);
		outgoing.method = options.method || req.method;
		outgoing.headers = { ...req.headers };
		if (req.headers?.[":authority"]) outgoing.headers.host = req.headers[":authority"];
		if (options.headers) outgoing.headers = {
			...outgoing.headers,
			...options.headers
		};
		for (const header in outgoing.headers) if (HEADER_BLACKLIST == header.toLowerCase()) {
			delete outgoing.headers[header];
			break;
		}
		if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
		if (options.auth) {
			delete outgoing.headers.authorization;
			outgoing.auth = options.auth;
		}
		if (options.ca) outgoing.ca = options.ca;
		if (target.protocol !== void 0 && exports.isSSL.test(target.protocol)) outgoing.rejectUnauthorized = typeof options.secure === "undefined" ? true : options.secure;
		outgoing.agent = options.agent || false;
		outgoing.localAddress = options.localAddress;
		if (!outgoing.agent) {
			outgoing.headers = outgoing.headers || {};
			if (typeof outgoing.headers.connection !== "string" || !upgradeHeader.test(outgoing.headers.connection)) outgoing.headers.connection = "close";
		}
		const targetPath = target && options.prependPath !== false && "pathname" in target ? getPath(`${target.pathname}${target.search ?? ""}`) : "/";
		let outgoingPath = options.toProxy ? req.url : getPath(req.url);
		outgoingPath = !options.ignorePath ? outgoingPath : "";
		outgoing.path = urlJoin(targetPath, outgoingPath ?? "");
		if (options.changeOrigin) outgoing.headers.host = target.protocol !== void 0 && required(outgoing.port, target.protocol) && !hasPort(outgoing.host) ? outgoing.host + ":" + outgoing.port : outgoing.host;
		outgoing.url = "href" in target && target.href || (target.protocol === "https" ? "https" : "http") + "://" + outgoing.host + (outgoing.port ? ":" + outgoing.port : "");
		if (req.httpVersionMajor > 1) for (const header of HTTP2_HEADER_BLACKLIST) delete outgoing.headers[header];
		return outgoing;
	}
	function setupSocket(socket) {
		socket.setTimeout(0);
		socket.setNoDelay(true);
		socket.setKeepAlive(true, 0);
		return socket;
	}
	function getPort(req) {
		const hostHeader = req.headers[":authority"] || req.headers.host;
		const res = hostHeader ? hostHeader.match(/:(\d+)/) : "";
		return res ? res[1] : hasEncryptedConnection(req) ? "443" : "80";
	}
	function hasEncryptedConnection(req) {
		const conn = req.connection;
		return conn instanceof node_tls_1.TLSSocket && conn.encrypted || Boolean(conn.pair);
	}
	function urlJoin(...args) {
		const queryParams = [];
		let queryParamRaw = "";
		args.forEach((url, index) => {
			const qpStart = url.indexOf("?");
			if (qpStart !== -1) {
				queryParams.push(url.substring(qpStart + 1));
				args[index] = url.substring(0, qpStart);
			}
		});
		queryParamRaw = queryParams.filter(Boolean).join("&");
		let retSegs = "";
		for (const seg of args) {
			if (!seg) continue;
			if (retSegs.endsWith("/")) if (seg.startsWith("/")) retSegs += seg.slice(1);
			else retSegs += seg;
			else if (seg.startsWith("/")) retSegs += seg;
			else retSegs += "/" + seg;
		}
		return queryParamRaw ? retSegs + "?" + queryParamRaw : retSegs;
	}
	function rewriteCookieProperty(header, config, property) {
		if (Array.isArray(header)) return header.map((headerElement) => {
			return rewriteCookieProperty(headerElement, config, property);
		});
		return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", "i"), (match, prefix, previousValue) => {
			let newValue;
			if (previousValue in config) newValue = config[previousValue];
			else if ("*" in config) newValue = config["*"];
			else return match;
			if (newValue) return prefix + newValue;
			else return "";
		});
	}
	function hasPort(host) {
		if (host.startsWith("[")) {
			const closingBracket = host.indexOf("]");
			return closingBracket !== -1 && host.length > closingBracket + 1;
		}
		return host.includes(":");
	}
	function getPath(url) {
		if (url === "" || url?.startsWith("?")) return url;
		const u = toURL(url);
		return `${u.pathname ?? ""}${u.search ?? ""}`;
	}
	function toURL(url) {
		if (url instanceof URL) return url;
		else if (typeof url === "object" && "href" in url && typeof url.href === "string") url = url.href;
		if (!url) url = "";
		if (typeof url != "string") url = `${url}`;
		if (url.startsWith("//")) url = `http://base.invalid${url}`;
		return new URL(url, "http://base.invalid");
	}
	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;
		}
		return port !== 0;
	}
}));
//#endregion
//#region ../../node_modules/.pnpm/http-proxy-3@1.23.3_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-outgoing.js
var require_web_outgoing = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
		Object.defineProperty(o, "default", {
			enumerable: true,
			value: v
		});
	}) : function(o, v) {
		o["default"] = v;
	});
	var __importStar = exports && exports.__importStar || (function() {
		var ownKeys = function(o) {
			ownKeys = Object.getOwnPropertyNames || function(o) {
				var ar = [];
				for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
				return ar;
			};
			return ownKeys(o);
		};
		return function(mod) {
			if (mod && mod.__esModule) return mod;
			var result = {};
			if (mod != null) {
				for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
			}
			__setModuleDefault(result, mod);
			return result;
		};
	})();
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.OUTGOING_PASSES = void 0;
	exports.removeChunked = removeChunked;
	exports.setConnection = setConnection;
	exports.setRedirectHostRewrite = setRedirectHostRewrite;
	exports.writeHeaders = writeHeaders;
	exports.writeStatusCode = writeStatusCode;
	const common = __importStar(require_common());
	const redirectRegex = /^201|30(1|2|7|8)$/;
	function removeChunked(_req, _res, proxyRes) {
		delete proxyRes.headers["transfer-encoding"];
	}
	function setConnection(req, _res, proxyRes) {
		if (req.httpVersion === "1.0") proxyRes.headers["connection"] = req.headers["connection"] || "close";
		else if (req.httpVersion !== "2.0" && !proxyRes.headers["connection"]) proxyRes.headers["connection"] = req.headers["connection"] || "keep-alive";
	}
	function setRedirectHostRewrite(req, _res, proxyRes, options) {
		if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) && proxyRes.headers["location"] && redirectRegex.test(`${proxyRes.statusCode}`)) {
			const target = common.toURL(options.target);
			const location = proxyRes.headers["location"];
			if (typeof location != "string") return;
			const u = common.toURL(location);
			if (target.host != u.host) return;
			if (options.hostRewrite) u.host = options.hostRewrite;
			else if (options.autoRewrite) u.host = req.headers[":authority"] ?? req.headers["host"] ?? "";
			if (options.protocolRewrite) u.protocol = options.protocolRewrite;
			proxyRes.headers["location"] = u.toString();
		}
	}
	function writeHeaders(_req, res, proxyRes, options) {
		const rewriteCookieDomainConfig = typeof options.cookieDomainRewrite === "string" ? { "*": options.cookieDomainRewrite } : options.cookieDomainRewrite;
		const rewriteCookiePathConfig = typeof options.cookiePathRewrite === "string" ? { "*": options.cookiePathRewrite } : options.cookiePathRewrite;
		const preserveHeaderKeyCase = options.preserveHeaderKeyCase;
		const setHeader = (key, header) => {
			if (header == void 0) return;
			if (rewriteCookieDomainConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookieDomainConfig, "domain");
			if (rewriteCookiePathConfig && key.toLowerCase() === "set-cookie") header = common.rewriteCookieProperty(header, rewriteCookiePathConfig, "path");
			res.setHeader(String(key).trim(), header);
		};
		let rawHeaderKeyMap;
		if (preserveHeaderKeyCase && proxyRes.rawHeaders != void 0) {
			rawHeaderKeyMap = {};
			for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
				const key = proxyRes.rawHeaders[i];
				rawHeaderKeyMap[key.toLowerCase()] = key;
			}
		}
		for (const key0 in proxyRes.headers) {
			let key = key0;
			if (_req.httpVersionMajor > 1 && (key === "connection" || key === "keep-alive")) continue;
			const header = proxyRes.headers[key];
			if (preserveHeaderKeyCase && rawHeaderKeyMap) key = rawHeaderKeyMap[key] ?? key;
			setHeader(key, header);
		}
	}
	function writeStatusCode(_req, res, proxyRes) {
		res.statusCode = proxyRes.statusCode;
		if (proxyRes.statusMessage && _req.httpVersionMajor === 1) res.statusMessage = proxyRes.statusMessage;
	}
	exports.OUTGOING_PASSES = {
		removeChunked,
		setConnection,
		setRedirectHostRewrite,
		writeHeaders,
		writeStatusCode
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/http-proxy-3@1.23.3_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/web-incoming.js
var require_web_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
		Object.defineProperty(o, "default", {
			enumerable: true,
			value: v
		});
	}) : function(o, v) {
		o["default"] = v;
	});
	var __importStar = exports && exports.__importStar || (function() {
		var ownKeys = function(o) {
			ownKeys = Object.getOwnPropertyNames || function(o) {
				var ar = [];
				for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
				return ar;
			};
			return ownKeys(o);
		};
		return function(mod) {
			if (mod && mod.__esModule) return mod;
			var result = {};
			if (mod != null) {
				for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
			}
			__setModuleDefault(result, mod);
			return result;
		};
	})();
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.WEB_PASSES = void 0;
	exports.deleteLength = deleteLength;
	exports.timeout = timeout;
	exports.XHeaders = XHeaders;
	exports.stream = stream;
	const http$2 = __importStar(__require("node:http"));
	const https$1 = __importStar(__require("node:https"));
	const followRedirects = __importStar(require_follow_redirects());
	const common = __importStar(require_common());
	const web_outgoing_1 = require_web_outgoing();
	const node_stream_1 = __require("node:stream");
	const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
	const nativeAgents = {
		http: http$2,
		https: https$1
	};
	function deleteLength(req) {
		if ((req.method === "DELETE" || req.method === "OPTIONS") && !req.headers["content-length"]) {
			req.headers["content-length"] = "0";
			delete req.headers["transfer-encoding"];
		}
	}
	function timeout(req, _res, options) {
		if (options.timeout) req.socket.setTimeout(options.timeout);
	}
	function XHeaders(req, _res, options) {
		if (!options.xfwd) return;
		const encrypted = common.hasEncryptedConnection(req);
		const values = {
			for: req.connection.remoteAddress || req.socket.remoteAddress,
			port: common.getPort(req),
			proto: encrypted ? "https" : "http"
		};
		for (const header of [
			"for",
			"port",
			"proto"
		]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
		req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers["host"] || "";
	}
	function stream(req, res, options, _, server, cb) {
		server.emit("start", req, res, options.target || options.forward);
		if (options.fetch || options.fetchOptions || process.env.FORCE_FETCH_PATH === "true") return stream2(req, res, options, _, server, cb);
		const agents = options.followRedirects ? followRedirects : nativeAgents;
		const http = agents.http;
		const https = agents.https;
		if (options.forward) {
			const proto = options.forward.protocol === "https:" ? https : http;
			const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
			const forwardReq = proto.request(outgoingOptions);
			const forwardError = createErrorHandler(forwardReq, options.forward);
			req.on("error", forwardError);
			forwardReq.on("error", forwardError);
			(options.buffer || req).pipe(forwardReq);
			if (!options.target) return res.end();
		}
		const proto = options.target.protocol === "https:" ? https : http;
		const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
		const proxyReq = proto.request(outgoingOptions);
		proxyReq.on("socket", (socket) => {
			if (server && !proxyReq.getHeader("expect")) server.emit("proxyReq", proxyReq, req, res, options, socket);
		});
		if (options.proxyTimeout) proxyReq.setTimeout(options.proxyTimeout, () => {
			proxyReq.destroy();
		});
		res.on("close", () => {
			if (!res.writableFinished) proxyReq.destroy();
		});
		const proxyError = createErrorHandler(proxyReq, options.target);
		req.on("error", proxyError);
		proxyReq.on("error", proxyError);
		function createErrorHandler(proxyReq, url) {
			return (err) => {
				if (req.socket.destroyed && err.code === "ECONNRESET") {
					server.emit("econnreset", err, req, res, url);
					proxyReq.destroy();
					return;
				}
				if (cb) cb(err, req, res, url);
				else server.emit("error", err, req, res, url);
			};
		}
		(options.buffer || req).pipe(proxyReq);
		proxyReq.on("response", (proxyRes) => {
			server?.emit("proxyRes", proxyRes, req, res);
			if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, proxyRes, options);
			if (!res.finished) {
				proxyRes.on("end", () => {
					server?.emit("end", req, res, proxyRes);
				});
				if (!options.selfHandleResponse) proxyRes.pipe(res);
			} else server?.emit("end", req, res, proxyRes);
		});
	}
	async function stream2(req, res, options, _, server, cb) {
		const handleError = (err, target) => {
			const e = err;
			if (e.code === void 0 && e.cause?.code) e.code = e.cause.code;
			if (cb) cb(err, req, res, target);
			else server.emit("error", err, req, res, target);
		};
		req.on("error", (err) => {
			if (req.socket.destroyed && err.code === "ECONNRESET") {
				const target = options.target || options.forward;
				if (target) server.emit("econnreset", err, req, res, target);
				return;
			}
			handleError(err);
		});
		const customFetch = options.fetch || fetch;
		const fetchOptions = options.fetchOptions ?? {};
		const prepareRequest = (outgoing) => {
			const requestOptions = {
				method: outgoing.method,
				...fetchOptions.requestOptions
			};
			const headers = new Headers(fetchOptions.requestOptions?.headers);
			if (!fetchOptions.requestOptions?.headers && outgoing.headers) {
				for (const [key, value] of Object.entries(outgoing.headers)) if (typeof key === "string") {
					if (Array.isArray(value)) for (const v of value) headers.append(key, v);
					else if (value != null) headers.append(key, value);
				}
			}
			if (options.auth) headers.set("authorization", `Basic ${Buffer.from(options.auth).toString("base64")}`);
			if (options.proxyTimeout) requestOptions.signal = AbortSignal.timeout(options.proxyTimeout);
			requestOptions.headers = headers;
			if (options.buffer) requestOptions.body = options.buffer;
			else if (req.method !== "GET" && req.method !== "HEAD") {
				requestOptions.body = req;
				requestOptions.duplex = "half";
			}
			return requestOptions;
		};
		if (options.forward) {
			const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req, "forward");
			const requestOptions = prepareRequest(outgoingOptions);
			let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
			if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
			if (fetchOptions.onBeforeRequest) try {
				await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
			} catch (err) {
				handleError(err, options.forward);
				return;
			}
			try {
				const result = await customFetch(targetUrl, requestOptions);
				if (fetchOptions.onAfterResponse) try {
					await fetchOptions.onAfterResponse(result, req, res, options);
				} catch (err) {
					handleError(err, options.forward);
					return;
				}
			} catch (err) {
				handleError(err, options.forward);
			}
			if (!options.target) return res.end();
		}
		const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
		const requestOptions = prepareRequest(outgoingOptions);
		let targetUrl = new URL(outgoingOptions.url).origin + outgoingOptions.path;
		if (targetUrl.startsWith("ws")) targetUrl = targetUrl.replace("ws", "http");
		if (fetchOptions.onBeforeRequest) try {
			await fetchOptions.onBeforeRequest(requestOptions, req, res, options);
		} catch (err) {
			handleError(err, options.target);
			return;
		}
		try {
			const response = await customFetch(targetUrl, requestOptions);
			if (fetchOptions.onAfterResponse) try {
				await fetchOptions.onAfterResponse(response, req, res, options);
			} catch (err) {
				handleError(err, options.target);
				return;
			}
			const fakeProxyRes = {
				statusCode: response.status,
				statusMessage: response.statusText,
				headers: Object.fromEntries(response.headers.entries()),
				rawHeaders: Object.entries(response.headers).flatMap(([key, value]) => {
					if (Array.isArray(value)) return value.flatMap((v) => v != null ? [key, v] : []);
					return value != null ? [key, value] : [];
				})
			};
			server?.emit("proxyRes", fakeProxyRes, req, res);
			if (!res.headersSent && !options.selfHandleResponse) for (const pass of web_o) pass(req, res, fakeProxyRes, options);
			if (!res.writableEnded) {
				const nodeStream = response.body ? node_stream_1.Readable.from(response.body) : null;
				if (nodeStream) {
					nodeStream.on("error", (err) => {
						handleError(err, options.target);
					});
					nodeStream.on("end", () => {
						server?.emit("end", req, res, fakeProxyRes);
					});
					if (!options.selfHandleResponse) nodeStream.pipe(res, { end: true });
					else nodeStream.resume();
				} else server?.emit("end", req, res, fakeProxyRes);
			} else server?.emit("end", req, res, fakeProxyRes);
		} catch (err) {
			handleError(err, options.target);
		}
	}
	exports.WEB_PASSES = {
		deleteLength,
		timeout,
		XHeaders,
		stream
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/http-proxy-3@1.23.3_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/passes/ws-incoming.js
var require_ws_incoming = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
		Object.defineProperty(o, "default", {
			enumerable: true,
			value: v
		});
	}) : function(o, v) {
		o["default"] = v;
	});
	var __importStar = exports && exports.__importStar || (function() {
		var ownKeys = function(o) {
			ownKeys = Object.getOwnPropertyNames || function(o) {
				var ar = [];
				for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
				return ar;
			};
			return ownKeys(o);
		};
		return function(mod) {
			if (mod && mod.__esModule) return mod;
			var result = {};
			if (mod != null) {
				for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
			}
			__setModuleDefault(result, mod);
			return result;
		};
	})();
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.WS_PASSES = void 0;
	exports.numOpenSockets = numOpenSockets;
	exports.checkMethodAndHeader = checkMethodAndHeader;
	exports.XHeaders = XHeaders;
	exports.stream = stream;
	const http$1 = __importStar(__require("node:http"));
	const https = __importStar(__require("node:https"));
	const common = __importStar(require_common());
	const web_outgoing_1 = require_web_outgoing();
	const log = (0, __importDefault((init_node(), __toCommonJS(node_exports))).default)("http-proxy-3:ws-incoming");
	const web_o = Object.values(web_outgoing_1.OUTGOING_PASSES);
	function createSocketCounter(name) {
		let sockets = /* @__PURE__ */ new Set();
		return ({ add, rm } = {}) => {
			if (add) {
				if (!add.id) add.id = Math.random();
				if (!sockets.has(add.id)) sockets.add(add.id);
			}
			if (rm) {
				if (!rm.id) rm.id = Math.random();
				if (sockets.has(rm.id)) sockets.delete(rm.id);
			}
			log("socket counter:", { [name]: sockets.size }, add ? "add" : rm ? "rm" : "");
			return sockets.size;
		};
	}
	const socketCounter = createSocketCounter("socket");
	const proxySocketCounter = createSocketCounter("proxySocket");
	var MockResponse = class {
		constructor() {
			this.headers = {};
			this.statusCode = 200;
			this.statusMessage = "";
		}
		setHeader(key, value) {
			this.headers[key] = value;
			return this;
		}
	};
	function numOpenSockets() {
		return socketCounter() + proxySocketCounter();
	}
	function checkMethodAndHeader(req, socket) {
		log("websocket: checkMethodAndHeader");
		if (req.method !== "GET" || !req.headers.upgrade) {
			socket.destroy();
			return true;
		}
		if (req.headers.upgrade.toLowerCase() !== "websocket") {
			socket.destroy();
			return true;
		}
	}
	function XHeaders(req, _socket, options) {
		if (!options.xfwd) return;
		log("websocket: XHeaders");
		const values = {
			for: req.connection.remoteAddress || req.socket.remoteAddress,
			port: common.getPort(req),
			proto: common.hasEncryptedConnection(req) ? "wss" : "ws"
		};
		for (const header of [
			"for",
			"port",
			"proto"
		]) req.headers["x-forwarded-" + header] = (req.headers["x-forwarded-" + header] || "") + (req.headers["x-forwarded-" + header] ? "," : "") + values[header];
	}
	function stream(req, socket, options, head, server, cb) {
		log("websocket: new stream");
		const proxySockets = [];
		socketCounter({ add: socket });
		const cleanUpProxySockets = () => {
			for (const p of proxySockets) p.end();
		};
		socket.on("close", () => {
			socketCounter({ rm: socket });
			cleanUpProxySockets();
		});
		socket.on("error", cleanUpProxySockets);
		const createHttpHeader = (line, headers) => {
			return Object.keys(headers).reduce((head, key) => {
				const value = headers[key];
				if (!Array.isArray(value)) {
					head.push(key + ": " + value);
					return head;
				}
				for (let i = 0; i < value.length; i++) head.push(key + ": " + value[i]);
				return head;
			}, [line]).join("\r\n") + "\r\n\r\n";
		};
		common.setupSocket(socket);
		if (head && head.length) socket.unshift(head);
		const proto = common.isSSL.test(options.target.protocol) ? https : http$1;
		const outgoingOptions = common.setupOutgoing(options.ssl || {}, options, req);
		const proxyReq = proto.request(outgoingOptions);
		if (server) server.emit("proxyReqWs", proxyReq, req, socket, options, head);
		proxyReq.on("error", onOutgoingError);
		proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => {
			log("upgrade");
			proxySocketCounter({ add: proxySocket });
			proxySockets.push(proxySocket);
			proxySocket.on("close", () => {
				proxySocketCounter({ rm: proxySocket });
			});
			proxySocket.on("error", onOutgoingError);
			proxySocket.on("end", () => {
				server.emit("close", proxyRes, proxySocket, proxyHead);
			});
			proxySocket.on("close", () => {
				socket.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);
			server.emit("open", proxySocket);
		});
		function onOutgoingError(err) {
			if (cb) cb(err, req, socket);
			else server.emit("error", err, req, socket);
			socket.destroySoon();
		}
		proxyReq.on("response", (proxyRes) => {
			log("got non-ws HTTP response", {
				statusCode: proxyRes.statusCode,
				statusMessage: proxyRes.statusMessage
			});
			const res = new MockResponse();
			for (const pass of web_o) pass(req, res, proxyRes, options);
			let writeChunk = (chunk) => {
				socket.write(chunk);
			};
			if (req.httpVersion === "1.1" && proxyRes.headers["content-length"] === void 0) {
				res.headers["transfer-encoding"] = "chunked";
				writeChunk = (chunk) => {
					socket.write(chunk.length.toString(16));
					socket.write("\r\n");
					socket.write(chunk);
					socket.write("\r\n");
				};
			}
			const proxyHead = createHttpHeader(`HTTP/${req.httpVersion} ${proxyRes.statusCode} ${proxyRes.statusMessage}`, res.headers);
			if (!socket.destroyed) {
				socket.write(proxyHead);
				proxyRes.on("data", (chunk) => {
					writeChunk(chunk);
				});
				proxyRes.on("end", () => {
					writeChunk("");
					socket.destroySoon();
				});
			} else proxyRes.resume();
		});
		proxyReq.end();
	}
	exports.WS_PASSES = {
		checkMethodAndHeader,
		XHeaders,
		stream
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/http-proxy-3@1.23.3_ms@2.1.3/node_modules/http-proxy-3/dist/lib/http-proxy/index.js
var require_http_proxy = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
		Object.defineProperty(o, "default", {
			enumerable: true,
			value: v
		});
	}) : function(o, v) {
		o["default"] = v;
	});
	var __importStar = exports && exports.__importStar || (function() {
		var ownKeys = function(o) {
			ownKeys = Object.getOwnPropertyNames || function(o) {
				var ar = [];
				for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
				return ar;
			};
			return ownKeys(o);
		};
		return function(mod) {
			if (mod && mod.__esModule) return mod;
			var result = {};
			if (mod != null) {
				for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
			}
			__setModuleDefault(result, mod);
			return result;
		};
	})();
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ProxyServer = void 0;
	const http = __importStar(__require("node:http"));
	const http2 = __importStar(__require("node:http2"));
	const web_incoming_1 = require_web_incoming();
	const ws_incoming_1 = require_ws_incoming();
	const node_events_1 = __require("node:events");
	const debug_1 = __importDefault((init_node(), __toCommonJS(node_exports)));
	const common_1 = require_common();
	const log = (0, debug_1.default)("http-proxy-3");
	exports.ProxyServer = class ProxyServer extends node_events_1.EventEmitter {
		/**
		* Creates the proxy server with specified options.
		* @param options - Config object passed to the proxy
		*/
		constructor(options = {}) {
			super();
			this.createRightProxy = (type) => {
				log("createRightProxy", { type });
				return (options) => {
					return (...args) => {
						const req = args[0];
						log("proxy: ", {
							type,
							path: req.url
						});
						const res = args[1];
						const passes = type === "ws" ? this.wsPasses : this.webPasses;
						if (type == "ws") res.on("error", (err) => {
							this.emit("error", err, req, res);
						});
						let counter = args.length - 1;
						let head;
						let cb;
						if (typeof args[counter] === "function") {
							cb = args[counter];
							counter--;
						}
						let requestOptions;
						if (!(args[counter] instanceof Buffer) && args[counter] !== res) {
							requestOptions = {
								...options,
								...args[counter]
							};
							counter--;
						} else requestOptions = { ...options };
						if (args[counter] instanceof Buffer) head = args[counter];
						for (const e of ["target", "forward"]) if (typeof requestOptions[e] === "string") requestOptions[e] = (0, common_1.toURL)(requestOptions[e]);
						if (!requestOptions.target && !requestOptions.forward) {
							this.emit("error", /* @__PURE__ */ new Error("Must set target or forward"), req, res);
							return;
						}
						for (const pass of passes)
 /**
						* Call of passes functions
						*     pass(req, res, options, head)
						*
						* In WebSockets case, the `res` variable
						* refer to the connection socket
						*    pass(req, socket, options, head)
						*/
						if (pass(req, res, requestOptions, head, this, cb)) break;
					};
				};
			};
			this.onError = (err) => {
				if (this.listeners("error").length === 1) throw err;
			};
			/**
			* A function that wraps the object in a webserver, for your convenience
			* @param port - Port to listen on
			* @param hostname - The hostname to listen on
			*/
			this.listen = (port, hostname) => {
				log("listen", {
					port,
					hostname
				});
				const requestListener = (req, res) => {
					this.web(req, res);
				};
				this._server = this.options.ssl ? http2.createSecureServer({
					...this.options.ssl,
					allowHTTP1: true
				}, requestListener) : http.createServer(requestListener);
				if (this.options.ws) this._server.on("upgrade", (req, socket, head) => {
					this.ws(req, socket, head);
				});
				this._server.listen(port, hostname);
				return this;
			};
			this.address = () => {
				return this._server?.address();
			};
			/**
			* A function that closes the inner webserver and stops listening on given port
			*/
			this.close = (cb) => {
				if (this._server == null) {
					cb?.();
					return;
				}
				this._server.close((err) => {
					this._server = null;
					cb?.(err);
				});
			};
			this.before = (type, passName, cb) => {
				if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
				const passes = type === "ws" ? this.wsPasses : this.webPasses;
				let i = false;
				passes.forEach((v, idx) => {
					if (v.name === passName) i = idx;
				});
				if (i === false) throw new Error("No such pass");
				passes.splice(i, 0, cb);
			};
			this.after = (type, passName, cb) => {
				if (type !== "ws" && type !== "web") throw new Error("type must be `web` or `ws`");
				const passes = type === "ws" ? this.wsPasses : this.webPasses;
				let i = false;
				passes.forEach((v, idx) => {
					if (v.name === passName) i = idx;
				});
				if (i === false) throw new Error("No such pass");
				passes.splice(i++, 0, cb);
			};
			log("creating a ProxyServer", options);
			options.prependPath = options.prependPath !== false;
			this.options = options;
			this.web = this.createRightProxy("web")(options);
			this.ws = this.createRightProxy("ws")(options);
			this.webPasses = Object.values(web_incoming_1.WEB_PASSES);
			this.wsPasses = Object.values(ws_incoming_1.WS_PASSES);
			this.on("error", this.onError);
		}
		/**
		* Creates the proxy server with specified options.
		* @param options Config object passed to the proxy
		* @returns Proxy object with handlers for `ws` and `web` requests
		*/
		static createProxyServer(options) {
			return new ProxyServer(options);
		}
		/**
		* Creates the proxy server with specified options.
		* @param options Config object passed to the proxy
		* @returns Proxy object with handlers for `ws` and `web` requests
		*/
		static createServer(options) {
			return new ProxyServer(options);
		}
		/**
		* Creates the proxy server with specified options.
		* @param options Config object passed to the proxy
		* @returns Proxy object with handlers for `ws` and `web` requests
		*/
		static createProxy(options) {
			return new ProxyServer(options);
		}
	};
}));
//#endregion
//#region src/node/server/middlewares/proxy.ts
var import_lib$1 = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.numOpenSockets = exports.ProxyServer = void 0;
	exports.createProxyServer = createProxyServer;
	const index_1 = require_http_proxy();
	Object.defineProperty(exports, "ProxyServer", {
		enumerable: true,
		get: function() {
			return index_1.ProxyServer;
		}
	});
	var ws_incoming_1 = require_ws_incoming();
	Object.defineProperty(exports, "numOpenSockets", {
		enumerable: true,
		get: function() {
			return ws_incoming_1.numOpenSockets;
		}
	});
	/**
	* Creates the proxy server.
	*
	* Examples:
	*
	*    httpProxy.createProxyServer({ .. }, 8000)
	*    // => '{ web: [Function], ws: [Function] ... }'
	*
	* @param {Object} Options Config object passed to the proxy
	*
	* @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
	*
	* @api public
	*/
	function createProxyServer(options = {}) {
		return new index_1.ProxyServer(options);
	}
})))(), 1);
const debug$11 = createDebugger("vite:proxy");
const rewriteOriginHeader = (proxyReq, options, config) => {
	if (options.rewriteWsOrigin) {
		const { target } = options;
		if (proxyReq.headersSent) {
			config.logger.warn(import_picocolors.default.yellow(`Unable to rewrite Origin header as headers are already sent.`));
			return;
		}
		if (proxyReq.getHeader("origin") && target) {
			const changedOrigin = typeof target === "object" ? `${target.protocol ?? "http:"}//${target.host}` : target;
			proxyReq.setHeader("origin", changedOrigin);
		}
	}
};
function proxyMiddleware(httpServer, options, config) {
	const proxies = {};
	Object.keys(options).forEach((context) => {
		let opts = options[context];
		if (!opts) return;
		if (typeof opts === "string") opts = {
			target: opts,
			changeOrigin: true
		};
		const proxy = import_lib$1.createProxyServer(opts);
		if (opts.configure) opts.configure(proxy, opts);
		proxy.on("error", (err, _req, res) => {
			if ("req" in res) {
				config.logger.error(`${import_picocolors.default.red(`http proxy error: ${res.req.url}`)}\n${err.stack}`, {
					timestamp: true,
					error: err
				});
				if (!res.headersSent && !res.writableEnded) res.writeHead(502, { "Content-Type": "text/plain" }).end();
			} else {
				config.logger.error(`${import_picocolors.default.red(`ws proxy error:`)}\n${err.stack}`, {
					timestamp: true,
					error: err
				});
				res.end();
			}
		});
		proxy.on("proxyReqWs", (proxyReq, _req, socket, options) => {
			rewriteOriginHeader(proxyReq, options, config);
			socket.on("error", (err) => {
				config.logger.error(`${import_picocolors.default.red(`ws proxy socket error:`)}\n${err.stack}`, {
					timestamp: true,
					error: err
				});
			});
		});
		proxies[context] = [proxy, { ...opts }];
	});
	if (httpServer) httpServer.on("upgrade", async (req, socket, head) => {
		const url = req.url;
		for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
			const [proxy, opts] = proxies[context];
			if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) {
				if (opts.bypass) try {
					const bypassResult = await opts.bypass(req, void 0, opts);
					if (typeof bypassResult === "string") {
						debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
						req.url = bypassResult;
						return;
					}
					if (bypassResult === false) {
						debug$11?.(`bypass: ${req.url} -> 404`);
						socket.end("HTTP/1.1 404 Not Found\r\n\r\n", "");
						return;
					}
				} catch (err) {
					config.logger.error(`${import_picocolors.default.red(`ws proxy bypass error:`)}\n${err.stack}`, {
						timestamp: true,
						error: err
					});
					return;
				}
				if (opts.rewrite) req.url = opts.rewrite(url);
				debug$11?.(`${req.url} -> ws ${opts.target}`);
				proxy.ws(req, socket, head);
				return;
			}
		}
	});
	return async function viteProxyMiddleware(req, res, next) {
		const url = req.url;
		for (const context in proxies) if (doesProxyContextMatchUrl(context, url)) {
			const [proxy, opts] = proxies[context];
			const options = {};
			if (opts.bypass) try {
				const bypassResult = await opts.bypass(req, res, opts);
				if (typeof bypassResult === "string") {
					debug$11?.(`bypass: ${req.url} -> ${bypassResult}`);
					req.url = bypassResult;
					if (res.writableEnded) return;
					return next();
				}
				if (bypassResult === false) {
					debug$11?.(`bypass: ${req.url} -> 404`);
					res.statusCode = 404;
					return res.end();
				}
			} catch (e) {
				debug$11?.(`bypass: ${req.url} -> ${e}`);
				return next(e);
			}
			debug$11?.(`${req.url} -> ${opts.target || opts.forward}`);
			if (opts.rewrite) req.url = opts.rewrite(req.url);
			proxy.web(req, res, options);
			return;
		}
		next();
	};
}
function doesProxyContextMatchUrl(context, url) {
	return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context);
}
//#endregion
//#region src/node/server/middlewares/htmlFallback.ts
const debug$10 = createDebugger("vite:html-fallback");
function htmlFallbackMiddleware(root, spaFallback, clientEnvironment) {
	const memoryFiles = clientEnvironment?.bundledDev?.memoryFiles;
	function checkFileExists(relativePath) {
		return memoryFiles?.has(relativePath.slice(1)) ?? fs.existsSync(path.join(root, relativePath));
	}
	return function viteHtmlFallbackMiddleware(req, _res, next) {
		if (req.method !== "GET" && req.method !== "HEAD" || req.url === "/favicon.ico" || !(req.headers.accept === void 0 || req.headers.accept === "" || req.headers.accept.includes("text/html") || req.headers.accept.includes("*/*"))) return next();
		const url = cleanUrl(req.url);
		let pathname;
		try {
			pathname = decodeURIComponent(url);
		} catch {
			return next();
		}
		if (pathname.endsWith(".html")) {
			if (checkFileExists(pathname)) {
				debug$10?.(`Rewriting ${req.method} ${req.url} to ${url}`);
				req.url = url;
				return next();
			}
		} else if (pathname.endsWith("/")) {
			if (checkFileExists(joinUrlSegments(pathname, "index.html"))) {
				const newUrl = url + "index.html";
				debug$10?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
				req.url = newUrl;
				return next();
			}
		} else if (checkFileExists(pathname + ".html")) {
			const newUrl = url + ".html";
			debug$10?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
			req.url = newUrl;
			return next();
		}
		if (spaFallback) {
			debug$10?.(`Rewriting ${req.method} ${req.url} to /index.html`);
			req.url = "/index.html";
		}
		next();
	};
}
//#endregion
//#region ../../node_modules/.pnpm/convert-source-map@2.0.0/node_modules/convert-source-map/index.js
var require_convert_source_map = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "commentRegex", { get: function getCommentRegex() {
		return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/gm;
	} });
	Object.defineProperty(exports, "mapFileCommentRegex", { get: function getMapFileCommentRegex() {
		return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/gm;
	} });
	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, read) {
		var r = exports.mapFileCommentRegex.exec(sm);
		var filename = r[1] || r[2];
		try {
			var sm = read(filename);
			if (sm != null && typeof sm.catch === "function") return sm.catch(throwError);
			else return sm;
		} catch (e) {
			throwError(e);
		}
		function throwError(e) {
			throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e.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(options) {
		var encoding, content, data;
		if (options != null && options.encoding === "uri") {
			encoding = "";
			content = this.toURI();
		} else {
			encoding = ";base64";
			content = this.toBase64();
		}
		data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
		return options != null && options.multiline ? "/*# " + data + " */" : "//# " + data;
	};
	Converter.prototype.toObject = function() {
		return JSON.parse(this.toJSON());
	};
	Converter.prototype.addProperty = function(key, value) {
		if (this.sourcemap.hasOwnProperty(key)) throw new Error("property \"" + key + "\" already exists on the sourcemap, use set property instead");
		return this.setProperty(key, value);
	};
	Converter.prototype.setProperty = function(key, value) {
		this.sourcemap[key] = value;
		return this;
	};
	Converter.prototype.getProperty = function(key) {
		return this.sourcemap[key];
	};
	exports.fromObject = function(obj) {
		return new Converter(obj);
	};
	exports.fromJSON = function(json) {
		return new Converter(json, { isJSON: true });
	};
	exports.fromURI = function(uri) {
		return new Converter(uri, { encoding: "uri" });
	};
	exports.fromBase64 = function(base64) {
		return new Converter(base64, { encoding: "base64" });
	};
	exports.fromComment = function(comment) {
		var m, encoding;
		comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
		m = exports.commentRegex.exec(comment);
		encoding = m && m[4] || "uri";
		return new Converter(comment, {
			encoding,
			hasComment: true
		});
	};
	function makeConverter(sm) {
		return new Converter(sm, { isJSON: true });
	}
	exports.fromMapFileComment = function(comment, read) {
		if (typeof read === "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, read);
		if (sm != null && typeof sm.then === "function") return sm.then(makeConverter);
		else return makeConverter(sm);
	};
	exports.fromSource = function(content) {
		var m = content.match(exports.commentRegex);
		return m ? exports.fromComment(m.pop()) : null;
	};
	exports.fromMapFileSource = function(content, read) {
		if (typeof read === "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(exports.mapFileCommentRegex);
		return m ? exports.fromMapFileComment(m.pop(), read) : null;
	};
	exports.removeComments = function(src) {
		return src.replace(exports.commentRegex, "");
	};
	exports.removeMapFileComments = function(src) {
		return src.replace(exports.mapFileCommentRegex, "");
	};
	exports.generateMapFileComment = function(file, options) {
		var data = "sourceMappingURL=" + file;
		return options && options.multiline ? "/*# " + data + " */" : "//# " + data;
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
/*!
* etag
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*/
var require_etag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* Module exports.
	* @public
	*/
	module.exports = etag;
	/**
	* Module dependencies.
	* @private
	*/
	var crypto$1 = __require("crypto");
	var Stats = __require("fs").Stats;
	/**
	* Module variables.
	* @private
	*/
	var toString = Object.prototype.toString;
	/**
	* Generate an entity tag.
	*
	* @param {Buffer|string} entity
	* @return {string}
	* @private
	*/
	function entitytag(entity) {
		if (entity.length === 0) return "\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\"";
		var hash = crypto$1.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
		return "\"" + (typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length).toString(16) + "-" + hash + "\"";
	}
	/**
	* Create a simple ETag.
	*
	* @param {string|Buffer|Stats} entity
	* @param {object} [options]
	* @param {boolean} [options.weak]
	* @return {String}
	* @public
	*/
	function etag(entity, options) {
		if (entity == null) throw new TypeError("argument entity is required");
		var isStats = isstats(entity);
		var weak = options && typeof options.weak === "boolean" ? options.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;
	}
	/**
	* Determine if object is a Stats object.
	*
	* @param {object} obj
	* @return {boolean}
	* @api private
	*/
	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";
	}
	/**
	* Generate a tag for a stat.
	*
	* @param {object} stat
	* @return {string}
	* @private
	*/
	function stattag(stat) {
		var mtime = stat.mtime.getTime().toString(16);
		return "\"" + stat.size.toString(16) + "-" + mtime + "\"";
	}
}));
//#endregion
//#region src/node/server/sourcemap.ts
var import_convert_source_map = /* @__PURE__ */ __toESM(require_convert_source_map(), 1);
const debug$9 = createDebugger("vite:sourcemap", { onlyWhenFocused: true });
/**
* Given a file path inside node_modules, returns the package root directory.
* For scoped packages like `node_modules/@scope/pkg/dist/foo.js`, returns `node_modules/@scope/pkg`.
* Returns `undefined` if the file is not inside node_modules.
*/
function getNodeModulesPackageRoot(filePath) {
	const normalized = normalizePath(filePath);
	const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
	if (nodeModulesIndex === -1) return void 0;
	const packageStart = nodeModulesIndex + 14;
	const rest = normalized.slice(packageStart);
	const firstSlash = rest.indexOf("/");
	let packageName;
	if (rest.startsWith("@")) {
		const secondSlash = rest.indexOf("/", firstSlash + 1);
		packageName = secondSlash === -1 ? rest : rest.slice(0, secondSlash);
	} else packageName = firstSlash === -1 ? rest : rest.slice(0, firstSlash);
	return normalized.slice(0, packageStart) + packageName;
}
const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
async function computeSourceRoute(map, file) {
	let sourceRoot;
	try {
		sourceRoot = await fsp.realpath(path.resolve(path.dirname(file), map.sourceRoot || ""));
	} catch {}
	return sourceRoot;
}
async function injectSourcesContent(map, file, logger) {
	let sourceRootPromise;
	const packageRoot = getNodeModulesPackageRoot(file);
	const missingSources = [];
	const sourcesContent = map.sourcesContent || [];
	const sourcesContentPromises = [];
	for (let index = 0; index < map.sources.length; index++) {
		const sourcePath = map.sources[index];
		if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) sourcesContentPromises.push((async () => {
			sourceRootPromise ??= computeSourceRoute(map, file);
			const sourceRoot = await sourceRootPromise;
			let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
			if (sourceRoot) resolvedSourcePath = path.resolve(sourceRoot, resolvedSourcePath);
			if (packageRoot) {
				const resolvedSourcePathNormalized = normalizePath(path.resolve(resolvedSourcePath));
				if (!isParentDirectory(packageRoot, resolvedSourcePathNormalized)) {
					sourcesContent[index] = null;
					logger.warnOnce(import_picocolors.default.yellow(`Sourcemap for ${JSON.stringify(file)} points to a source file outside its package: ${JSON.stringify(resolvedSourcePathNormalized)}`));
					return;
				}
			}
			sourcesContent[index] = await fsp.readFile(resolvedSourcePath, "utf-8").catch(() => {
				missingSources.push(resolvedSourcePath);
				return null;
			});
		})());
	}
	await Promise.all(sourcesContentPromises);
	map.sourcesContent = sourcesContent;
	if (missingSources.length) {
		logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
		debug$9?.(`Missing sources:\n  ` + missingSources.join(`\n  `));
	}
}
function genSourceMapUrl(map) {
	if (typeof map !== "string") map = JSON.stringify(map);
	return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
}
function getCodeWithSourcemap(type, code, map) {
	if (debug$9) code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/\n`;
	if (type === "js") code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
	else if (type === "css") code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
	return code;
}
function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) {
	let { x_google_ignoreList } = map;
	if (x_google_ignoreList === void 0) x_google_ignoreList = [];
	if (map.sources) {
		for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
			const sourcePath = map.sources[sourcesIndex];
			if (!sourcePath) continue;
			const ignoreList = sourcemapIgnoreList(path.isAbsolute(sourcePath) ? sourcePath : path.resolve(path.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 (!map.x_google_ignoreList) map.x_google_ignoreList = x_google_ignoreList;
		}
	}
}
function extractSourcemapFromFile(code, filePath, logger) {
	const map = (import_convert_source_map.fromSource(code) || import_convert_source_map.fromMapFileSource(code, createConvertSourceMapReadMap(filePath, logger)))?.toObject();
	if (map) return {
		code: code.replace(import_convert_source_map.default.mapFileCommentRegex, blankReplacer),
		map
	};
}
function createConvertSourceMapReadMap(originalFileName, logger) {
	const packageRoot = getNodeModulesPackageRoot(originalFileName);
	return (filename) => {
		const resolvedPath = path.resolve(path.dirname(originalFileName), filename);
		if (packageRoot && !isParentDirectory(packageRoot, normalizePath(resolvedPath))) {
			logger.warnOnce(import_picocolors.default.yellow(`Sourcemap in "${originalFileName}" references a map file outside its package: "${filename}"`));
			return "{}";
		}
		return fs.readFileSync(resolvedPath, "utf-8");
	};
}
//#endregion
//#region src/node/server/send.ts
var import_etag = /* @__PURE__ */ __toESM(require_etag(), 1);
const debug$8 = createDebugger("vite:send", { onlyWhenFocused: true });
const alias = {
	js: "text/javascript",
	css: "text/css",
	html: "text/html",
	json: "application/json"
};
function send$1(req, res, content, type, options) {
	const { etag = (0, import_etag.default)(content, { weak: true }), cacheControl = "no-cache", headers, map } = options;
	if (res.writableEnded) return;
	if (req.headers["if-none-match"] === etag) {
		res.statusCode = 304;
		res.end();
		return;
	}
	res.setHeader("Content-Type", alias[type] || type);
	res.setHeader("Cache-Control", cacheControl);
	res.setHeader("Etag", etag);
	if (headers) for (const name in headers) res.setHeader(name, headers[name]);
	if (map && "version" in map && map.mappings) {
		if (type === "js" || type === "css") content = getCodeWithSourcemap(type, content.toString(), map);
	} else if (type === "js" && (!map || map.mappings !== "")) {
		const code = content.toString();
		if (import_convert_source_map.default.mapFileCommentRegex.test(code)) debug$8?.(`Skipped injecting fallback sourcemap for ${req.url}`);
		else {
			const urlWithoutTimestamp = removeTimestampQuery(req.url);
			content = getCodeWithSourcemap(type, code, new MagicString(code).generateMap({
				source: path.basename(urlWithoutTimestamp),
				hires: "boundary",
				includeContent: true
			}));
		}
	}
	res.statusCode = 200;
	if (req.method === "HEAD") res.end();
	else res.end(content);
}
//#endregion
//#region ../../node_modules/.pnpm/totalist@3.0.1/node_modules/totalist/sync/index.mjs
function totalist(dir, callback, pre = "") {
	dir = resolve$1(".", dir);
	let arr = readdirSync(dir);
	let i = 0, abs, stats;
	for (; i < arr.length; i++) {
		abs = join$1(dir, arr[i]);
		stats = statSync(abs);
		stats.isDirectory() ? totalist(abs, callback, join$1(pre, arr[i])) : callback(join$1(pre, arr[i]), abs, stats);
	}
}
//#endregion
//#region ../../node_modules/.pnpm/@polka+url@1.0.0-next.29/node_modules/@polka/url/build.mjs
/**
* @typedef ParsedURL
* @type {import('.').ParsedURL}
*/
/**
* @typedef Request
* @property {string} url
* @property {ParsedURL} _parsedUrl
*/
/**
* @param {Request} req
* @returns {ParsedURL|void}
*/
function parse$1(req) {
	let raw = req.url;
	if (raw == null) return;
	let prev = req._parsedUrl;
	if (prev && prev.raw === raw) return prev;
	let pathname = raw, search = "", query, hash;
	if (raw.length > 1) {
		let idx = raw.indexOf("#", 1);
		if (idx !== -1) {
			hash = raw.substring(idx);
			pathname = raw.substring(0, idx);
		}
		idx = pathname.indexOf("?", 1);
		if (idx !== -1) {
			search = pathname.substring(idx);
			pathname = pathname.substring(0, idx);
			if (search.length > 1) query = qs.parse(search.substring(1));
		}
	}
	return req._parsedUrl = {
		pathname,
		search,
		query,
		hash,
		raw
	};
}
//#endregion
//#region ../../node_modules/.pnpm/mrmime@2.0.1/node_modules/mrmime/index.mjs
const 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",
	"jxl": "image/jxl",
	"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",
	"m2t": "video/mp2t",
	"m2ts": "video/mp2t",
	"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",
	"mts": "video/mp2t",
	"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)];
}
//#endregion
//#region ../../node_modules/.pnpm/sirv@3.0.2_patch_hash=c07c56eb72faea34341d465cde2314e89db472106ed378181e3447893af6bf95/node_modules/sirv/build.mjs
const noop = () => {};
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, name, headers;
	for (; i < arr.length; i++) {
		abs = normalize(join(dir, name = arr[i]));
		if (abs.startsWith(dir) && fs$2.existsSync(abs)) {
			stats = fs$2.statSync(abs);
			if (stats.isDirectory()) continue;
			if (shouldServe && !shouldServe(abs)) continue;
			headers = toHeaders(name, stats, isEtag);
			headers["Cache-Control"] = isEtag ? "no-cache" : "no-store";
			return {
				abs,
				stats,
				headers
			};
		}
	}
}
function is404(req, res) {
	return res.statusCode = 404, res.end();
}
function send(req, 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 (req.headers.range) {
		code = 206;
		let [x, y] = req.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);
	fs$2.createReadStream(file, opts).pipe(res);
}
const ENCODING = {
	".br": "br",
	".gz": "gzip"
};
function toHeaders(name, stats, isEtag) {
	let enc = ENCODING[name.slice(-3)];
	let ctype = lookup(name.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 build_default$1(dir, opts = {}) {
	dir = resolve(dir || ".");
	let isNotFound = opts.onNoMatch || is404;
	let setHeaders = opts.setHeaders || noop;
	let extensions = opts.extensions || ["html", "htm"];
	let gzips = opts.gzip && extensions.map((x) => `${x}.gz`).concat("gz");
	let brots = opts.brotli && extensions.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, (name, abs, stats) => {
		if (/\.well-known[\\+\/]/.test(name)) {} else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
		let headers = toHeaders(name, stats, isEtag);
		if (cc) headers["Cache-Control"] = cc;
		FILES["/" + name.normalize().replace(/\\+/g, "/")] = {
			abs,
			stats,
			headers
		};
	});
	let lookup = opts.dev ? viaLocal.bind(0, dir.endsWith(sep) ? dir : dir + sep, isEtag) : viaCache.bind(0, FILES);
	return function(req, res, next) {
		let extns = [""];
		let pathname = parse$1(req).pathname;
		let val = req.headers["accept-encoding"] || "";
		if (gzips && val.includes("gzip")) extns.unshift(...gzips);
		if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
		extns.push(...extensions);
		if (pathname.indexOf("%") !== -1) try {
			pathname = decodeURI(pathname);
		} catch (err) {}
		let data = lookup(pathname, extns, opts.shouldServe) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns, opts.shouldServe);
		if (!data) return next ? next() : isNotFound(req, res);
		if (isEtag && req.headers["if-none-match"] === data.headers["ETag"]) {
			res.writeHead(304);
			return res.end();
		}
		if (gzips || brots) res.setHeader("Vary", "Accept-Encoding");
		setHeaders(res, pathname, data.stats);
		send(req, res, data.abs, data.stats, data.headers);
	};
}
//#endregion
//#region src/node/server/middlewares/static.ts
var import_escape_html = /* @__PURE__ */ __toESM(require_escape_html(), 1);
const knownJavascriptExtensionRE = /\.(?:[tj]sx?|[cm][tj]s)$/;
const ERR_DENIED_FILE = "ERR_DENIED_FILE";
const sirvOptions = ({ config, getHeaders, disableFsServeCheck }) => {
	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 name in headers) res.setHeader(name, headers[name]);
		},
		shouldServe: disableFsServeCheck ? void 0 : (filePath) => {
			const servingAccessResult = checkLoadingAccess(config, filePath);
			if (servingAccessResult === "denied") {
				const error = /* @__PURE__ */ new Error("denied access");
				error.code = ERR_DENIED_FILE;
				error.path = filePath;
				throw error;
			}
			if (servingAccessResult === "fallback") return false;
			return true;
		}
	};
};
function servePublicMiddleware(server, publicFiles) {
	const dir = server.config.publicDir;
	const serve = build_default$1(dir, sirvOptions({
		config: server.config,
		getHeaders: () => server.config.server.headers,
		disableFsServeCheck: true
	}));
	const toFilePath = (url) => {
		let filePath = cleanUrl(url);
		if (filePath.includes("%")) try {
			filePath = decodeURI(filePath);
		} catch {}
		return normalizePath(filePath);
	};
	return function viteServePublicMiddleware(req, res, next) {
		if (publicFiles && !publicFiles.has(toFilePath(req.url)) || isImportRequest(req.url) || isInternalRequest(req.url) || urlRE$1.test(req.url)) return next();
		serve(req, res, next);
	};
}
function serveStaticMiddleware(server) {
	const dir = server.config.root;
	const serve = build_default$1(dir, sirvOptions({
		config: server.config,
		getHeaders: () => server.config.server.headers
	}));
	return function viteServeStaticMiddleware(req, res, next) {
		const cleanedUrl = cleanUrl(req.url);
		if (cleanedUrl.endsWith("/") || path.extname(cleanedUrl) === ".html" || isInternalRequest(req.url) || req.url?.startsWith("//")) return next();
		const url = new URL(req.url, "http://example.com");
		const pathname = decodeURIIfPossible(url.pathname);
		if (pathname === void 0) return next();
		let redirectedPathname;
		for (const { find, replacement } of server.config.resolve.alias) if (typeof find === "string" ? pathname.startsWith(find) : find.test(pathname)) {
			redirectedPathname = pathname.replace(find, replacement);
			break;
		}
		if (redirectedPathname) {
			if (redirectedPathname.startsWith(withTrailingSlash(dir))) redirectedPathname = redirectedPathname.slice(dir.length);
		}
		const resolvedPathname = redirectedPathname || pathname;
		let fileUrl = path.resolve(dir, removeLeadingSlash(resolvedPathname));
		if (resolvedPathname.endsWith("/") && fileUrl[fileUrl.length - 1] !== "/") fileUrl = withTrailingSlash(fileUrl);
		if (redirectedPathname) {
			url.pathname = encodeURI(redirectedPathname);
			req.url = url.href.slice(url.origin.length);
		}
		try {
			serve(req, res, next);
		} catch (e) {
			if (e && "code" in e && e.code === ERR_DENIED_FILE) {
				respondWithAccessDenied(e.path, server, res);
				return;
			}
			throw e;
		}
	};
}
function serveRawFsMiddleware(server) {
	const serveFromRoot = build_default$1("/", sirvOptions({
		config: server.config,
		getHeaders: () => server.config.server.headers
	}));
	return function viteServeRawFsMiddleware(req, res, next) {
		if (req.url.startsWith(FS_PREFIX)) {
			const url = new URL(req.url, "http://example.com");
			const pathname = decodeURIIfPossible(url.pathname);
			if (pathname === void 0) return next();
			let newPathname = pathname.slice(FS_PREFIX.length);
			if (isWindows) newPathname = newPathname.replace(/^[A-Z]:/i, "");
			url.pathname = encodeURI(newPathname);
			req.url = url.href.slice(url.origin.length);
			try {
				serveFromRoot(req, res, next);
			} catch (e) {
				if (e && "code" in e && e.code === ERR_DENIED_FILE) {
					respondWithAccessDenied(e.path, server, res);
					return;
				}
				throw e;
			}
		} else next();
	};
}
function isFileServingAllowed(configOrUrl, urlOrServer) {
	const config = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
	const url = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
	if (!config.server.fs.strict) return true;
	return isFileLoadingAllowed(config, fsPathFromUrl(url));
}
/**
* Warning: parameters are not validated, only works with normalized absolute paths
*
* @param targetPath - normalized absolute path
* @param filePath - normalized absolute path
*/
function isFileInTargetPath(targetPath, filePath) {
	return isSameFilePath(targetPath, filePath) || isParentDirectory(targetPath, filePath);
}
const windowsDriveRE = /^[A-Z]:/i;
/**
* Warning: parameters are not validated, only works with normalized absolute paths
*/
function isFileLoadingAllowed(config, filePath) {
	const { fs } = config.server;
	if (!fs.strict) return true;
	if (isWindows && filePath.includes("~")) return false;
	if ((isWindows && windowsDriveRE.test(filePath) ? filePath.slice(2) : filePath).includes(":")) return false;
	const filePathWithoutTrailingSlash = filePath.endsWith("/") ? filePath.slice(0, -1) : filePath;
	if (config.fsDenyGlob(filePathWithoutTrailingSlash)) return false;
	if (config.safeModulePaths.has(filePath)) return true;
	if (fs.allow.some((uri) => isFileInTargetPath(uri, filePath))) return true;
	return false;
}
function checkLoadingAccess(config, path) {
	if (isFileLoadingAllowed(config, slash(path))) return "allowed";
	if (isFileReadable(path)) return "denied";
	return "fallback";
}
function respondWithAccessDenied(id, server, res) {
	const urlMessage = `The request id "${id}" is outside of Vite serving allow list.`;
	const hintMessage = `
${server.config.server.fs.allow.map((i) => `- ${i}`).join("\n")}

Refer to docs https://vite.dev/config/server-options.html#server-fs-allow for configurations and more details.`;
	server.config.logger.error(urlMessage);
	server.config.logger.warnOnce(hintMessage + "\n");
	res.statusCode = 403;
	res.write(renderRestrictedErrorHTML(urlMessage + "\n" + hintMessage));
	res.end();
}
function renderRestrictedErrorHTML(msg) {
	return String.raw`
    <body>
      <h1>403 Restricted</h1>
      <p>${(0, import_escape_html.default)(msg).replace(/\n/g, "<br/>")}</p>
      <style>
        body {
          padding: 1em 2em;
        }
      </style>
    </body>
  `;
}
//#endregion
//#region src/node/server/transformRequest.ts
const ERR_LOAD_URL = "ERR_LOAD_URL";
const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL";
const ERR_DENIED_ID = "ERR_DENIED_ID";
const debugLoad = createDebugger("vite:load");
const debugTransform = createDebugger("vite:transform");
const debugCache$1 = createDebugger("vite:cache");
function transformRequest(environment, url, options) {
	if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
	const timestamp = monotonicDateNow();
	url = removeTimestampQuery(url);
	const pending = environment._pendingRequests.get(url);
	if (pending) return environment.moduleGraph.getModuleByUrl(url).then((module) => {
		if (!module || pending.timestamp > module.lastInvalidationTimestamp) return pending.request;
		else {
			pending.abort();
			return transformRequest(environment, url, options);
		}
	});
	const request = doTransform(environment, url, options, timestamp);
	let cleared = false;
	const clearCache = () => {
		if (!cleared) {
			environment._pendingRequests.delete(url);
			cleared = true;
		}
	};
	environment._pendingRequests.set(url, {
		request,
		timestamp,
		abort: clearCache
	});
	return request.finally(clearCache);
}
async function doTransform(environment, url, options, timestamp) {
	const { pluginContainer } = environment;
	let module = await environment.moduleGraph.getModuleByUrl(url);
	if (module) {
		const cached = await getCachedTransformResult(environment, url, module, timestamp);
		if (cached) return cached;
	}
	const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0) ?? void 0;
	const id = module?.id ?? resolved?.id ?? url;
	module ??= environment.moduleGraph.getModuleById(id);
	if (module) {
		await environment.moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
		const cached = await getCachedTransformResult(environment, url, module, timestamp);
		if (cached) return cached;
	}
	const result = loadAndTransform(environment, id, url, options, timestamp, module, resolved);
	const { depsOptimizer } = environment;
	if (!depsOptimizer?.isOptimizedDepFile(id)) environment._registerRequestProcessing(id, () => result);
	return result;
}
async function getCachedTransformResult(environment, url, module, timestamp) {
	const prettyUrl = debugCache$1 ? prettifyUrl(url, environment.config.root) : "";
	const softInvalidatedTransformResult = await handleModuleSoftInvalidation(environment, module, timestamp);
	if (softInvalidatedTransformResult) {
		debugCache$1?.(`[memory-hmr] ${prettyUrl}`);
		return softInvalidatedTransformResult;
	}
	const cached = module.transformResult;
	if (cached) {
		debugCache$1?.(`[memory] ${prettyUrl}`);
		return cached;
	}
}
async function loadAndTransform(environment, id, url, options, timestamp, mod, resolved) {
	const { config, pluginContainer, logger } = environment;
	const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : "";
	const moduleGraph = environment.moduleGraph;
	if (!options.skipFsCheck && id[0] !== "\0" && isServerAccessDeniedForTransform(config, id)) {
		const err = /* @__PURE__ */ new Error(`Denied ID ${id}`);
		err.code = ERR_DENIED_ID;
		err.id = id;
		throw err;
	}
	let code = null;
	let map = null;
	let moduleType;
	const loadStart = debugLoad ? performance$1.now() : 0;
	const loadResult = await pluginContainer.load(id);
	if (loadResult == null) {
		const file = cleanUrl(id);
		if (options.skipFsCheck || isFileLoadingAllowed(environment.getTopLevelConfig(), slash(file))) {
			try {
				code = await fsp.readFile(file, "utf-8");
				debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`);
			} catch (e) {
				if (e.code !== "ENOENT" && e.code !== "EISDIR") throw e;
			}
			if (code != null && environment.pluginContainer.watcher) ensureWatchedFile(environment.pluginContainer.watcher, file, config.root);
		}
		if (code) try {
			const extracted = extractSourcemapFromFile(code, file, logger);
			if (extracted) {
				code = extracted.code;
				map = extracted.map;
			}
		} catch (e) {
			logger.warn(`Failed to load source map for ${file}.\n${e}`, { timestamp: true });
		}
	} else {
		debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`);
		if (isObject$1(loadResult)) {
			code = loadResult.code;
			map = loadResult.map;
			moduleType = loadResult.moduleType;
		} else code = loadResult;
	}
	if (code == null) {
		const isPublicFile = checkPublicFile(url, environment.getTopLevelConfig());
		let publicDirName = path.relative(config.root, config.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 = moduleGraph.idToModuleMap.get(id)?.importers.values().next().value;
		const importer = importerMod?.file || importerMod?.url;
		const err = /* @__PURE__ */ new Error(`Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}`);
		err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL;
		throw err;
	}
	if (moduleType === void 0) {
		const guessedModuleType = getModuleTypeFromId(id);
		if (guessedModuleType && guessedModuleType !== "js") moduleType = guessedModuleType;
	}
	if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
	mod ??= await moduleGraph._ensureEntryFromUrl(url, void 0, resolved);
	const transformStart = debugTransform ? performance$1.now() : 0;
	const transformResult = await pluginContainer.transform(code, id, {
		inMap: map,
		moduleType
	});
	const originalCode = code;
	if (transformResult.code === originalCode) debugTransform?.(timeFrom(transformStart) + import_picocolors.default.dim(` [skipped] ${prettyUrl}`));
	else {
		debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`);
		code = transformResult.code;
		map = transformResult.map;
	}
	let normalizedMap;
	if (typeof map === "string") normalizedMap = JSON.parse(map);
	else if (map) normalizedMap = map;
	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, config.server.sourcemapIgnoreList, logger);
		if (path.isAbsolute(mod.file)) {
			let modDirname;
			for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) {
				const sourcePath = normalizedMap.sources[sourcesIndex];
				if (sourcePath) {
					if (path.isAbsolute(sourcePath)) {
						modDirname ??= path.dirname(mod.file);
						normalizedMap.sources[sourcesIndex] = path.relative(modDirname, sourcePath);
					}
				}
			}
		}
	}
	if (environment._closing && environment.config.dev.recoverable) throwClosedServerError();
	const topLevelConfig = environment.getTopLevelConfig();
	const result = environment.config.dev.moduleRunnerTransform ? await ssrTransform(code, normalizedMap, url, originalCode, { json: { stringify: topLevelConfig.json.stringify === true && topLevelConfig.json.namedExports !== true } }) : {
		code,
		map: normalizedMap,
		etag: (0, import_etag.default)(code, { weak: true })
	};
	if (timestamp > mod.lastInvalidationTimestamp) moduleGraph.updateModuleTransformResult(mod, result);
	return result;
}
/**
* When a module is soft-invalidated, we can preserve its previous `transformResult` and
* return similar code to before:
*
* - Client: We need to transform the import specifiers with new timestamps
* - SSR: We don't need to change anything as `ssrLoadModule` controls it
*/
async function handleModuleSoftInvalidation(environment, mod, timestamp) {
	const transformResult = mod.invalidationState;
	mod.invalidationState = void 0;
	if (!transformResult || transformResult === "HARD_INVALIDATED") return;
	if (mod.transformResult) throw new Error(`Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result`);
	let result;
	if (transformResult.ssr) result = transformResult;
	else {
		await init;
		const source = transformResult.code;
		const s = new MagicString(source);
		const [imports] = parse$2(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(stripBase(removeImportQuery(urlWithoutTimestamp), environment.config.base));
			for (const importedMod of mod.importedModules) {
				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 && environment.config.dev.preTransformRequests) environment.warmupRequest(hmrUrl);
				break;
			}
		}
		const code = s.toString();
		result = {
			...transformResult,
			code,
			etag: (0, import_etag.default)(code, { weak: true })
		};
	}
	if (timestamp > mod.lastInvalidationTimestamp) environment.moduleGraph.updateModuleTransformResult(mod, result);
	return result;
}
const defaultModuleTypes = {
	js: "js",
	mjs: "js",
	cjs: "js",
	jsx: "jsx",
	ts: "ts",
	mts: "ts",
	cts: "ts",
	tsx: "tsx",
	json: "json",
	txt: "text",
	css: "css"
};
function getModuleTypeFromId(id) {
	let pos = -1;
	while ((pos = id.indexOf(".", pos + 1)) >= 0) {
		const moduleType = defaultModuleTypes[id.slice(pos + 1)];
		if (moduleType) return moduleType;
	}
}
//#endregion
//#region ../../node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.mjs
var import_js_tokens = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
	var HashbangComment, Identifier, JSXIdentifier, JSXPunctuator, JSXString, JSXText, KeywordsWithExpressionAfter, KeywordsWithNoLineTerminatorAfter, LineTerminatorSequence, MultiLineComment, Newline, NumericLiteral, Punctuator, RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]?|[^\/[\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/uy, SingleLineComment, StringLiteral, Template, TokensNotPrecedingObjectLiteral, TokensPrecedingExpression, WhiteSpace;
	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]+\})+/uy;
	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}]+/uy;
	LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
	MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
	SingleLineComment = /\/\/.*/y;
	HashbangComment = /^#!.*/;
	JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
	JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/uy;
	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);
	module.exports = function* (input, { jsx = false } = {}) {
		var braces, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match, mode, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
		({length} = input);
		lastIndex = 0;
		lastSignificantToken = "";
		stack = [{ tag: "JS" }];
		braces = [];
		parenNesting = 0;
		postfixIncDec = false;
		if (match = HashbangComment.exec(input)) {
			yield {
				type: "HashbangComment",
				value: match[0]
			};
			lastIndex = match[0].length;
		}
		while (lastIndex < length) {
			mode = stack[stack.length - 1];
			switch (mode.tag) {
				case "JS":
				case "JSNonExpressionParen":
				case "InterpolationInTemplate":
				case "InterpolationInJSX":
					if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
						RegularExpressionLiteral.lastIndex = lastIndex;
						if (match = RegularExpressionLiteral.exec(input)) {
							lastIndex = RegularExpressionLiteral.lastIndex;
							lastSignificantToken = match[0];
							postfixIncDec = true;
							yield {
								type: "RegularExpressionLiteral",
								value: match[0],
								closed: match[1] !== void 0 && match[1] !== "\\"
							};
							continue;
						}
					}
					Punctuator.lastIndex = lastIndex;
					if (match = Punctuator.exec(input)) {
						punctuator = match[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 (mode.tag === "JSNonExpressionParen" && parenNesting === mode.nesting) {
									stack.pop();
									nextLastSignificantToken = "?NonExpressionParenEnd";
									postfixIncDec = false;
								}
								break;
							case "{":
								Punctuator.lastIndex = 0;
								isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
								braces.push(isExpression);
								postfixIncDec = false;
								break;
							case "}":
								switch (mode.tag) {
									case "InterpolationInTemplate":
										if (braces.length === mode.nesting) {
											Template.lastIndex = lastIndex;
											match = Template.exec(input);
											lastIndex = Template.lastIndex;
											lastSignificantToken = match[0];
											if (match[1] === "${") {
												lastSignificantToken = "?InterpolationInTemplate";
												postfixIncDec = false;
												yield {
													type: "TemplateMiddle",
													value: match[0]
												};
											} else {
												stack.pop();
												postfixIncDec = true;
												yield {
													type: "TemplateTail",
													value: match[0],
													closed: match[1] === "`"
												};
											}
											continue;
										}
										break;
									case "InterpolationInJSX": if (braces.length === mode.nesting) {
										stack.pop();
										lastIndex += 1;
										lastSignificantToken = "}";
										yield {
											type: "JSXPunctuator",
											value: "}"
										};
										continue;
									}
								}
								postfixIncDec = braces.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 (match = Identifier.exec(input)) {
						lastIndex = Identifier.lastIndex;
						nextLastSignificantToken = match[0];
						switch (match[0]) {
							case "for":
							case "if":
							case "while":
							case "with": if (lastSignificantToken !== "." && lastSignificantToken !== "?.") nextLastSignificantToken = "?NonExpressionParenKeyword";
						}
						lastSignificantToken = nextLastSignificantToken;
						postfixIncDec = !KeywordsWithExpressionAfter.test(match[0]);
						yield {
							type: match[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
							value: match[0]
						};
						continue;
					}
					StringLiteral.lastIndex = lastIndex;
					if (match = StringLiteral.exec(input)) {
						lastIndex = StringLiteral.lastIndex;
						lastSignificantToken = match[0];
						postfixIncDec = true;
						yield {
							type: "StringLiteral",
							value: match[0],
							closed: match[2] !== void 0
						};
						continue;
					}
					NumericLiteral.lastIndex = lastIndex;
					if (match = NumericLiteral.exec(input)) {
						lastIndex = NumericLiteral.lastIndex;
						lastSignificantToken = match[0];
						postfixIncDec = true;
						yield {
							type: "NumericLiteral",
							value: match[0]
						};
						continue;
					}
					Template.lastIndex = lastIndex;
					if (match = Template.exec(input)) {
						lastIndex = Template.lastIndex;
						lastSignificantToken = match[0];
						if (match[1] === "${") {
							lastSignificantToken = "?InterpolationInTemplate";
							stack.push({
								tag: "InterpolationInTemplate",
								nesting: braces.length
							});
							postfixIncDec = false;
							yield {
								type: "TemplateHead",
								value: match[0]
							};
						} else {
							postfixIncDec = true;
							yield {
								type: "NoSubstitutionTemplate",
								value: match[0],
								closed: match[1] === "`"
							};
						}
						continue;
					}
					break;
				case "JSXTag":
				case "JSXTagEnd":
					JSXPunctuator.lastIndex = lastIndex;
					if (match = JSXPunctuator.exec(input)) {
						lastIndex = JSXPunctuator.lastIndex;
						nextLastSignificantToken = match[0];
						switch (match[0]) {
							case "<":
								stack.push({ tag: "JSXTag" });
								break;
							case ">":
								stack.pop();
								if (lastSignificantToken === "/" || mode.tag === "JSXTagEnd") {
									nextLastSignificantToken = "?JSX";
									postfixIncDec = true;
								} else stack.push({ tag: "JSXChildren" });
								break;
							case "{":
								stack.push({
									tag: "InterpolationInJSX",
									nesting: braces.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: match[0]
						};
						continue;
					}
					JSXIdentifier.lastIndex = lastIndex;
					if (match = JSXIdentifier.exec(input)) {
						lastIndex = JSXIdentifier.lastIndex;
						lastSignificantToken = match[0];
						yield {
							type: "JSXIdentifier",
							value: match[0]
						};
						continue;
					}
					JSXString.lastIndex = lastIndex;
					if (match = JSXString.exec(input)) {
						lastIndex = JSXString.lastIndex;
						lastSignificantToken = match[0];
						yield {
							type: "JSXString",
							value: match[0],
							closed: match[2] !== void 0
						};
						continue;
					}
					break;
				case "JSXChildren":
					JSXText.lastIndex = lastIndex;
					if (match = JSXText.exec(input)) {
						lastIndex = JSXText.lastIndex;
						lastSignificantToken = match[0];
						yield {
							type: "JSXText",
							value: match[0]
						};
						continue;
					}
					switch (input[lastIndex]) {
						case "<":
							stack.push({ tag: "JSXTag" });
							lastIndex++;
							lastSignificantToken = "<";
							yield {
								type: "JSXPunctuator",
								value: "<"
							};
							continue;
						case "{":
							stack.push({
								tag: "InterpolationInJSX",
								nesting: braces.length
							});
							lastIndex++;
							lastSignificantToken = "?InterpolationInJSX";
							postfixIncDec = false;
							yield {
								type: "JSXPunctuator",
								value: "{"
							};
							continue;
					}
			}
			WhiteSpace.lastIndex = lastIndex;
			if (match = WhiteSpace.exec(input)) {
				lastIndex = WhiteSpace.lastIndex;
				yield {
					type: "WhiteSpace",
					value: match[0]
				};
				continue;
			}
			LineTerminatorSequence.lastIndex = lastIndex;
			if (match = LineTerminatorSequence.exec(input)) {
				lastIndex = LineTerminatorSequence.lastIndex;
				postfixIncDec = false;
				if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
				yield {
					type: "LineTerminatorSequence",
					value: match[0]
				};
				continue;
			}
			MultiLineComment.lastIndex = lastIndex;
			if (match = MultiLineComment.exec(input)) {
				lastIndex = MultiLineComment.lastIndex;
				if (Newline.test(match[0])) {
					postfixIncDec = false;
					if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) lastSignificantToken = "?NoLineTerminatorHere";
				}
				yield {
					type: "MultiLineComment",
					value: match[0],
					closed: match[1] !== void 0
				};
				continue;
			}
			SingleLineComment.lastIndex = lastIndex;
			if (match = SingleLineComment.exec(input)) {
				lastIndex = SingleLineComment.lastIndex;
				postfixIncDec = false;
				yield {
					type: "SingleLineComment",
					value: match[0]
				};
				continue;
			}
			firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
			lastIndex += firstCodePoint.length;
			lastSignificantToken = firstCodePoint;
			postfixIncDec = false;
			yield {
				type: mode.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
				value: firstCodePoint
			};
		}
	};
})))(), 1);
const FILL_COMMENT = " ";
function stripLiteralFromToken(token, fillChar, filter) {
	if (token.type === "SingleLineComment") return FILL_COMMENT.repeat(token.value.length);
	if (token.type === "MultiLineComment") return token.value.replace(/[^\n]/g, FILL_COMMENT);
	if (token.type === "StringLiteral") {
		if (!token.closed) return token.value;
		const body = token.value.slice(1, -1);
		if (filter(body)) return token.value[0] + fillChar.repeat(body.length) + token.value[token.value.length - 1];
	}
	if (token.type === "NoSubstitutionTemplate") {
		const body = token.value.slice(1, -1);
		if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\``;
	}
	if (token.type === "RegularExpressionLiteral") {
		const body = token.value;
		if (filter(body)) return body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${fillChar.repeat($1.length)}/${$2}`);
	}
	if (token.type === "TemplateHead") {
		const body = token.value.slice(1, -2);
		if (filter(body)) return `\`${body.replace(/[^\n]/g, fillChar)}\${`;
	}
	if (token.type === "TemplateTail") {
		const body = token.value.slice(0, -2);
		if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\``;
	}
	if (token.type === "TemplateMiddle") {
		const body = token.value.slice(1, -2);
		if (filter(body)) return `}${body.replace(/[^\n]/g, fillChar)}\${`;
	}
	return token.value;
}
function optionsWithDefaults(options) {
	return {
		fillChar: options?.fillChar ?? " ",
		filter: options?.filter ?? (() => true)
	};
}
function stripLiteral(code, options) {
	let result = "";
	const _options = optionsWithDefaults(options);
	for (const token of (0, import_js_tokens.default)(code, { jsx: false })) result += stripLiteralFromToken(token, _options.fillChar, _options.filter);
	return result;
}
//#endregion
//#region src/node/environment.ts
/**
* Creates a function that hides the complexities of a WeakMap with an initial value
* to implement object metadata. Used by plugins to implement cross hooks per
* environment metadata
*
* @experimental
*/
function perEnvironmentState(initial) {
	const stateMap = /* @__PURE__ */ new WeakMap();
	return function(context) {
		const { environment } = context;
		if (!stateMap.has(environment)) stateMap.set(environment, initial(environment));
		return stateMap.get(environment);
	};
}
//#endregion
//#region src/node/assetSource.ts
const ALLOWED_META_NAME = [
	"msapplication-tileimage",
	"msapplication-square70x70logo",
	"msapplication-square150x150logo",
	"msapplication-wide310x150logo",
	"msapplication-square310x310logo",
	"msapplication-config",
	"twitter:image"
];
const ALLOWED_META_PROPERTY = [
	"og:image",
	"og:image:url",
	"og:image:secure_url",
	"og:audio",
	"og:audio:secure_url",
	"og:video",
	"og:video:secure_url"
];
const DEFAULT_HTML_ASSET_SOURCES = {
	audio: { srcAttributes: ["src"] },
	embed: { srcAttributes: ["src"] },
	img: {
		srcAttributes: ["src"],
		srcsetAttributes: ["srcset"]
	},
	image: { srcAttributes: ["href", "xlink:href"] },
	input: { srcAttributes: ["src"] },
	link: {
		srcAttributes: ["href"],
		srcsetAttributes: ["imagesrcset"]
	},
	object: { srcAttributes: ["data"] },
	source: {
		srcAttributes: ["src"],
		srcsetAttributes: ["srcset"]
	},
	track: { srcAttributes: ["src"] },
	use: { srcAttributes: ["href", "xlink:href"] },
	video: { srcAttributes: ["src", "poster"] },
	meta: {
		srcAttributes: ["content"],
		filter({ attributes }) {
			if (attributes.name && ALLOWED_META_NAME.includes(attributes.name.trim().toLowerCase())) return true;
			if (attributes.property && ALLOWED_META_PROPERTY.includes(attributes.property.trim().toLowerCase())) return true;
			return false;
		}
	}
};
/**
* Given a HTML node, find all attributes that references an asset to be processed
*/
function getNodeAssetAttributes(node, additionalAssetSources) {
	const defaults = DEFAULT_HTML_ASSET_SOURCES[node.nodeName];
	const additional = additionalAssetSources?.[node.nodeName];
	if (!defaults && !additional) return [];
	const attributes = {};
	for (const attr of node.attrs) attributes[getAttrKey(attr)] = attr.value;
	if ("vite-ignore" in attributes) return [{
		type: "remove",
		key: "vite-ignore",
		value: "",
		attributes,
		location: node.sourceCodeLocation.attrs["vite-ignore"]
	}];
	const actions = [];
	function handleAttributeKey(key, type, filter) {
		const value = attributes[key];
		if (!value) return;
		if (filter && !filter({
			key,
			value,
			attributes
		})) return;
		actions.push({
			type,
			key,
			value,
			attributes,
			location: node.sourceCodeLocation.attrs[key]
		});
	}
	if (defaults) {
		defaults.srcAttributes?.forEach((key) => handleAttributeKey(key, "src", defaults.filter));
		defaults.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset", defaults.filter));
	}
	if (additional) {
		additional.srcAttributes?.forEach((key) => handleAttributeKey(key, "src", additional.filter));
		additional.srcsetAttributes?.forEach((key) => handleAttributeKey(key, "srcset", additional.filter));
	}
	return actions;
}
function getAttrKey(attr) {
	return attr.prefix === void 0 ? attr.name : `${attr.prefix}:${attr.name}`;
}
//#endregion
//#region src/node/plugins/asset.ts
const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
const jsSourceMapRE = /\.[cm]?js\.map$/;
const noInlineRE = /[?&]no-inline\b/;
const inlineRE$3 = /[?&]inline\b/;
const assetCache = /* @__PURE__ */ new WeakMap();
/** a set of referenceId for entry CSS assets for each environment */
const cssEntriesMap = /* @__PURE__ */ new WeakMap();
function registerCustomMime() {
	mimes.ico = "image/x-icon";
	mimes.cur = "image/x-icon";
	mimes.flac = "audio/flac";
	mimes.eot = "application/vnd.ms-fontobject";
}
function renderAssetUrlInJS(pluginContext, chunk, opts, code) {
	const { environment } = pluginContext;
	const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, environment.config.isWorker);
	let match;
	let s;
	assetUrlRE.lastIndex = 0;
	while (match = assetUrlRE.exec(code)) {
		s ||= new MagicString(code);
		const [full, referenceId, postfix = ""] = match;
		const file = pluginContext.getFileName(referenceId);
		chunk.viteMetadata.importedAssets.add(cleanUrl(file));
		const replacement = toOutputFilePathInJS(environment, file + postfix, "asset", chunk.fileName, "js", toRelativeRuntime);
		const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
		s.update(match.index, match.index + full.length, replacementString);
	}
	const publicAssetUrlMap = publicAssetUrlCache.get(environment.getTopLevelConfig());
	publicAssetUrlRE.lastIndex = 0;
	while (match = publicAssetUrlRE.exec(code)) {
		s ||= new MagicString(code);
		const [full, hash] = match;
		const replacement = toOutputFilePathInJS(environment, publicAssetUrlMap.get(hash).slice(1), "public", chunk.fileName, "js", toRelativeRuntime);
		const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
		s.update(match.index, match.index + full.length, replacementString);
	}
	return s;
}
/**
* Also supports loading plain strings with import text from './foo.txt?raw'
*/
function assetPlugin(config) {
	registerCustomMime();
	return {
		name: "vite:asset",
		perEnvironmentStartEndDuringDev: true,
		buildStart() {
			assetCache.set(this.environment, /* @__PURE__ */ new Map());
			cssEntriesMap.set(this.environment, /* @__PURE__ */ new Map());
		},
		resolveId: {
			filter: { id: [
				urlRE$1,
				DEFAULT_ASSETS_RE,
				...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude).map((v) => typeof v === "string" ? pm.makeRe(v, { dot: true }) : v)
			] },
			handler(id) {
				if (!config.assetsInclude(cleanUrl(id)) && !urlRE$1.test(id)) return;
				if (checkPublicFile(id, config)) return id;
			}
		},
		load: {
			filter: { id: {
				include: [
					rawRE$1,
					urlRE$1,
					DEFAULT_ASSETS_RE,
					...makeIdFiltersToMatchWithQuery(config.rawAssetsInclude)
				],
				exclude: /^\0/
			} },
			async handler(id) {
				if (rawRE$1.test(id)) {
					const file = checkPublicFile(id, config) || cleanUrl(id);
					this.addWatchFile(file);
					return {
						code: `export default ${JSON.stringify(await fsp.readFile(file, "utf-8"))}`,
						map: { mappings: "" },
						moduleType: "js"
					};
				}
				if (!urlRE$1.test(id) && !config.assetsInclude(cleanUrl(id))) return;
				id = removeUrlQuery(id);
				let url = await fileToUrl$1(this, id);
				if (!url.startsWith("data:") && this.environment.mode === "dev") {
					const mod = this.environment.moduleGraph.getModuleById(id);
					if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
				}
				return {
					code: `export default ${JSON.stringify(encodeURIPath(url))}`,
					moduleSideEffects: config.command === "build" && this.getModuleInfo(id)?.isEntry ? "no-treeshake" : false,
					meta: config.command === "build" ? { "vite:asset": true } : void 0,
					moduleType: "js"
				};
			}
		},
		...config.command === "build" ? { renderChunk(code, chunk, opts) {
			const s = renderAssetUrlInJS(this, chunk, opts, code);
			if (s) return {
				code: s.toString(),
				map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
			};
			else return null;
		} } : {},
		generateBundle(_, bundle) {
			let importedFiles;
			for (const file in bundle) {
				const chunk = bundle[file];
				if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config.assetsInclude(chunk.moduleIds[0]) && this.getModuleInfo(chunk.moduleIds[0])?.meta["vite:asset"]) {
					if (!importedFiles) {
						importedFiles = /* @__PURE__ */ new Set();
						for (const file in bundle) {
							const chunk = bundle[file];
							if (chunk.type === "chunk") {
								for (const importedFile of chunk.imports) importedFiles.add(importedFile);
								for (const importedFile of chunk.dynamicImports) importedFiles.add(importedFile);
							}
						}
					}
					if (!importedFiles.has(file)) delete bundle[file];
				}
			}
			if (config.command === "build" && !this.environment.config.build.emitAssets) {
				for (const file in bundle) if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) delete bundle[file];
			}
		},
		watchChange(id) {
			assetCache.get(this.environment)?.delete(normalizePath(id));
		}
	};
}
async function fileToUrl$1(pluginContext, id, asFileUrl = false) {
	const { environment } = pluginContext;
	if (!environment.config.isBundled) return fileToDevUrl(environment, id, asFileUrl);
	else return fileToBuiltUrl(pluginContext, id);
}
async function fileToDevUrl(environment, id, asFileUrl = false) {
	const config = environment.getTopLevelConfig();
	const publicFile = checkPublicFile(id, config);
	if (inlineRE$3.test(id)) {
		const file = publicFile || cleanUrl(id);
		return assetToDataURL(environment, file, await fsp.readFile(file));
	}
	const cleanedId = cleanUrl(id);
	if (cleanedId.endsWith(".svg")) {
		const file = publicFile || cleanedId;
		const content = await fsp.readFile(file);
		if (shouldInline(environment, file, id, content, void 0, void 0)) return assetToDataURL(environment, file, content);
	}
	if (asFileUrl) return pathToFileURL(cleanedId).href;
	let rtn;
	if (publicFile) rtn = id;
	else if (id.startsWith(withTrailingSlash(config.root))) rtn = "/" + path.posix.relative(config.root, id);
	else rtn = path.posix.join(FS_PREFIX, id);
	return joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.decodedBase), removeLeadingSlash(rtn));
}
function getPublicAssetFilename(hash, config) {
	return publicAssetUrlCache.get(config)?.get(hash);
}
const publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
function publicFileToBuiltUrl(url, config) {
	if (config.command !== "build") return joinUrlSegments(config.decodedBase, url);
	const hash = getHash(url);
	let cache = publicAssetUrlCache.get(config);
	if (!cache) {
		cache = /* @__PURE__ */ new Map();
		publicAssetUrlCache.set(config, cache);
	}
	if (!cache.get(hash)) cache.set(hash, url);
	return `__VITE_PUBLIC_ASSET__${hash}__`;
}
const GIT_LFS_PREFIX = Buffer$1.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;
}
/**
* Register an asset to be emitted as part of the bundle (if necessary)
* and returns the resolved public URL
*/
async function fileToBuiltUrl(pluginContext, id, skipPublicCheck = false, forceInline) {
	const environment = pluginContext.environment;
	const topLevelConfig = environment.getTopLevelConfig();
	if (!skipPublicCheck) {
		const publicFile = checkPublicFile(id, topLevelConfig);
		if (publicFile) if (inlineRE$3.test(id)) id = publicFile;
		else return publicFileToBuiltUrl(id, topLevelConfig);
	}
	const cache = assetCache.get(environment);
	const cached = cache.get(id);
	if (cached) return cached;
	let { file, postfix } = splitFileAndPostfix(id);
	const content = await fsp.readFile(file);
	let url;
	if (shouldInline(environment, file, id, content, pluginContext, forceInline)) url = assetToDataURL(environment, file, content);
	else {
		const originalFileName = normalizePath(path.relative(environment.config.root, file));
		const referenceId = pluginContext.emitFile({
			type: "asset",
			name: path.basename(file),
			originalFileName,
			source: content
		});
		if (environment.config.command === "build" && noInlineRE.test(postfix)) postfix = postfix.replace(noInlineRE, "").replace(/^&/, "?");
		if (environment.config.command === "serve" && environment.config.isBundled) url = toOutputFilePathInJSForBundledDev(environment, pluginContext.getFileName(referenceId));
		else url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
	}
	cache.set(id, url);
	return url;
}
function toOutputFilePathInJSForBundledDev(environment, filename) {
	const outputUrl = toOutputFilePathInJS(environment, filename, "asset", "assets/dummy.js", "js", () => {
		throw new Error("unreachable");
	});
	if (typeof outputUrl === "object") throw new Error("unreachable");
	return outputUrl;
}
async function urlToBuiltUrl(pluginContext, url, importer, forceInline) {
	const topLevelConfig = pluginContext.environment.getTopLevelConfig();
	if (checkPublicFile(url, topLevelConfig)) return publicFileToBuiltUrl(url, topLevelConfig);
	return fileToBuiltUrl(pluginContext, normalizePath(url[0] === "/" ? path.join(topLevelConfig.root, url) : path.join(path.dirname(importer), url)), true, forceInline);
}
function shouldInline(environment, file, id, content, buildPluginContext, forceInline) {
	if (noInlineRE.test(id)) return false;
	if (inlineRE$3.test(id)) return true;
	if (buildPluginContext) {
		if (environment.config.build.lib) return true;
		if (buildPluginContext.getModuleInfo(id)?.isEntry) return false;
	}
	if (forceInline !== void 0) return forceInline;
	if (file.endsWith(".html")) return false;
	if (file.endsWith(".svg") && id.includes("#")) return false;
	let limit;
	const { assetsInlineLimit } = environment.config.build;
	if (typeof assetsInlineLimit === "function") {
		const userShouldInline = assetsInlineLimit(file, content);
		if (userShouldInline != null) return userShouldInline;
		limit = DEFAULT_ASSETS_INLINE_LIMIT;
	} else limit = Number(assetsInlineLimit);
	return content.length < limit && !isGitLfsPlaceholder(content);
}
function assetToDataURL(environment, file, content) {
	if (environment.config.build.lib && isGitLfsPlaceholder(content)) environment.logger.warn(import_picocolors.default.yellow(`Inlined file ${file} was not downloaded via Git LFS`));
	if (file.endsWith(".svg")) return svgToDataURL(content);
	else return `data:${lookup(file) ?? "application/octet-stream"};base64,${content.toString("base64")}`;
}
const 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");
}
//#endregion
//#region ../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js
var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const path$2 = __require("path");
	const fs$1 = __require("fs");
	const os$1 = __require("os");
	const url = __require("url");
	const fsReadFileAsync = fs$1.promises.readFile;
	/** @type {(name: string, sync: boolean) => string[]} */
	function getDefaultSearchPlaces(name, sync) {
		return [
			"package.json",
			`.${name}rc.json`,
			`.${name}rc.js`,
			`.${name}rc.cjs`,
			...sync ? [] : [`.${name}rc.mjs`],
			`.config/${name}rc`,
			`.config/${name}rc.json`,
			`.config/${name}rc.js`,
			`.config/${name}rc.cjs`,
			...sync ? [] : [`.config/${name}rc.mjs`],
			`${name}.config.js`,
			`${name}.config.cjs`,
			...sync ? [] : [`${name}.config.mjs`]
		];
	}
	/**
	* @type {(p: string) => string}
	*
	* see #17
	* On *nix, if cwd is not under homedir,
	* the last path will be '', ('/build' -> '')
	* but it should be '/' actually.
	* And on Windows, this will never happen. ('C:\build' -> 'C:')
	*/
	function parentDir(p) {
		return path$2.dirname(p) || path$2.sep;
	}
	/** @type {import('./index').LoaderSync} */
	const jsonLoader = (_, content) => JSON.parse(content);
	const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
	/** @type {import('./index').LoadersSync} */
	const defaultLoadersSync = Object.freeze({
		".js": requireFunc,
		".json": requireFunc,
		".cjs": requireFunc,
		noExt: jsonLoader
	});
	module.exports.defaultLoadersSync = defaultLoadersSync;
	/** @type {import('./index').Loader} */
	const dynamicImport = async (id) => {
		try {
			return (await import(
				/* webpackIgnore: true */
				url.pathToFileURL(id).href
)).default;
		} catch (e) {
			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 e;
				throw requireE;
			}
		}
	};
	/** @type {import('./index').Loaders} */
	const defaultLoaders = Object.freeze({
		".js": dynamicImport,
		".mjs": dynamicImport,
		".cjs": dynamicImport,
		".json": jsonLoader,
		noExt: jsonLoader
	});
	module.exports.defaultLoaders = defaultLoaders;
	/**
	* @param {string} name
	* @param {import('./index').Options | import('./index').OptionsSync} options
	* @param {boolean} sync
	* @returns {Required<import('./index').Options | import('./index').OptionsSync>}
	*/
	function getOptions(name, options, sync) {
		/** @type {Required<import('./index').Options>} */
		const conf = {
			stopDir: os$1.homedir(),
			searchPlaces: getDefaultSearchPlaces(name, sync),
			ignoreEmptySearchPlaces: true,
			cache: true,
			transform: (x) => x,
			packageProp: [name],
			...options,
			loaders: {
				...sync ? defaultLoadersSync : defaultLoaders,
				...options.loaders
			}
		};
		conf.searchPlaces.forEach((place) => {
			const key = path$2.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;
	}
	/** @type {(props: string | string[], obj: Record<string, any>) => unknown} */
	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;
	}
	/** @param {string} filepath */
	function validateFilePath(filepath) {
		if (!filepath) throw new Error("load must pass a non-empty string");
	}
	/** @type {(loader: import('./index').Loader, ext: string) => void} */
	function validateLoader(loader, ext) {
		if (!loader) throw new Error(`No loader specified for extension "${ext}"`);
		if (typeof loader !== "function") throw new Error("loader is not a function");
	}
	/** @type {(enableCache: boolean) => <T>(c: Map<string, T>, filepath: string, res: T) => T} */
	const makeEmplace = (enableCache) => (c, filepath, res) => {
		if (enableCache) c.set(filepath, res);
		return res;
	};
	/** @type {import('./index').lilconfig} */
	module.exports.lilconfig = function lilconfig(name, options) {
		const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, false);
		const searchCache = /* @__PURE__ */ new Map();
		const loadCache = /* @__PURE__ */ new Map();
		const emplace = makeEmplace(cache);
		return {
			async search(searchFrom = process.cwd()) {
				/** @type {import('./index').LilconfigResult} */
				const result = {
					config: null,
					filepath: ""
				};
				/** @type {Set<string>} */
				const visited = /* @__PURE__ */ new Set();
				let dir = searchFrom;
				dirLoop: while (true) {
					if (cache) {
						const r = searchCache.get(dir);
						if (r !== void 0) {
							for (const p of visited) searchCache.set(p, r);
							return r;
						}
						visited.add(dir);
					}
					for (const searchPlace of searchPlaces) {
						const filepath = path$2.join(dir, searchPlace);
						try {
							await fs$1.promises.access(filepath);
						} catch {
							continue;
						}
						const content = String(await fsReadFileAsync(filepath));
						const loaderKey = path$2.extname(searchPlace) || "noExt";
						const loader = loaders[loaderKey];
						if (searchPlace === "package.json") {
							const maybeConfig = getPackageProp(packageProp, await loader(filepath, content));
							if (maybeConfig != null) {
								result.config = maybeConfig;
								result.filepath = filepath;
								break dirLoop;
							}
							continue;
						}
						const isEmpty = content.trim() === "";
						if (isEmpty && ignoreEmptySearchPlaces) continue;
						if (isEmpty) {
							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 = result.filepath === "" && result.config === null ? transform(null) : transform(result);
				if (cache) for (const p of visited) searchCache.set(p, transformed);
				return transformed;
			},
			async load(filepath) {
				validateFilePath(filepath);
				const absPath = path$2.resolve(process.cwd(), filepath);
				if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
				const { base, ext } = path$2.parse(absPath);
				const loaderKey = ext || "noExt";
				const loader = loaders[loaderKey];
				validateLoader(loader, loaderKey);
				const content = String(await fsReadFileAsync(absPath));
				if (base === "package.json") return emplace(loadCache, absPath, transform({
					config: getPackageProp(packageProp, await loader(absPath, content)),
					filepath: absPath
				}));
				/** @type {import('./index').LilconfigResult} */
				const result = {
					config: null,
					filepath: absPath
				};
				const isEmpty = content.trim() === "";
				if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
					config: void 0,
					filepath: absPath,
					isEmpty: true
				}));
				result.config = isEmpty ? void 0 : await loader(absPath, content);
				return emplace(loadCache, absPath, transform(isEmpty ? {
					...result,
					isEmpty,
					config: void 0
				} : result));
			},
			clearLoadCache() {
				if (cache) loadCache.clear();
			},
			clearSearchCache() {
				if (cache) searchCache.clear();
			},
			clearCaches() {
				if (cache) {
					loadCache.clear();
					searchCache.clear();
				}
			}
		};
	};
	/** @type {import('./index').lilconfigSync} */
	module.exports.lilconfigSync = function lilconfigSync(name, options) {
		const { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, true);
		const searchCache = /* @__PURE__ */ new Map();
		const loadCache = /* @__PURE__ */ new Map();
		const emplace = makeEmplace(cache);
		return {
			search(searchFrom = process.cwd()) {
				/** @type {import('./index').LilconfigResult} */
				const result = {
					config: null,
					filepath: ""
				};
				/** @type {Set<string>} */
				const visited = /* @__PURE__ */ new Set();
				let dir = searchFrom;
				dirLoop: while (true) {
					if (cache) {
						const r = searchCache.get(dir);
						if (r !== void 0) {
							for (const p of visited) searchCache.set(p, r);
							return r;
						}
						visited.add(dir);
					}
					for (const searchPlace of searchPlaces) {
						const filepath = path$2.join(dir, searchPlace);
						try {
							fs$1.accessSync(filepath);
						} catch {
							continue;
						}
						const loaderKey = path$2.extname(searchPlace) || "noExt";
						const loader = loaders[loaderKey];
						const content = String(fs$1.readFileSync(filepath));
						if (searchPlace === "package.json") {
							const maybeConfig = getPackageProp(packageProp, loader(filepath, content));
							if (maybeConfig != null) {
								result.config = maybeConfig;
								result.filepath = filepath;
								break dirLoop;
							}
							continue;
						}
						const isEmpty = content.trim() === "";
						if (isEmpty && ignoreEmptySearchPlaces) continue;
						if (isEmpty) {
							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 = result.filepath === "" && result.config === null ? transform(null) : transform(result);
				if (cache) for (const p of visited) searchCache.set(p, transformed);
				return transformed;
			},
			load(filepath) {
				validateFilePath(filepath);
				const absPath = path$2.resolve(process.cwd(), filepath);
				if (cache && loadCache.has(absPath)) return loadCache.get(absPath);
				const { base, ext } = path$2.parse(absPath);
				const loaderKey = ext || "noExt";
				const loader = loaders[loaderKey];
				validateLoader(loader, loaderKey);
				const content = String(fs$1.readFileSync(absPath));
				if (base === "package.json") return transform({
					config: getPackageProp(packageProp, loader(absPath, content)),
					filepath: absPath
				});
				const result = {
					config: null,
					filepath: absPath
				};
				const isEmpty = content.trim() === "";
				if (isEmpty && ignoreEmptySearchPlaces) return emplace(loadCache, absPath, transform({
					filepath: absPath,
					config: void 0,
					isEmpty: true
				}));
				result.config = isEmpty ? void 0 : loader(absPath, content);
				return emplace(loadCache, absPath, transform(isEmpty ? {
					...result,
					isEmpty,
					config: void 0
				} : result));
			},
			clearLoadCache() {
				if (cache) loadCache.clear();
			},
			clearSearchCache() {
				if (cache) searchCache.clear();
			},
			clearCaches() {
				if (cache) {
					loadCache.clear();
					searchCache.clear();
				}
			}
		};
	};
}));
//#endregion
//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.16_tsx@4.22.4_yaml@2.9.0/node_modules/postcss-load-config/src/req.js
var require_req = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { createRequire: createRequire$1 } = __require("node:module");
	const { fileURLToPath: fileURLToPath$1, pathToFileURL: pathToFileURL$1 } = __require("node:url");
	const TS_EXT_RE = /\.[mc]?ts$/;
	let tsx;
	let jiti;
	let importError = [];
	/**
	* @param {string} name
	* @param {string} rootFile
	* @returns {Promise<any>}
	*/
	async function req(name, rootFile = fileURLToPath$1(import.meta.url)) {
		let url = createRequire$1(rootFile).resolve(name);
		try {
			return (await import(`${pathToFileURL$1(url)}?t=${Date.now()}`)).default;
		} catch (err) {
			if (!TS_EXT_RE.test(url))
 /* c8 ignore start */
			throw err;
		}
		if (tsx === void 0) try {
			tsx = await import("tsx/cjs/api");
		} catch (error) {
			importError.push(error);
		}
		if (tsx) {
			let loaded = tsx.require(name, rootFile);
			return loaded && "__esModule" in loaded ? loaded.default : loaded;
		}
		if (jiti === void 0) try {
			jiti = (await import("jiti")).default;
		} catch (error) {
			importError.push(error);
		}
		if (jiti) return jiti(rootFile, { interopDefault: true })(name);
		throw new Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error) => error.message).join("\n")}`);
	}
	module.exports = req;
}));
//#endregion
//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.16_tsx@4.22.4_yaml@2.9.0/node_modules/postcss-load-config/src/options.js
var require_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const req = require_req();
	/**
	* Load Options
	*
	* @private
	* @method options
	*
	* @param  {Object} config  PostCSS Config
	*
	* @return {Promise<Object>} options PostCSS Options
	*/
	async function options(config, file) {
		if (config.parser && typeof config.parser === "string") try {
			config.parser = await req(config.parser, file);
		} catch (err) {
			throw new Error(`Loading PostCSS Parser failed: ${err.message}\n\n(@${file})`);
		}
		if (config.syntax && typeof config.syntax === "string") try {
			config.syntax = await req(config.syntax, file);
		} catch (err) {
			throw new Error(`Loading PostCSS Syntax failed: ${err.message}\n\n(@${file})`);
		}
		if (config.stringifier && typeof config.stringifier === "string") try {
			config.stringifier = await req(config.stringifier, file);
		} catch (err) {
			throw new Error(`Loading PostCSS Stringifier failed: ${err.message}\n\n(@${file})`);
		}
		return config;
	}
	module.exports = options;
}));
//#endregion
//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.16_tsx@4.22.4_yaml@2.9.0/node_modules/postcss-load-config/src/plugins.js
var require_plugins = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const req = require_req();
	/**
	* Plugin Loader
	*
	* @private
	* @method load
	*
	* @param  {String} plugin PostCSS Plugin Name
	* @param  {Object} options PostCSS Plugin Options
	*
	* @return {Promise<Function>} PostCSS Plugin
	*/
	async function load(plugin, options, file) {
		try {
			if (options === null || options === void 0 || Object.keys(options).length === 0) return await req(plugin, file);
			else return (await req(plugin, file))(options);
		} catch (err) {
			throw new Error(`Loading PostCSS Plugin failed: ${err.message}\n\n(@${file})`);
		}
	}
	/**
	* Load Plugins
	*
	* @private
	* @method plugins
	*
	* @param {Object} config PostCSS Config Plugins
	*
	* @return {Promise<Array>} plugins PostCSS Plugins
	*/
	async function plugins(config, file) {
		let list = [];
		if (Array.isArray(config.plugins)) list = config.plugins.filter(Boolean);
		else {
			list = Object.entries(config.plugins).filter(([, options]) => {
				return options !== false;
			}).map(([plugin, options]) => {
				return load(plugin, options, file);
			});
			list = await Promise.all(list);
		}
		if (list.length && list.length > 0) list.forEach((plugin, i) => {
			if (plugin.default) plugin = plugin.default;
			if (plugin.postcss === true) plugin = plugin();
			else if (plugin.postcss) plugin = plugin.postcss;
			if (!(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}]\n\n(@${file})`);
		});
		return list;
	}
	module.exports = plugins;
}));
//#endregion
//#region ../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.16_tsx@4.22.4_yaml@2.9.0/node_modules/postcss-load-config/src/index.js
var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { resolve: resolve$3 } = __require("node:path");
	const config = require_src$1();
	const loadOptions = require_options();
	const loadPlugins = require_plugins();
	const req = require_req();
	const interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
	/**
	* Process the result from cosmiconfig
	*
	* @param  {Object} ctx Config Context
	* @param  {Object} result Cosmiconfig result
	*
	* @return {Promise<Object>} PostCSS Config
	*/
	async function processResult(ctx, result) {
		let file = result.filepath || "";
		let projectConfig = interopRequireDefault(result.config).default || {};
		if (typeof projectConfig === "function") projectConfig = projectConfig(ctx);
		else projectConfig = Object.assign({}, projectConfig, ctx);
		if (!projectConfig.plugins) projectConfig.plugins = [];
		let res = {
			file,
			options: await loadOptions(projectConfig, file),
			plugins: await loadPlugins(projectConfig, file)
		};
		delete projectConfig.plugins;
		return res;
	}
	/**
	* Builds the Config Context
	*
	* @param  {Object} ctx Config Context
	*
	* @return {Object} Config Context
	*/
	function createContext(ctx) {
		/**
		* @type {Object}
		*
		* @prop {String} cwd=process.cwd() Config search start location
		* @prop {String} env=process.env.NODE_ENV Config Enviroment, will be set to `development` by `postcss-load-config` if `process.env.NODE_ENV` is `undefined`
		*/
		ctx = Object.assign({
			cwd: process.cwd(),
			env: process.env.NODE_ENV
		}, ctx);
		if (!ctx.env) process.env.NODE_ENV = "development";
		return ctx;
	}
	async function loader(filepath) {
		return req(filepath);
	}
	let yaml;
	async function yamlLoader(_, content) {
		if (!yaml) try {
			yaml = await import("yaml");
		} catch (e) {
			/* c8 ignore start */
			throw new Error(`'yaml' is required for the YAML configuration files. Make sure it is installed\nError: ${e.message}`);
		}
		return yaml.parse(content);
	}
	/** @return {import('lilconfig').Options} */
	const withLoaders = (options = {}) => {
		let moduleName = "postcss";
		return {
			...options,
			loaders: {
				...options.loaders,
				".cjs": loader,
				".cts": loader,
				".js": loader,
				".mjs": loader,
				".mts": loader,
				".ts": loader,
				".yaml": yamlLoader,
				".yml": yamlLoader
			},
			searchPlaces: [
				...options.searchPlaces || [],
				"package.json",
				`.${moduleName}rc`,
				`.${moduleName}rc.json`,
				`.${moduleName}rc.yaml`,
				`.${moduleName}rc.yml`,
				`.${moduleName}rc.ts`,
				`.${moduleName}rc.cts`,
				`.${moduleName}rc.mts`,
				`.${moduleName}rc.js`,
				`.${moduleName}rc.cjs`,
				`.${moduleName}rc.mjs`,
				`${moduleName}.config.ts`,
				`${moduleName}.config.cts`,
				`${moduleName}.config.mts`,
				`${moduleName}.config.js`,
				`${moduleName}.config.cjs`,
				`${moduleName}.config.mjs`
			]
		};
	};
	/**
	* Load Config
	*
	* @method rc
	*
	* @param  {Object} ctx Config Context
	* @param  {String} path Config Path
	* @param  {Object} options Config Options
	*
	* @return {Promise} config PostCSS Config
	*/
	function rc(ctx, path, options) {
		/**
		* @type {Object} The full Config Context
		*/
		ctx = createContext(ctx);
		/**
		* @type {String} `process.cwd()`
		*/
		path = path ? resolve$3(path) : process.cwd();
		return config.lilconfig("postcss", withLoaders(options)).search(path).then((result) => {
			if (!result) throw new Error(`No PostCSS Config found in: ${path}`);
			return processResult(ctx, result);
		});
	}
	/**
	* 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
	*/
	module.exports = rc;
}));
//#endregion
//#region src/node/idResolver.ts
/**
* Some projects like Astro were overriding config.createResolver to add a custom
* alias plugin. For the client and ssr environments, we root through it to avoid
* breaking changes for now.
*/
function createBackCompatIdResolver(config, options) {
	const compatResolve = config.createResolver(options);
	let resolve;
	return async (environment, id, importer, aliasOnly) => {
		if (environment.name === "client" || environment.name === "ssr") return compatResolve(id, importer, aliasOnly, environment.name === "ssr");
		resolve ??= createIdResolver(config, options);
		return resolve(environment, id, importer, aliasOnly);
	};
}
/**
* Create an internal resolver to be used in special scenarios, e.g.
* optimizer and handling css @imports
*/
function createIdResolver(config, options) {
	const scan = options?.scan;
	const pluginContainerMap = /* @__PURE__ */ new Map();
	async function resolve(environment, id, importer) {
		let pluginContainer = pluginContainerMap.get(environment);
		if (!pluginContainer) {
			pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias }), ...oxcResolvePlugin({
				root: config.root,
				isProduction: config.isProduction,
				isBuild: config.command === "build",
				asSrc: true,
				preferRelative: false,
				tryIndex: true,
				...options,
				idOnly: true
			}, environment.config, true)], void 0, false);
			pluginContainerMap.set(environment, pluginContainer);
		}
		return await pluginContainer.resolveId(id, importer, { scan });
	}
	const aliasOnlyPluginContainerMap = /* @__PURE__ */ new Map();
	async function resolveAlias(environment, id, importer) {
		let pluginContainer = aliasOnlyPluginContainerMap.get(environment);
		if (!pluginContainer) {
			pluginContainer = await createEnvironmentPluginContainer(environment, [alias$1({ entries: environment.config.resolve.alias })], void 0, false);
			aliasOnlyPluginContainerMap.set(environment, pluginContainer);
		}
		return await pluginContainer.resolveId(id, importer, { scan });
	}
	return async (environment, id, importer, aliasOnly) => {
		return (await (aliasOnly ? resolveAlias : resolve)(environment, id, importer))?.id;
	};
}
//#endregion
//#region src/node/baseEnvironment.ts
const environmentColors = [
	import_picocolors.default.blue,
	import_picocolors.default.magenta,
	import_picocolors.default.green,
	import_picocolors.default.gray
];
var PartialEnvironment = class {
	name;
	getTopLevelConfig() {
		return this._topLevelConfig;
	}
	config;
	logger;
	/**
	* @internal
	*/
	_options;
	/**
	* @internal
	*/
	_topLevelConfig;
	constructor(name, topLevelConfig, options = topLevelConfig.environments[name]) {
		if (!/^[\w$]+$/.test(name)) throw new Error(`Invalid environment name "${name}". Environment names must only contain alphanumeric characters and "$", "_".`);
		this.name = name;
		this._topLevelConfig = topLevelConfig;
		this._options = options;
		this.config = new Proxy(options, { get: (target, prop) => {
			if (prop === "logger") return this.logger;
			if (prop in target) return this._options[prop];
			return this._topLevelConfig[prop];
		} });
		const environment = import_picocolors.default.dim(`(${this.name})`);
		const infoColor = environmentColors[[...this.name].reduce((acc, c) => acc + c.charCodeAt(0), 0) % environmentColors.length || 0];
		this.logger = {
			get hasWarned() {
				return topLevelConfig.logger.hasWarned;
			},
			info(msg, opts) {
				return topLevelConfig.logger.info(msg, {
					...opts,
					environment: infoColor(environment)
				});
			},
			warn(msg, opts) {
				return topLevelConfig.logger.warn(msg, {
					...opts,
					environment: import_picocolors.default.yellow(environment)
				});
			},
			warnOnce(msg, opts) {
				return topLevelConfig.logger.warnOnce(msg, {
					...opts,
					environment: import_picocolors.default.yellow(environment)
				});
			},
			error(msg, opts) {
				return topLevelConfig.logger.error(msg, {
					...opts,
					environment: import_picocolors.default.red(environment)
				});
			},
			clearScreen(type) {
				return topLevelConfig.logger.clearScreen(type);
			},
			hasErrorLogged(error) {
				return topLevelConfig.logger.hasErrorLogged(error);
			}
		};
	}
};
var BaseEnvironment = class extends PartialEnvironment {
	get plugins() {
		return this.config.plugins;
	}
	/**
	* @internal
	*/
	_initiated = false;
	constructor(name, config, options = config.environments[name]) {
		super(name, config, options);
	}
};
//#endregion
//#region src/node/server/searchRoot.ts
const ROOT_FILES = ["pnpm-workspace.yaml", "lerna.json"];
function hasWorkspacePackageJSON(root) {
	const path = join(root, "package.json");
	if (!isFileReadable(path)) return false;
	try {
		return !!(JSON.parse(fs.readFileSync(path, "utf-8")) || {}).workspaces;
	} catch {
		return false;
	}
}
function hasWorkspaceDenoJSON(root) {
	for (const name of ["deno.json", "deno.jsonc"]) {
		const path = join(root, name);
		if (!isFileReadable(path)) continue;
		try {
			if ((JSON.parse(fs.readFileSync(path, "utf-8")) || {}).workspace) return true;
		} catch {}
	}
	return false;
}
function hasRootFile(root) {
	return ROOT_FILES.some((file) => fs.existsSync(join(root, file)));
}
function hasPackageJSON(root) {
	const path = join(root, "package.json");
	return fs.existsSync(path);
}
/**
* Search up for the nearest `package.json`
*/
function searchForPackageRoot(current, root = current) {
	if (hasPackageJSON(current)) return current;
	const dir = dirname(current);
	if (!dir || dir === current) return root;
	return searchForPackageRoot(dir, root);
}
/**
* Search up for the nearest workspace root
*/
function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
	if (hasRootFile(current)) return current;
	if (hasWorkspacePackageJSON(current)) return current;
	if (hasWorkspaceDenoJSON(current)) return current;
	const dir = dirname(current);
	if (!dir || dir === current) return root;
	return searchForWorkspaceRoot(dir, root);
}
//#endregion
//#region src/node/plugins/manifest.ts
const endsWithJSRE = /\.[cm]?js$/;
function manifestPlugin() {
	const getState = perEnvironmentState(() => {
		return {
			manifest: {},
			outputCount: 0,
			reset() {
				this.manifest = {};
				this.outputCount = 0;
			}
		};
	});
	return perEnvironmentPlugin("native:manifest", (environment) => {
		if (!environment.config.build.manifest) return false;
		const root = environment.config.root;
		const outPath = environment.config.build.manifest === true ? ".vite/manifest.json" : environment.config.build.manifest;
		const envs = {};
		function getChunkName(chunk) {
			return getChunkOriginalFileName(chunk, root, false) ?? `_${path.basename(chunk.fileName)}`;
		}
		return [
			{
				name: "native:manifest-envs",
				buildStart() {
					envs[environment.name] = this.environment;
				}
			},
			viteManifestPlugin({
				root,
				outPath,
				isOutputOptionsForLegacyChunks: environment.config.isOutputOptionsForLegacyChunks,
				cssEntries() {
					return Object.fromEntries([...cssEntriesMap.get(envs[environment.name]).values()].map(({ name, referenceId }) => {
						return [referenceId, name];
					}));
				}
			}),
			{
				name: "native:manifest-compatible",
				generateBundle(_, bundle) {
					const asset = bundle[outPath];
					if (asset.type === "asset") {
						let manifest;
						for (const output of Object.values(bundle)) {
							const importedCss = output.viteMetadata?.importedCss;
							const importedAssets = output.viteMetadata?.importedAssets;
							if (!importedCss?.size && !importedAssets?.size) continue;
							manifest ??= JSON.parse(asset.source.toString());
							if (output.type === "chunk") {
								const item = manifest[getChunkName(output)];
								if (!item) continue;
								if (importedCss?.size) item.css = [...importedCss];
								if (importedAssets?.size) item.assets = [...importedAssets];
							} else if (output.type === "asset" && output.names.length > 0) {
								const keys = output.originalFileNames.length > 0 ? output.originalFileNames : [`_${path.basename(output.fileName)}`];
								for (const key of keys) {
									const item = manifest[key];
									if (!item) continue;
									if (!(item.file && endsWithJSRE.test(item.file))) {
										if (importedCss?.size) item.css = [...importedCss];
										if (importedAssets?.size) item.assets = [...importedAssets];
									}
								}
							}
						}
						const output = this.environment.config.build.rolldownOptions.output;
						const outputLength = Array.isArray(output) ? output.length : 1;
						if (manifest && outputLength === 1) {
							asset.source = JSON.stringify(manifest, void 0, 2);
							return;
						}
						const state = getState(this);
						state.outputCount++;
						state.manifest = Object.assign(state.manifest, manifest ?? JSON.parse(asset.source.toString()));
						if (state.outputCount >= outputLength) {
							asset.source = JSON.stringify(state.manifest, void 0, 2);
							state.reset();
						} else delete bundle[outPath];
					}
				}
			}
		];
	});
}
function getChunkOriginalFileName(chunk, root, isLegacy) {
	if (chunk.facadeModuleId) {
		let name = normalizePath(path.relative(root, chunk.facadeModuleId));
		if (isLegacy && !chunk.name.includes("-legacy")) {
			const ext = path.extname(name);
			const endPos = ext.length !== 0 ? -ext.length : void 0;
			name = `${name.slice(0, endPos)}-legacy${ext}`;
		}
		return name.replace(/\0/g, "");
	}
}
//#endregion
//#region src/node/plugins/css.ts
var import_src = /* @__PURE__ */ __toESM(require_src(), 1);
const decoder = new TextDecoder();
const _cssConfigDefaults = Object.freeze({
	/** @experimental */
	transformer: "postcss",
	preprocessorMaxWorkers: true,
	/** @experimental */
	devSourcemap: false
});
const cssConfigDefaults = _cssConfigDefaults;
function resolveCSSOptions(options) {
	const resolved = mergeWithDefaults(_cssConfigDefaults, options ?? {});
	if (resolved.transformer === "lightningcss") {
		resolved.lightningcss ??= {};
		resolved.lightningcss.targets ??= convertTargets(ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET);
	}
	return resolved;
}
const cssModuleRE = new RegExp(`\\.module${CSS_LANGS_RE.source}`);
const directRequestRE = /[?&]direct\b/;
const htmlProxyRE$1 = /[?&]html-proxy\b/;
const htmlProxyIndexRE = /&index=(\d+)/;
const commonjsProxyRE = /[?&]commonjs-proxy/;
const inlineRE$2 = /[?&]inline\b/;
const inlineCSSRE$1 = /[?&]inline-css\b/;
const styleAttrRE = /[?&]style-attr\b/;
const functionCallRE = /^[A-Z_][.\w-]*\(/i;
const transformOnlyRE = /[?&]transform-only\b/;
const nonEscapedDoubleQuoteRe = /(?<!\\)"/g;
const defaultCssBundleName = "style.css";
const isModuleCSSRequest = (request) => cssModuleRE.test(request);
const isDirectCSSRequest = (request) => CSS_LANGS_RE.test(request) && directRequestRE.test(request);
const isDirectRequest = (request) => directRequestRE.test(request);
const cssModulesCache = /* @__PURE__ */ new WeakMap();
const removedPureCssFilesCache = /* @__PURE__ */ new WeakMap();
const cssBundleNameCache = /* @__PURE__ */ new WeakMap();
const postcssConfigCache = /* @__PURE__ */ new WeakMap();
function encodePublicUrlsInCSS(config) {
	return config.command === "build";
}
const cssUrlAssetRE = /__VITE_CSS_URL__([\da-f]+)__/g;
/**
* Plugin applied before user plugins
*/
function cssPlugin(config) {
	const isBuild = config.command === "build";
	let moduleCache;
	const idResolver = createBackCompatIdResolver(config, {
		preferRelative: true,
		tryIndex: false,
		extensions: []
	});
	let preprocessorWorkerController;
	if (config.css.transformer !== "lightningcss") resolvePostcssConfig(config).catch(() => {});
	return {
		name: "vite:css",
		buildStart() {
			moduleCache = /* @__PURE__ */ new Map();
			cssModulesCache.set(config, moduleCache);
			removedPureCssFilesCache.set(config, /* @__PURE__ */ new Map());
			preprocessorWorkerController = createPreprocessorWorkerController(normalizeMaxWorkers(config.css.preprocessorMaxWorkers));
			preprocessorWorkerControllerCache.set(config, preprocessorWorkerController);
		},
		async buildEnd() {
			await preprocessorWorkerController?.close();
		},
		load: {
			filter: { id: CSS_LANGS_RE },
			handler(id) {
				if (urlRE$1.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")}__"`;
					}
				}
			}
		},
		transform: {
			filter: { id: {
				include: CSS_LANGS_RE,
				exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
			} },
			async handler(raw, id) {
				const { environment } = this;
				const resolveUrl = (url, importer) => idResolver(environment, url, importer);
				const urlResolver = async (url, importer) => {
					const decodedUrl = decodeURI(url);
					if (checkPublicFile(decodedUrl, config)) if (encodePublicUrlsInCSS(config)) return [publicFileToBuiltUrl(decodedUrl, config), void 0];
					else return [joinUrlSegments(joinUrlSegments(config.server.origin ?? "", config.base), decodedUrl), void 0];
					const [id, fragment] = decodedUrl.split("#");
					let resolved = await resolveUrl(id, importer);
					if (resolved) {
						if (fragment) resolved += "#" + fragment;
						let url = await fileToUrl$1(this, resolved);
						if (!url.startsWith("data:") && this.environment.mode === "dev") {
							const mod = [...this.environment.moduleGraph.getModulesByFile(resolved) ?? []].find((mod) => mod.type === "asset");
							if (mod?.lastHMRTimestamp) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
						}
						return [url, cleanUrl(resolved)];
					}
					if (config.command === "build") {
						if (!(config.build.rolldownOptions.external ? resolveUserExternal(config.build.rolldownOptions.external, decodedUrl, id, false) : false)) config.logger.warnOnce(`\n${decodedUrl} referenced in ${id} didn't resolve at build time, it will remain unchanged to be resolved at runtime`);
					}
					return [url, void 0];
				};
				const { code: css, modules, deps, map } = await compileCSS(environment, id, raw, preprocessorWorkerController, urlResolver);
				if (modules) moduleCache.set(id, modules);
				if (deps) for (const file of deps) this.addWatchFile(file);
				return {
					code: css,
					map
				};
			}
		}
	};
}
/**
* Plugin applied after user plugins
*/
function cssPostPlugin(config) {
	const styles = /* @__PURE__ */ new Map();
	let codeSplitEmitQueue = createSerialPromiseQueue();
	const urlEmitQueue = createSerialPromiseQueue();
	let pureCssChunks;
	let hasEmitted = false;
	let chunkCSSMap;
	const rolldownOptionsOutput = config.build.rolldownOptions.output;
	const assetFileNames = (Array.isArray(rolldownOptionsOutput) ? rolldownOptionsOutput[0] : rolldownOptionsOutput)?.assetFileNames;
	const getCssAssetDirname = (cssAssetName, originalFileName) => {
		const cssAssetNameDir = path.dirname(cssAssetName);
		if (!assetFileNames) return path.join(config.build.assetsDir, cssAssetNameDir);
		else if (typeof assetFileNames === "string") return path.join(path.dirname(assetFileNames), cssAssetNameDir);
		else return path.dirname(assetFileNames({
			type: "asset",
			name: cssAssetName,
			names: [cssAssetName],
			originalFileName,
			originalFileNames: originalFileName ? [originalFileName] : [],
			source: "/* vite internal call, ignore */"
		}));
	};
	function getCssBundleName() {
		const cached = cssBundleNameCache.get(config);
		if (cached) return cached;
		const cssBundleName = config.build.lib ? resolveLibCssFilename(config.build.lib, config.root, config.packageCache) : defaultCssBundleName;
		cssBundleNameCache.set(config, cssBundleName);
		return cssBundleName;
	}
	return {
		name: "vite:css-post",
		renderStart() {
			pureCssChunks = /* @__PURE__ */ new Set();
			hasEmitted = false;
			chunkCSSMap = /* @__PURE__ */ new Map();
			codeSplitEmitQueue = createSerialPromiseQueue();
		},
		transform: {
			filter: { id: {
				include: CSS_LANGS_RE,
				exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
			} },
			async handler(css, id) {
				css = stripBomTag(css);
				const inlineCSS = inlineCSSRE$1.test(id);
				const isHTMLProxy = htmlProxyRE$1.test(id);
				if (inlineCSS && isHTMLProxy) {
					if (styleAttrRE.test(id)) css = css.replace(/"/g, "&quot;");
					const index = htmlProxyIndexRE.exec(id)?.[1];
					if (index == null) throw new Error(`HTML proxy index in "${id}" not found`);
					addToHTMLProxyTransformResult(`${getHash(cleanUrl(id))}_${Number.parseInt(index)}`, css);
					return {
						code: `export default ''`,
						map: { mappings: "" }
					};
				}
				const inlined = inlineRE$2.test(id);
				const modules = cssModulesCache.get(config).get(id);
				const modulesCode = modules && !inlined && dataToEsm(modules, {
					namedExports: true,
					preferConst: true
				});
				if (config.command === "serve") {
					const getContentWithSourcemap = async (content) => {
						if (config.css.devSourcemap) {
							const sourcemap = this.getCombinedSourcemap();
							if (sourcemap.mappings) await injectSourcesContent(sourcemap, cleanUrl(id), config.logger);
							return getCodeWithSourcemap("css", content, sourcemap);
						}
						return content;
					};
					if (isDirectCSSRequest(id)) return null;
					if (inlined) return `export default ${JSON.stringify(css)}`;
					if (this.environment.config.consumer === "server") return modulesCode || "export {}";
					const cssContent = await getContentWithSourcemap(css);
					return {
						code: [
							this.environment.config.isBundled ? `const { updateStyle: __vite__updateStyle, removeStyle: __vite__removeStyle } = import.meta.hot._internal` : `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path.posix.join(config.base, CLIENT_PUBLIC_PATH))}`,
							`const __vite__id = ${JSON.stringify(id)}`,
							`const __vite__css = ${JSON.stringify(cssContent)}`,
							`__vite__updateStyle(__vite__id, __vite__css)`,
							`${modulesCode || "import.meta.hot.accept()"}`,
							`import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`
						].join("\n"),
						map: { mappings: "" },
						moduleType: "js"
					};
				}
				if (!inlined) styles.set(id, css);
				let code;
				if (modulesCode) code = modulesCode;
				else if (inlined) {
					let content = css;
					if (config.build.cssMinify) content = await minifyCSS(content, config, true, id);
					code = `export default ${JSON.stringify(content)}`;
				} else code = "";
				return {
					code,
					map: { mappings: "" },
					moduleSideEffects: modulesCode || inlined ? false : "no-treeshake",
					moduleType: "js"
				};
			}
		},
		...config.command === "build" ? {
			async renderChunk(code, chunk, opts, meta) {
				let chunkCSS;
				const renderedModules = new Proxy({}, { get(_target, p) {
					for (const name in meta.chunks) {
						const module = meta.chunks[name].modules[p];
						if (module) return module;
					}
				} });
				const isJsChunkEmpty = code === "" && !chunk.isEntry;
				let isPureCssChunk = chunk.exports.length === 0;
				const ids = Object.keys(chunk.modules);
				for (const id of ids) if (styles.has(id)) {
					if (transformOnlyRE.test(id)) continue;
					const cssScopeTo = this.getModuleInfo(id)?.meta?.vite?.cssScopeTo;
					if (cssScopeTo && !isCssScopeToRendered(cssScopeTo, renderedModules)) continue;
					if (cssModuleRE.test(id)) isPureCssChunk = false;
					chunkCSS = (chunkCSS || "") + styles.get(id);
				} else if (!isJsChunkEmpty) isPureCssChunk = false;
				const publicAssetUrlMap = publicAssetUrlCache.get(config);
				const resolveAssetUrlsInCss = (chunkCSS, cssAssetName, originalFileName) => {
					const encodedPublicUrls = encodePublicUrlsInCSS(config);
					const cssAssetDirname = encodedPublicUrls || config.base === "./" || config.base === "" ? slash(getCssAssetDirname(cssAssetName, originalFileName)) : void 0;
					const toRelative = (filename) => {
						const relativePath = normalizePath(path.relative(cssAssetDirname, filename));
						return relativePath[0] === "." ? relativePath : "./" + relativePath;
					};
					chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = "") => {
						const filename = this.getFileName(fileHash) + postfix;
						chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
						return encodeURIPath(toOutputFilePathInCss(filename, "asset", cssAssetName, "css", config, toRelative));
					});
					if (encodedPublicUrls) {
						const relativePathToPublicFromCSS = normalizePath(path.relative(cssAssetDirname, ""));
						chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
							const publicUrl = publicAssetUrlMap.get(hash).slice(1);
							return encodeURIPath(toOutputFilePathInCss(publicUrl, "public", cssAssetName, "css", config, () => `${relativePathToPublicFromCSS}/${publicUrl}`));
						});
					}
					return chunkCSS;
				};
				function ensureFileExt(name, ext) {
					return normalizePath(path.format({
						...path.parse(name),
						base: void 0,
						ext
					}));
				}
				let s;
				const urlEmitTasks = [];
				if (code.includes("__VITE_CSS_URL__")) {
					let match;
					cssUrlAssetRE.lastIndex = 0;
					while (match = cssUrlAssetRE.exec(code)) {
						const [full, idHex] = match;
						const id = Buffer.from(idHex, "hex").toString();
						const originalFileName = cleanUrl(id);
						const cssAssetName = ensureFileExt(path.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, originalFileName);
						urlEmitTasks.push({
							cssAssetName,
							originalFileName,
							content: cssContent,
							start: match.index,
							end: match.index + full.length
						});
					}
				}
				await urlEmitQueue.run(async () => Promise.all(urlEmitTasks.map(async (info) => {
					info.content = await finalizeCss(info.content, config);
				})));
				if (urlEmitTasks.length > 0) {
					const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker);
					s ||= new MagicString(code);
					for (const { cssAssetName, originalFileName, content, start, end } of urlEmitTasks) {
						const referenceId = this.emitFile({
							type: "asset",
							name: cssAssetName,
							originalFileName,
							source: content
						});
						const filename = this.getFileName(referenceId);
						chunk.viteMetadata.importedAssets.add(cleanUrl(filename));
						const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
						const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
						s.update(start, end, replacementString);
					}
				}
				if (chunkCSS !== void 0) {
					if (isPureCssChunk && (opts.format === "es" || opts.format === "cjs")) pureCssChunks.add(chunk);
					if (this.environment.config.build.cssCodeSplit) {
						if ((opts.format === "es" || opts.format === "cjs") && !chunk.fileName.includes("-legacy")) {
							const isEntry = chunk.isEntry && isPureCssChunk;
							const cssFullAssetName = ensureFileExt(chunk.name, ".css");
							const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path.basename(cssFullAssetName) : cssFullAssetName;
							const originalFileName = getChunkOriginalFileName(chunk, config.root, this.environment.config.isOutputOptionsForLegacyChunks?.(opts) ?? false);
							chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssAssetName, originalFileName);
							chunkCSS = await codeSplitEmitQueue.run(async () => {
								return finalizeCss(chunkCSS, config);
							});
							const referenceId = this.emitFile({
								type: "asset",
								name: cssAssetName,
								originalFileName,
								source: chunkCSS
							});
							if (isEntry) cssEntriesMap.get(this.environment).set(chunk.fileName, {
								referenceId,
								name: chunk.name
							});
							chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
						} else if (this.environment.config.consumer === "client") {
							chunkCSS = await finalizeCss(chunkCSS, config);
							let cssString = JSON.stringify(chunkCSS);
							cssString = renderAssetUrlInJS(this, chunk, opts, cssString)?.toString() || cssString;
							const style = `__vite_style__`;
							const injectCode = `var ${style} = document.createElement('style');${style}.textContent = ${cssString};document.head.appendChild(${style});`;
							s ||= new MagicString(code);
							injectInlinedCSS(s, this, code, opts.format, injectCode);
						}
					} else {
						chunkCSS = resolveAssetUrlsInCss(chunkCSS, getCssBundleName(), defaultCssBundleName);
						chunkCSSMap.set(chunk.fileName, chunkCSS);
					}
				}
				if (s) if (config.build.sourcemap) return {
					code: s.toString(),
					map: s.generateMap({ hires: "boundary" })
				};
				else return { code: s.toString() };
				return null;
			},
			augmentChunkHash(chunk) {
				if (chunk.viteMetadata?.importedCss.size) {
					let hash = "";
					for (const id of chunk.viteMetadata.importedCss) hash += id;
					return hash;
				}
			}
		} : {},
		async generateBundle(opts, bundle) {
			if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts)) return;
			if ((config.command !== "build" || this.environment.config.build.emitAssets) && !this.environment.config.build.cssCodeSplit && !hasEmitted) {
				let extractedCss = "";
				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));
					extractedCss += 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]);
				if (extractedCss) {
					hasEmitted = true;
					extractedCss = await finalizeCss(extractedCss, config);
					this.emitFile({
						name: getCssBundleName(),
						type: "asset",
						source: extractedCss,
						originalFileName: defaultCssBundleName
					});
				}
			}
			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((file) => {
							if (pureCssChunkNames.includes(file)) {
								const { importedCss, importedAssets } = bundle[file].viteMetadata;
								importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
								importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
								chunkImportsPureCssChunk = true;
								return false;
							}
							return true;
						});
						if (chunkImportsPureCssChunk) chunk.code = replaceEmptyChunk(chunk.code);
					}
				}
				const removedPureCssFiles = removedPureCssFilesCache.get(config);
				pureCssChunkNames.forEach((fileName) => {
					const emptyJsPlaceholder = bundle[fileName];
					if (emptyJsPlaceholder.isEntry) {
						const { importedAssets, importedCss } = emptyJsPlaceholder.viteMetadata;
						const cssReferenceId = cssEntriesMap.get(this.environment).get(emptyJsPlaceholder.preliminaryFileName).referenceId;
						const realCssEntryName = this.getFileName(cssReferenceId);
						const realCssEntry = bundle[realCssEntryName];
						importedCss.delete(realCssEntryName);
						if (importedAssets.size) realCssEntry.viteMetadata.importedAssets = importedAssets;
						if (importedCss.size) realCssEntry.viteMetadata.importedCss = importedCss;
					}
					removedPureCssFiles.set(fileName, emptyJsPlaceholder);
					delete bundle[fileName];
					delete bundle[`${fileName}.map`];
				});
			}
			const cssAssets = Object.values(bundle).filter((asset) => asset.type === "asset" && asset.fileName.endsWith(".css"));
			for (const cssAsset of cssAssets) if (typeof cssAsset.source === "string") cssAsset.source = cssAsset.source.replace(viteHashUpdateMarkerRE, "");
		}
	};
}
function injectInlinedCSS(s, ctx, code, format, injectCode) {
	let injectionPoint;
	if (format === "iife" || format === "umd") {
		const m = (format === "iife" ? IIFE_BEGIN_RE : UMD_BEGIN_RE).exec(code);
		if (!m) ctx.error("Injection point for inlined CSS not found");
		injectionPoint = m.index + m[0].length;
	} else if (format === "es") if (code.startsWith("#!")) {
		const newlinePos = code.indexOf("\n");
		if (newlinePos === -1) {
			s.append(`\n${injectCode}`);
			return;
		}
		injectionPoint = newlinePos + 1;
	} else injectionPoint = 0;
	else ctx.error("Non supported format");
	s.appendRight(injectionPoint, injectCode);
}
function cssAnalysisPlugin(config) {
	return {
		name: "vite:css-analysis",
		applyToEnvironment(environment) {
			return !environment.config.isBundled;
		},
		transform: {
			filter: { id: {
				include: CSS_LANGS_RE,
				exclude: [commonjsProxyRE, SPECIAL_QUERY_RE]
			} },
			handler(_, id) {
				const { moduleGraph } = this.environment;
				const thisModule = moduleGraph.getModuleById(id);
				if (thisModule) {
					const isSelfAccepting = !cssModulesCache.get(config)?.get(id) && !inlineRE$2.test(id) && !htmlProxyRE$1.test(id);
					const pluginImports = this._addedImports;
					if (pluginImports) {
						const depModules = /* @__PURE__ */ new Set();
						for (const file of pluginImports) depModules.add(moduleGraph.createFileOnlyEntry(file));
						moduleGraph.updateModuleInfo(thisModule, depModules, null, /* @__PURE__ */ new Set(), null, isSelfAccepting);
					} else thisModule.isSelfAccepting = isSelfAccepting;
				}
			}
		}
	};
}
function isCssScopeToRendered(cssScopeTo, renderedModules) {
	const [importerId, exp] = cssScopeTo;
	const importer = renderedModules[importerId];
	return importer && (exp === void 0 || importer.renderedExports.includes(exp));
}
/**
* Create a replacer function that takes code and replaces given pure CSS chunk imports
* @param pureCssChunkNames The chunks that only contain pure CSS and should be replaced
* @param outputFormat The module output format to decide whether to replace `import` or `require`
*/
function getEmptyChunkReplacer(pureCssChunkNames, outputFormat) {
	const emptyChunkFiles = pureCssChunkNames.map((file) => escapeRegex(path.basename(file))).join("|");
	const emptyChunkRE = new RegExp(outputFormat === "es" ? `\\bimport\\s*["'][^"']*(?:${emptyChunkFiles})["'];` : `(\\b|,\\s*)require\\(\\s*["'\`][^"'\`]*(?:${emptyChunkFiles})["'\`]\\)(;|,)`, "g");
	return (code) => code.replace(emptyChunkRE, (m, p1, p2) => {
		if (outputFormat === "es") return `/* empty css ${"".padEnd(m.length - 15)}*/`;
		if (p2 === ";") return `${p2}/* empty css ${"".padEnd(m.length - 16)}*/`;
		return `${p1}/* empty css ${"".padEnd(m.length - 15 - p1.length)}*/`;
	});
}
const fileURLWithWindowsDriveRE = /^file:\/\/\/[a-zA-Z]:\//;
function createCSSResolvers(config) {
	let cssResolve;
	let sassResolve;
	let lessResolve;
	return {
		get css() {
			return cssResolve ??= createBackCompatIdResolver(config, {
				extensions: [".css"],
				mainFields: ["style"],
				conditions: ["style", DEV_PROD_CONDITION],
				tryIndex: false,
				preferRelative: true
			});
		},
		get sass() {
			if (!sassResolve) {
				const resolver = createBackCompatIdResolver(config, {
					extensions: [
						".scss",
						".sass",
						".css"
					],
					mainFields: ["sass", "style"],
					conditions: [
						"sass",
						"style",
						DEV_PROD_CONDITION
					],
					tryIndex: true,
					tryPrefix: "_",
					preferRelative: true,
					skipMainField: true
				});
				sassResolve = async (...args) => {
					if (args[1].startsWith("file://")) args[1] = fileURLToPath(args[1], { windows: isWindows && !fileURLWithWindowsDriveRE.test(args[1]) ? false : void 0 });
					return resolver(...args);
				};
			}
			return sassResolve;
		},
		get less() {
			return lessResolve ??= createBackCompatIdResolver(config, {
				extensions: [".less", ".css"],
				mainFields: ["less", "style"],
				conditions: [
					"less",
					"style",
					DEV_PROD_CONDITION
				],
				tryIndex: false,
				preferRelative: true
			});
		}
	};
}
function getCssResolversKeys(resolvers) {
	return Object.keys(resolvers);
}
async function compileCSSPreprocessors(environment, id, lang, code, workerController) {
	const { config } = environment;
	const { preprocessorOptions, devSourcemap } = config.css;
	const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
	const opts = {
		...preprocessorOptions && preprocessorOptions[lang] || {},
		filename: cleanUrl(id),
		enableSourcemap: devSourcemap ?? false
	};
	const preProcessor = workerController[lang];
	const preprocessResult = await preProcessor(environment, code, config.root, opts, atImportResolvers);
	if (preprocessResult.error) throw preprocessResult.error;
	let deps;
	if (preprocessResult.deps.length > 0) {
		const normalizedFilename = normalizePath(opts.filename);
		deps = new Set([...preprocessResult.deps].filter((dep) => normalizePath(dep) !== normalizedFilename));
	}
	return {
		code: preprocessResult.code,
		map: combineSourcemapsIfExists(opts.filename, preprocessResult.map, preprocessResult.additionalMap),
		deps
	};
}
const configToAtImportResolvers = /* @__PURE__ */ new WeakMap();
function getAtImportResolvers(config) {
	let atImportResolvers = configToAtImportResolvers.get(config);
	if (!atImportResolvers) {
		atImportResolvers = createCSSResolvers(config);
		configToAtImportResolvers.set(config, atImportResolvers);
	}
	return atImportResolvers;
}
async function compileCSS(environment, id, code, workerController, urlResolver) {
	const { config } = environment;
	const lang = CSS_LANGS_RE.exec(id)?.[1];
	const deps = /* @__PURE__ */ new Set();
	let preprocessorMap;
	if (isPreProcessor(lang)) {
		const preprocessorResult = await compileCSSPreprocessors(environment, id, lang, code, workerController);
		code = preprocessorResult.code;
		preprocessorMap = preprocessorResult.map;
		preprocessorResult.deps?.forEach((dep) => deps.add(dep));
	} else if (lang === "sss" && config.css.transformer === "lightningcss") {
		const sssResult = await transformSugarSS(environment, id, code);
		code = sssResult.code;
		preprocessorMap = sssResult.map;
	}
	const transformResult = await (config.css.transformer === "lightningcss" ? compileLightningCSS(environment, id, code, deps, workerController, urlResolver) : compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver));
	if (!transformResult) return {
		code,
		map: config.css.devSourcemap ? preprocessorMap : { mappings: "" },
		deps
	};
	return {
		...transformResult,
		map: config.css.devSourcemap ? combineSourcemapsIfExists(cleanUrl(id), typeof transformResult.map === "string" ? JSON.parse(transformResult.map) : transformResult.map, preprocessorMap) : { mappings: "" },
		deps
	};
}
async function compilePostCSS(environment, id, code, deps, lang, workerController, urlResolver) {
	const { config } = environment;
	const { modules: modulesOptions, devSourcemap } = config.css;
	const isModule = modulesOptions !== false && cssModuleRE.test(id);
	const needInlineImport = code.includes("@import");
	const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code);
	const postcssConfig = await resolvePostcssConfig(environment.getTopLevelConfig());
	if (lang !== "sss" && !postcssConfig && !isModule && !needInlineImport && !hasUrl) return;
	const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
	const postcssPlugins = postcssConfig?.plugins.slice() ?? [];
	if (needInlineImport) postcssPlugins.unshift((await importPostcssImport()).default({
		async resolve(id, basedir, _importOptions, atRule) {
			const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
			if (publicFile) return publicFile;
			const resolved = await atImportResolvers.css(environment, id, atRule.source?.input.file);
			if (resolved) return path.resolve(resolved);
			if (!path.isAbsolute(id)) environment.logger.error(import_picocolors.default.red(`Unable to resolve \`@import "${id}"\` from ${basedir}`));
			return id;
		},
		async load(id) {
			const code = await fs.promises.readFile(id, "utf-8");
			const lang = CSS_LANGS_RE.exec(id)?.[1];
			if (isPreProcessor(lang)) {
				const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
				result.deps?.forEach((dep) => deps.add(dep));
				return result.code;
			}
			return code;
		},
		nameLayer(index) {
			return `vite--anon-layer-${getHash(id)}-${index}`;
		}
	}));
	if (urlResolver && (postcssPlugins.length > 0 || isModule || hasUrl)) postcssPlugins.push(UrlRewritePostcssPlugin({
		resolver: urlResolver,
		deps,
		logger: environment.logger
	}));
	let modules;
	if (isModule) postcssPlugins.unshift((await importPostcssModules()).default({
		...modulesOptions,
		localsConvention: modulesOptions?.localsConvention,
		getJSON(cssFileName, _modules, outputFileName) {
			modules = _modules;
			if (modulesOptions && typeof modulesOptions.getJSON === "function") modulesOptions.getJSON(cssFileName, _modules, outputFileName);
		},
		async resolve(id, importer) {
			for (const key of getCssResolversKeys(atImportResolvers)) {
				const resolved = await atImportResolvers[key](environment, id, importer);
				if (resolved) return path.resolve(resolved);
			}
			return id;
		}
	}));
	const postcssOptions = postcssConfig?.options ?? {};
	const postcssParser = lang === "sss" ? await loadSss(config.root) : postcssOptions.parser;
	if (!postcssPlugins.length && !postcssParser) return;
	return {
		...await runPostCSS(id, code, postcssPlugins, {
			...postcssOptions,
			parser: postcssParser
		}, deps, environment.logger, devSourcemap),
		modules
	};
}
async function transformSugarSS(environment, id, code) {
	const { config } = environment;
	const { devSourcemap } = config.css;
	return await runPostCSS(id, code, [], { parser: await loadSss(config.root) }, void 0, environment.logger, devSourcemap);
}
async function runPostCSS(id, code, plugins, options, deps, logger, enableSourcemap) {
	let postcssResult;
	try {
		const source = removeDirectQuery(id);
		postcssResult = await (await importPostcss()).default(plugins).process(code, {
			...options,
			to: source,
			from: source,
			...enableSourcemap ? { map: {
				inline: false,
				annotation: false,
				sourcesContent: true
			} } : {}
		});
		for (const message of postcssResult.messages) if (message.type === "dependency") deps?.add(normalizePath(message.file));
		else if (message.type === "dir-dependency") {
			const { dir, glob: globPattern = "**" } = message;
			const files = globSync(globPattern, {
				absolute: true,
				cwd: path.resolve(path.dirname(id), dir),
				expandDirectories: false,
				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][postcss] ${warning.text}`;
			msg += `\n${generateCodeFrame(code, {
				line: warning.line,
				column: warning.column - 1
			}, warning.endLine !== void 0 && warning.endColumn !== void 0 ? {
				line: warning.endLine,
				column: warning.endColumn - 1
			} : void 0)}`;
			logger.warn(import_picocolors.default.yellow(msg));
		}
	} catch (e) {
		e.message = `[postcss] ${e.message}`;
		e.code = code;
		e.loc = {
			file: e.file,
			line: e.line,
			column: e.column - 1
		};
		throw e;
	}
	if (!enableSourcemap) return {
		code: postcssResult.css,
		map: { mappings: "" }
	};
	const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), cleanUrl(id));
	return {
		code: postcssResult.css,
		map: postcssMap
	};
}
function createCachedImport(imp) {
	let cached;
	return () => {
		if (!cached) cached = imp().then((module) => {
			cached = module;
			return module;
		});
		return cached;
	};
}
const importPostcssImport = createCachedImport(() => import("./postcss-import.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
const importPostcssModules = createCachedImport(() => import("./build.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)));
const importPostcss = createCachedImport(() => import("postcss"));
const preprocessorWorkerControllerCache = /* @__PURE__ */ new WeakMap();
let alwaysFakeWorkerWorkerControllerCache;
/**
* @experimental
*/
async function preprocessCSS(code, filename, config) {
	let workerController = preprocessorWorkerControllerCache.get(config);
	if (!workerController) {
		alwaysFakeWorkerWorkerControllerCache ||= createPreprocessorWorkerController(0);
		workerController = alwaysFakeWorkerWorkerControllerCache;
	}
	return await compileCSS(new PartialEnvironment("client", config), filename, code, workerController);
}
async function formatPostcssSourceMap(rawMap, file) {
	const inputFileDir = path.dirname(file);
	const sources = rawMap.sources.map((source) => {
		const cleanSource = cleanUrl(decodeURIComponent(source));
		if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
		return normalizePath(path.resolve(inputFileDir, cleanSource));
	});
	return {
		file,
		mappings: rawMap.mappings,
		names: rawMap.names,
		sources,
		sourcesContent: rawMap.sourcesContent,
		version: rawMap.version
	};
}
function combineSourcemapsIfExists(filename, map1, map2) {
	if (!map1 || !map2) return map1;
	if (map1.mappings === "" || map2.mappings === "") return { mappings: "" };
	return combineSourcemaps(filename, [map1, map2]);
}
const viteHashUpdateMarker = "/*$vite$:1*/";
const viteHashUpdateMarkerRE = /\/\*\$vite\$:\d+\*\//;
async function finalizeCss(css, config) {
	if (css.includes("@import") || css.includes("@charset")) css = hoistAtRules(css);
	if (config.build.cssMinify) css = await minifyCSS(css, config, false);
	css += viteHashUpdateMarker;
	return css;
}
async function resolvePostcssConfig(config) {
	let result = postcssConfigCache.get(config);
	if (result !== void 0) return await result;
	const inlineOptions = config.css.postcss;
	if (isObject$1(inlineOptions)) {
		const options = { ...inlineOptions };
		delete options.plugins;
		result = {
			options,
			plugins: inlineOptions.plugins || []
		};
	} else {
		const searchPath = typeof inlineOptions === "string" ? inlineOptions : config.root;
		result = (0, import_src.default)({}, searchPath, { stopDir: searchForWorkspaceRoot(config.root) }).catch((e) => {
			if (!e.message.includes("No PostCSS Config found")) if (e instanceof Error) {
				const { name, message, stack } = e;
				e.name = "Failed to load PostCSS config";
				e.message = `Failed to load PostCSS config (searchPath: ${searchPath}): [${name}] ${message}\n${stack}`;
				e.stack = "";
				throw e;
			} else throw new Error(`Failed to load PostCSS config: ${e}`);
			return null;
		});
		result.then((resolved) => {
			postcssConfigCache.set(config, resolved);
		}, () => {});
	}
	postcssConfigCache.set(config, result);
	return result;
}
const cssUrlRE = /(?<!@import\s+)(?<=^|[^\w\-\u0080-\uffff])url\((\s*('[^']+'|"[^"]+")\s*|(?:\\.|[^'")\\])+)\)/;
const cssDataUriRE = /(?<=^|[^\w\-\u0080-\uffff])data-uri\((\s*('[^']+'|"[^"]+")\s*|[^'")]+)\)/;
const importCssRE = /@import\s+(?:url\()?('[^']+\.css'|"[^"]+\.css"|[^'"\s)]+\.css)/;
const cssImageSetRE = /(?<=image-set\()((?:[\w-]{1,256}\([^)]*\)|[^)])*)(?=\))/;
const UrlRewritePostcssPlugin = (opts) => {
	if (!opts) throw new Error("base or replace is required");
	return {
		postcssPlugin: "vite-url-rewrite",
		Once(root) {
			const promises = [];
			root.walkDecls((declaration) => {
				const importer = declaration.source?.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 = async (rawUrl) => {
						const [newUrl, resolvedId] = await opts.resolver(rawUrl, importer);
						if (resolvedId) opts.deps.add(resolvedId);
						return newUrl;
					};
					if (isCssUrl && isCssImageSet) promises.push(rewriteCssUrls(declaration.value, replacerForDeclaration).then((url) => rewriteCssImageSet(url, replacerForDeclaration)).then((url) => {
						declaration.value = url;
					}));
					else promises.push((isCssImageSet ? rewriteCssImageSet : rewriteCssUrls)(declaration.value, replacerForDeclaration).then((url) => {
						declaration.value = url;
					}));
				}
			});
			if (promises.length) return Promise.all(promises);
		}
	};
};
UrlRewritePostcssPlugin.postcss = true;
function rewriteCssUrls(css, replacer) {
	return asyncReplace(css, cssUrlRE, async (match) => {
		const [matched, rawUrl] = match;
		return await doUrlReplace(rawUrl.trim(), matched, replacer);
	});
}
function rewriteCssDataUris(css, replacer) {
	return asyncReplace(css, cssDataUriRE, async (match) => {
		const [matched, rawUrl] = match;
		return await doUrlReplace(rawUrl.trim(), matched, replacer, "data-uri");
	});
}
function rewriteImportCss(css, replacer) {
	return asyncReplace(css, importCssRE, async (match) => {
		const [matched, rawUrl] = match;
		return await doImportCSSReplace(rawUrl, matched, replacer);
	});
}
const cssNotProcessedRE = /(?:gradient|element|cross-fade|image)\(/;
async function rewriteCssImageSet(css, replacer) {
	return await asyncReplace(css, cssImageSetRE, async (match) => {
		const [, rawUrl] = match;
		return await processSrcSet(rawUrl, async ({ url }) => {
			if (cssUrlRE.test(url)) return await rewriteCssUrls(url, replacer);
			if (!cssNotProcessedRE.test(url)) return await doUrlReplace(url, url, replacer);
			return url;
		});
	});
}
function skipUrlReplacer(unquotedUrl) {
	return isExternalUrl(unquotedUrl) || isDataUrl(unquotedUrl) || unquotedUrl[0] === "#" || functionCallRE.test(unquotedUrl) || unquotedUrl.startsWith("__VITE_ASSET__") || unquotedUrl.startsWith("__VITE_PUBLIC_ASSET__");
}
async function doUrlReplace(rawUrl, matched, replacer, funcName = "url") {
	let wrap = "";
	const first = rawUrl[0];
	let unquotedUrl = rawUrl;
	if (first === `"` || first === `'`) {
		wrap = first;
		unquotedUrl = rawUrl.slice(1, -1);
	}
	if (skipUrlReplacer(unquotedUrl)) return matched;
	unquotedUrl = unquotedUrl.replace(/\\(\W)/g, "$1");
	let newUrl = await replacer(unquotedUrl, rawUrl);
	if (newUrl === false) return matched;
	if (wrap === "" && (newUrl !== encodeURI(newUrl) || newUrl.includes(")"))) wrap = "\"";
	if (wrap === "'" && newUrl.includes("'")) wrap = "\"";
	if (wrap === "\"" && newUrl.includes("\"")) newUrl = newUrl.replace(nonEscapedDoubleQuoteRe, "\\\"");
	return `${funcName}(${wrap}${newUrl}${wrap})`;
}
async function doImportCSSReplace(rawUrl, matched, replacer) {
	let wrap = "";
	const first = rawUrl[0];
	let unquotedUrl = rawUrl;
	if (first === `"` || first === `'`) {
		wrap = first;
		unquotedUrl = rawUrl.slice(1, -1);
	}
	if (skipUrlReplacer(unquotedUrl)) return matched;
	const newUrl = await replacer(unquotedUrl, rawUrl);
	if (newUrl === false) return matched;
	return `@import ${matched.includes("url(") ? "url(" : ""}${wrap}${newUrl}${wrap}`;
}
async function minifyCSS(css, config, inlined, filename = defaultCssBundleName) {
	if (config.build.cssMinify === "esbuild") {
		const { transform, formatMessages } = await importEsbuild();
		try {
			const { code, warnings } = await transform(css, {
				loader: "css",
				target: config.build.cssTarget || void 0,
				sourcefile: filename,
				...resolveMinifyCssEsbuildOptions(config.esbuild || {})
			});
			if (warnings.length) {
				const msgs = await formatMessages(warnings, { kind: "warning" });
				config.logger.warn(import_picocolors.default.yellow(`[esbuild css minify]\n${msgs.join("\n")}`));
			}
			return inlined ? code.trimEnd() : code;
		} catch (e) {
			if (e.errors) {
				e.message = "[esbuild css minify] " + e.message;
				e.frame = "\n" + (await formatMessages(e.errors, { kind: "error" })).join("\n");
				e.loc = e.errors[0].location;
			}
			throw e;
		}
	}
	try {
		const { code, warnings } = (await importLightningCSS()).transform({
			...config.css.lightningcss,
			targets: convertTargets(config.build.cssTarget),
			cssModules: void 0,
			filename,
			code: Buffer.from(css),
			minify: true
		});
		for (const warning of warnings) {
			let msg = `[lightningcss minify] ${warning.message}`;
			msg += `\n${generateCodeFrame(css, {
				line: warning.loc.line,
				column: warning.loc.column - 1
			})}`;
			config.logger.warn(import_picocolors.default.yellow(msg));
		}
		return decoder.decode(code) + (inlined ? "" : "\n");
	} catch (e) {
		e.message = `[lightningcss minify] ${e.message}`;
		const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(css);
		if (friendlyMessage) e.message += friendlyMessage;
		if (e.loc) {
			e.loc = {
				line: e.loc.line,
				column: e.loc.column - 1
			};
			e.frame = generateCodeFrame(css, e.loc);
		}
		throw e;
	}
}
function resolveMinifyCssEsbuildOptions(options) {
	const base = {
		charset: options.charset,
		logLevel: options.logLevel,
		logLimit: options.logLimit,
		logOverride: options.logOverride,
		legalComments: options.legalComments
	};
	if (options.minifyIdentifiers != null || options.minifySyntax != null || options.minifyWhitespace != null) return {
		...base,
		minifyIdentifiers: options.minifyIdentifiers ?? true,
		minifySyntax: options.minifySyntax ?? true,
		minifyWhitespace: options.minifyWhitespace ?? true
	};
	else return {
		...base,
		minify: true
	};
}
const atImportRE = /@import(?:\s*(?:url\([^)]*\)|"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
const atCharsetRE = /@charset(?:\s*(?:"(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*').*?|[^;]*);/g;
function hoistAtRules(css) {
	const s = new MagicString(css);
	const cleanCss = emptyCssComments(css);
	let match;
	atImportRE.lastIndex = 0;
	while (match = atImportRE.exec(cleanCss)) {
		s.remove(match.index, match.index + match[0].length);
		s.appendLeft(0, match[0]);
	}
	atCharsetRE.lastIndex = 0;
	let foundCharset = false;
	while (match = atCharsetRE.exec(cleanCss)) {
		s.remove(match.index, match.index + match[0].length);
		if (!foundCharset) {
			s.prepend(match[0]);
			foundCharset = true;
		}
	}
	return s.toString();
}
const loadedPreprocessorPath = {};
function loadPreprocessorPath(lang, root) {
	const cached = loadedPreprocessorPath[lang];
	if (cached) return cached;
	const resolved = nodeResolveWithVite(lang, void 0, { root }) ?? nodeResolveWithVite(lang, _dirname, { root });
	if (resolved) return loadedPreprocessorPath[lang] = resolved;
	const installCommand = getPackageManagerCommand("install");
	throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it? Try \`${installCommand} -D ${lang}\`.`);
}
function loadSassPackage(root, skipEmbedded = false) {
	if (!skipEmbedded) try {
		return {
			name: "sass-embedded",
			path: loadPreprocessorPath("sass-embedded", root)
		};
	} catch (e1) {
		try {
			return {
				name: "sass",
				path: loadPreprocessorPath("sass", root)
			};
		} catch {
			throw e1;
		}
	}
	return {
		name: "sass",
		path: loadPreprocessorPath("sass", root)
	};
}
let cachedSss;
async function loadSss(root) {
	if (!cachedSss) cachedSss = (async () => {
		return cachedSss = (await import(pathToFileURL(loadPreprocessorPath("sugarss", root)).href)).default;
	})();
	return cachedSss;
}
function cleanScssBugUrl(url) {
	if (typeof window !== "undefined" && typeof location !== "undefined" && typeof location.href === "string") {
		const prefix = location.href.replace(/\/$/, "");
		return url.replace(prefix, "");
	} else return url;
}
const makeScssWorker = (environment, resolvers, _maxWorkers) => {
	let compilerPromise;
	return {
		async run(sassPath, data, options) {
			const sass = await import(sassPath);
			compilerPromise ??= sass.initAsyncCompiler();
			const compiler = await compilerPromise;
			const sassOptions = { ...options };
			sassOptions.url = pathToFileURL(options.filename);
			sassOptions.sourceMap = options.enableSourcemap;
			const skipRebaseUrls = (unquotedUrl, rawUrl) => {
				if (!(rawUrl[0] === "\"" || rawUrl[0] === "'") && unquotedUrl[0] === "$") return true;
				return unquotedUrl.startsWith("#{");
			};
			const internalImporter = {
				async canonicalize(url, context) {
					const importer = context.containingUrl ? fileURLToPath(context.containingUrl) : options.filename;
					const resolved = await resolvers.sass(environment, url, cleanScssBugUrl(importer));
					if (resolved && (resolved.endsWith(".css") || resolved.endsWith(".scss") || resolved.endsWith(".sass"))) return pathToFileURL(resolved);
					return null;
				},
				async load(canonicalUrl) {
					const ext = path.extname(canonicalUrl.pathname);
					let syntax = "scss";
					if (ext === ".sass") syntax = "indented";
					else if (ext === ".css") syntax = "css";
					const result = await rebaseUrls(environment, fileURLToPath(canonicalUrl), options.filename, resolvers.sass, skipRebaseUrls);
					return {
						contents: result.contents ?? await fsp.readFile(result.file, "utf-8"),
						syntax,
						sourceMapUrl: canonicalUrl
					};
				}
			};
			sassOptions.importers = [...sassOptions.importers ?? [], internalImporter];
			sassOptions.importer ??= internalImporter;
			const result = await compiler.compileStringAsync(data, sassOptions);
			return {
				css: result.css,
				map: result.sourceMap ? JSON.stringify(result.sourceMap) : void 0,
				stats: { includedFiles: result.loadedUrls.filter((url) => url.protocol === "file:").map((url) => fileURLToPath(url)) }
			};
		},
		async stop() {
			await (await compilerPromise)?.dispose();
			compilerPromise = void 0;
		}
	};
};
const scssProcessor = (maxWorkers) => {
	let worker;
	let failedSassEmbedded;
	const normalizedErrors = /* @__PURE__ */ new WeakSet();
	return {
		async close() {
			await worker?.stop();
		},
		async process(environment, source, root, options, resolvers) {
			let sassPackage = loadSassPackage(root, failedSassEmbedded ?? false);
			if (failedSassEmbedded === void 0) {
				failedSassEmbedded = false;
				try {
					await import(sassPackage.path);
				} catch (e) {
					if (/sass-embedded-[a-z0-9]+-[a-z0-9]+/i.test(e.message)) {
						failedSassEmbedded = true;
						sassPackage = loadSassPackage(root, failedSassEmbedded);
					}
				}
			}
			worker ??= makeScssWorker(environment, resolvers, maxWorkers);
			const { content: data, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
			const optionsWithoutAdditionalData = {
				...options,
				additionalData: void 0
			};
			try {
				const result = await worker.run(pathToFileURL(sassPackage.path).href, data, optionsWithoutAdditionalData);
				const deps = result.stats.includedFiles.map((f) => cleanScssBugUrl(f));
				const map = result.map ? JSON.parse(result.map.toString()) : void 0;
				if (map) map.sources = map.sources.map((url) => url.startsWith("file://") ? normalizePath(fileURLToPath(url)) : url);
				return {
					code: result.css.toString(),
					map,
					additionalMap,
					deps
				};
			} catch (e) {
				if (!normalizedErrors.has(e)) {
					e.message = `[sass] ${e.message}`;
					e.id = e.file;
					e.frame = e.formatted;
					if (e.span?.start) {
						e.line = e.span.start.line + 1;
						e.column = e.span.start.column + 1;
						e.frame = e.message;
					}
					normalizedErrors.add(e);
				}
				return {
					code: "",
					error: e,
					deps: []
				};
			}
		}
	};
};
/**
* relative url() inside \@imported sass and less files must be rebased to use
* root file as base.
*/
async function rebaseUrls(environment, file, rootFile, resolver, ignoreUrl) {
	file = path.resolve(file);
	const fileDir = path.dirname(file);
	const rootDir = path.dirname(rootFile);
	if (fileDir === rootDir) return { file };
	const content = await fsp.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 (unquotedUrl, rawUrl) => {
		if (ignoreUrl?.(unquotedUrl, rawUrl)) return false;
		if (unquotedUrl[0] === "/") return unquotedUrl;
		const absolute = await resolver(environment, unquotedUrl, file) || path.resolve(fileDir, unquotedUrl);
		return normalizePath(path.relative(rootDir, absolute));
	};
	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
	};
}
const makeLessWorker = (environment, resolvers, maxWorkers) => {
	const skipRebaseUrls = (unquotedUrl, _rawUrl) => {
		return unquotedUrl[0] === "@";
	};
	const viteLessResolve = async (filename, dir, rootFile, mime) => {
		const resolved = await resolvers.less(environment, filename, path.join(dir, "*"));
		if (!resolved) return void 0;
		if (mime === "application/javascript") return { resolved: path.resolve(resolved) };
		const result = await rebaseUrls(environment, resolved, rootFile, resolvers.less, skipRebaseUrls);
		return {
			resolved,
			contents: "contents" in result ? result.contents : void 0
		};
	};
	return new WorkerWithFallback(async () => {
		const [fsp, path] = await Promise.all([import("node:fs/promises"), import("node:path")]);
		let ViteLessManager;
		const createViteLessPlugin = (less, rootFile) => {
			const { FileManager } = less;
			ViteLessManager ??= class ViteManager extends FileManager {
				rootFile;
				constructor(rootFile) {
					super();
					this.rootFile = rootFile;
				}
				supports(filename) {
					return !/^(?:https?:)?\/\//.test(filename);
				}
				supportsSync() {
					return false;
				}
				async loadFile(filename, dir, opts, env) {
					const result = await viteLessResolve(filename, dir, this.rootFile, opts.mime);
					if (result) return {
						filename: path.resolve(result.resolved),
						contents: result.contents ?? await fsp.readFile(result.resolved, "utf-8")
					};
					else return super.loadFile(filename, dir, opts, env);
				}
			};
			return {
				install(_, pluginManager) {
					pluginManager.addFileManager(new ViteLessManager(rootFile));
				},
				minVersion: [
					3,
					0,
					0
				]
			};
		};
		return async (lessPath, content, options) => {
			const nodeLess = (await import(lessPath)).default;
			const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename);
			return await nodeLess.render(content, {
				paths: ["node_modules"],
				...options,
				plugins: [viteResolverPlugin, ...options.plugins || []],
				...options.enableSourcemap ? { sourceMap: {
					outputSourceFiles: true,
					disableSourcemapAnnotation: true,
					sourceMapFileInline: false
				} } : {}
			});
		};
	}, {
		parentFunctions: { viteLessResolve },
		shouldUseFake(_lessPath, _content, options) {
			return !!options.plugins && options.plugins.length > 0;
		},
		max: maxWorkers
	});
};
const lessProcessor = (maxWorkers) => {
	let worker;
	return {
		close() {
			worker?.stop();
		},
		async process(environment, source, root, options, resolvers) {
			const lessPath = loadPreprocessorPath("less", root);
			worker ??= makeLessWorker(environment, resolvers, maxWorkers);
			const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap);
			let result;
			const optionsWithoutAdditionalData = {
				...options,
				additionalData: void 0
			};
			try {
				result = await worker.run(pathToFileURL(lessPath).href, content, optionsWithoutAdditionalData);
			} catch (e) {
				const error = e;
				const normalizedError = /* @__PURE__ */ new Error(`[less] ${error.message || error.type}`);
				normalizedError.loc = {
					file: error.filename || options.filename,
					line: error.line,
					column: error.column
				};
				return {
					code: "",
					error: normalizedError,
					deps: []
				};
			}
			const map = result.map && JSON.parse(result.map);
			if (map) delete map.sourcesContent;
			return {
				code: result.css.toString(),
				map,
				additionalMap,
				deps: result.imports
			};
		}
	};
};
const makeStylWorker = (maxWorkers) => {
	return new WorkerWithFallback(() => {
		return async (stylusPath, content, root, options) => {
			const stylus = (await import(stylusPath)).default;
			const ref = stylus(content, {
				paths: ["node_modules"],
				...options
			});
			if (options.define) for (const key in options.define) ref.define(key, options.define[key]);
			if (options.enableSourcemap) ref.set("sourcemap", {
				comment: false,
				inline: false,
				basePath: root
			});
			return {
				code: ref.render(),
				map: ref.sourcemap,
				deps: ref.deps()
			};
		};
	}, {
		shouldUseFake(_stylusPath, _content, _root, options) {
			return !!(options.define && Object.values(options.define).some((d) => typeof d === "function") || options.Evaluator);
		},
		max: maxWorkers
	});
};
const stylProcessor = (maxWorkers) => {
	let worker;
	return {
		close() {
			worker?.stop();
		},
		async process(_environment, source, root, options, _resolvers) {
			const stylusPath = loadPreprocessorPath("stylus", root);
			worker ??= makeStylWorker(maxWorkers);
			const { content, map: additionalMap } = await getSource(source, options.filename, options.additionalData, options.enableSourcemap, "\n");
			const importsDeps = (options.imports ?? []).map((dep) => path.resolve(dep));
			const optionsWithoutAdditionalData = {
				...options,
				additionalData: void 0
			};
			try {
				const { code, map, deps } = await worker.run(pathToFileURL(stylusPath).href, content, root, optionsWithoutAdditionalData);
				return {
					code,
					map: formatStylusSourceMap(map, root),
					additionalMap,
					deps: [...deps, ...importsDeps]
				};
			} catch (e) {
				const wrapped = /* @__PURE__ */ new Error(`[stylus] ${e.message}`);
				wrapped.name = e.name;
				wrapped.stack = e.stack;
				return {
					code: "",
					error: wrapped,
					deps: []
				};
			}
		}
	};
};
function formatStylusSourceMap(mapBefore, root) {
	if (!mapBefore) return void 0;
	const map = { ...mapBefore };
	const resolveFromRoot = (p) => normalizePath(path.resolve(root, p));
	if (map.file) map.file = resolveFromRoot(map.file);
	map.sources = map.sources.map(resolveFromRoot);
	return map;
}
async function getSource(source, filename, additionalData, enableSourcemap, sep = "") {
	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 + sep + source };
	const ms = new MagicString(source);
	ms.appendLeft(0, sep);
	ms.appendLeft(0, additionalData);
	const map = ms.generateMap({ hires: "boundary" });
	map.file = filename;
	map.sources = [filename];
	return {
		content: ms.toString(),
		map
	};
}
const createPreprocessorWorkerController = (maxWorkers) => {
	const scss = scssProcessor(maxWorkers);
	const less = lessProcessor(maxWorkers);
	const styl = stylProcessor(maxWorkers);
	const sassProcess = (environment, source, root, options, resolvers) => {
		const opts = { ...options };
		opts.syntax = "indented";
		return scss.process(environment, source, root, opts, resolvers);
	};
	const close = async () => {
		await Promise.all([
			less.close(),
			scss.close(),
			styl.close()
		]);
	};
	return {
		["less"]: less.process,
		["scss"]: scss.process,
		["sass"]: sassProcess,
		["styl"]: styl.process,
		["stylus"]: styl.process,
		close
	};
};
const normalizeMaxWorkers = (maxWorker) => {
	if (maxWorker === void 0) return 0;
	if (maxWorker === true) return void 0;
	return maxWorker;
};
const preprocessorSet = /* @__PURE__ */ new Set([
	"less",
	"sass",
	"scss",
	"styl",
	"stylus"
]);
function isPreProcessor(lang) {
	return lang && preprocessorSet.has(lang);
}
const absoluteOrProtocolRelativeUrlRE = /^(?:[a-z]+:)?\/\//i;
const importEsbuild = createCachedImport(() => import("esbuild"));
const importLightningCSS = createCachedImport(() => import("lightningcss"));
async function compileLightningCSS(environment, id, src, deps, workerController, urlResolver) {
	const { config } = environment;
	const filename = removeDirectQuery(id);
	let res;
	try {
		res = styleAttrRE.test(id) ? (await importLightningCSS()).transformStyleAttribute({
			filename,
			code: Buffer.from(src),
			targets: config.css.lightningcss?.targets,
			minify: config.isProduction && !!config.build.cssMinify,
			analyzeDependencies: true
		}) : await (await importLightningCSS()).bundleAsync({
			...config.css.lightningcss,
			filename,
			projectRoot: config.root,
			resolver: {
				async read(filePath) {
					if (filePath === filename) return src;
					const code = fs.readFileSync(filePath, "utf-8");
					const lang = CSS_LANGS_RE.exec(filePath)?.[1];
					if (isPreProcessor(lang)) {
						const result = await compileCSSPreprocessors(environment, id, lang, code, workerController);
						result.deps?.forEach((dep) => deps.add(dep));
						return result.code;
					} else if (lang === "sss") return (await transformSugarSS(environment, id, code)).code;
					return code;
				},
				async resolve(id, from) {
					const publicFile = checkPublicFile(id, environment.getTopLevelConfig());
					if (publicFile) return publicFile;
					if (absoluteOrProtocolRelativeUrlRE.test(id)) return { external: id };
					const atImportResolvers = getAtImportResolvers(environment.getTopLevelConfig());
					const lang = CSS_LANGS_RE.exec(from)?.[1];
					let resolver;
					switch (lang) {
						case "css":
						case "sss":
						case "styl":
						case "stylus":
						case void 0:
							resolver = atImportResolvers.css;
							break;
						case "sass":
						case "scss":
							resolver = atImportResolvers.sass;
							break;
						case "less":
							resolver = atImportResolvers.less;
							break;
						default: throw new Error(`Unknown lang: ${lang}`);
					}
					const resolved = await resolver(environment, id, from);
					if (resolved) {
						deps.add(resolved);
						return resolved;
					}
					return id;
				}
			},
			minify: config.isProduction && !!config.build.cssMinify,
			sourceMap: config.command === "build" ? !!config.build.sourcemap : config.css.devSourcemap,
			analyzeDependencies: { preserveImports: true },
			cssModules: cssModuleRE.test(id) ? config.css.lightningcss?.cssModules ?? true : void 0
		});
	} catch (e) {
		e.message = `[lightningcss] ${e.message}`;
		if (e.loc) {
			e.loc = {
				file: e.fileName.replace(NULL_BYTE_PLACEHOLDER, "\0"),
				line: e.loc.line,
				column: e.loc.column - 1
			};
			try {
				const friendlyMessage = getLightningCssErrorMessageForIeSyntaxes(fs.readFileSync(e.fileName, "utf-8"));
				if (friendlyMessage) e.message += friendlyMessage;
			} catch {}
		}
		throw e;
	}
	for (const warning of res.warnings) {
		let msg = `[vite:css][lightningcss] ${warning.message}`;
		msg += `\n${generateCodeFrame(src, {
			line: warning.loc.line,
			column: warning.loc.column - 1
		})}`;
		environment.logger.warn(import_picocolors.default.yellow(msg));
	}
	let css = decoder.decode(res.code);
	for (const dep of res.dependencies) switch (dep.type) {
		case "file":
			deps.add(dep.filePath);
			break;
		case "glob": {
			for (const file of globSync(dep.glob)) deps.add(file);
			const files = globSync(dep.glob, {
				absolute: true,
				expandDirectories: false,
				ignore: ["**/node_modules/**"]
			});
			for (let i = 0; i < files.length; i++) deps.add(files[i]);
			break;
		}
		case "url": {
			let replaceUrl;
			if (skipUrlReplacer(dep.url)) replaceUrl = dep.url;
			else if (urlResolver) {
				const [newUrl, resolvedId] = await urlResolver(dep.url, dep.loc.filePath.replace(NULL_BYTE_PLACEHOLDER, "\0"));
				if (resolvedId) deps.add(resolvedId);
				replaceUrl = newUrl;
			} else replaceUrl = dep.url;
			css = css.replace(dep.placeholder, () => replaceUrl.replaceAll("\"", "\\\""));
			break;
		}
		case "import":
			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, value] of sortedEntries) {
			modules[key] = value.name;
			for (const c of value.composes) modules[key] += " " + c.name;
		}
	}
	return {
		code: css,
		map: "map" in res ? res.map?.toString() : void 0,
		modules
	};
}
function getLightningCssErrorMessageForIeSyntaxes(code) {
	if (/[\s;{]\*[a-zA-Z-][\w-]+\s*:/.test(code)) return ".\nThis file contains star property hack (e.g. `*zoom`), which was used in the past to support old Internet Explorer versions. This is not a valid CSS syntax and will be ignored by modern browsers. \nWhile this is not supported by LightningCSS, you can set `css.lightningcss.errorRecovery: true` to strip these codes.";
	if (/min-width:\s*0\\0/.test(code)) return ".\nThis file contains @media zero hack (e.g. `@media (min-width: 0\\0)`), which was used in the past to support old Internet Explorer versions. This is not a valid CSS syntax and will be ignored by modern browsers. \nWhile this is not supported by LightningCSS, you can set `css.lightningcss.errorRecovery: true` to strip these codes.";
}
const map = {
	chrome: "chrome",
	edge: "edge",
	firefox: "firefox",
	hermes: false,
	ie: "ie",
	ios: "ios_saf",
	node: false,
	opera: "opera",
	rhino: false,
	safari: "safari"
};
const esMap = {
	2015: [
		"chrome49",
		"edge13",
		"safari10",
		"ios10",
		"firefox44",
		"opera36"
	],
	2016: [
		"chrome50",
		"edge13",
		"safari10",
		"ios10",
		"firefox43",
		"opera37"
	],
	2017: [
		"chrome58",
		"edge15",
		"safari11",
		"ios11",
		"firefox52",
		"opera45"
	],
	2018: [
		"chrome63",
		"edge79",
		"safari12",
		"ios12",
		"firefox58",
		"opera50"
	],
	2019: [
		"chrome73",
		"edge79",
		"safari12.1",
		"ios12.1",
		"firefox64",
		"opera60"
	],
	2020: [
		"chrome80",
		"edge80",
		"safari14.1",
		"ios14.5",
		"firefox80",
		"opera67"
	],
	2021: [
		"chrome85",
		"edge85",
		"safari14.1",
		"ios14.5",
		"firefox80",
		"opera71"
	],
	2022: [
		"chrome94",
		"edge94",
		"safari16.4",
		"ios16.4",
		"firefox93",
		"opera80"
	],
	2023: [
		"chrome110",
		"edge110",
		"safari16.4",
		"ios16.4",
		"firefox146",
		"opera96"
	],
	2024: [
		"chrome119",
		"edge119",
		"safari17.4",
		"ios17.4",
		"firefox145",
		"opera105"
	],
	2025: [
		"chrome136",
		"edge136",
		"safari26.0",
		"ios26.0",
		"firefox138",
		"opera121"
	]
};
const esRE = /es(6|\d{4})/;
const versionRE = /\d/;
const convertTargetsCache = /* @__PURE__ */ new Map();
const convertTargets = (esbuildTarget) => {
	if (!esbuildTarget) return {};
	const cached = convertTargetsCache.get(esbuildTarget);
	if (cached) return cached;
	const targets = {};
	const entriesWithoutES = arraify(esbuildTarget).flatMap((e) => {
		const match = esRE.exec(e);
		if (!match) return e;
		const year = match[1] === "6" ? 2015 : Number(match[1]);
		if (!esMap[year]) throw new Error(`Unsupported target "${e}"`);
		return esMap[year];
	});
	for (const entry of entriesWithoutES) {
		if (entry === "esnext") continue;
		const index = entry.search(versionRE);
		if (index >= 0) {
			const browser = map[entry.slice(0, index)];
			if (browser === false) continue;
			if (browser) {
				const [major, minor = 0] = entry.slice(index).split(".").map((v) => parseInt(v, 10));
				if (!isNaN(major) && !isNaN(minor)) {
					const version = major << 16 | minor << 8;
					if (!targets[browser] || version < targets[browser]) targets[browser] = version;
					continue;
				}
			}
		}
		throw new Error(`Unsupported target "${entry}"`);
	}
	convertTargetsCache.set(esbuildTarget, targets);
	return targets;
};
function resolveLibCssFilename(libOptions, root, packageCache) {
	if (typeof libOptions.cssFileName === "string") return `${libOptions.cssFileName}.css`;
	else if (typeof libOptions.fileName === "string") return `${libOptions.fileName}.css`;
	const packageJson = findNearestMainPackageData(root, packageCache)?.data;
	const name = packageJson ? getPkgName(packageJson.name) : void 0;
	if (!name) throw new Error("Name in package.json is required if option \"build.lib.cssFileName\" is not provided.");
	return `${name}.css`;
}
//#endregion
//#region src/node/plugins/modulePreloadPolyfill.ts
const modulePreloadPolyfillId = "vite/modulepreload-polyfill";
const resolvedModulePreloadPolyfillId = "\0vite/modulepreload-polyfill.js";
function modulePreloadPolyfillPlugin() {
	return {
		name: "vite:modulepreload-polyfill",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) return viteModulePreloadPolyfillPlugin({ isServer: environment.config.consumer !== "client" });
			return true;
		},
		resolveId: {
			filter: { id: exactRegex(modulePreloadPolyfillId) },
			handler(_id) {
				return resolvedModulePreloadPolyfillId;
			}
		},
		load: {
			filter: { id: exactRegex(resolvedModulePreloadPolyfillId) },
			handler(_id) {
				return "";
			}
		}
	};
}
//#endregion
//#region src/node/plugins/html.ts
const htmlProxyRE = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/;
const isHtmlProxyRE = /[?&]html-proxy\b/;
const inlineCSSRE = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
const inlineImportRE = /(?<!(?<!\.\.)\.)\bimport\s*\(("(?:[^"]|(?<=\\)")*"|'(?:[^']|(?<=\\)')*')\)/dg;
const htmlLangRE = /\.(?:html|htm)$/;
const spaceRe = /[\t\n\f\r ]/;
const importMapRE = /[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
const importMapAppendRE = new RegExp([/[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i, /[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?>/i].map((r) => r.source).join("|"), "i");
const isHTMLProxy = (id) => isHtmlProxyRE.test(id);
const isHTMLRequest = (request) => htmlLangRE.test(request);
const htmlProxyMap = /* @__PURE__ */ new WeakMap();
const htmlProxyResult = /* @__PURE__ */ new Map();
function htmlInlineProxyPlugin(config) {
	htmlProxyMap.set(config, /* @__PURE__ */ new Map());
	return {
		name: "vite:html-inline-proxy",
		resolveId: {
			filter: { id: isHtmlProxyRE },
			handler(id) {
				return id;
			}
		},
		load: {
			filter: { id: isHtmlProxyRE },
			handler(id) {
				const proxyMatch = htmlProxyRE.exec(id);
				if (proxyMatch) {
					const index = Number(proxyMatch[1]);
					const url = cleanUrl(id).replace(normalizePath(config.root), "");
					const result = htmlProxyMap.get(config).get(url)?.[index];
					if (result) return {
						...result,
						moduleSideEffects: true
					};
					else throw new Error(`No matching HTML proxy module found from ${id}`);
				}
			}
		}
	};
}
function addToHTMLProxyCache(config, filePath, index, result) {
	if (!htmlProxyMap.get(config)) htmlProxyMap.set(config, /* @__PURE__ */ new Map());
	if (!htmlProxyMap.get(config).get(filePath)) htmlProxyMap.get(config).set(filePath, []);
	htmlProxyMap.get(config).get(filePath)[index] = result;
}
function addToHTMLProxyTransformResult(hash, code) {
	htmlProxyResult.set(hash, code);
}
const noInlineLinkRels = /* @__PURE__ */ new Set([
	"icon",
	"apple-touch-icon",
	"apple-touch-startup-image",
	"manifest"
]);
const isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
function nodeIsElement(node) {
	return node.nodeName[0] !== "#";
}
function traverseNodes(node, visitor) {
	if (node.nodeName === "template") node = node.content;
	visitor(node);
	if (nodeIsElement(node) || node.nodeName === "#document" || node.nodeName === "#document-fragment") node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
}
async function traverseHtml(html, filePath, warn, visitor) {
	const { parse, ErrorCodes } = await import("./dist.js");
	const warnings = {};
	traverseNodes(parse(html, {
		scriptingEnabled: false,
		sourceCodeLocationInfo: true,
		onParseError: (e) => {
			handleParseError(e, ErrorCodes, html, filePath, warnings);
		}
	}), visitor);
	for (const message of Object.values(warnings)) warn(import_picocolors.default.yellow(`\n${message}`));
}
function getScriptInfo(node) {
	let src;
	let srcSourceCodeLocation;
	let isModule = false;
	let isAsync = false;
	let isIgnored = false;
	for (const p of node.attrs) {
		if (p.prefix !== void 0) continue;
		if (p.name === "src") {
			if (!src) {
				src = p;
				srcSourceCodeLocation = node.sourceCodeLocation?.attrs.src;
			}
		} else if (p.name === "type" && p.value === "module") isModule = true;
		else if (p.name === "async") isAsync = true;
		else if (p.name === "vite-ignore") isIgnored = true;
	}
	return {
		src,
		srcSourceCodeLocation,
		isModule,
		isAsync,
		isIgnored
	};
}
const attrValueStartRE = /=\s*(.)/;
function overwriteAttrValue(s, sourceCodeLocation, newValue) {
	const srcString = s.slice(sourceCodeLocation.startOffset, sourceCodeLocation.endOffset);
	const valueStart = attrValueStartRE.exec(srcString);
	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 removeViteIgnoreAttr(s, sourceCodeLocation) {
	const loc = sourceCodeLocation.attrs?.["vite-ignore"];
	if (loc) s.remove(loc.startOffset, loc.endOffset);
	return s;
}
/**
* Format parse5 @type {ParserError} to @type {RollupError}
*/
function formatParseError(parserError, id, html) {
	return {
		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
		}
	};
}
function handleParseError(parserError, errorCodes, html, filePath, warnings) {
	switch (parserError.code) {
		case errorCodes.missingDoctype: return;
		case errorCodes.abandonedHeadElementChild: return;
		case errorCodes.duplicateAttribute: return;
		case errorCodes.nonVoidHtmlElementStartTagWithTrailingSolidus: return;
		case errorCodes.unexpectedQuestionMarkInsteadOfTagName: return;
	}
	const parseError = formatParseError(parserError, filePath, html);
	warnings[parseError.code] ??= `Unable to parse HTML; ${parseError.message}\n at ${parseError.loc.file}:${parseError.loc.line}:${parseError.loc.column}\n` + parseError.frame;
}
/**
* Collects CSS files for a chunk by traversing its imports depth-first,
* using a cache to avoid re-analyzing chunks while still returning the
* correct files when the same chunk is reached via different entry points.
*/
function getCssFilesForChunk(chunk, bundle, analyzedImportedCssFiles, seenChunks = /* @__PURE__ */ new Set(), seenCss = /* @__PURE__ */ new Set()) {
	if (seenChunks.has(chunk.fileName)) return [];
	seenChunks.add(chunk.fileName);
	if (analyzedImportedCssFiles.has(chunk)) {
		const additionals = analyzedImportedCssFiles.get(chunk).filter((file) => !seenCss.has(file));
		additionals.forEach((file) => seenCss.add(file));
		return additionals;
	}
	const allFiles = [];
	const filteredFiles = [];
	chunk.imports.forEach((file) => {
		const importee = bundle[file];
		if (importee?.type === "chunk") {
			const importeeCss = getCssFilesForChunk(importee, bundle, analyzedImportedCssFiles, seenChunks, seenCss);
			filteredFiles.push(...importeeCss);
			if (analyzedImportedCssFiles.has(importee)) allFiles.push(...analyzedImportedCssFiles.get(importee));
			else allFiles.push(...importeeCss);
		}
	});
	chunk.viteMetadata.importedCss.forEach((file) => {
		allFiles.push(file);
		if (!seenCss.has(file)) {
			seenCss.add(file);
			filteredFiles.push(file);
		}
	});
	analyzedImportedCssFiles.set(chunk, unique(allFiles));
	return filteredFiles;
}
/**
* Compiles index.html into an entry js module
*/
function buildHtmlPlugin(config) {
	const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
	preHooks.unshift(injectCspNonceMetaTagHook(config));
	preHooks.unshift(preImportMapHook(config));
	preHooks.push(htmlEnvHook(config));
	postHooks.push(injectNonceAttributeTagHook(config));
	postHooks.push(postImportMapHook(config));
	const processedHtml = perEnvironmentState(() => /* @__PURE__ */ new Map());
	const isExcludedUrl = (url) => url[0] === "#" || isExternalUrl(url) || isDataUrl(url);
	isAsyncScriptMap.set(config, /* @__PURE__ */ new Map());
	return {
		name: "vite:build-html",
		applyToEnvironment(environment) {
			return environment.config.isBundled;
		},
		transform: {
			filter: { id: /\.html$/ },
			async handler(html, id) {
				id = normalizePath(id);
				const relativeUrlPath = normalizePath(path.relative(config.root, id));
				const publicPath = `/${relativeUrlPath}`;
				const publicBase = getBaseInHTML(relativeUrlPath, config);
				const publicToRelative = (filename) => publicBase + filename;
				const toOutputPublicFilePath = (url) => toOutputFilePathInHtml(url.slice(1), "public", relativeUrlPath, "html", config, publicToRelative);
				const nodeStartWithLeadingWhitespace = (node) => {
					const startOffset = node.sourceCodeLocation.startOffset;
					if (startOffset === 0) return 0;
					const lineStartOffset = startOffset - node.sourceCodeLocation.startCol;
					let isLineEmpty = false;
					try {
						isLineEmpty = !s.slice(Math.max(0, lineStartOffset), startOffset).trim();
					} catch {}
					return isLineEmpty ? lineStartOffset : startOffset;
				};
				html = await applyHtmlTransforms(html, preHooks, this, {
					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(config.build.rolldownOptions.input || {});
				const processAssetUrl = async (url, shouldInline) => {
					if (url !== "" && !namedOutput.includes(url) && !namedOutput.includes(removeLeadingSlash(url))) try {
						return await urlToBuiltUrl(this, url, id, shouldInline);
					} catch (e) {
						if (e.code !== "ENOENT") throw e;
					}
					return url;
				};
				const setModuleSideEffectPromises = [];
				await traverseHtml(html, id, config.logger.warn, (node) => {
					if (!nodeIsElement(node)) return;
					let shouldRemove = false;
					if (node.nodeName === "script") {
						const { src, srcSourceCodeLocation, isModule, isAsync, isIgnored } = getScriptInfo(node);
						if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
						else {
							const url = src && src.value;
							const isPublicFile = !!(url && checkPublicFile(url, config));
							if (isPublicFile) overwriteAttrValue(s, srcSourceCodeLocation, partialEncodeURIPath(toOutputPublicFilePath(url)));
							if (isModule) {
								inlineModuleIndex++;
								if (url && !isExcludedUrl(url) && !isPublicFile) {
									setModuleSideEffectPromises.push(this.resolve(url, id).then((resolved) => {
										if (!resolved) return Promise.reject(/* @__PURE__ */ new Error(`Failed to resolve ${url} from ${id}`));
										const moduleInfo = this.getModuleInfo(resolved.id);
										if (moduleInfo) moduleInfo.moduleSideEffects = true;
										else if (!resolved.external) return this.load({
											...resolved,
											moduleSideEffects: true
										}).then(() => {});
									}));
									js += `\nimport ${JSON.stringify(url)}`;
									shouldRemove = true;
								} else if (node.childNodes.length) {
									const contents = node.childNodes.pop().value;
									addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code: contents });
									js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`;
									shouldRemove = true;
								}
								everyScriptIsAsync &&= isAsync;
								someScriptsAreAsync ||= isAsync;
								someScriptsAreDefer ||= !isAsync;
							} else if (url && !isPublicFile) {
								if (!isExcludedUrl(url)) config.logger.warn(`<script src="${url}"> in "${publicPath}" can't be bundled without type="module" attribute`);
							} else if (node.childNodes.length) {
								const scriptNode = node.childNodes.pop();
								scriptUrls.push(...extractImportExpressionFromClassicScript(scriptNode));
							}
						}
					}
					const assetAttributes = getNodeAssetAttributes(node, config.html?.additionalAssetSources);
					for (const attr of assetAttributes) if (attr.type === "remove") {
						s.remove(attr.location.startOffset, attr.location.endOffset);
						continue;
					} else if (attr.type === "srcset") assetUrlsPromises.push((async () => {
						const processedEncodedUrl = await processSrcSet(attr.value, async ({ url }) => {
							const decodedUrl = decodeURIIfPossible(url);
							if (decodedUrl !== void 0 && !isExcludedUrl(decodedUrl)) {
								const result = await processAssetUrl(url);
								return result !== decodedUrl ? encodeURIPath(result) : url;
							}
							return url;
						});
						if (processedEncodedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedEncodedUrl);
					})());
					else if (attr.type === "src") {
						const url = decodeURIIfPossible(attr.value);
						if (url === void 0) {} else if (checkPublicFile(url, config)) overwriteAttrValue(s, attr.location, partialEncodeURIPath(toOutputPublicFilePath(url)));
						else if (!isExcludedUrl(url)) if (node.nodeName === "link" && isCSSRequest(url) && !("media" in attr.attributes || "disabled" in attr.attributes)) {
							const importExpression = `\nimport ${JSON.stringify(url)}`;
							styleUrls.push({
								url,
								start: nodeStartWithLeadingWhitespace(node),
								end: node.sourceCodeLocation.endOffset
							});
							js += importExpression;
						} else {
							const shouldInline = node.nodeName === "link" && attr.attributes.rel && parseRelAttr(attr.attributes.rel).some((v) => noInlineLinkRels.has(v)) ? false : void 0;
							assetUrlsPromises.push((async () => {
								const processedUrl = await processAssetUrl(url, shouldInline);
								if (processedUrl !== url) overwriteAttrValue(s, attr.location, partialEncodeURIPath(processedUrl));
							})());
						}
					}
					const inlineStyle = findNeedTransformStyleAttribute(node);
					if (inlineStyle) {
						inlineModuleIndex++;
						const code = inlineStyle.attr.value;
						addToHTMLProxyCache(config, id.replace(normalizePath(config.root), ""), inlineModuleIndex, { code });
						js += `\nimport "${id}?html-proxy&inline-css&style-attr&index=${inlineModuleIndex}.css"`;
						const hash = getHash(cleanUrl(id));
						overwriteAttrValue(s, inlineStyle.location, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
					}
					if (node.nodeName === "style" && node.childNodes.length) {
						const styleNode = node.childNodes.pop();
						const filePath = id.replace(normalizePath(config.root), "");
						inlineModuleIndex++;
						addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code: styleNode.value });
						js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`;
						const hash = getHash(cleanUrl(id));
						s.update(styleNode.sourceCodeLocation.startOffset, styleNode.sourceCodeLocation.endOffset, `__VITE_INLINE_CSS__${hash}_${inlineModuleIndex}__`);
					}
					if (shouldRemove) s.remove(nodeStartWithLeadingWhitespace(node), node.sourceCodeLocation.endOffset);
				});
				isAsyncScriptMap.get(config).set(id, everyScriptIsAsync);
				if (someScriptsAreAsync && someScriptsAreDefer) config.logger.warn(`\nMixed 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 } of scriptUrls) if (checkPublicFile(url, config)) s.update(start, end, partialEncodeURIPath(toOutputPublicFilePath(url)));
				else if (!isExcludedUrl(url)) s.update(start, end, partialEncodeURIPath(await urlToBuiltUrl(this, url, id)));
				const resolvedStyleUrls = await Promise.all(styleUrls.map(async (styleUrl) => ({
					...styleUrl,
					resolved: await this.resolve(styleUrl.url, id)
				})));
				for (const { start, end, url, resolved } of resolvedStyleUrls) if (resolved == null) {
					config.logger.warnOnce(`\n${url} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
					const importExpression = `\nimport ${JSON.stringify(url)}`;
					js = js.replace(importExpression, "");
				} else s.remove(start, end);
				processedHtml(this).set(id, s.toString());
				const { modulePreload } = this.environment.config.build;
				if (modulePreload !== false && modulePreload.polyfill && (someScriptsAreAsync || someScriptsAreDefer)) js = `import "${modulePreloadPolyfillId}";\n${js}`;
				await Promise.all(setModuleSideEffectPromises);
				return {
					code: js,
					map: { mappings: "" },
					moduleSideEffects: "no-treeshake"
				};
			}
		},
		async generateBundle(options, bundle) {
			const analyzedImportedCssFiles = /* @__PURE__ */ new Map();
			const inlineEntryChunk = /* @__PURE__ */ new Set();
			const getImportedChunks = (chunk, seen = /* @__PURE__ */ new Set()) => {
				const chunks = [];
				chunk.imports.forEach((file) => {
					const importee = bundle[file];
					if (importee) {
						if (importee.type === "chunk" && !seen.has(file)) {
							seen.add(file);
							chunks.push(...getImportedChunks(importee, seen));
							chunks.push(importee);
						}
					} else chunks.push(file);
				});
				return chunks;
			};
			const toScriptTag = (chunkOrUrl, toOutputPath, isAsync) => ({
				tag: "script",
				attrs: {
					...isAsync ? { async: true } : {},
					type: "module",
					crossorigin: true,
					src: typeof chunkOrUrl === "string" ? chunkOrUrl : toOutputPath(chunkOrUrl.fileName)
				}
			});
			const toPreloadTag = (filename, toOutputPath) => ({
				tag: "link",
				attrs: {
					rel: "modulepreload",
					crossorigin: true,
					href: toOutputPath(filename)
				}
			});
			const toStyleSheetLinkTag = (file, toOutputPath) => ({
				tag: "link",
				attrs: {
					rel: "stylesheet",
					crossorigin: true,
					href: toOutputPath(file)
				}
			});
			const getCssTagsForChunk = (chunk, toOutputPath) => getCssFilesForChunk(chunk, bundle, analyzedImportedCssFiles).map((file) => toStyleSheetLinkTag(file, toOutputPath));
			for (const [normalizedId, html] of processedHtml(this)) {
				const relativeUrlPath = normalizePath(path.relative(config.root, normalizedId));
				const assetsBase = getBaseInHTML(relativeUrlPath, config);
				const toOutputFilePath = (filename, type) => {
					if (isExternalUrl(filename)) return filename;
					else return toOutputFilePathInHtml(filename, type, relativeUrlPath, "html", config, (filename) => assetsBase + filename);
				};
				const toOutputAssetFilePath = (filename) => toOutputFilePath(filename, "asset");
				const toOutputPublicAssetFilePath = (filename) => toOutputFilePath(filename, "public");
				const isAsync = isAsyncScriptMap.get(config).get(normalizedId);
				let result = html;
				const chunk = Object.values(bundle).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.facadeModuleId && normalizePath(chunk.facadeModuleId) === normalizedId);
				let canInlineEntry = false;
				if (chunk) {
					if (options.format === "es" && isEntirelyImport(chunk.code)) canInlineEntry = true;
					const imports = getImportedChunks(chunk);
					let assetTags;
					if (canInlineEntry) assetTags = imports.map((chunk) => toScriptTag(chunk, toOutputAssetFilePath, isAsync));
					else {
						const { modulePreload } = this.environment.config.build;
						assetTags = [toScriptTag(chunk, toOutputAssetFilePath, isAsync)];
						if (modulePreload !== false) {
							const resolveDependencies = typeof modulePreload === "object" && modulePreload.resolveDependencies;
							const importsFileNames = imports.filter((chunkOrUrl) => typeof chunkOrUrl !== "string").map((chunk) => chunk.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 (!this.environment.config.build.cssCodeSplit) {
					const cssBundleName = cssBundleNameCache.get(config);
					const cssChunk = cssBundleName && Object.values(bundle).find((chunk) => chunk.type === "asset" && chunk.names.includes(cssBundleName));
					if (cssChunk) result = injectToHead(result, [{
						tag: "link",
						attrs: {
							rel: "stylesheet",
							crossorigin: true,
							href: toOutputAssetFilePath(cssChunk.fileName)
						}
					}]);
				}
				let match;
				let s;
				inlineCSSRE.lastIndex = 0;
				while (match = inlineCSSRE.exec(result)) {
					s ||= new MagicString(result);
					const { 0: full, 1: scopedName } = match;
					const cssTransformedCode = htmlProxyResult.get(scopedName);
					s.update(match.index, match.index + full.length, cssTransformedCode);
				}
				if (s) result = s.toString();
				result = await applyHtmlTransforms(result, [...normalHooks, ...postHooks], this, {
					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, config));
					return encodeURIPath(URL$1.canParse(publicAssetPath) ? publicAssetPath : normalizePath(publicAssetPath));
				});
				if (chunk && canInlineEntry) inlineEntryChunk.add(chunk.fileName);
				const shortEmitName = normalizePath(path.relative(config.root, normalizedId));
				this.emitFile({
					type: "asset",
					originalFileName: normalizedId,
					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(node) {
	const attr = node.attrs.find((prop) => prop.prefix === void 0 && prop.name === "style" && (prop.value.includes("url(") || prop.value.includes("image-set(")));
	if (!attr) return void 0;
	return {
		attr,
		location: node.sourceCodeLocation?.attrs?.style
	};
}
function extractImportExpressionFromClassicScript(scriptTextNode) {
	const startOffset = scriptTextNode.sourceCodeLocation.startOffset;
	const cleanCode = stripLiteral(scriptTextNode.value);
	const scriptUrls = [];
	let match;
	inlineImportRE.lastIndex = 0;
	while (match = inlineImportRE.exec(cleanCode)) {
		const [, [urlStart, urlEnd]] = match.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(config) {
	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(path.relative(config.root, ctx.filename));
			config.logger.warnOnce(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) <script type="importmap"> should come before <script type="module"> and <link rel="modulepreload"> in /${relativeHtml}`)));
		}
	};
}
/**
* Move importmap before the first module script and modulepreload link
*/
function postImportMapHook(config) {
	const decoder = new TextDecoder();
	return function(html, { bundle }) {
		const chunkImportMapEnabled = config.command === "build" && config.build.chunkImportMap;
		if (importMapAppendRE.test(html)) {
			let importMap;
			html = html.replace(importMapRE, (match) => {
				importMap = match;
				return "";
			});
			if (importMap) {
				html = html.replace(importMapAppendRE, (match) => `${importMap}\n${match}`);
				if (chunkImportMapEnabled) this.warn("The `build.chunkImportMap` option is enabled but an import map also exists in the input HTML file. This leads to multiple import maps generated in the output HTML, which is not supported by older browsers and Firefox.");
			}
		}
		if (chunkImportMapEnabled) {
			const nonce = config.html?.cspNonce;
			const importMap = bundle[getImportMapFilename(config)];
			const importMapHtml = serializeTag({
				tag: "script",
				attrs: {
					type: "importmap",
					...nonce ? { nonce } : {}
				},
				children: typeof importMap.source === "string" ? importMap.source : decoder.decode(importMap.source)
			});
			if (importMapAppendRE.test(html)) html = html.replace(importMapAppendRE, (match) => `${importMapHtml}\n${match}`);
			else html = `${importMapHtml}\n${html}`;
		}
		return html;
	};
}
function injectCspNonceMetaTagHook(config) {
	return () => {
		if (!config.html?.cspNonce) return;
		return [{
			tag: "meta",
			injectTo: "head",
			attrs: {
				property: "csp-nonce",
				nonce: config.html.cspNonce
			}
		}];
	};
}
/**
* Support `%ENV_NAME%` syntax in html files
*/
function htmlEnvHook(config) {
	const pattern = /%(\S+?)%/g;
	const envPrefix = resolveEnvPrefix({ envPrefix: config.envPrefix });
	const env = { ...config.env };
	for (const key in config.define) if (key.startsWith(`import.meta.env.`)) {
		const val = config.define[key];
		if (typeof val === "string") try {
			const parsed = JSON.parse(val);
			env[key.slice(16)] = typeof parsed === "string" ? parsed : val;
		} catch {
			env[key.slice(16)] = val;
		}
		else env[key.slice(16)] = JSON.stringify(val);
	}
	return (html, ctx) => {
		return html.replace(pattern, (text, key) => {
			if (key in env) return env[key];
			else {
				if (envPrefix.some((prefix) => key.startsWith(prefix))) {
					const relativeHtml = normalizePath(path.relative(config.root, ctx.filename));
					config.logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) ${text} is not defined in env variables found in /${relativeHtml}. Is the variable mistyped?`)));
				}
				return text;
			}
		});
	};
}
function injectNonceAttributeTagHook(config) {
	const processRelType = /* @__PURE__ */ new Set([
		"stylesheet",
		"modulepreload",
		"preload"
	]);
	return async (html, { filename }) => {
		const nonce = config.html?.cspNonce;
		if (!nonce) return;
		const s = new MagicString(html);
		await traverseHtml(html, filename, config.logger.warn, (node) => {
			if (!nodeIsElement(node)) return;
			const { nodeName, attrs, sourceCodeLocation } = node;
			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 }) => name === "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(plugins) {
	const preHooks = [];
	const normalHooks = [];
	const postHooks = [];
	for (const plugin of plugins) {
		const hook = plugin.transformIndexHtml;
		if (!hook) continue;
		if (typeof hook === "function") normalHooks.push(hook);
		else {
			const handler = hook.handler;
			if (hook.order === "pre") preHooks.push(handler);
			else if (hook.order === "post") postHooks.push(handler);
			else normalHooks.push(handler);
		}
	}
	return [
		preHooks,
		normalHooks,
		postHooks
	];
}
const elementsAllowedInHead = /* @__PURE__ */ new Set([
	"title",
	"base",
	"link",
	"style",
	"meta",
	"script",
	"noscript",
	"template"
]);
function headTagInsertCheck(tags, ctx) {
	if (!tags.length) return;
	const { logger } = ctx.server?.config || {};
	const disallowedTags = tags.filter((tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag));
	if (disallowedTags.length) {
		const dedupedTags = unique(disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`));
		logger?.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`[${dedupedTags.join(",")}] can not be used inside the <head> Element, please check the 'injectTo' value`)));
	}
}
async function applyHtmlTransforms(html, hooks, pluginContext, ctx) {
	for (const hook of hooks) {
		const res = await hook.call(pluginContext, 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 ??= []).push(tag);
					break;
				case "body-prepend":
					(bodyPrependTags ??= []).push(tag);
					break;
				case "head":
					(headTags ??= []).push(tag);
					break;
				default: (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;
}
const entirelyImportRE = /^(?:import\s*(?:"[^"\n]*[^\\\n]"|'[^'\n]*[^\\\n]');*|\/\*[\s\S]*?\*\/|\/\/.*[$\n])*$/;
function isEntirelyImport(code) {
	return entirelyImportRE.test(code.trim());
}
function getBaseInHTML(urlRelativePath, config) {
	return config.base === "./" || config.base === "" ? path.posix.join(path.posix.relative(urlRelativePath, "").slice(0, -2), "./") : config.base;
}
const headInjectRE = /([ \t]*)<\/head>/i;
const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
const htmlInjectRE = /<\/html>/i;
const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
const bodyInjectRE = /([ \t]*)<\/body>/i;
const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
const 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, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
	} else {
		if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
		if (bodyPrependInjectRE.test(html)) return html.replace(bodyPrependInjectRE, (match, p1) => `${serializeTags(tags, p1)}\n${match}`);
	}
	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, (match, p1) => `${match}\n${serializeTags(tags, incrementIndent(p1))}`);
		if (headInjectRE.test(html)) return html.replace(headInjectRE, (match, p1) => `${match}\n${serializeTags(tags, p1)}`);
		return prependInjectFallback(html, tags);
	} else {
		if (bodyInjectRE.test(html)) return html.replace(bodyInjectRE, (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`);
		if (htmlInjectRE.test(html)) return html.replace(htmlInjectRE, `${serializeTags(tags)}\n$&`);
		return html + `\n` + serializeTags(tags);
	}
}
function prependInjectFallback(html, tags) {
	if (htmlPrependInjectRE.test(html)) return html.replace(htmlPrependInjectRE, `$&\n${serializeTags(tags)}`);
	if (doctypePrependInjectRE.test(html)) return html.replace(doctypePrependInjectRE, `$&\n${serializeTags(tags)}`);
	return serializeTags(tags) + html;
}
const 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)}\n`).join("");
	return "";
}
function serializeAttrs(attrs) {
	let res = "";
	for (const key in attrs) if (typeof attrs[key] === "boolean") res += attrs[key] ? ` ${key}` : ``;
	else res += ` ${key}="${(0, import_escape_html.default)(attrs[key])}"`;
	return res;
}
function incrementIndent(indent = "") {
	return `${indent}${indent[0] === "	" ? "	" : "  "}`;
}
function getImportMapFilename(config) {
	const chunkImportMap = config.build.rolldownOptions.experimental?.chunkImportMap;
	if (typeof chunkImportMap === "object" && chunkImportMap.fileName) return chunkImportMap.fileName;
	return "importmap.json";
}
//#endregion
//#region src/node/server/middlewares/transform.ts
const debugCache = createDebugger("vite:cache");
const knownIgnoreList = /* @__PURE__ */ new Set(["/", "/favicon.ico"]);
const documentFetchDests = /* @__PURE__ */ new Set([
	"document",
	"iframe",
	"frame",
	"fencedframe"
]);
function isDocumentFetchDest(req) {
	const fetchDest = req.headers["sec-fetch-dest"];
	return fetchDest !== void 0 && documentFetchDests.has(fetchDest);
}
const urlRE = /[?&]url\b/;
const rawRE = /[?&]raw\b/;
const inlineRE$1 = /[?&]inline\b/;
const svgRE = /\.svg\b/;
function isServerAccessDeniedForTransform(config, id) {
	if (rawRE.test(id) || urlRE.test(id) || inlineRE$1.test(id) || svgRE.test(id)) return checkLoadingAccess(config, cleanUrl(id)) !== "allowed" || checkLoadingAccess(config, id) !== "allowed";
	return false;
}
/**
* A middleware that short-circuits the middleware chain to serve cached transformed modules
*/
function cachedTransformMiddleware(server) {
	return function viteCachedTransformMiddleware(req, res, next) {
		const environment = server.environments.client;
		if (isDocumentFetchDest(req)) {
			res.appendHeader("Vary", "Sec-Fetch-Dest");
			return next();
		}
		const ifNoneMatch = req.headers["if-none-match"];
		if (ifNoneMatch) {
			const moduleByEtag = environment.moduleGraph.getModuleByEtag(ifNoneMatch);
			if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag.url === req.url) {
				if (!isCSSRequest(req.url)) {
					debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`);
					res.statusCode = 304;
					return res.end();
				}
			}
		}
		next();
	};
}
function transformMiddleware(server) {
	const { root, publicDir } = server.config;
	const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root));
	const publicPath = `${publicDir.slice(root.length)}/`;
	return async function viteTransformMiddleware(req, res, next) {
		const environment = server.environments.client;
		if (req.method !== "GET" && req.method !== "HEAD" || knownIgnoreList.has(req.url) || isDocumentFetchDest(req)) return next();
		let url;
		try {
			url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, "\0");
		} catch (e) {
			if (e instanceof URIError) {
				server.config.logger.warn(import_picocolors.default.yellow(`Malformed URI sequence in request URL: ${removeTimestampQuery(req.url)}`));
				return next();
			}
			return next(e);
		}
		const withoutQuery = cleanUrl(url);
		try {
			if (withoutQuery.endsWith(".map")) {
				const depsOptimizer = environment.depsOptimizer;
				if (depsOptimizer?.isOptimizedDepUrl(url)) {
					const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath(path.resolve(server.config.root, url.slice(1)));
					if (!depsOptimizer.isOptimizedDepFile(sourcemapPath)) return next();
					try {
						const map = JSON.parse(await fsp.readFile(sourcemapPath, "utf-8"));
						applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger);
						return send$1(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
					} catch {
						const dummySourceMap = {
							version: 3,
							file: sourcemapPath.replace(/\.map$/, ""),
							sources: [],
							sourcesContent: [],
							names: [],
							mappings: ";;;;;;;;;"
						};
						return send$1(req, res, JSON.stringify(dummySourceMap), "json", {
							cacheControl: "no-cache",
							headers: server.config.server.headers
						});
					}
				} else {
					const originalUrl = url.replace(/\.map($|\?)/, "$1");
					const map = (await environment.moduleGraph.getModuleByUrl(originalUrl))?.transformResult?.map;
					if (map) return send$1(req, res, JSON.stringify(map), "json", { headers: server.config.server.headers });
					else return next();
				}
			}
			if (publicDirInRoot && url.startsWith(publicPath)) warnAboutExplicitPublicPathInUrl(url);
			if (req.headers["sec-fetch-dest"] === "script" || isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) {
				url = removeImportQuery(url);
				url = unwrapId(url);
				if (isCSSRequest(url)) {
					if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) url = injectQuery(url, "direct");
					const ifNoneMatch = req.headers["if-none-match"];
					if (ifNoneMatch && (await environment.moduleGraph.getModuleByUrl(url))?.transformResult?.etag === ifNoneMatch) {
						debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`);
						res.statusCode = 304;
						return res.end();
					}
				}
				const result = await environment.transformRequest(url);
				if (result) {
					const depsOptimizer = environment.depsOptimizer;
					const type = isDirectCSSRequest(url) ? "css" : "js";
					const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url);
					return send$1(req, res, result.code, type, {
						etag: result.etag,
						cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache",
						headers: server.config.server.headers,
						map: result.map
					});
				}
			}
		} catch (e) {
			if (e?.code === "ERR_OPTIMIZE_DEPS_PROCESSING_ERROR") {
				if (!res.writableEnded) {
					res.statusCode = 504;
					res.statusMessage = "Optimize Deps Processing Error";
					res.end();
				}
				server.config.logger.error(e.message);
				return;
			}
			if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP") {
				if (!res.writableEnded) {
					res.statusCode = 504;
					res.statusMessage = "Outdated Optimize Dep";
					res.end();
				}
				return;
			}
			if (e?.code === "ERR_CLOSED_SERVER") {
				if (!res.writableEnded) {
					res.statusCode = 504;
					res.statusMessage = "Outdated Request";
					res.end();
				}
				return;
			}
			if (e?.code === "ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR") {
				if (!res.writableEnded) {
					res.statusCode = 404;
					res.end();
				}
				server.config.logger.warn(import_picocolors.default.yellow(e.message));
				return;
			}
			if (e?.code === "ERR_LOAD_URL") return next();
			if (e?.code === "ERR_DENIED_ID") {
				const id = e.id;
				let servingAccessResult = checkLoadingAccess(server.config, cleanUrl(id));
				if (servingAccessResult === "allowed") servingAccessResult = checkLoadingAccess(server.config, id);
				if (servingAccessResult === "denied") {
					respondWithAccessDenied(id, server, res);
					return true;
				}
				if (servingAccessResult === "fallback") {
					next();
					return true;
				}
				throw new Error(`Unexpected access result for id ${id}`);
			}
			return next(e);
		}
		next();
	};
	function warnAboutExplicitPublicPathInUrl(url) {
		let warning;
		if (isImportRequest(url)) {
			const rawUrl = removeImportQuery(url);
			if (urlRE.test(url)) warning = `Assets in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(rawUrl)}, use ${import_picocolors.default.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 ${import_picocolors.default.cyan(rawUrl.replace(publicPath, "/src/"))} instead of ${import_picocolors.default.cyan(rawUrl)}.\nIf you intend to use the URL of that asset, use ${import_picocolors.default.cyan(injectQuery(rawUrl.replace(publicPath, "/"), "url"))}.`;
		} else warning = `Files in the public directory are served at the root path.\nInstead of ${import_picocolors.default.cyan(url)}, use ${import_picocolors.default.cyan(url.replace(publicPath, "/"))}.`;
		server.config.logger.warn(import_picocolors.default.yellow(warning));
	}
}
//#endregion
//#region src/node/plugins/define.ts
const nonJsRe = /\.json(?:$|\?)/;
const isNonJsRequest = (request) => nonJsRe.test(request);
const escapedDotRE = /(?<!\\)\\./g;
function definePlugin(config) {
	const isBuild = config.command === "build";
	const isBuildLib = isBuild && config.build.lib;
	const processEnv = {};
	if (!isBuildLib) {
		const nodeEnv = process.env.NODE_ENV || config.mode;
		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)
		});
	}
	function generatePattern(environment) {
		const isBundled = environment.config.isBundled;
		const keepProcessEnv = environment.config.keepProcessEnv;
		const importMetaKeys = {};
		const importMetaEnvKeys = {};
		const importMetaFallbackKeys = {};
		if (isBuild) importMetaKeys["import.meta.hot"] = `undefined`;
		if (isBundled) {
			for (const key in config.env) {
				const val = JSON.stringify(config.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 environment.config.define) {
			userDefine[key] = handleDefineValue(environment.config.define[key]);
			if (isBuild && key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = environment.config.define[key];
		}
		const define = {
			...keepProcessEnv ? {} : processEnv,
			...importMetaKeys,
			...userDefine,
			...importMetaFallbackKeys
		};
		const ssr = environment.config.consumer === "server";
		if ("import.meta.env.SSR" in define) define["import.meta.env.SSR"] = ssr + "";
		const importMetaEnvVal = serializeDefine({
			...importMetaEnvKeys,
			SSR: ssr + "",
			...userDefineEnv
		});
		const patternKeys = Object.keys(userDefine);
		if (!keepProcessEnv && Object.keys(processEnv).length) patternKeys.push("process.env");
		if (Object.keys(importMetaKeys).length) patternKeys.push("import.meta.env", "import.meta.hot");
		return [
			define,
			patternKeys.length ? new RegExp(patternKeys.map((key) => escapeRegex(key).replaceAll(escapedDotRE, "\\??\\.")).join("|")) : null,
			importMetaEnvVal
		];
	}
	const patternsCache = /* @__PURE__ */ new WeakMap();
	function getPattern(environment) {
		let pattern = patternsCache.get(environment);
		if (!pattern) {
			pattern = generatePattern(environment);
			patternsCache.set(environment, pattern);
		}
		return pattern;
	}
	return {
		name: "vite:define",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) return {
				name: "vite:define",
				options(option) {
					const [define, _pattern, importMetaEnvVal] = getPattern(this.environment);
					define["import.meta.env"] = importMetaEnvVal;
					define["import.meta.env.*"] = "undefined";
					option.transform ??= {};
					option.transform.define = {
						...option.transform.define,
						...define
					};
				}
			};
			return true;
		},
		transform: { handler(code, id) {
			if (this.environment.config.consumer === "client") return;
			if (isHTMLRequest(id) || isCSSRequest(id) || isNonJsRequest(id) || config.assetsInclude(id)) return;
			const [define, pattern] = getPattern(this.environment);
			if (!pattern) return;
			pattern.lastIndex = 0;
			if (!pattern.test(code)) return;
			return replaceDefine(this.environment, code, id, define);
		} }
	};
}
function replaceDefine(environment, code, id, define) {
	const result = transformSync(id, code, {
		lang: "js",
		sourceType: "module",
		define,
		sourcemap: environment.config.command === "build" ? !!environment.config.build.sourcemap : true,
		tsconfig: false
	});
	if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
	return {
		code: result.code,
		map: result.map || null
	};
}
/**
* Like `JSON.stringify` but keeps raw string values as a literal
* in the generated code. For example: `"window"` would refer to
* the global `window` object directly.
*/
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(value) {
	if (typeof value === "undefined") return "undefined";
	if (typeof value === "string") return value;
	return JSON.stringify(value);
}
//#endregion
//#region src/node/plugins/clientInjections.ts
const normalizedClientEntry$1 = normalizePath(CLIENT_ENTRY);
const normalizedEnvEntry$1 = normalizePath(ENV_ENTRY);
/**
* some values used by the client needs to be dynamically injected by the server
* @server-only
*/
function clientInjectionsPlugin(config) {
	let injectConfigValues;
	const getDefineReplacer = perEnvironmentState((environment) => {
		const userDefine = {};
		for (const key in environment.config.define) if (!key.startsWith("import.meta.env.")) userDefine[key] = environment.config.define[key];
		const serializedDefines = serializeDefine(userDefine);
		const definesReplacement = () => serializedDefines;
		return (code) => code.replace(`__DEFINES__`, definesReplacement);
	});
	return {
		name: "vite:client-inject",
		applyToEnvironment(environment) {
			return !environment.config.isBundled;
		},
		async buildStart() {
			injectConfigValues = await createClientConfigValueReplacer(config);
		},
		transform(code, id) {
			const ssr = this.environment.config.consumer === "server";
			const cleanId = cleanUrl(id);
			if (cleanId === normalizedClientEntry$1 || cleanId === normalizedEnvEntry$1) return getDefineReplacer(this)(injectConfigValues(code));
			else if (!ssr && code.includes("process.env.NODE_ENV")) {
				const nodeEnv = this.environment.config.define?.["process.env.NODE_ENV"] || JSON.stringify(process.env.NODE_ENV || config.mode);
				return replaceDefine(this.environment, code, id, {
					"process.env.NODE_ENV": nodeEnv,
					"global.process.env.NODE_ENV": nodeEnv,
					"globalThis.process.env.NODE_ENV": nodeEnv
				});
			}
		}
	};
}
function escapeReplacement(value) {
	const jsonValue = JSON.stringify(value);
	return () => jsonValue;
}
async function createClientConfigValueReplacer(config) {
	const resolvedServerHostname = (await resolveHostname(config.server.host)).name;
	const resolvedServerPort = config.server.port;
	const devBase = config.base;
	const serverHost = `${resolvedServerHostname}:${resolvedServerPort}${devBase}`;
	const wsConfig = isObject$1(config.server.ws) ? config.server.ws : void 0;
	const host = wsConfig?.host || null;
	const protocol = wsConfig?.protocol || null;
	const timeout = wsConfig?.timeout || 3e4;
	const isWsServerSpecified = !!wsConfig?.server;
	const hmrConfigName = path.basename(config.configFile || "vite.config.js");
	const overlay = (isObject$1(config.server.hmr) ? config.server.hmr : void 0)?.overlay !== false;
	let port = wsConfig?.clientPort || wsConfig?.port || null;
	if (config.server.middlewareMode && !isWsServerSpecified) port ||= 24678;
	let directTarget = wsConfig?.host || resolvedServerHostname;
	directTarget += `:${wsConfig?.port || resolvedServerPort}`;
	directTarget += devBase;
	let hmrBase = devBase;
	if (wsConfig?.path) hmrBase = path.posix.join(hmrBase, wsConfig.path);
	const modeReplacement = escapeReplacement(config.mode);
	const baseReplacement = escapeReplacement(devBase);
	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(timeout);
	const hmrEnableOverlayReplacement = escapeReplacement(overlay);
	const hmrConfigNameReplacement = escapeReplacement(hmrConfigName);
	const wsTokenReplacement = escapeReplacement(config.webSocketToken);
	const serverForwardConsoleReplacement = escapeReplacement(config.server.forwardConsole);
	const bundleDevReplacement = escapeReplacement(config.experimental.bundledDev || false);
	return (code) => code.replace(`__MODE__`, modeReplacement).replace(/__BASE__/g, baseReplacement).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).replace(`__WS_TOKEN__`, wsTokenReplacement).replace(`__SERVER_FORWARD_CONSOLE__`, serverForwardConsoleReplacement).replaceAll(`__BUNDLED_DEV__`, bundleDevReplacement);
}
async function getHmrImplementation(config) {
	const content = fs.readFileSync(normalizedClientEntry$1, "utf-8");
	return (await createClientConfigValueReplacer(config))(content).replace(/import\s*['"]@vite\/env['"]/, "");
}
//#endregion
//#region src/node/server/middlewares/indexHtml.ts
function createDevHtmlTransformFn(config) {
	const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins);
	const transformHooks = [
		preImportMapHook(config),
		injectCspNonceMetaTagHook(config),
		...preHooks,
		htmlEnvHook(config),
		devHtmlHook,
		...normalHooks,
		...postHooks,
		injectNonceAttributeTagHook(config),
		postImportMapHook(config)
	];
	const pluginContext = new BasicMinimalPluginContext({
		...basePluginContextMeta,
		watchMode: true
	}, config.logger);
	return (server, url, html, originalUrl) => {
		return applyHtmlTransforms(html, transformHooks, pluginContext, {
			path: url,
			filename: getHtmlFilename(url, server),
			server,
			originalUrl
		});
	};
}
function getHtmlFilename(url, server) {
	if (url.startsWith(FS_PREFIX)) return decodeURIComponent(fsPathFromId(url));
	else return decodeURIComponent(normalizePath(path.join(server.config.root, url.slice(1))));
}
function shouldPreTransform(url, config) {
	return !checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url));
}
const wordCharRE = /\w/;
function isBareRelative(url) {
	return wordCharRE.test(url[0]) && !url.includes(":");
}
function getHtmlDirnameForRelativeUrl(htmlPath) {
	return htmlPath.endsWith("/") ? htmlPath : path.posix.dirname(htmlPath);
}
const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => {
	const replacer = (url) => {
		if (url[0] === "/" && url[1] !== "/" || (url[0] === "." || isBareRelative(url)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") url = path.posix.join(config.base, url);
		let preTransformUrl;
		if (!isClassicScriptLink && shouldPreTransform(url, config)) {
			if (url[0] === "/" && url[1] !== "/") preTransformUrl = url;
			else if (url[0] === "." || isBareRelative(url)) preTransformUrl = path.posix.join(config.base, getHtmlDirnameForRelativeUrl(htmlPath), url);
		}
		if (server) {
			const mod = server.environments.client.moduleGraph.urlToModuleMap.get(preTransformUrl || url);
			if (mod && mod.lastHMRTimestamp > 0) url = injectQuery(url, `t=${mod.lastHMRTimestamp}`);
		}
		if (server && preTransformUrl) {
			try {
				preTransformUrl = decodeURI(preTransformUrl);
			} catch {
				return url;
			}
			preTransformRequest(server, preTransformUrl, config.decodedBase);
		}
		return url;
	};
	return useSrcSetReplacer ? processSrcSetSync(url, ({ url }) => replacer(url)) : replacer(url);
};
const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => {
	const { config, watcher } = server;
	const base = config.base || "/";
	const decodedBase = config.decodedBase || "/";
	let proxyModulePath;
	let proxyModuleUrl;
	const trailingSlash = htmlPath.endsWith("/");
	if (!trailingSlash && fs.existsSync(filename)) {
		proxyModulePath = htmlPath.startsWith(FS_PREFIX) ? filename : htmlPath;
		proxyModuleUrl = htmlPath;
	} else {
		proxyModulePath = `\0${`${htmlPath}${trailingSlash ? "index.html" : ""}`}`;
		proxyModuleUrl = wrapId(proxyModulePath);
	}
	proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl);
	const s = new MagicString(html);
	let inlineModuleIndex = -1;
	const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath(config.root), ""));
	const styleUrl = [];
	const inlineStyles = [];
	const inlineModulePaths = [];
	const addInlineModule = (node, ext) => {
		inlineModuleIndex++;
		const contentNode = node.childNodes[0];
		const code = contentNode.value;
		let map;
		if (proxyModulePath[0] !== "\0") {
			map = new MagicString(html).snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset).generateMap({ hires: "boundary" });
			map.sources = [filename];
			map.file = filename;
		}
		addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, {
			code,
			map
		});
		const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`;
		inlineModulePaths.push(modulePath);
		s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, `<script type="module" src="${modulePath}"><\/script>`);
		preTransformRequest(server, modulePath, decodedBase);
	};
	await traverseHtml(html, filename, config.logger.warn, (node) => {
		if (!nodeIsElement(node)) return;
		if (node.nodeName === "script") {
			const { src, srcSourceCodeLocation, isModule, isIgnored } = getScriptInfo(node);
			if (isIgnored) removeViteIgnoreAttr(s, node.sourceCodeLocation);
			else if (src) {
				const processedUrl = processNodeUrl(src.value, false, config, htmlPath, originalUrl, server, !isModule);
				if (processedUrl !== src.value) overwriteAttrValue(s, srcSourceCodeLocation, processedUrl);
			} else if (isModule && node.childNodes.length) addInlineModule(node, "js");
			else if (node.childNodes.length) {
				const scriptNode = node.childNodes[node.childNodes.length - 1];
				for (const { url, start, end } of extractImportExpressionFromClassicScript(scriptNode)) {
					const processedUrl = processNodeUrl(url, false, config, htmlPath, originalUrl);
					if (processedUrl !== url) s.update(start, end, processedUrl);
				}
			}
		}
		const inlineStyle = findNeedTransformStyleAttribute(node);
		if (inlineStyle) {
			inlineModuleIndex++;
			inlineStyles.push({
				index: inlineModuleIndex,
				location: inlineStyle.location,
				code: inlineStyle.attr.value
			});
		}
		if (node.nodeName === "style" && node.childNodes.length) {
			const children = node.childNodes[0];
			styleUrl.push({
				start: children.sourceCodeLocation.startOffset,
				end: children.sourceCodeLocation.endOffset,
				code: children.value
			});
		}
		const assetAttributes = getNodeAssetAttributes(node, config.html?.additionalAssetSources);
		for (const attr of assetAttributes) if (attr.type === "remove") s.remove(attr.location.startOffset, attr.location.endOffset);
		else {
			const processedUrl = processNodeUrl(attr.value, attr.type === "srcset", config, htmlPath, originalUrl);
			if (processedUrl !== attr.value) overwriteAttrValue(s, attr.location, processedUrl);
		}
	});
	const clientModuleGraph = server?.environments.client.moduleGraph;
	if (clientModuleGraph) await Promise.all(inlineModulePaths.map(async (url) => {
		const module = await clientModuleGraph.getModuleByUrl(url);
		if (module) clientModuleGraph.invalidateModule(module);
	}));
	await Promise.all([...styleUrl.map(async ({ start, end, code }, index) => {
		const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`;
		const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
		ensureWatchedFile(watcher, mod.file, config.root);
		const result = await server.environments.client.pluginContainer.transform(code, mod.id);
		let content = "";
		if (result.map && "version" in result.map) {
			if (result.map.mappings) await injectSourcesContent(result.map, proxyModulePath, config.logger);
			content = getCodeWithSourcemap("css", result.code, result.map);
		} else content = result.code;
		s.overwrite(start, end, content);
	}), ...inlineStyles.map(async ({ index, location, code }) => {
		const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`;
		const mod = await server.environments.client.moduleGraph.ensureEntryFromUrl(url, false);
		ensureWatchedFile(watcher, mod.file, config.root);
		await server?.environments.client.pluginContainer.transform(code, mod.id);
		const hash = getHash(cleanUrl(mod.id));
		overwriteAttrValue(s, location, htmlProxyResult.get(`${hash}_${index}`) ?? "");
	})]);
	html = s.toString();
	return {
		html,
		tags: [{
			tag: "script",
			attrs: {
				type: "module",
				src: path.posix.join(base, CLIENT_PUBLIC_PATH)
			},
			injectTo: "head-prepend"
		}]
	};
};
function indexHtmlMiddleware(root, server) {
	const isDev = isDevServer(server);
	const fullBundle = isDev && server.environments.client.bundledDev;
	return async function viteIndexHtmlMiddleware(req, res, next) {
		if (res.writableEnded) return next();
		const url = req.url && cleanUrl(req.url);
		if (url?.endsWith(".html") && req.headers["sec-fetch-dest"] !== "script") {
			if (fullBundle) {
				let pathname;
				try {
					pathname = decodeURIComponent(url);
				} catch {
					return next();
				}
				const filePath = pathname.slice(1);
				let file = fullBundle.memoryFiles.get(filePath);
				if (!file && fullBundle.memoryFiles.size !== 0) return next();
				if ([
					"document",
					"iframe",
					"frame",
					"fencedframe",
					"",
					void 0
				].includes(req.headers["sec-fetch-dest"]) && (await fullBundle.triggerBundleRegenerationIfStale() || file === void 0)) file = { source: await generateFallbackHtml(server) };
				if (!file) return next();
				const html = typeof file.source === "string" ? file.source : Buffer.from(file.source);
				const headers = server.config.server.headers;
				return send$1(req, res, html, "html", {
					headers,
					etag: file.etag
				});
			}
			let filePath;
			if (isDev && url.startsWith(FS_PREFIX)) filePath = decodeURIComponent(fsPathFromId(url));
			else filePath = normalizePath(path.resolve(path.join(root, decodeURIComponent(url))));
			if (isDev) {
				const servingAccessResult = checkLoadingAccess(server.config, filePath);
				if (servingAccessResult === "denied") return respondWithAccessDenied(filePath, server, res);
				if (servingAccessResult === "fallback") return next();
			} else if (!isParentDirectory(root, filePath)) return next();
			if (fs.existsSync(filePath)) {
				const headers = isDev ? server.config.server.headers : server.config.preview.headers;
				try {
					let html = await fsp.readFile(filePath, "utf-8");
					if (isDev) html = await server.transformIndexHtml(url, html, req.originalUrl);
					return send$1(req, res, html, "html", { headers });
				} catch (e) {
					return next(e);
				}
			}
		}
		next();
	};
}
function preTransformRequest(server, decodedUrl, decodedBase) {
	if (!server.config.server.preTransformRequests) return;
	decodedUrl = unwrapId(stripBase(decodedUrl, decodedBase));
	server.warmupRequest(decodedUrl);
}
async function generateFallbackHtml(server) {
	return `
<!DOCTYPE html>
<html lang="en">
<head>
  <script type="module">
    ${(await getHmrImplementation(server.config)).replaceAll("<\/script>", "<\\/script>")}
  <\/script>
  <style>
    :root {
      --page-bg: #ffffff;
      --text-color: #1d1d1f;
      --spinner-track: #f5f5f7;
      --spinner-accent: #0071e3;
    }
    @media (prefers-color-scheme: dark) {
      :root {
        --page-bg: #1e1e1e;
        --text-color: #f5f5f5;
        --spinner-track: #424242;
      }
    }

    body {
      margin: 0;
      min-height: 100vh;
      display: flex;
      background-color: var(--page-bg);
      color: var(--text-color);
    }

    .container {
      margin: auto;
      padding: 2rem;
      text-align: center;
      border-radius: 1rem;
    }

    .spinner {
      width: 3rem;
      height: 3rem;
      margin: 2rem auto;
      border: 3px solid var(--spinner-track);
      border-top-color: var(--spinner-accent);
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin { to { transform: rotate(360deg) } }
  </style>
</head>
<body>
  <div class="container">
    <h1>Bundling in progress</h1>
    <p>The page will automatically reload when ready.</p>
    <div class="spinner"></div>
  </div>
</body>
</html>
`;
}
//#endregion
//#region src/node/server/middlewares/time.ts
const logTime = createDebugger("vite:time");
function timeMiddleware(root) {
	return function viteTimeMiddleware(req, res, next) {
		const start = performance$1.now();
		const end = res.end;
		res.end = (...args) => {
			logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`);
			return end.call(res, ...args);
		};
		next();
	};
}
//#endregion
//#region src/node/server/mixedModuleGraph.ts
/**
* Backward compatible ModuleNode and ModuleGraph with mixed nodes from both the client and ssr environments
* It would be good to take the types names for the new EnvironmentModuleNode and EnvironmentModuleGraph but we can't
* do that at this point without breaking to much code in the ecosystem.
* We are going to deprecate these types and we can try to use them back in the future.
*/
const EMPTY_OBJECT$1 = Object.freeze({});
var ModuleNode = class {
	_moduleGraph;
	_clientModule;
	_ssrModule;
	constructor(moduleGraph, clientModule, ssrModule) {
		this._moduleGraph = moduleGraph;
		this._clientModule = clientModule;
		this._ssrModule = ssrModule;
	}
	_get(prop) {
		return this._clientModule?.[prop] ?? this._ssrModule?.[prop];
	}
	_set(prop, value) {
		if (this._clientModule) this._clientModule[prop] = value;
		if (this._ssrModule) this._ssrModule[prop] = value;
	}
	_wrapModuleSet(prop, module) {
		if (!module) return /* @__PURE__ */ new Set();
		return createBackwardCompatibleModuleSet(this._moduleGraph, prop, module);
	}
	_getModuleSetUnion(prop) {
		const importedModules = /* @__PURE__ */ new Set();
		const ids = /* @__PURE__ */ new Set();
		if (this._clientModule) for (const mod of this._clientModule[prop]) {
			if (mod.id) ids.add(mod.id);
			importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
		}
		if (this._ssrModule) {
			for (const mod of this._ssrModule[prop]) if (mod.id && !ids.has(mod.id)) importedModules.add(this._moduleGraph.getBackwardCompatibleModuleNode(mod));
		}
		return importedModules;
	}
	_getModuleInfoUnion(prop) {
		const _clientValue = this._clientModule?.[prop];
		const _ssrValue = this._ssrModule?.[prop];
		if (_clientValue == null && _ssrValue == null) return void 0;
		return new Proxy({}, { get: (_, key) => {
			if (key === "meta") return this.meta || EMPTY_OBJECT$1;
			if (_clientValue) {
				if (key in _clientValue) return _clientValue[key];
			}
			if (_ssrValue) {
				if (key in _ssrValue) return _ssrValue[key];
			}
		} });
	}
	_getModuleObjectUnion(prop) {
		const _clientValue = this._clientModule?.[prop];
		const _ssrValue = this._ssrModule?.[prop];
		if (_clientValue == null && _ssrValue == null) return void 0;
		const info = {};
		if (_ssrValue) Object.assign(info, _ssrValue);
		if (_clientValue) Object.assign(info, _clientValue);
		return info;
	}
	get url() {
		return this._get("url");
	}
	set url(value) {
		this._set("url", value);
	}
	get id() {
		return this._get("id");
	}
	set id(value) {
		this._set("id", value);
	}
	get file() {
		return this._get("file");
	}
	set file(value) {
		this._set("file", value);
	}
	get type() {
		return this._get("type");
	}
	get info() {
		return this._getModuleInfoUnion("info");
	}
	get meta() {
		return this._getModuleObjectUnion("meta");
	}
	get importers() {
		return this._getModuleSetUnion("importers");
	}
	get clientImportedModules() {
		return this._wrapModuleSet("importedModules", this._clientModule);
	}
	get ssrImportedModules() {
		return this._wrapModuleSet("importedModules", this._ssrModule);
	}
	get importedModules() {
		return this._getModuleSetUnion("importedModules");
	}
	get acceptedHmrDeps() {
		return this._wrapModuleSet("acceptedHmrDeps", this._clientModule);
	}
	get acceptedHmrExports() {
		return this._clientModule?.acceptedHmrExports ?? null;
	}
	get importedBindings() {
		return this._clientModule?.importedBindings ?? null;
	}
	get isSelfAccepting() {
		return this._clientModule?.isSelfAccepting;
	}
	get transformResult() {
		return this._clientModule?.transformResult ?? null;
	}
	set transformResult(value) {
		if (this._clientModule) this._clientModule.transformResult = value;
	}
	get ssrTransformResult() {
		return this._ssrModule?.transformResult ?? null;
	}
	set ssrTransformResult(value) {
		if (this._ssrModule) this._ssrModule.transformResult = value;
	}
	get ssrModule() {
		return this._ssrModule?.ssrModule ?? null;
	}
	get ssrError() {
		return this._ssrModule?.ssrError ?? null;
	}
	get lastHMRTimestamp() {
		return Math.max(this._clientModule?.lastHMRTimestamp ?? 0, this._ssrModule?.lastHMRTimestamp ?? 0);
	}
	set lastHMRTimestamp(value) {
		if (this._clientModule) this._clientModule.lastHMRTimestamp = value;
		if (this._ssrModule) this._ssrModule.lastHMRTimestamp = value;
	}
	get lastInvalidationTimestamp() {
		return Math.max(this._clientModule?.lastInvalidationTimestamp ?? 0, this._ssrModule?.lastInvalidationTimestamp ?? 0);
	}
	get invalidationState() {
		return this._clientModule?.invalidationState;
	}
	get ssrInvalidationState() {
		return this._ssrModule?.invalidationState;
	}
};
function mapIterator(iterable, transform) {
	return {
		[Symbol.iterator]() {
			return this;
		},
		next() {
			const r = iterable.next();
			return r.done ? r : {
				value: transform(r.value),
				done: false
			};
		}
	};
}
var ModuleGraph = class {
	/** @internal */
	_moduleGraphs;
	/** @internal */
	get _client() {
		return this._moduleGraphs.client();
	}
	/** @internal */
	get _ssr() {
		return this._moduleGraphs.ssr();
	}
	urlToModuleMap;
	idToModuleMap;
	etagToModuleMap;
	fileToModulesMap;
	moduleNodeCache = new DualWeakMap();
	constructor(moduleGraphs) {
		this._moduleGraphs = moduleGraphs;
		const getModuleMapUnion = (prop) => () => {
			if (this._ssr[prop].size === 0) return this._client[prop];
			const map = new Map(this._client[prop]);
			for (const [key, module] of this._ssr[prop]) if (!map.has(key)) map.set(key, module);
			return map;
		};
		this.urlToModuleMap = createBackwardCompatibleModuleMap(this, "urlToModuleMap", getModuleMapUnion("urlToModuleMap"));
		this.idToModuleMap = createBackwardCompatibleModuleMap(this, "idToModuleMap", getModuleMapUnion("idToModuleMap"));
		this.etagToModuleMap = createBackwardCompatibleModuleMap(this, "etagToModuleMap", () => this._client.etagToModuleMap);
		this.fileToModulesMap = createBackwardCompatibleFileToModulesMap(this);
	}
	getModuleById(id) {
		const clientModule = this._client.getModuleById(id);
		const ssrModule = this._ssr.getModuleById(id);
		if (!clientModule && !ssrModule) return;
		return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
	}
	async getModuleByUrl(url, _ssr) {
		const [clientModule, ssrModule] = await Promise.all([this._client.getModuleByUrl(url), this._ssr.getModuleByUrl(url)]);
		if (!clientModule && !ssrModule) return;
		return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
	}
	getModulesByFile(file) {
		const clientModules = this._client.getModulesByFile(file);
		const ssrModules = this._ssr.getModulesByFile(file);
		if (!clientModules && !ssrModules) return;
		const result = /* @__PURE__ */ new Set();
		if (clientModules) for (const mod of clientModules) result.add(this.getBackwardCompatibleBrowserModuleNode(mod));
		if (ssrModules) {
			for (const mod of ssrModules) if (mod.id == null || !this._client.getModuleById(mod.id)) result.add(this.getBackwardCompatibleServerModuleNode(mod));
		}
		return result;
	}
	onFileChange(file) {
		this._client.onFileChange(file);
		this._ssr.onFileChange(file);
	}
	onFileDelete(file) {
		this._client.onFileDelete(file);
		this._ssr.onFileDelete(file);
	}
	/** @internal */
	_getModuleGraph(environment) {
		switch (environment) {
			case "client": return this._client;
			case "ssr": return this._ssr;
			default: throw new Error(`Invalid module node environment ${environment}`);
		}
	}
	invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
		if (mod._clientModule) this._client.invalidateModule(mod._clientModule, new Set([...seen].map((mod) => mod._clientModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
		if (mod._ssrModule) this._ssr.invalidateModule(mod._ssrModule, new Set([...seen].map((mod) => mod._ssrModule).filter(Boolean)), timestamp, isHmr, softInvalidate);
	}
	invalidateAll() {
		this._client.invalidateAll();
		this._ssr.invalidateAll();
	}
	async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) {
		const module = await (ssr ? this._ssr : this._client).ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
		return this.getBackwardCompatibleModuleNode(module);
	}
	createFileOnlyEntry(file) {
		const clientModule = this._client.createFileOnlyEntry(file);
		const ssrModule = this._ssr.createFileOnlyEntry(file);
		return this.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
	}
	async resolveUrl(url, ssr) {
		return ssr ? this._ssr.resolveUrl(url) : this._client.resolveUrl(url);
	}
	updateModuleTransformResult(mod, result, ssr) {
		const environment = ssr ? "ssr" : "client";
		this._getModuleGraph(environment).updateModuleTransformResult(environment === "client" ? mod._clientModule : mod._ssrModule, result);
	}
	getModuleByEtag(etag) {
		const mod = this._client.etagToModuleMap.get(etag);
		return mod && this.getBackwardCompatibleBrowserModuleNode(mod);
	}
	getBackwardCompatibleBrowserModuleNode(clientModule) {
		return this.getBackwardCompatibleModuleNodeDual(clientModule, clientModule.id ? this._ssr.getModuleById(clientModule.id) : void 0);
	}
	getBackwardCompatibleServerModuleNode(ssrModule) {
		return this.getBackwardCompatibleModuleNodeDual(ssrModule.id ? this._client.getModuleById(ssrModule.id) : void 0, ssrModule);
	}
	getBackwardCompatibleModuleNode(mod) {
		return mod.environment === "client" ? this.getBackwardCompatibleBrowserModuleNode(mod) : this.getBackwardCompatibleServerModuleNode(mod);
	}
	getBackwardCompatibleModuleNodeDual(clientModule, ssrModule) {
		const cached = this.moduleNodeCache.get(clientModule, ssrModule);
		if (cached) return cached;
		const moduleNode = new ModuleNode(this, clientModule, ssrModule);
		this.moduleNodeCache.set(clientModule, ssrModule, moduleNode);
		return moduleNode;
	}
};
var DualWeakMap = class {
	map = /* @__PURE__ */ new WeakMap();
	undefinedKey = {};
	get(key1, key2) {
		const k1 = key1 ?? this.undefinedKey;
		const k2 = key2 ?? this.undefinedKey;
		return this.map.get(k1)?.get(k2);
	}
	set(key1, key2, value) {
		const k1 = key1 ?? this.undefinedKey;
		const k2 = key2 ?? this.undefinedKey;
		if (!this.map.has(k1)) this.map.set(k1, /* @__PURE__ */ new Map());
		this.map.get(k1).set(k2, value);
	}
};
function createBackwardCompatibleModuleSet(moduleGraph, prop, module) {
	return {
		[Symbol.iterator]() {
			return this.keys();
		},
		has(key) {
			if (!key.id) return false;
			const keyModule = moduleGraph._getModuleGraph(module.environment).getModuleById(key.id);
			return keyModule !== void 0 && module[prop].has(keyModule);
		},
		values() {
			return this.keys();
		},
		keys() {
			return mapIterator(module[prop].keys(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
		},
		get size() {
			return module[prop].size;
		},
		forEach(callback, thisArg) {
			return module[prop].forEach((mod) => {
				const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
				callback.call(thisArg, backwardCompatibleMod, backwardCompatibleMod, this);
			});
		}
	};
}
function createBackwardCompatibleModuleMap(moduleGraph, prop, getModuleMap) {
	return {
		[Symbol.iterator]() {
			return this.entries();
		},
		get(key) {
			const clientModule = moduleGraph._client[prop].get(key);
			const ssrModule = moduleGraph._ssr[prop].get(key);
			if (!clientModule && !ssrModule) return;
			return moduleGraph.getBackwardCompatibleModuleNodeDual(clientModule, ssrModule);
		},
		set(key, mod) {
			const clientModule = mod._clientModule;
			if (clientModule) moduleGraph._client[prop].set(key, clientModule);
			const ssrModule = mod._ssrModule;
			if (ssrModule) moduleGraph._ssr[prop].set(key, ssrModule);
		},
		keys() {
			return getModuleMap().keys();
		},
		values() {
			return mapIterator(getModuleMap().values(), (mod) => moduleGraph.getBackwardCompatibleModuleNode(mod));
		},
		entries() {
			return mapIterator(getModuleMap().entries(), ([key, mod]) => [key, moduleGraph.getBackwardCompatibleModuleNode(mod)]);
		},
		get size() {
			return getModuleMap().size;
		},
		forEach(callback, thisArg) {
			return getModuleMap().forEach((mod, key) => {
				const backwardCompatibleMod = moduleGraph.getBackwardCompatibleModuleNode(mod);
				callback.call(thisArg, backwardCompatibleMod, key, this);
			});
		}
	};
}
function createBackwardCompatibleFileToModulesMap(moduleGraph) {
	const getFileToModulesMap = () => {
		if (!moduleGraph._ssr.fileToModulesMap.size) return moduleGraph._client.fileToModulesMap;
		const map = new Map(moduleGraph._client.fileToModulesMap);
		for (const [key, modules] of moduleGraph._ssr.fileToModulesMap) {
			const modulesSet = map.get(key);
			if (!modulesSet) map.set(key, modules);
			else for (const ssrModule of modules) {
				let hasModule = false;
				for (const clientModule of modulesSet) {
					hasModule ||= clientModule.id === ssrModule.id;
					if (hasModule) break;
				}
				if (!hasModule) modulesSet.add(ssrModule);
			}
		}
		return map;
	};
	const getBackwardCompatibleModules = (modules) => new Set([...modules].map((mod) => moduleGraph.getBackwardCompatibleModuleNode(mod)));
	return {
		[Symbol.iterator]() {
			return this.entries();
		},
		get(key) {
			const clientModules = moduleGraph._client.fileToModulesMap.get(key);
			const ssrModules = moduleGraph._ssr.fileToModulesMap.get(key);
			if (!clientModules && !ssrModules) return;
			const modules = clientModules ?? /* @__PURE__ */ new Set();
			if (ssrModules) {
				for (const ssrModule of ssrModules) if (ssrModule.id) {
					let found = false;
					for (const mod of modules) {
						found ||= mod.id === ssrModule.id;
						if (found) break;
					}
					if (!found) modules.add(ssrModule);
				}
			}
			return getBackwardCompatibleModules(modules);
		},
		keys() {
			return getFileToModulesMap().keys();
		},
		values() {
			return mapIterator(getFileToModulesMap().values(), getBackwardCompatibleModules);
		},
		entries() {
			return mapIterator(getFileToModulesMap().entries(), ([key, modules]) => [key, getBackwardCompatibleModules(modules)]);
		},
		get size() {
			return getFileToModulesMap().size;
		},
		forEach(callback, thisArg) {
			return getFileToModulesMap().forEach((modules, key) => {
				callback.call(thisArg, getBackwardCompatibleModules(modules), key, this);
			});
		}
	};
}
//#endregion
//#region src/node/server/middlewares/notFound.ts
function notFoundMiddleware() {
	return function vite404Middleware(_, res) {
		res.statusCode = 404;
		res.end();
	};
}
//#endregion
//#region src/node/server/middlewares/hostCheck.ts
function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) {
	const list = [];
	if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) list.push(resolvedServerOptions.host);
	if (typeof resolvedServerOptions.ws === "object" && resolvedServerOptions.ws.host) list.push(resolvedServerOptions.ws.host);
	if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) list.push(resolvedPreviewOptions.host);
	if (resolvedServerOptions.origin) try {
		const serverOriginUrl = new URL(resolvedServerOptions.origin);
		list.push(serverOriginUrl.hostname);
	} catch {}
	return list;
}
function hostValidationMiddleware(allowedHosts, isPreview) {
	return hostValidationMiddleware$1({
		allowedHosts: Object.freeze([...allowedHosts]),
		generateErrorMessage(hostname) {
			const hostnameWithQuotes = JSON.stringify(hostname);
			return `Blocked request. This host (${hostnameWithQuotes}) is not allowed.\nTo allow this host, add ${hostnameWithQuotes} to \`${`${isPreview ? "preview" : "server"}.allowedHosts`}\` in vite.config.js.`;
		}
	});
}
//#endregion
//#region src/node/server/middlewares/rejectInvalidRequest.ts
/**
* disallows request that contains `#` in the URL
*/
function rejectInvalidRequestMiddleware() {
	return function viteRejectInvalidRequestMiddleware(req, res, next) {
		if (req.url?.includes("#")) {
			res.writeHead(400);
			res.end();
			return;
		}
		return next();
	};
}
//#endregion
//#region src/node/server/middlewares/memoryFiles.ts
function memoryFilesMiddleware(server) {
	const memoryFiles = server.environments.client.bundledDev?.memoryFiles;
	if (!memoryFiles) throw new Error("memoryFilesMiddleware can only be used for fullBundleMode");
	const headers = server.config.server.headers;
	return function viteMemoryFilesMiddleware(req, res, next) {
		const cleanedUrl = cleanUrl(req.url);
		if (cleanedUrl.endsWith(".html")) return next();
		let pathname;
		try {
			pathname = decodeURIComponent(cleanedUrl);
		} catch {
			return next();
		}
		const filePath = pathname.slice(1);
		const file = memoryFiles.get(filePath);
		if (file) {
			if (file.etag) {
				if (req.headers["if-none-match"] === file.etag) {
					res.statusCode = 304;
					res.end();
					return;
				}
				res.setHeader("Etag", file.etag);
			}
			const mime = lookup(filePath);
			if (mime) res.setHeader("Content-Type", mime);
			for (const name in headers) res.setHeader(name, headers[name]);
			return res.end(file.source);
		}
		next();
	};
}
//#endregion
//#region src/node/server/middlewares/triggerLazyBundling.ts
function triggerLazyBundlingMiddleware(server) {
	const bundledDev = server.environments.client.bundledDev;
	if (!bundledDev) throw new Error("triggerLazyBundlingMiddleware can only be used for fullBundleMode");
	return async function viteTriggerLazyBundlingMiddleware(req, res, next) {
		if (!req.url?.startsWith("/@vite/lazy?")) return next();
		let params;
		try {
			params = new URL(`http://localhost${req.url}`).searchParams;
		} catch {
			return next();
		}
		const moduleId = params.get("id");
		const clientId = params.get("clientId");
		const code = await bundledDev.triggerLazyBundling(moduleId, clientId);
		if (code == null) return next();
		res.setHeader("Content-Type", "application/javascript");
		return res.end(code);
	};
}
//#endregion
//#region src/node/server/index.ts
var server_exports = /* @__PURE__ */ __exportAll({
	_createServer: () => _createServer,
	createServer: () => createServer$2,
	createServerCloseFn: () => createServerCloseFn,
	resolveForwardConsoleOptions: () => resolveForwardConsoleOptions,
	resolveServerOptions: () => resolveServerOptions,
	restartServerWithUrls: () => restartServerWithUrls,
	serverConfigDefaults: () => serverConfigDefaults
});
var import_connect = /* @__PURE__ */ __toESM(require_connect(), 1);
var import_lib = /* @__PURE__ */ __toESM(require_lib$1(), 1);
var import_chokidar = /* @__PURE__ */ __toESM(require_chokidar(), 1);
var import_launch_editor_middleware = /* @__PURE__ */ __toESM(require_launch_editor_middleware(), 1);
var import_dist = require_dist();
const usedConfigs = /* @__PURE__ */ new WeakSet();
async function resolveForwardConsoleOptions(value) {
	value ??= (await (0, import_dist.determineAgent)()).isAgent;
	if (value === false) return {
		enabled: false,
		unhandledErrors: false,
		logLevels: []
	};
	if (value === true) return {
		enabled: true,
		unhandledErrors: true,
		logLevels: ["error", "warn"]
	};
	const unhandledErrors = value.unhandledErrors ?? true;
	const logLevels = value.logLevels ?? [];
	return {
		enabled: unhandledErrors || logLevels.length > 0,
		unhandledErrors,
		logLevels
	};
}
function createServer$2(inlineConfig = {}) {
	return _createServer(inlineConfig, { listen: true });
}
async function _createServer(inlineConfig = {}, options) {
	disableCache();
	const config = isResolvedConfig(inlineConfig) ? inlineConfig : await resolveConfig(inlineConfig, "serve");
	if (usedConfigs.has(config)) throw new Error(`There is already a server associated with the config.`);
	if (config.command !== "serve") throw new Error(`Config was resolved for a "build", expected a "serve" command.`);
	usedConfigs.add(config);
	const initPublicFilesPromise = initPublicFiles(config);
	const { root, server: serverConfig } = config;
	const httpsOptions = await resolveHttpsConfig(config.server.https);
	const { middlewareMode } = serverConfig;
	const resolvedOutDirs = getResolvedOutDirs(config.root, config.build.outDir, config.build.rolldownOptions.output);
	const emptyOutDir = resolveEmptyOutDir(config.build.emptyOutDir, config.root, resolvedOutDirs);
	const resolvedWatchOptions = resolveChokidarOptions({
		disableGlobbing: true,
		...serverConfig.watch
	}, resolvedOutDirs, emptyOutDir, config.cacheDir);
	const middlewares = (0, import_connect.default)();
	const httpServer = middlewareMode ? null : await resolveHttpServer(middlewares, httpsOptions);
	const ws = createWebSocketServer(httpServer, config, httpsOptions);
	const publicFiles = await initPublicFilesPromise;
	const { publicDir } = config;
	if (httpServer) setClientErrorHandler(httpServer, config.logger);
	const watcher = serverConfig.watch !== null ? import_chokidar.watch([
		...config.experimental.bundledDev ? [] : [root],
		...config.configFileDependencies,
		...getEnvFilesForMode(config.mode, config.envDir),
		...publicDir && publicFiles ? [publicDir] : []
	], resolvedWatchOptions) : createNoopWatcher(resolvedWatchOptions);
	const environments = {};
	await Promise.all(Object.entries(config.environments).map(async ([name, environmentOptions]) => {
		const environment = await environmentOptions.dev.createEnvironment(name, config, { ws });
		environments[name] = environment;
		await environment.init({
			watcher,
			previousInstance: options.previousEnvironments?.[environment.name]
		});
	}));
	let moduleGraph = new ModuleGraph({
		client: () => environments.client.moduleGraph,
		ssr: () => environments.ssr.moduleGraph
	});
	let pluginContainer = createPluginContainer(environments);
	const closeHttpServer = createServerCloseFn(httpServer);
	const devHtmlTransformFn = createDevHtmlTransformFn(config);
	let closeServerPromise;
	const closeServer = async () => {
		if (!middlewareMode) teardownSIGTERMListener(closeServerAndExit);
		await Promise.allSettled([
			watcher.close(),
			ws.close(),
			Promise.allSettled(Object.values(server.environments).map((environment) => environment.close())),
			closeHttpServer(),
			server._ssrCompatModuleRunner?.close()
		]);
		server.resolvedUrls = null;
		server._ssrCompatModuleRunner = void 0;
	};
	let hot = ws;
	let server = {
		config,
		middlewares,
		httpServer,
		watcher,
		ws,
		get hot() {
			warnFutureDeprecation(config, "removeServerHot");
			return hot;
		},
		set hot(h) {
			hot = h;
		},
		environments,
		get pluginContainer() {
			warnFutureDeprecation(config, "removeServerPluginContainer");
			return pluginContainer;
		},
		set pluginContainer(p) {
			pluginContainer = p;
		},
		get moduleGraph() {
			warnFutureDeprecation(config, "removeServerModuleGraph");
			return moduleGraph;
		},
		set moduleGraph(graph) {
			moduleGraph = graph;
		},
		resolvedUrls: null,
		ssrTransform(code, inMap, url, originalCode = code) {
			return ssrTransform(code, inMap, url, originalCode, { json: { stringify: config.json.stringify === true && config.json.namedExports !== true } });
		},
		transformRequest(url, options) {
			warnFutureDeprecation(config, "removeServerTransformRequest");
			return server.environments[options?.ssr ? "ssr" : "client"].transformRequest(url);
		},
		warmupRequest(url, options) {
			warnFutureDeprecation(config, "removeServerWarmupRequest");
			return server.environments[options?.ssr ? "ssr" : "client"].warmupRequest(url);
		},
		transformIndexHtml(url, html, originalUrl) {
			return devHtmlTransformFn(server, url, html, originalUrl);
		},
		async ssrLoadModule(url, opts) {
			warnFutureDeprecation(config, "removeSsrLoadModule");
			return ssrLoadModule(url, server, opts?.fixStacktrace);
		},
		ssrFixStacktrace(e) {
			warnFutureDeprecation(config, "removeSsrLoadModule", "ssrFixStacktrace doesn't need to be used for Environment Module Runners.");
			ssrFixStacktrace(e, server.environments.ssr.moduleGraph);
		},
		ssrRewriteStacktrace(stack) {
			warnFutureDeprecation(config, "removeSsrLoadModule", "ssrRewriteStacktrace doesn't need to be used for Environment Module Runners.");
			return ssrRewriteStacktrace(stack, server.environments.ssr.moduleGraph).result;
		},
		async reloadModule(module) {
			warnFutureDeprecation(config, "removeServerReloadModule");
			if (serverConfig.hmr !== false && module.file) {
				const environmentModule = module._clientModule ?? module._ssrModule;
				updateModules(environments[environmentModule.environment], module.file, [environmentModule], monotonicDateNow());
			}
		},
		async listen(port, isRestart) {
			const hostname = await resolveHostname(config.server.host);
			if (httpServer) httpServer.prependListener("listening", () => {
				server.resolvedUrls = resolveServerUrls(httpServer, config.server, hostname, httpsOptions, config);
			});
			await startServer(server, hostname, port);
			if (httpServer) {
				if (!isRestart && config.server.open) server.openBrowser();
			}
			return server;
		},
		openBrowser() {
			const options = server.config.server;
			const url = getServerUrlByHost(server.resolvedUrls, options.host);
			if (url) {
				const path = typeof options.open === "string" ? new URL(options.open, url).href : url;
				if (server.config.server.preTransformRequests) setTimeout(() => {
					(path.startsWith("https:") ? get$1 : get)(path, { headers: { Accept: "text/html" } }, (res) => {
						res.on("end", () => {});
					}).on("error", () => {}).end();
				}, 0);
				openBrowser(path, true, server.config.logger);
			} else server.config.logger.warn("No URL available to open in browser");
		},
		async close() {
			if (!closeServerPromise) closeServerPromise = closeServer();
			return closeServerPromise;
		},
		printUrls() {
			if (server.resolvedUrls) printServerUrls(server.resolvedUrls, serverConfig.host, config.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(options) {
			bindCLIShortcuts(server, options);
		},
		async restart(forceOptimize) {
			if (!server._restartPromise) {
				server._forceOptimizeOnRestart = !!forceOptimize;
				server._restartPromise = restartServer(server).finally(() => {
					server._restartPromise = null;
					server._forceOptimizeOnRestart = false;
				});
			}
			return server._restartPromise;
		},
		waitForRequestsIdle(ignoredId) {
			return environments.client.waitForRequestsIdle(ignoredId);
		},
		_setInternalServer(_server) {
			server = _server;
		},
		_restartPromise: options.previousRestartPromise ?? null,
		_forceOptimizeOnRestart: options.previousForceOptimizeOnRestart ?? false,
		_shortcutsState: options.previousShortcutsState
	};
	const reflexServer = new Proxy(server, {
		get: (_, property) => {
			return server[property];
		},
		set: (_, property, value) => {
			server[property] = value;
			return true;
		}
	});
	const closeServerAndExit = async (_, exitCode) => {
		try {
			await server.close();
		} finally {
			process.exitCode ??= exitCode ? 128 + exitCode : void 0;
			process.exit();
		}
	};
	if (!middlewareMode) setupSIGTERMListener(closeServerAndExit);
	const onHMRUpdate = async (type, file) => {
		if (serverConfig.hmr !== false) await handleHMRUpdate(type, file, server);
	};
	const onFileAddUnlink = async (file, isUnlink) => {
		file = normalizePath(file);
		reloadOnTsconfigChange(server, file);
		await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: isUnlink ? "delete" : "create" })));
		if (publicDir && publicFiles) {
			if (file.startsWith(publicDir)) {
				const path = file.slice(publicDir.length);
				publicFiles[isUnlink ? "delete" : "add"](path);
				if (!isUnlink) {
					const clientModuleGraph = server.environments.client.moduleGraph;
					const etag = (await clientModuleGraph.getModuleByUrl(path))?.transformResult?.etag;
					if (etag) clientModuleGraph.etagToModuleMap.delete(etag);
				}
			}
		}
		if (isUnlink) for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileDelete(file);
		await onHMRUpdate(isUnlink ? "delete" : "create", file);
	};
	const onFileChange = async (file) => {
		file = normalizePath(file);
		reloadOnTsconfigChange(server, file);
		await Promise.all(Object.values(server.environments).map((environment) => environment.pluginContainer.watchChange(file, { event: "update" })));
		for (const environment of Object.values(server.environments)) environment.moduleGraph.onFileChange(file);
		await onHMRUpdate("update", file);
	};
	watcher.on("change", (file) => {
		onFileChange(file).catch((e) => server.config.logger.error(e));
	});
	watcher.on("add", (file) => {
		onFileAddUnlink(file, false).catch((e) => server.config.logger.error(e));
	});
	watcher.on("unlink", (file) => {
		onFileAddUnlink(file, true).catch((e) => server.config.logger.error(e));
	});
	if (!middlewareMode && httpServer) httpServer.once("listening", () => {
		serverConfig.port = httpServer.address().port;
	});
	if (process.env.DEBUG) middlewares.use(timeMiddleware(root));
	middlewares.use(rejectInvalidRequestMiddleware());
	const { cors } = serverConfig;
	if (cors !== false) middlewares.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
	const { allowedHosts } = serverConfig;
	if (allowedHosts !== true && !serverConfig.https) middlewares.use(hostValidationMiddleware(allowedHosts, false));
	const configureServerContext = new BasicMinimalPluginContext({
		...basePluginContextMeta,
		watchMode: true
	}, config.logger);
	const postHooks = [];
	for (const hook of config.getSortedPluginHooks("configureServer")) postHooks.push(await hook.call(configureServerContext, reflexServer));
	if (!config.experimental.bundledDev) middlewares.use(cachedTransformMiddleware(server));
	const { proxy } = serverConfig;
	if (proxy) {
		const middlewareServer = (isObject$1(middlewareMode) ? middlewareMode.server : null) || httpServer;
		middlewares.use(proxyMiddleware(middlewareServer, proxy, config));
	}
	if (config.base !== "/") middlewares.use(baseMiddleware(config.rawBase, !!middlewareMode));
	middlewares.use("/__open-in-editor", (0, import_launch_editor_middleware.default)());
	middlewares.use(function viteHMRPingMiddleware(req, res, next) {
		if (req.headers.accept === "text/x-vite-ping") res.writeHead(204).end();
		else next();
	});
	if (publicDir) middlewares.use(servePublicMiddleware(server, publicFiles));
	if (config.experimental.bundledDev) {
		middlewares.use(triggerLazyBundlingMiddleware(server));
		middlewares.use(memoryFilesMiddleware(server));
	} else {
		middlewares.use(transformMiddleware(server));
		middlewares.use(serveRawFsMiddleware(server));
		middlewares.use(serveStaticMiddleware(server));
	}
	if (config.appType === "spa" || config.appType === "mpa") middlewares.use(htmlFallbackMiddleware(root, config.appType === "spa", server.environments.client));
	postHooks.forEach((fn) => fn && fn());
	if (config.appType === "spa" || config.appType === "mpa") {
		middlewares.use(indexHtmlMiddleware(root, server));
		middlewares.use(notFoundMiddleware());
	}
	middlewares.use(errorMiddleware(server, !!middlewareMode));
	let initingServer;
	let serverInited = false;
	const initServer = async (onListen) => {
		if (serverInited) return;
		if (initingServer) return initingServer;
		initingServer = (async function() {
			if (!config.experimental.bundledDev) await environments.client.pluginContainer.buildStart();
			if (onListen || options.listen) await Promise.all(Object.values(environments).map((e) => e.listen(server)));
			initingServer = void 0;
			serverInited = true;
		})();
		return initingServer;
	};
	if (!middlewareMode && httpServer) {
		const listen = httpServer.listen.bind(httpServer);
		httpServer.listen = (async (port, ...args) => {
			try {
				await initServer(true);
			} catch (e) {
				httpServer.emit("error", e);
				return;
			}
			return listen(port, ...args);
		});
	} else await initServer(false);
	return server;
}
async function startServer(server, hostname, inlinePort) {
	const httpServer = server.httpServer;
	if (!httpServer) throw new Error("Cannot call server.listen in middleware mode.");
	const options = server.config.server;
	const configPort = inlinePort ?? options.port;
	const port = (!configPort || configPort === server._configServerPort ? server._currentServerPort : configPort) ?? 5173;
	server._configServerPort = configPort;
	server._currentServerPort = await httpServerStart(httpServer, {
		port,
		strictPort: options.strictPort,
		host: hostname.host,
		logger: server.config.logger
	});
}
function createServerCloseFn(server) {
	if (!server) return () => Promise.resolve();
	let hasListened = false;
	const openSockets = /* @__PURE__ */ new Set();
	server.on("connection", (socket) => {
		openSockets.add(socket);
		socket.on("close", () => {
			openSockets.delete(socket);
		});
	});
	server.once("listening", () => {
		hasListened = true;
	});
	return () => new Promise((resolve, reject) => {
		openSockets.forEach((s) => s.destroy());
		if (hasListened) server.close((err) => {
			if (err) reject(err);
			else resolve();
		});
		else resolve();
	});
}
function resolvedAllowDir(root, dir) {
	return normalizePath(path.resolve(root, dir));
}
const _serverConfigDefaults = Object.freeze({
	port: DEFAULT_DEV_PORT,
	strictPort: false,
	host: "localhost",
	allowedHosts: [],
	https: void 0,
	open: false,
	proxy: void 0,
	cors: { origin: defaultAllowedOrigins },
	headers: {},
	warmup: {
		clientFiles: [],
		ssrFiles: []
	},
	middlewareMode: false,
	fs: {
		strict: true,
		deny: [
			".env",
			".env.*",
			"*.{crt,pem,key,p12,pfx,cer,der}",
			".npmrc",
			".yarnrc.yml",
			"**/.git/**"
		]
	},
	preTransformRequests: true,
	perEnvironmentStartEndDuringDev: false,
	perEnvironmentWatchChangeDuringDev: false,
	forwardConsole: void 0
});
const serverConfigDefaults = _serverConfigDefaults;
const RESERVED_ALLOWED_HOSTS_CHARACTERS_RE = /[\\"']/;
async function resolveServerOptions(root, raw, logger) {
	const _server = mergeWithDefaults({
		..._serverConfigDefaults,
		host: void 0,
		sourcemapIgnoreList: isInNodeModules
	}, raw ?? {});
	setupHmrWsOptionCompat(_server);
	const workspaceRoot = searchForWorkspaceRoot(root);
	const server = {
		..._server,
		fs: {
			..._server.fs,
			allow: raw?.fs?.allow ?? [workspaceRoot]
		},
		sourcemapIgnoreList: _server.sourcemapIgnoreList === false ? () => false : _server.sourcemapIgnoreList,
		forwardConsole: await resolveForwardConsoleOptions(_server.forwardConsole)
	};
	let allowDirs = server.fs.allow;
	const cwd = searchForPackageRoot(root);
	if (process.versions.pnp) try {
		const yarnCacheDir = execSync(`yarn config get ${execSync("yarn config get enableGlobalCache", { cwd }).toString().trim() === "true" ? "globalFolder" : "cacheFolder"}`, { cwd }).toString().trim();
		allowDirs.push(yarnCacheDir);
	} catch (e) {
		logger.warn(`Get yarn cache dir error: ${e.message}`, { timestamp: true });
	}
	const pnpmModulesYaml = path.join(workspaceRoot, "node_modules", ".modules.yaml");
	try {
		const content = fs.readFileSync(pnpmModulesYaml, "utf-8");
		const virtualStoreDir = JSON.parse(content).virtualStoreDir;
		if (virtualStoreDir) {
			if (path.isAbsolute(virtualStoreDir)) allowDirs.push(virtualStoreDir);
			else if (virtualStoreDir.startsWith("..")) allowDirs.push(path.resolve(path.join(workspaceRoot, "node_modules"), virtualStoreDir));
		}
	} catch {}
	allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i));
	const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR);
	if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) allowDirs.push(resolvedClientDir);
	server.fs.allow = allowDirs;
	if (server.origin?.endsWith("/")) {
		server.origin = server.origin.slice(0, -1);
		logger.warn(import_picocolors.default.yellow(`${import_picocolors.default.bold("(!)")} server.origin should not end with "/". Using "${server.origin}" instead.`));
	}
	if (process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS && Array.isArray(server.allowedHosts)) {
		const rawAdditionalHosts = process.env.__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS;
		if (RESERVED_ALLOWED_HOSTS_CHARACTERS_RE.test(rawAdditionalHosts)) logger.warn(import_picocolors.default.yellow(`${import_picocolors.default.bold("(!)")} Skipping additional allowed hosts from environment variable due to reserved characters. Received: "${rawAdditionalHosts}".`));
		else {
			const additionalHosts = rawAdditionalHosts.split(",").map((host) => host.trim()).filter(Boolean);
			server.allowedHosts = [...server.allowedHosts, ...additionalHosts];
		}
	}
	return server;
}
async function restartServer(server) {
	global.__vite_start_time = performance$1.now();
	let inlineConfig = server.config.inlineConfig;
	if (server._forceOptimizeOnRestart) inlineConfig = mergeConfig(inlineConfig, { forceOptimizeDeps: true });
	{
		let newServer = null;
		try {
			newServer = await _createServer(inlineConfig, {
				listen: false,
				previousEnvironments: server.environments,
				previousShortcutsState: server._shortcutsState,
				previousRestartPromise: server._restartPromise,
				previousForceOptimizeOnRestart: server._forceOptimizeOnRestart
			});
		} catch (err) {
			server.config.logger.error(err.message, { timestamp: true });
			server.config.logger.error("server restart failed", { timestamp: true });
			return;
		}
		server._shortcutsState = void 0;
		await server.close();
		const middlewares = server.middlewares;
		newServer._configServerPort = server._configServerPort;
		newServer._currentServerPort = server._currentServerPort;
		Object.assign(server, newServer);
		middlewares.stack = newServer.middlewares.stack;
		server.middlewares = middlewares;
		newServer._setInternalServer(server);
	}
	const { logger, server: { port, middlewareMode } } = server.config;
	if (!middlewareMode) await server.listen(port, true);
	else await Promise.all(Object.values(server.environments).map((e) => e.listen(server)));
	logger.info("server restarted.", { timestamp: true });
	if (server._shortcutsState?.options) bindCLIShortcuts(server, { print: false }, true);
}
/**
* Internal function to restart the Vite server and print URLs if changed
*/
async function restartServerWithUrls(server) {
	if (server.config.server.middlewareMode) {
		await server.restart();
		return;
	}
	const { port: prevPort, host: prevHost } = server.config.server;
	const prevUrls = server.resolvedUrls;
	await server.restart();
	const { logger, server: { port, host } } = server.config;
	if ((port ?? 5173) !== (prevPort ?? 5173) || host !== prevHost || diffDnsOrderChange(prevUrls, server.resolvedUrls)) {
		logger.info("");
		server.printUrls();
	}
}
//#endregion
//#region src/node/server/hmr.ts
const debugHmr = createDebugger("vite:hmr");
const whitespaceRE = /\s/;
const normalizedClientDir = normalizePath(CLIENT_DIR);
function getShortName(file, root) {
	return file.startsWith(withTrailingSlash(root)) ? path.posix.relative(root, file) : file;
}
const normalizeHotChannel = (channel, enableHmr, normalizeClient = true) => {
	const normalizedListenerMap = /* @__PURE__ */ new WeakMap();
	const normalizedClients = /* @__PURE__ */ new WeakMap();
	let invokeHandlers;
	let listenerForInvokeHandler;
	const handleInvoke = async (payload) => {
		if (!invokeHandlers) return { error: {
			name: "TransportError",
			message: "invokeHandlers is not set",
			stack: (/* @__PURE__ */ new Error()).stack
		} };
		const { name, data: args } = payload.data;
		try {
			const invokeHandler = invokeHandlers[name];
			return { result: await invokeHandler(...args) };
		} catch (error) {
			return { error: {
				name: error.name,
				message: error.message,
				stack: error.stack,
				...error
			} };
		}
	};
	return {
		...channel,
		on: (event, fn) => {
			if (event === "connection" || !normalizeClient) {
				channel.on?.(event, fn);
				return;
			}
			const listenerWithNormalizedClient = (data, client) => {
				if (!normalizedClients.has(client)) normalizedClients.set(client, { send: (...args) => {
					let payload;
					if (typeof args[0] === "string") payload = {
						type: "custom",
						event: args[0],
						data: args[1]
					};
					else payload = args[0];
					client.send(payload);
				} });
				fn(data, normalizedClients.get(client));
			};
			normalizedListenerMap.set(fn, listenerWithNormalizedClient);
			channel.on?.(event, listenerWithNormalizedClient);
		},
		off: (event, fn) => {
			if (event === "connection" || !normalizeClient) {
				channel.off?.(event, fn);
				return;
			}
			const normalizedListener = normalizedListenerMap.get(fn);
			if (normalizedListener) channel.off?.(event, normalizedListener);
		},
		setInvokeHandler(_invokeHandlers) {
			invokeHandlers = _invokeHandlers;
			if (!_invokeHandlers) {
				if (listenerForInvokeHandler) channel.off?.("vite:invoke", listenerForInvokeHandler);
				return;
			}
			listenerForInvokeHandler = async (payload, client) => {
				const responseInvoke = payload.id.replace("send", "response");
				client.send({
					type: "custom",
					event: "vite:invoke",
					data: {
						name: payload.name,
						id: responseInvoke,
						data: await handleInvoke({
							type: "custom",
							event: "vite:invoke",
							data: payload
						})
					}
				});
			};
			channel.on?.("vite:invoke", listenerForInvokeHandler);
		},
		handleInvoke,
		send: (...args) => {
			let payload;
			if (typeof args[0] === "string") payload = {
				type: "custom",
				event: args[0],
				data: args[1]
			};
			else payload = args[0];
			if (enableHmr || payload.type === "connected" || payload.type === "ping" || payload.type === "custom" || payload.type === "error") channel.send?.(payload);
		},
		listen() {
			return channel.listen?.();
		},
		close() {
			return channel.close?.();
		}
	};
};
function getSortedPluginsByHotUpdateHook(plugins) {
	const sortedPlugins = [];
	let pre = 0, normal = 0, post = 0;
	for (const plugin of plugins) {
		const hook = plugin.hotUpdate ?? plugin.handleHotUpdate;
		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;
}
const sortedHotUpdatePluginsCache = /* @__PURE__ */ new WeakMap();
function getSortedHotUpdatePlugins(environment) {
	let sortedPlugins = sortedHotUpdatePluginsCache.get(environment);
	if (!sortedPlugins) {
		sortedPlugins = getSortedPluginsByHotUpdateHook(environment.plugins);
		sortedHotUpdatePluginsCache.set(environment, sortedPlugins);
	}
	return sortedPlugins;
}
async function handleHMRUpdate(type, file, server) {
	const { config } = server;
	const mixedModuleGraph = ignoreDeprecationWarnings(() => server.moduleGraph);
	const environments = Object.values(server.environments);
	const shortFile = getShortName(file, config.root);
	const isConfig = file === config.configFile;
	const isConfigDependency = config.configFileDependencies.some((name) => file === name);
	const isEnv = config.envDir !== false && getEnvFilesForMode(config.mode, config.envDir).includes(file);
	if (isConfig || isConfigDependency || isEnv) {
		debugHmr?.(`[config change] ${import_picocolors.default.dim(shortFile)}`);
		config.logger.info(import_picocolors.default.green(`${normalizePath(path.relative(process.cwd(), file))} changed, restarting server...`), {
			clear: true,
			timestamp: true
		});
		try {
			await restartServerWithUrls(server);
		} catch (e) {
			config.logger.error(import_picocolors.default.red(e));
		}
		return;
	}
	debugHmr?.(`[file change] ${import_picocolors.default.dim(shortFile)}`);
	if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
		environments.forEach(({ hot }) => hot.send({
			type: "full-reload",
			path: "*",
			triggeredBy: path.resolve(config.root, file)
		}));
		return;
	}
	if (config.experimental.bundledDev) return;
	const timestamp = monotonicDateNow();
	const contextMeta = {
		type,
		file,
		timestamp,
		read: () => readModifiedFile(file),
		server
	};
	const hotMap = /* @__PURE__ */ new Map();
	for (const environment of environments) {
		const mods = new Set(environment.moduleGraph.getModulesByFile(file));
		if (type === "create") for (const mod of environment.moduleGraph._hasResolveFailedErrorModules) mods.add(mod);
		const options = {
			...contextMeta,
			modules: [...mods]
		};
		hotMap.set(environment, { options });
	}
	const mixedMods = new Set(mixedModuleGraph.getModulesByFile(file));
	const mixedHmrContext = {
		...contextMeta,
		modules: [...mixedMods]
	};
	const contextForHandleHotUpdate = new BasicMinimalPluginContext({
		...basePluginContextMeta,
		watchMode: true
	}, config.logger);
	const clientEnvironment = server.environments.client;
	const ssrEnvironment = server.environments.ssr;
	const clientContext = clientEnvironment.pluginContainer.minimalContext;
	const clientHotUpdateOptions = hotMap.get(clientEnvironment).options;
	const ssrHotUpdateOptions = hotMap.get(ssrEnvironment)?.options;
	try {
		for (const plugin of getSortedHotUpdatePlugins(server.environments.client)) if (plugin.hotUpdate) {
			const filteredModules = await getHookHandler(plugin.hotUpdate).call(clientContext, clientHotUpdateOptions);
			if (filteredModules) {
				clientHotUpdateOptions.modules = filteredModules;
				mixedHmrContext.modules = mixedHmrContext.modules.filter((mixedMod) => filteredModules.some((mod) => mixedMod.id === mod.id) || ssrHotUpdateOptions?.modules.some((ssrMod) => ssrMod.id === mixedMod.id));
				mixedHmrContext.modules.push(...filteredModules.filter((mod) => !mixedHmrContext.modules.some((mixedMod) => mixedMod.id === mod.id)).map((mod) => mixedModuleGraph.getBackwardCompatibleModuleNode(mod)));
			}
		} else if (type === "update") {
			warnFutureDeprecation(config, "removePluginHookHandleHotUpdate", `Used in plugin "${plugin.name}".`, false);
			const filteredModules = await getHookHandler(plugin.handleHotUpdate).call(contextForHandleHotUpdate, mixedHmrContext);
			if (filteredModules) {
				mixedHmrContext.modules = filteredModules;
				clientHotUpdateOptions.modules = clientHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
				clientHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !clientHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._clientModule).filter(Boolean));
				if (ssrHotUpdateOptions) {
					ssrHotUpdateOptions.modules = ssrHotUpdateOptions.modules.filter((mod) => filteredModules.some((mixedMod) => mod.id === mixedMod.id));
					ssrHotUpdateOptions.modules.push(...filteredModules.filter((mixedMod) => !ssrHotUpdateOptions.modules.some((mod) => mod.id === mixedMod.id)).map((mixedMod) => mixedMod._ssrModule).filter(Boolean));
				}
			}
		}
	} catch (error) {
		hotMap.get(server.environments.client).error = error;
	}
	for (const environment of environments) {
		if (environment.name === "client") continue;
		const hot = hotMap.get(environment);
		const context = environment.pluginContainer.minimalContext;
		try {
			for (const plugin of getSortedHotUpdatePlugins(environment)) if (plugin.hotUpdate) {
				const filteredModules = await getHookHandler(plugin.hotUpdate).call(context, hot.options);
				if (filteredModules) hot.options.modules = filteredModules;
			}
		} catch (error) {
			hot.error = error;
		}
	}
	async function hmr(environment) {
		try {
			const { options, error } = hotMap.get(environment);
			if (error) throw error;
			if (!options.modules.length) {
				if (file.endsWith(".html") && environment.name === "client") {
					environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(shortFile), {
						clear: true,
						timestamp: true
					});
					environment.hot.send({
						type: "full-reload",
						path: config.server.middlewareMode ? "*" : "/" + normalizePath(path.relative(config.root, file))
					});
				} else debugHmr?.(`(${environment.name}) [no modules matched] ${import_picocolors.default.dim(shortFile)}`);
				return;
			}
			updateModules(environment, shortFile, options.modules, timestamp);
		} catch (err) {
			environment.hot.send({
				type: "error",
				err: prepareError(err)
			});
		}
	}
	await (server.config.server.hotUpdateEnvironments ?? ((server, hmr) => {
		return Promise.all(Object.values(server.environments).map((environment) => hmr(environment)));
	}))(server, hmr);
}
function updateModules(environment, file, modules, timestamp, firstInvalidatedBy) {
	const { hot } = environment;
	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);
		environment.moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true);
		if (needFullReload) continue;
		if (hasDeadEnd) {
			needFullReload = hasDeadEnd;
			continue;
		}
		if (firstInvalidatedBy && boundaries.some(({ acceptedVia }) => normalizeHmrUrl(acceptedVia.url) === firstInvalidatedBy)) {
			needFullReload = "circular import invalidate";
			continue;
		}
		updates.push(...boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
			type: `${boundary.type}-update`,
			timestamp,
			path: normalizeHmrUrl(boundary.url),
			acceptedPath: normalizeHmrUrl(acceptedVia.url),
			explicitImportRequired: boundary.type === "js" ? isExplicitImportRequired(acceptedVia.url) : false,
			isWithinCircularImport,
			firstInvalidatedBy
		})));
	}
	const isClientHtmlChange = file.endsWith(".html") && environment.name === "client" && modules.every((mod) => mod.type !== "js");
	if (needFullReload || isClientHtmlChange) {
		const reason = typeof needFullReload === "string" ? import_picocolors.default.dim(` (${needFullReload})`) : "";
		environment.logger.info(import_picocolors.default.green(`page reload `) + import_picocolors.default.dim(file) + reason, {
			clear: !firstInvalidatedBy,
			timestamp: true
		});
		hot.send({
			type: "full-reload",
			triggeredBy: path.resolve(environment.config.root, file),
			path: !isClientHtmlChange || environment.config.server.middlewareMode || updates.length > 0 ? "*" : "/" + file
		});
		return;
	}
	if (updates.length === 0) {
		debugHmr?.(import_picocolors.default.yellow(`no update happened `) + import_picocolors.default.dim(file));
		return;
	}
	const filePaths = [...new Set(updates.map((u) => u.path))];
	const { formatted, truncated } = formatAndTruncateFileList(filePaths);
	if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
	environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
		clear: !firstInvalidatedBy,
		timestamp: true
	});
	hot.send({
		type: "update",
		updates
	});
}
function areAllImportsAccepted(importedBindings, acceptedExports) {
	for (const binding of importedBindings) if (!acceptedExports.has(binding)) return false;
	return true;
}
function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) {
	if (traversedModules.has(node)) return false;
	traversedModules.add(node);
	if (node.id && node.isSelfAccepting === void 0) {
		debugHmr?.(`[propagate update] stop propagation because not analyzed: ${import_picocolors.default.dim(node.id)}`);
		return false;
	}
	if (node.isSelfAccepting) {
		const boundary = node;
		boundaries.push({
			boundary,
			acceptedVia: boundary,
			isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
		});
		return false;
	}
	if (node.acceptedHmrExports) {
		const boundary = node;
		boundaries.push({
			boundary,
			acceptedVia: boundary,
			isWithinCircularImport: isNodeWithinCircularImports(node, currentChain)
		});
	} else if (!node.importers.size) return true;
	for (const importer of node.importers) {
		const subChain = currentChain.concat(importer);
		if (importer.acceptedHmrDeps.has(node)) {
			boundaries.push({
				boundary: importer,
				acceptedVia: node,
				isWithinCircularImport: isNodeWithinCircularImports(importer, subChain)
			});
			continue;
		}
		if (node.id && node.acceptedHmrExports && importer.importedBindings) {
			const importedBindingsFromNode = importer.importedBindings.get(node.id);
			if (importedBindingsFromNode && areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) continue;
		}
		if (!currentChain.includes(importer) && propagateUpdate(importer, traversedModules, boundaries, subChain)) return true;
	}
	return false;
}
/**
* Check importers recursively if it's an import loop. An accepted module within
* an import loop cannot recover its execution order and should be reloaded.
*
* @param node The node that accepts HMR and is a boundary
* @param nodeChain The chain of nodes/imports that lead to the node.
*   (The last node in the chain imports the `node` parameter)
* @param currentChain The current chain tracked from the `node` parameter
* @param traversedModules The set of modules that have traversed
*/
function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
	if (traversedModules.has(node)) return false;
	traversedModules.add(node);
	for (const importer of node.importers) {
		if (importer === node) continue;
		const importerIndex = nodeChain.indexOf(importer);
		if (importerIndex > -1) {
			if (debugHmr) {
				const importChain = [
					importer,
					...[...currentChain].reverse(),
					...nodeChain.slice(importerIndex, -1).reverse()
				];
				debugHmr(import_picocolors.default.yellow(`circular imports detected: `) + importChain.map((m) => import_picocolors.default.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 t = monotonicDateNow();
	mods.forEach((mod) => {
		mod.lastHMRTimestamp = t;
		mod.lastHMRInvalidationReceived = false;
		debugHmr?.(`[dispose] ${import_picocolors.default.dim(mod.file)}`);
	});
	hot.send({
		type: "prune",
		paths: [...mods].map((m) => m.url)
	});
}
/**
* Lex import.meta.hot.accept() for accepted deps.
* Since hot.accept() can only accept string literals or array of string
* literals, we don't really need a heavy @babel/parse call on the entire source.
*
* @returns selfAccepts
*/
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 (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 } of urls) exportNames.add(url);
	return urls.size > 0;
}
function normalizeHmrUrl(url) {
	if (url[0] !== "." && url[0] !== "/") url = wrapId(url);
	return url;
}
function error(pos) {
	const err = /* @__PURE__ */ new Error("import.meta.hot.accept() can only accept string literals or an Array of string literals.");
	err.pos = pos;
	throw err;
}
async function readModifiedFile(file) {
	const content = await fsp.readFile(file, "utf-8");
	if (!content) {
		const mtime = (await fsp.stat(file)).mtimeMs;
		for (let n = 0; n < 10; n++) {
			await new Promise((r) => setTimeout(r, 10));
			if ((await fsp.stat(file)).mtimeMs !== mtime) break;
		}
		return await fsp.readFile(file, "utf-8");
	} else return content;
}
function createServerHotChannel() {
	const innerEmitter = new EventEmitter();
	const outsideEmitter = new EventEmitter();
	return {
		skipFsCheck: true,
		send(payload) {
			outsideEmitter.emit("send", payload);
		},
		off(event, listener) {
			innerEmitter.off(event, listener);
		},
		on: ((event, listener) => {
			innerEmitter.on(event, listener);
		}),
		close() {
			innerEmitter.removeAllListeners();
			outsideEmitter.removeAllListeners();
		},
		listen() {
			innerEmitter.emit("connection");
		},
		api: {
			innerEmitter,
			outsideEmitter
		}
	};
}
//#endregion
//#region src/node/external.ts
const debug$7 = createDebugger("vite:external");
const isExternalCache = /* @__PURE__ */ new WeakMap();
function shouldExternalize(environment, id, importer) {
	let isExternal = isExternalCache.get(environment);
	if (!isExternal) {
		isExternal = createIsExternal(environment);
		isExternalCache.set(environment, isExternal);
	}
	return isExternal(id, importer);
}
function createIsConfiguredAsExternal(environment) {
	const { config } = environment;
	const { root, resolve } = config;
	const { external, noExternal } = resolve;
	const noExternalFilter = typeof noExternal !== "boolean" && !(Array.isArray(noExternal) && noExternal.length === 0) && createFilter$1(void 0, noExternal, { resolve: false });
	const targetConditions = resolve.externalConditions;
	const resolveOptions = {
		...resolve,
		root,
		isProduction: false,
		isBuild: true,
		conditions: targetConditions
	};
	const isExternalizable = (id, importer, configuredAsExternal) => {
		if (!bareImportRE.test(id) || id.includes("\0")) return false;
		try {
			const resolved = tryNodeResolve(id, config.command === "build" ? void 0 : importer, resolveOptions, void 0, false);
			if (!resolved) return false;
			if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;
			return canExternalizeFile(resolved.id);
		} catch {
			debug$7?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
			return false;
		}
	};
	return (id, importer) => {
		if (external !== true && external.includes(id)) return true;
		const pkgName = getNpmPackageName(id);
		if (!pkgName) return isExternalizable(id, importer, false);
		if (external !== true && external.includes(pkgName)) return isExternalizable(id, importer, true);
		if (typeof noExternal === "boolean") return !noExternal;
		if (noExternalFilter && !noExternalFilter(pkgName)) return false;
		return isExternalizable(id, importer, external === true);
	};
}
function createIsExternal(environment) {
	const processedIds = /* @__PURE__ */ new Map();
	const isConfiguredAsExternal = createIsConfiguredAsExternal(environment);
	return (id, importer) => {
		if (processedIds.has(id)) return processedIds.get(id);
		let isExternal = false;
		if (id[0] !== "." && !path.isAbsolute(id)) isExternal = isBuiltin(environment.config.resolve.builtins, id) || isConfiguredAsExternal(id, importer);
		processedIds.set(id, isExternal);
		return isExternal;
	};
}
function canExternalizeFile(filePath) {
	const ext = path.extname(filePath);
	return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
}
//#endregion
//#region src/node/plugins/worker.ts
var WorkerOutputCache = class {
	/**
	* worker bundle information for each input id
	* used to bundle the same worker file only once
	*/
	bundles = /* @__PURE__ */ new Map();
	/** list of assets emitted for the worker bundles */
	assets = /* @__PURE__ */ new Map();
	fileNameHash = /* @__PURE__ */ new Map();
	invalidatedBundles = /* @__PURE__ */ new Set();
	saveWorkerBundle(file, watchedFiles, outputEntryFilename, outputEntryCode, outputAssets, logger) {
		for (const asset of outputAssets) this.saveAsset(asset, logger);
		const bundle = {
			entryFilename: outputEntryFilename,
			entryCode: outputEntryCode,
			entryUrlPlaceholder: this.generateEntryUrlPlaceholder(outputEntryFilename),
			referencedAssets: new Set(outputAssets.map((asset) => asset.fileName)),
			watchedFiles
		};
		this.bundles.set(file, bundle);
		return bundle;
	}
	saveAsset(asset, logger) {
		const duplicateAsset = this.assets.get(asset.fileName);
		if (duplicateAsset) {
			if (!isSameContent(duplicateAsset.source, asset.source)) logger.warn(`\n` + import_picocolors.default.yellow(`The emitted file ${JSON.stringify(asset.fileName)} overwrites a previously emitted file of the same name.`));
		}
		this.assets.set(asset.fileName, asset);
	}
	invalidateAffectedBundles(file) {
		for (const [bundleInputFile, bundle] of this.bundles.entries()) if (bundle.watchedFiles.includes(file)) this.invalidatedBundles.add(bundleInputFile);
	}
	removeBundleIfInvalidated(file) {
		if (this.invalidatedBundles.has(file)) {
			this.invalidatedBundles.delete(file);
			this.removeBundle(file);
		}
	}
	removeBundle(file) {
		const bundle = this.bundles.get(file);
		if (!bundle) return;
		this.bundles.delete(file);
		this.fileNameHash.delete(getHash(bundle.entryFilename));
		this.assets.delete(bundle.entryFilename);
		const keptBundles = [...this.bundles.values()];
		for (const asset of bundle.referencedAssets) if (keptBundles.every((b) => !b.referencedAssets.has(asset))) this.assets.delete(asset);
	}
	getWorkerBundle(file) {
		return this.bundles.get(file);
	}
	getAssets() {
		return this.assets.values();
	}
	getEntryFilenameFromHash(hash) {
		return this.fileNameHash.get(hash);
	}
	generateEntryUrlPlaceholder(entryFilename) {
		const hash = getHash(entryFilename);
		if (!this.fileNameHash.has(hash)) this.fileNameHash.set(hash, entryFilename);
		return `__VITE_WORKER_ASSET__${hash}__`;
	}
};
const workerOrSharedWorkerRE = /(?:\?|&)(worker|sharedworker)(?:&|$)/;
const workerFileRE = /(?:\?|&)worker_file&type=(\w+)(?:&|$)/;
const inlineRE = /[?&]inline\b/;
const WORKER_FILE_ID = "worker_file";
const workerOutputCaches = /* @__PURE__ */ new WeakMap();
async function bundleWorkerEntry(config, id) {
	const input = cleanUrl(id);
	const workerOutput = workerOutputCaches.get(config.mainConfig || config);
	workerOutput.removeBundleIfInvalidated(input);
	const bundleInfo = workerOutput.getWorkerBundle(input);
	if (bundleInfo) return bundleInfo;
	const newBundleChain = [...config.bundleChain, input];
	if (config.bundleChain.includes(input)) throw new Error(`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.map((id) => prettifyUrl(id, config.root)).join(" -> ")}`);
	const { rolldown } = await import("rolldown");
	const { plugins, rolldownOptions, format } = config.worker;
	const workerEnvironment = new BuildEnvironment("client", await plugins(newBundleChain));
	await workerEnvironment.init();
	const chunkMetadataMap = new ChunkMetadataMap();
	const workerBuildTarget = workerEnvironment.config.build.target;
	const bundle = await rolldown({
		...rolldownOptions,
		input,
		plugins: workerEnvironment.plugins.map((p) => injectEnvironmentToHooks(workerEnvironment, chunkMetadataMap, p)),
		onLog(level, log) {
			onRollupLog(level, log, workerEnvironment);
		},
		transform: {
			target: workerBuildTarget === false ? void 0 : workerBuildTarget,
			...rolldownOptions.transform,
			define: {
				...rolldownOptions.transform?.define,
				"process.env.NODE_ENV": "process.env.NODE_ENV"
			}
		},
		moduleTypes: {
			".css": "js",
			...rolldownOptions.moduleTypes
		},
		preserveEntrySignatures: false,
		experimental: {
			...rolldownOptions.experimental,
			viteMode: true
		}
	});
	let result;
	let watchedFiles;
	try {
		const workerOutputConfig = config.worker.rolldownOptions.output;
		const workerConfig = workerOutputConfig ? Array.isArray(workerOutputConfig) ? workerOutputConfig[0] || {} : workerOutputConfig : {};
		result = await bundle.generate({
			entryFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
			chunkFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].js"),
			assetFileNames: path.posix.join(config.build.assetsDir, "[name]-[hash].[ext]"),
			minify: workerEnvironment.config.build.minify === "oxc" ? true : workerEnvironment.config.build.minify === false ? "dce-only" : void 0,
			...workerConfig,
			format,
			sourcemap: workerEnvironment.config.build.sourcemap
		});
		watchedFiles = (await bundle.watchFiles).map((f) => normalizePath(f));
	} catch (e) {
		if (e instanceof Error && e.name === "RollupError" && e.code === "INVALID_OPTION" && e.message.includes("\"output.format\"")) e.message = e.message.replace("output.format", "worker.format");
		throw e;
	} finally {
		await bundle.close();
	}
	const { output: [outputChunk, ...outputChunks] } = result;
	const assets = outputChunks.map((outputChunk) => outputChunk.type === "asset" ? outputChunk : {
		fileName: outputChunk.fileName,
		originalFileName: null,
		originalFileNames: [],
		source: outputChunk.code
	});
	if ((config.build.sourcemap === "hidden" || config.build.sourcemap === true) && outputChunk.map) assets.push({
		fileName: outputChunk.fileName + ".map",
		originalFileName: null,
		originalFileNames: [],
		source: outputChunk.map.toString()
	});
	return workerOutputCaches.get(config.mainConfig || config).saveWorkerBundle(input, watchedFiles, outputChunk.fileName, outputChunk.code, assets, config.logger);
}
const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g;
async function workerFileToUrl(config, id) {
	const workerOutput = workerOutputCaches.get(config.mainConfig || config);
	const bundle = await bundleWorkerEntry(config, id);
	workerOutput.saveAsset({
		fileName: bundle.entryFilename,
		originalFileName: null,
		originalFileNames: [],
		source: bundle.entryCode
	}, config.logger);
	return bundle;
}
function webWorkerPostPlugin(_config) {
	return {
		name: "vite:worker-post",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) {
				if (environment.config.worker.format === "iife") return viteWebWorkerPostPlugin();
				return false;
			}
			return true;
		},
		transform: {
			filter: { code: "import.meta" },
			order: "post",
			async handler(code, id) {
				if (this.environment.config.worker.format === "iife") {
					await init;
					let imports;
					try {
						imports = parse$2(code)[0];
					} catch {
						return;
					}
					let injectedImportMeta = false;
					let s;
					for (const { s: start, e: end, d: dynamicIndex } of imports) if (dynamicIndex === -2) if (code.slice(end, end + 4) === ".url") {
						s ||= new MagicString(code);
						s.overwrite(start, end + 4, "self.location.href");
					} else {
						s ||= new MagicString(code);
						if (!injectedImportMeta) {
							s.prepend("const _vite_importMeta = { url: self.location.href };\n");
							injectedImportMeta = true;
						}
						s.overwrite(start, end, "_vite_importMeta");
					}
					if (!s) return;
					return {
						code: s.toString(),
						map: s.generateMap({
							hires: "boundary",
							source: id
						})
					};
				}
			}
		}
	};
}
function webWorkerPlugin(config) {
	const isBuild = config.command === "build";
	const isWorker = config.isWorker;
	workerOutputCaches.set(config, new WorkerOutputCache());
	const emittedAssets = /* @__PURE__ */ new Set();
	return {
		name: "vite:worker",
		buildStart() {
			if (isWorker) return;
			emittedAssets.clear();
		},
		load: {
			filter: { id: workerOrSharedWorkerRE },
			async handler(id) {
				const workerMatch = workerOrSharedWorkerRE.exec(id);
				if (!workerMatch) return;
				const { format } = config.worker;
				const workerConstructor = workerMatch[1] === "sharedworker" ? "SharedWorker" : "Worker";
				const isBundled = this.environment.config.isBundled;
				const workerType = isBundled ? format === "es" ? "module" : "classic" : "module";
				const workerTypeOption = `{
          ${workerType === "module" ? `type: "module",` : ""}
          name: options?.name
        }`;
				let urlCode;
				if (isBundled) if (isWorker && config.bundleChain.at(-1) === cleanUrl(id)) urlCode = "self.location.href";
				else if (inlineRE.test(id)) {
					const result = await bundleWorkerEntry(config, id);
					for (const file of result.watchedFiles) this.addWatchFile(file);
					const jsContent = `const jsContent = ${JSON.stringify(result.entryCode)};`;
					return {
						code: workerConstructor === "Worker" ? `${jsContent}
            const blob = typeof self !== "undefined" && self.Blob && new Blob([${workerType === "classic" ? `'(self.URL || self.webkitURL).revokeObjectURL(self.location.href);',` : `'URL.revokeObjectURL(import.meta.url);',`}jsContent], { 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;charset=utf-8,' + encodeURIComponent(jsContent),
                  ${workerTypeOption}
                );
              }
            }` : `${jsContent}
            export default function WorkerWrapper(options) {
              return new ${workerConstructor}(
                'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent),
                ${workerTypeOption}
              );
            }
            `,
						map: { mappings: "" }
					};
				} else {
					const result = await workerFileToUrl(config, id);
					let url;
					if (this.environment.config.command === "serve" && this.environment.config.isBundled) url = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
					else url = result.entryUrlPlaceholder;
					urlCode = JSON.stringify(url);
					for (const file of result.watchedFiles) this.addWatchFile(file);
				}
				else {
					let url = await fileToUrl$1(this, cleanUrl(id));
					url = injectQuery(url, `${WORKER_FILE_ID}&type=${workerType}`);
					urlCode = JSON.stringify(url);
				}
				if (urlRE$1.test(id)) return {
					code: `export default ${urlCode}`,
					map: { mappings: "" }
				};
				return {
					code: `export default function WorkerWrapper(options) {
            return new ${workerConstructor}(
              ${urlCode},
              ${workerTypeOption}
            );
          }`,
					map: { mappings: "" }
				};
			}
		},
		transform: {
			filter: { id: workerFileRE },
			handler(raw, id) {
				const workerFileMatch = workerFileRE.exec(id);
				if (workerFileMatch) {
					const workerType = workerFileMatch[1];
					let injectEnv = "";
					if (workerType === "classic") injectEnv = `importScripts(${JSON.stringify(path.posix.join(config.base, ENV_PUBLIC_PATH))})\n`;
					else if (workerType === "module") injectEnv = `import ${JSON.stringify(ENV_PUBLIC_PATH)}\n`;
					else if (workerType === "ignore") if (this.environment.config.isBundled) injectEnv = "";
					else {
						const environment = this.environment;
						injectEnv = ((environment.mode === "dev" ? environment.moduleGraph : void 0)?.getModuleById(ENV_ENTRY))?.transformResult?.code || "";
					}
					if (injectEnv) {
						const s = new MagicString(raw);
						s.prepend(injectEnv + ";\n");
						return {
							code: s.toString(),
							map: s.generateMap({ hires: "boundary" })
						};
					}
				}
			}
		},
		...isBuild ? { renderChunk(code, chunk, outputOptions) {
			let s;
			const result = () => {
				return s && {
					code: s.toString(),
					map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
				};
			};
			workerAssetUrlRE.lastIndex = 0;
			if (workerAssetUrlRE.test(code)) {
				const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, this.environment.config.isWorker);
				let match;
				s = new MagicString(code);
				workerAssetUrlRE.lastIndex = 0;
				const workerOutputCache = workerOutputCaches.get(config.mainConfig || config);
				while (match = workerAssetUrlRE.exec(code)) {
					const [full, hash] = match;
					const filename = workerOutputCache.getEntryFilenameFromHash(hash);
					if (!filename) {
						this.warn(`Could not find worker asset for hash: ${hash}`);
						continue;
					}
					const replacement = toOutputFilePathInJS(this.environment, filename, "asset", chunk.fileName, "js", toRelativeRuntime);
					const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
					s.update(match.index, match.index + full.length, replacementString);
				}
			}
			return result();
		} } : {},
		generateBundle(opts, bundle) {
			if (this.environment.config.isOutputOptionsForLegacyChunks?.(opts) || isWorker) return;
			for (const asset of workerOutputCaches.get(config).getAssets()) {
				if (emittedAssets.has(asset.fileName)) continue;
				emittedAssets.add(asset.fileName);
				const duplicateAsset = bundle[asset.fileName];
				if (duplicateAsset) {
					if (isSameContent(duplicateAsset.type === "asset" ? duplicateAsset.source : duplicateAsset.code, asset.source)) continue;
				}
				this.emitFile({
					type: "asset",
					fileName: asset.fileName,
					source: asset.source
				});
			}
		},
		watchChange(file) {
			if (isWorker) return;
			workerOutputCaches.get(config).invalidateAffectedBundles(normalizePath(file));
		}
	};
}
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);
}
//#endregion
//#region src/node/plugins/preAlias.ts
/**
* A plugin to avoid an aliased AND optimized dep from being aliased in src
*/
function preAliasPlugin(config) {
	const findPatterns = getAliasPatterns(config.resolve.alias);
	return {
		name: "vite:pre-alias",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) return false;
			return !isDepOptimizationDisabled(environment.config.optimizeDeps);
		},
		async resolveId(id, importer, options) {
			const environment = this.environment;
			const ssr = environment.config.consumer === "server";
			const depsOptimizer = environment.depsOptimizer;
			if (importer && depsOptimizer && bareImportRE.test(id) && !options.scan && id !== "@vite/client" && id !== "@vite/env") {
				if (findPatterns.find((pattern) => matches(pattern, id))) {
					const optimizedId = await tryOptimizedResolve(depsOptimizer, id, importer, config.resolve.preserveSymlinks, config.packageCache);
					if (optimizedId) return optimizedId;
					if (depsOptimizer.options.noDiscovery) return;
					const resolved = await this.resolve(id, importer, options);
					if (resolved && !depsOptimizer.isOptimizedDepFile(resolved.id)) {
						const optimizeDeps = depsOptimizer.options;
						const resolvedId = cleanUrl(resolved.id);
						if (!(resolvedId === id || resolvedId.includes("\0")) && fs.existsSync(resolvedId) && !moduleListContains(optimizeDeps.exclude, id) && path.isAbsolute(resolvedId) && (isInNodeModules(resolvedId) || optimizeDeps.include?.includes(id)) && isOptimizable(resolvedId, optimizeDeps) && (!ssr || optimizeAliasReplacementForSSR(resolvedId, optimizeDeps))) {
							const optimizedInfo = depsOptimizer.registerMissingImport(id, resolvedId);
							return { id: depsOptimizer.getOptimizedDepId(optimizedInfo) };
						}
					}
					return resolved;
				}
			}
		}
	};
}
function optimizeAliasReplacementForSSR(id, optimizeDeps) {
	if (optimizeDeps.include?.includes(id)) return true;
	return false;
}
function matches(pattern, importee) {
	if (pattern instanceof RegExp) return pattern.test(importee);
	if (importee.length < pattern.length) return false;
	if (importee === pattern) return true;
	return importee.startsWith(withTrailingSlash(pattern));
}
function getAliasPatterns(entries) {
	if (Array.isArray(entries)) return entries.map((entry) => entry.find);
	return Object.entries(entries).map(([find]) => find);
}
function getAliasPatternMatcher(entries) {
	const patterns = getAliasPatterns(entries);
	return (importee) => patterns.some((pattern) => matches(pattern, importee));
}
//#endregion
//#region src/node/plugins/importAnalysis.ts
const debug$6 = createDebugger("vite:import-analysis");
const clientDir = normalizePath(CLIENT_DIR);
const skipRE = /\.(?:map|json)(?:$|\?)/;
const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
const optimizedDepChunkRE = /\/chunk-[A-Z\d]{8}\.js/;
const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//;
const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/;
const templateLiteralRE = /^\s*`(.*)`\s*$/;
function isExplicitImportRequired(url) {
	return !isJSRequest(url) && !isCSSRequest(url);
}
function normalizeResolvedIdToUrl(environment, url, resolved) {
	const root = environment.config.root;
	const depsOptimizer = environment.depsOptimizer;
	if (resolved.id.startsWith(withTrailingSlash(root))) url = resolved.id.slice(root.length);
	else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || resolved.id !== "/@react-refresh" && path.isAbsolute(resolved.id) && fs.existsSync(cleanUrl(resolved.id))) url = path.posix.join(FS_PREFIX, resolved.id);
	else url = resolved.id;
	if (url[0] !== "." && url[0] !== "/") url = wrapId(resolved.id);
	return url;
}
function extractImportedBindings(id, source, importSpec, importedBindings) {
	let bindings = importedBindings.get(id);
	if (!bindings) {
		bindings = /* @__PURE__ */ new Set();
		importedBindings.set(id, bindings);
	}
	if (importSpec.d > -1 || importSpec.d === -2) {
		bindings.add("*");
		return;
	}
	const exp = source.slice(importSpec.ss, importSpec.se);
	ESM_STATIC_IMPORT_RE.lastIndex = 0;
	const match = ESM_STATIC_IMPORT_RE.exec(exp);
	if (!match) return;
	const parsed = parseStaticImport({
		type: "static",
		code: match[0],
		start: match.index,
		end: match.index + match[0].length,
		imports: match.groups.imports,
		specifier: match.groups.specifier
	});
	if (parsed.namespacedImport) bindings.add("*");
	if (parsed.defaultImport) bindings.add("default");
	if (parsed.namedImports) for (const name of Object.keys(parsed.namedImports)) bindings.add(name);
}
/**
* Dev-only plugin that lexes, resolves, rewrites and analyzes url imports.
*
* - Imports are resolved to ensure they exist on disk
*
* - Lexes HMR accept calls and updates import relationships in the module graph
*
* - Bare module imports are resolved (by @rollup-plugin/node-resolve) to
* absolute file paths, e.g.
*
*     ```js
*     import 'foo'
*     ```
*     is rewritten to
*     ```js
*     import '/@fs//project/node_modules/foo/dist/foo.js'
*     ```
*
* - CSS imports are appended with `.js` since both the js module and the actual
* css (referenced via `<link>`) may go through the transform pipeline:
*
*     ```js
*     import './style.css'
*     ```
*     is rewritten to
*     ```js
*     import './style.css.js'
*     ```
*/
function importAnalysisPlugin(config) {
	const { root, base } = config;
	const clientPublicPath = path.posix.join(base, CLIENT_PUBLIC_PATH);
	const enablePartialAccept = config.experimental.hmrPartialAccept;
	const matchAlias = getAliasPatternMatcher(config.resolve.alias);
	let _env;
	let _ssrEnv;
	function getEnv(ssr) {
		if (!_ssrEnv || !_env) {
			const importMetaEnvKeys = {};
			const userDefineEnv = {};
			for (const key in config.env) importMetaEnvKeys[key] = JSON.stringify(config.env[key]);
			for (const key in config.define) if (key.startsWith("import.meta.env.")) userDefineEnv[key.slice(16)] = config.define[key];
			const env = `import.meta.env = ${serializeDefine({
				...importMetaEnvKeys,
				SSR: "__vite_ssr__",
				...userDefineEnv
			})};`;
			_ssrEnv = env.replace("__vite_ssr__", "true");
			_env = env.replace("__vite_ssr__", "false");
		}
		return ssr ? _ssrEnv : _env;
	}
	return {
		name: "vite:import-analysis",
		applyToEnvironment(environment) {
			return !environment.config.isBundled;
		},
		async transform(source, importer) {
			const environment = this.environment;
			const ssr = environment.config.consumer === "server";
			const moduleGraph = environment.moduleGraph;
			if (canSkipImportAnalysis(importer)) {
				debug$6?.(import_picocolors.default.dim(`[skipped] ${prettifyUrl(importer, root)}`));
				return null;
			}
			const msAtStart = debug$6 ? performance$1.now() : 0;
			await init;
			let imports;
			let exports;
			source = stripBomTag(source);
			try {
				[imports, exports] = parse$2(source);
			} catch (_e) {
				const e = _e;
				const { message, showCodeFrame } = createParseErrorInfo(importer, source);
				this.error(message, showCodeFrame ? e.idx : void 0);
			}
			const depsOptimizer = environment.depsOptimizer;
			const importerModule = moduleGraph.getModuleById(importer);
			if (!importerModule) throwOutdatedRequest(importer);
			if (!imports.length && !this._addedImports) {
				const prunedImports = await moduleGraph.updateModuleInfo(importerModule, /* @__PURE__ */ new Set(), null, /* @__PURE__ */ new Set(), null, false);
				if (prunedImports) handlePrunedModules(prunedImports, environment);
				debug$6?.(`${timeFrom(msAtStart)} ${import_picocolors.default.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 normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => {
				let importerFile = importer;
				if (depsOptimizer && moduleListContains(depsOptimizer.options.exclude, url)) {
					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(url, importerFile).catch((e) => {
					if (e instanceof Error) e.pos ??= pos;
					throw e;
				});
				if (!resolved || resolved.meta?.["vite:alias"]?.noResolved) {
					if (ssr) return [url, null];
					importerModule.isSelfAccepting = false;
					moduleGraph._hasResolveFailedErrorModules.add(importerModule);
					return this.error(`Failed to resolve import "${url}" from "${normalizePath(path.relative(process.cwd(), importerFile))}". Does the file exist?`, pos);
				}
				if (isExternalUrl(resolved.id)) return [resolved.id, resolved.id];
				url = normalizeResolvedIdToUrl(environment, url, resolved);
				try {
					const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved);
					if (environment.config.consumer === "client" && depModule.lastHMRTimestamp > 0) url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`);
				} catch (e) {
					e.pos = pos;
					throw e;
				}
				if (environment.config.consumer === "client") {
					const isRelative = url[0] === ".";
					const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
					if (isExplicitImportRequired(url)) url = injectQuery(url, "import");
					else if ((isRelative || isSelfImport) && !DEP_VERSION_RE.test(url)) {
						const versionMatch = DEP_VERSION_RE.exec(importer);
						if (versionMatch) url = injectQuery(url, versionMatch[1]);
					}
				}
				if (!ssr) url = joinUrlSegments(base, url);
				return [url, resolved.id];
			};
			const orderedImportedUrls = new Array(imports.length);
			const orderedAcceptedUrls = new Array(imports.length);
			const orderedAcceptedExports = new Array(imports.length);
			let _isNodeModeResult = config.legacy?.inconsistentCjsInterop ? false : void 0;
			const isNodeMode = () => {
				_isNodeModeResult ??= isFilePathESM(importer, config.packageCache);
				return _isNodeModeResult;
			};
			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) && !specifier.startsWith("file://") || isDataUrl(specifier)) && !matchAlias(specifier)) return;
					if (ssr && !matchAlias(specifier)) {
						if (shouldExternalize(environment, specifier, importer)) return;
						if (isBuiltin(environment.config.resolve.builtins, specifier)) return;
					}
					if (specifier === clientPublicPath) return;
					if (specifier[0] === "/" && !(config.assetsInclude(cleanUrl(specifier)) || urlRE$1.test(specifier)) && checkPublicFile(specifier, config)) 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.`);
					let [url, resolvedId] = await normalizeUrl(specifier, start);
					resolvedId = resolvedId || url;
					config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)));
					if (url !== specifier) {
						let rewriteDone = false;
						if (!depsOptimizer?.isOptimizedDepFile(importer) && depsOptimizer?.isOptimizedDepFile(resolvedId) && !optimizedDepChunkRE.test(resolvedId)) {
							const file = cleanUrl(resolvedId);
							const depInfo = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
							const needsInterop = await optimizedDepNeedsInterop(environment, depsOptimizer.metadata, file);
							if (needsInterop === void 0) {
								if (depInfo?.isDynamicEntry) config.logger.error(import_picocolors.default.red(`Vite Error, ${url} optimized info should be defined`));
							} else if (needsInterop) {
								debug$6?.(`${url} needs interop`);
								interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
								rewriteDone = true;
							}
						} else if (url.startsWith(wrapId("__vite-browser-external")) && source.slice(expStart, start).includes("{")) {
							interopNamedImports(str(), importSpecifier, url, index, importer, isNodeMode(), config);
							rewriteDone = true;
						}
						if (!rewriteDone) {
							const rewrittenUrl = JSON.stringify(url);
							const s = isDynamicImport ? start : start - 1;
							const e = isDynamicImport ? end : end + 1;
							str().overwrite(s, e, rewrittenUrl, { contentOnly: true });
						}
					}
					const hmrUrl = unwrapId(stripBase(url, base));
					const isLocalImport = !isExternalUrl(hmrUrl) && !isDataUrl(hmrUrl);
					if (isLocalImport) orderedImportedUrls[index] = hmrUrl;
					if (enablePartialAccept && importedBindings) extractImportedBindings(resolvedId, source, importSpecifier, importedBindings);
					if (!isDynamicImport && isLocalImport && environment.config.dev.preTransformRequests) {
						const url = removeImportQuery(hmrUrl);
						environment.warmupRequest(url);
					}
				} else if (!importer.startsWith(withTrailingSlash(clientDir))) {
					if (!isInNodeModules(importer)) {
						if (!hasViteIgnoreRE.test(source.slice(dynamicIndex + 1, end))) this.warn(`\n` + import_picocolors.default.cyan(importerModule.file) + `\n` + import_picocolors.default.reset(generateCodeFrame(source, start, end)) + import_picocolors.default.yellow(`\nThe above dynamic import cannot be analyzed by Vite.\nSee ${import_picocolors.default.blue(`https://vite.dev/guide/features#dynamic-import`)} 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.\n`));
					}
					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((url) => removeTimestampQuery(url)));
			const acceptedUrls = mergeAcceptedUrls(orderedAcceptedUrls);
			const acceptedExports = mergeAcceptedUrls(orderedAcceptedExports);
			const isClassicWorker = importer.includes("worker_file") && importer.includes("type=classic");
			if (hasEnv && !isClassicWorker) str().prepend(getEnv(ssr));
			if (hasHMR && !ssr && !isClassicWorker) {
				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, start, end } of acceptedUrls) {
				let [normalized, resolvedId] = await normalizeUrl(url, start).catch(() => []);
				if (resolvedId) {
					const mod = moduleGraph.getModuleById(resolvedId);
					if (!mod) {
						this.error(`module was not found for ${JSON.stringify(resolvedId)}`, start);
						return;
					}
					normalized = mod.url;
				} else this.error({
					message: `Failed to resolve ${JSON.stringify(url)} from ${importer}.`,
					pos: start
				});
				normalizedAcceptedUrls.add(normalized);
				const hmrAccept = normalizeHmrUrl(normalized);
				str().overwrite(start, end, JSON.stringify(hmrAccept), { 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(([url]) => importedUrls.add(stripBase(url, base)));
				if (ssr && importerModule.isSelfAccepting) isSelfAccepting = true;
				if (!isSelfAccepting && isPartiallySelfAccepting && acceptedExports.size >= exports.length && exports.every((e) => acceptedExports.has(e.n))) isSelfAccepting = true;
				const prunedImports = await moduleGraph.updateModuleInfo(importerModule, importedUrls, importedBindings, normalizedAcceptedUrls, isPartiallySelfAccepting ? acceptedExports : null, isSelfAccepting, staticImportedUrls);
				if (prunedImports) handlePrunedModules(prunedImports, environment);
			}
			debug$6?.(`${timeFrom(msAtStart)} ${import_picocolors.default.dim(`[${importedUrls.size} imports rewritten] ${prettifyUrl(importer, root)}`)}`);
			if (s) return transformStableResult(s, importer, config);
			else return source;
		}
	};
}
function mergeAcceptedUrls(orderedUrls) {
	const acceptedUrls = /* @__PURE__ */ new Set();
	for (const urls of orderedUrls) {
		if (!urls) continue;
		for (const url of urls) acceptedUrls.add(url);
	}
	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("�");
	return {
		message: "Failed to parse source for import analysis because the content contains invalid JS syntax. " + (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 ${path.extname(importer)} file format, or if it's an asset, add "**/*${path.extname(importer)}" to \`assetsInclude\` in your configuration.`),
		showCodeFrame: !probablyBinary
	};
}
const interopHelper = (m, n) => n || !m?.__esModule ? {
	...typeof m === "object" && !Array.isArray(m) || typeof m === "function" ? m : {},
	default: m
} : m;
const interopHelperStr = interopHelper.toString().replaceAll("\n", "");
function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, isNodeMode, config) {
	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 => (${interopHelperStr})(m.default, ${!!config.legacy?.inconsistentCjsInterop ? 0 : 1}))` + getLineBreaks(exp), { contentOnly: true });
	else {
		const rewritten = transformCjsImport(exp, rewrittenUrl, source.slice(start, end), importIndex, importer, isNodeMode, config);
		if (rewritten) {
			str.overwrite(expStart, expEnd, rewritten.importLine + getLineBreaks(exp), { contentOnly: true });
			if (rewritten.hoistedAssignments) str.appendLeft(getFileStartIndex(source), rewritten.hoistedAssignments + ";");
		} 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) : "";
}
/**
* Detect import statements to a known optimized CJS dependency and provide
* ES named imports interop. We do this by rewriting named imports to a variable
* assignment to the corresponding property on the `module.exports` of the cjs
* module. Note this doesn't support dynamic re-assignments from within the cjs
* module.
*
* Note that es-module-lexer treats `export * from '...'` as an import as well,
* so, we may encounter ExportAllDeclaration here, in which case `undefined`
* will be returned.
*
* Credits \@csr632 via #837
*/
function transformCjsImport(importExp, url, rawUrl, importIndex, importer, isNodeMode, config) {
	const node = parseAst(importExp).body[0];
	if (config.command === "serve" && node.type === "ExportAllDeclaration" && !node.exported) config.logger.warn(import_picocolors.default.yellow(`\nUnable 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 (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") {
		if (!node.specifiers.length) return { importLine: `import "${url}"` };
		const importNames = [];
		const exportNames = [];
		let defaultExports = "";
		for (const spec of node.specifiers) if (spec.type === "ImportSpecifier") {
			const importedName = getIdentifierNameOrLiteralValue(spec.imported);
			importNames.push({
				importedName,
				localName: spec.local.name
			});
		} 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") {
			const importedName = getIdentifierNameOrLiteralValue(spec.local);
			const exportedName = getIdentifierNameOrLiteralValue(spec.exported);
			if (exportedName === "default") {
				defaultExports = makeLegalIdentifier(`__vite__cjsExportDefault_${importIndex}`);
				importNames.push({
					importedName,
					localName: defaultExports
				});
			} else {
				const localName = `__vite__cjsExport${spec.exported.type === "Literal" ? `L_${getHash(spec.exported.value)}` : "I_" + spec.exported.name}`;
				importNames.push({
					importedName,
					localName
				});
				exportNames.push(`${localName} as ${spec.exported.type === "Literal" ? JSON.stringify(exportedName) : exportedName}`);
			}
		}
		const cjsModuleName = makeLegalIdentifier(`__vite__cjsImport${importIndex}_${rawUrl}`);
		const importLine = `import ${cjsModuleName} from "${url}"`;
		const lines = [];
		importNames.forEach(({ importedName, localName }) => {
			if (importedName === "*") lines.push(`const ${localName} = (${interopHelperStr})(${cjsModuleName}, ${+isNodeMode})`);
			else if (importedName === "default") if (isNodeMode) lines.push(`const ${localName} = ${cjsModuleName}`);
			else lines.push(`const ${localName} = !${cjsModuleName}.__esModule ? ${cjsModuleName} : ${cjsModuleName}.default`);
			else lines.push(`const ${localName} = ${cjsModuleName}["${importedName}"]`);
		});
		if (defaultExports) lines.push(`export default ${defaultExports}`);
		if (exportNames.length) lines.push(`export { ${exportNames.join(", ")} }`);
		return {
			importLine,
			hoistedAssignments: lines.join("; ")
		};
	}
}
function getIdentifierNameOrLiteralValue(node) {
	return node.type === "Identifier" ? node.name : node.value;
}
function __vite__injectQuery(url, queryToInject) {
	if (url[0] !== "." && url[0] !== "/") return url;
	const pathname = url.replace(/[?#].*$/, "");
	const { search, hash } = new URL(url, "http://vite.dev");
	return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
}
//#endregion
//#region src/node/plugins/wasm.ts
const wasmHelperId = "\0vite/wasm-helper.js";
const wasmInitRE = /(?<![?#].*)\.wasm\?init/;
const wasmDirectRE = /(?<![?#].*)\.wasm$/;
const wasmInitUrlRE = /__VITE_WASM_INIT__([\w$]+)__/g;
const wasmHelper = async (opts = {}, url) => {
	let result;
	if (url.startsWith("data:")) {
		const urlContent = url.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 result = await instantiateFromUrl(url, opts);
	return result.instance;
};
const wasmHelperCode = wasmHelper.toString();
const instantiateFromUrl = async (url, opts) => {
	const response = await fetch(url);
	const contentType = response.headers.get("Content-Type") || "";
	if ("instantiateStreaming" in WebAssembly && contentType.startsWith("application/wasm")) return WebAssembly.instantiateStreaming(response, opts);
	else {
		const buffer = await response.arrayBuffer();
		return WebAssembly.instantiate(buffer, opts);
	}
};
const instantiateFromUrlCode = instantiateFromUrl.toString();
const instantiateFromFile = async (fileUrlString, opts) => {
	const { readFile } = await import("node:fs/promises");
	const buffer = await readFile(new URL(
		fileUrlString,
		/** #__KEEP__ */
		import.meta.url
	));
	return WebAssembly.instantiate(buffer, opts);
};
const instantiateFromFileCode = instantiateFromFile.toString();
const wasmHelperPlugin = () => {
	return perEnvironmentPlugin("vite:wasm-helper", (env) => {
		return {
			name: "vite:wasm-helper",
			resolveId: {
				filter: { id: exactRegex(wasmHelperId) },
				handler(id) {
					return id;
				}
			},
			load: {
				filter: { id: [
					exactRegex(wasmHelperId),
					wasmInitRE,
					wasmDirectRE
				] },
				async handler(id) {
					const ssr = this.environment.config.consumer === "server";
					if (id === wasmHelperId) return `
const instantiateFromUrl = ${ssr ? instantiateFromFileCode : instantiateFromUrlCode}
export default ${wasmHelperCode}
`;
					const isInit = wasmInitRE.test(id);
					const cleanedId = id.split("?")[0];
					let url = await fileToUrl$1(this, cleanedId, ssr);
					assetUrlRE.lastIndex = 0;
					if (ssr && assetUrlRE.test(url)) url = url.replace("__VITE_ASSET__", "__VITE_WASM_INIT__");
					if (isInit) return `
  import initWasm from "${wasmHelperId}"
  export default opts => initWasm(opts, ${JSON.stringify(url)})
  `;
					const glueCode = generateGlueCode(await parseWasm(cleanedId), {
						initWasm: "__vite__initWasm",
						wasmUrl: "__vite__wasmUrl"
					});
					return `
import __vite__initWasm from "${wasmHelperId}"
const __vite__wasmUrl = ${JSON.stringify(url)}
${glueCode}
`;
				}
			},
			renderChunk: env.config.consumer === "server" ? {
				filter: { code: wasmInitUrlRE },
				handler(code, chunk, opts, meta) {
					const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, this.environment.config.isWorker);
					let match;
					let s;
					wasmInitUrlRE.lastIndex = 0;
					while (match = wasmInitUrlRE.exec(code)) {
						const [full, referenceId] = match;
						const file = this.getFileName(referenceId);
						chunk.viteMetadata.importedAssets.add(cleanUrl(file));
						const { runtime } = toRelativeRuntime(file, chunk.fileName);
						s ??= meta.magicString ?? new MagicString(code);
						s.update(match.index, match.index + full.length, `"+${runtime}+"`);
					}
					if (!s) return null;
					return meta.magicString ? { code: s } : {
						code: s.toString(),
						map: this.environment.config.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
					};
				}
			} : void 0
		};
	});
};
async function parseWasm(wasmFilePath) {
	try {
		const wasmBinary = await fsp.readFile(wasmFilePath);
		const wasmModule = await WebAssembly.compile(wasmBinary);
		const importMap = Object.create(null);
		for (const item of WebAssembly.Module.imports(wasmModule)) {
			importMap[item.module] ??= [];
			importMap[item.module].push(item.name);
		}
		return {
			imports: Object.entries(importMap).map(([from, names]) => ({
				from,
				names
			})),
			exports: WebAssembly.Module.exports(wasmModule).map((item) => item.name)
		};
	} catch (e) {
		throw new Error(`Failed to parse WASM file "${wasmFilePath}": ${e.message}`, { cause: e });
	}
}
function generateGlueCode(wasmInfo, names) {
	const importStatements = wasmInfo.imports.map(({ from }, i) => {
		return `import * as __vite__wasmImport_${i} from ${JSON.stringify(from)};`;
	});
	const importObject = wasmInfo.imports.map(({ from, names: importNames }, i) => {
		return {
			key: JSON.stringify(from),
			value: importNames.map((name) => {
				return {
					key: JSON.stringify(name),
					value: `__vite__wasmImport_${i}[${JSON.stringify(name)}]`
				};
			})
		};
	});
	const initCode = `const __vite__wasmModule = (await ${names.initWasm}(${codegenSimpleObject(importObject)}, ${names.wasmUrl})).exports;`;
	if (wasmInfo.exports.length === 0) return [...importStatements, initCode].join("\n");
	const exportStatements = [];
	const nameMap = /* @__PURE__ */ new Map();
	for (const [index, name] of wasmInfo.exports.entries()) if (isValidJsDeclareName(name)) exportStatements.push(`  ${name},`);
	else {
		const placeholderName = `__vite__wasmExport_${index}`;
		exportStatements.push(`  ${JSON.stringify(name)}: ${placeholderName},`);
		nameMap.set(name, placeholderName);
	}
	if (nameMap.size > 0) {
		exportStatements.unshift(`const {`);
		exportStatements.push(`} = __vite__wasmModule;`);
		exportStatements.push(`export {`);
		for (const name of wasmInfo.exports) {
			const localName = nameMap.get(name);
			if (localName) exportStatements.push(`  ${localName} as ${JSON.stringify(name)},`);
			else exportStatements.push(`  ${name},`);
		}
		exportStatements.push(`};`);
	} else {
		exportStatements.unshift(`export const {`);
		exportStatements.push(`} = __vite__wasmModule;`);
	}
	return [
		...importStatements,
		initCode,
		...exportStatements
	].join("\n");
}
function codegenSimpleObject(obj) {
	if (obj.length === 0) return "{}";
	return `{ ${obj.map(({ key, value }) => {
		return `${key}: ${typeof value === "string" ? value : codegenSimpleObject(value)}`;
	}).join(", ")} }`;
}
const VALID_JS_IDENTIFIER = /^[$_\p{ID_Start}][$\p{ID_Continue}]*$/u;
const RESERVED_WORDS = /* @__PURE__ */ new Set([
	"abstract",
	"boolean",
	"break",
	"byte",
	"case",
	"catch",
	"char",
	"class",
	"const",
	"continue",
	"debugger",
	"default",
	"delete",
	"do",
	"double",
	"else",
	"enum",
	"export",
	"extends",
	"false",
	"final",
	"finally",
	"float",
	"for",
	"function",
	"goto",
	"if",
	"implements",
	"import",
	"in",
	"instanceof",
	"int",
	"interface",
	"let",
	"long",
	"native",
	"new",
	"null",
	"package",
	"private",
	"protected",
	"public",
	"return",
	"short",
	"static",
	"super",
	"switch",
	"synchronized",
	"this",
	"throw",
	"throws",
	"transient",
	"true",
	"try",
	"typeof",
	"var",
	"void",
	"volatile",
	"while",
	"with",
	"yield"
]);
function isValidJsDeclareName(name) {
	return !RESERVED_WORDS.has(name) && VALID_JS_IDENTIFIER.test(name);
}
//#endregion
//#region src/node/plugins/workerImportMetaUrl.ts
function err$1(e, pos) {
	const error = new Error(e);
	error.pos = pos;
	return error;
}
function findClosingParen(input, fromIndex) {
	let count = 1;
	for (let i = fromIndex; i < input.length; i++) {
		if (input[i] === "(") count++;
		if (input[i] === ")") count--;
		if (count === 0) return i;
	}
	return -1;
}
function extractWorkerTypeFromAst(expression, optsStartIndex) {
	if (expression.type !== "ObjectExpression") return;
	let lastSpreadElementIndex = -1;
	let typeProperty = null;
	let typePropertyIndex = -1;
	for (let i = 0; i < expression.properties.length; i++) {
		const property = expression.properties[i];
		if (property.type === "SpreadElement") {
			lastSpreadElementIndex = i;
			continue;
		}
		if (property.type === "Property" && (property.key.type === "Identifier" && property.key.name === "type" || property.key.type === "Literal" && property.key.value === "type")) {
			typeProperty = property;
			typePropertyIndex = i;
		}
	}
	if (typePropertyIndex === -1 && lastSpreadElementIndex === -1) return "classic";
	if (typePropertyIndex < lastSpreadElementIndex) throw err$1("Expected object spread to be used before the definition of the type property. Vite needs a static value for the type property to correctly infer it.", optsStartIndex);
	if (typeProperty?.value.type !== "Literal") throw err$1("Expected worker options type property to be a literal value.", optsStartIndex);
	return typeProperty?.value.value === "module" ? "module" : "classic";
}
async function parseWorkerOptions(rawOpts, optsStartIndex) {
	let opts = {};
	try {
		opts = evalValue(rawOpts);
	} catch {
		const optsNode = (await parseAstAsync(`(${rawOpts})`)).body[0].expression;
		const type = extractWorkerTypeFromAst(optsNode, optsStartIndex);
		if (type) return { type };
		throw err$1("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$1(`Expected worker options to be an object, got ${typeof opts}`, optsStartIndex);
	return opts;
}
async function getWorkerType(raw, clean, i) {
	const commaIndex = clean.indexOf(",", i);
	if (commaIndex === -1) return "classic";
	const endIndex = findClosingParen(clean, i);
	if (commaIndex > endIndex) return "classic";
	let workerOptString = raw.substring(commaIndex + 1, endIndex);
	if (hasViteIgnoreRE.test(workerOptString)) return "ignore";
	const cleanWorkerOptString = clean.substring(commaIndex + 1, endIndex);
	const trimmedCleanWorkerOptString = cleanWorkerOptString.trim();
	if (!trimmedCleanWorkerOptString.length) return "classic";
	if (trimmedCleanWorkerOptString.endsWith(",")) workerOptString = workerOptString.slice(0, cleanWorkerOptString.lastIndexOf(","));
	const workerOpts = await parseWorkerOptions(workerOptString, commaIndex + 1);
	if (workerOpts.type && (workerOpts.type === "module" || workerOpts.type === "classic")) return workerOpts.type;
	return "classic";
}
const workerImportMetaUrlRE = /\bnew\s+(?:Worker|SharedWorker)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\))/dg;
function workerImportMetaUrlPlugin(config) {
	let workerResolver;
	const fsResolveOptions = {
		...config.resolve,
		root: config.root,
		isProduction: config.isProduction,
		isBuild: config.command === "build",
		packageCache: config.packageCache,
		asSrc: true
	};
	return {
		name: "vite:worker-import-meta-url",
		applyToEnvironment(environment) {
			return environment.config.consumer === "client";
		},
		transform: {
			filter: { code: workerImportMetaUrlRE },
			async handler(code, id) {
				const isBundled = this.environment.config.isBundled;
				let s;
				const cleanString = stripLiteral(code);
				const re = new RegExp(workerImportMetaUrlRE);
				let match;
				while (match = re.exec(cleanString)) {
					const [[, endIndex], [expStart, expEnd], [urlStart, urlEnd]] = match.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 ||= new MagicString(code);
					const workerType = await getWorkerType(code, cleanString, endIndex);
					const url = rawUrl.slice(1, -1);
					let file;
					if (url[0] === ".") {
						file = path.resolve(path.dirname(id), url);
						file = slash(tryFsResolve(file, fsResolveOptions) ?? file);
					} else {
						workerResolver ??= createBackCompatIdResolver(config, {
							extensions: [],
							tryIndex: false,
							preferRelative: true
						});
						file = await workerResolver(this.environment, url, id);
						file ??= url[0] === "/" ? slash(path.join(config.publicDir, url)) : slash(path.resolve(path.dirname(id), url));
					}
					if (isBundled && config.isWorker && config.bundleChain.at(-1) === cleanUrl(file)) s.update(expStart, expEnd, "self.location.href");
					else {
						let builtUrl;
						if (isBundled) {
							const result = await workerFileToUrl(config, file);
							if (this.environment.config.command === "serve") builtUrl = toOutputFilePathInJSForBundledDev(this.environment, result.entryFilename);
							else builtUrl = result.entryUrlPlaceholder;
							for (const file of result.watchedFiles) this.addWatchFile(file);
						} else {
							builtUrl = await fileToUrl$1(this, cleanUrl(file));
							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, config);
				return null;
			}
		}
	};
}
//#endregion
//#region src/node/plugins/importAnalysisBuild.ts
/**
* A flag for injected helpers. This flag will be set to `false` if the output
* target is not native es - so that injected helper logic can be conditionally
* dropped.
*/
const isModernFlag = `__VITE_IS_MODERN__`;
const preloadMethod = `__vitePreload`;
const preloadMarker = `__VITE_PRELOAD__`;
const preloadHelperId = "\0vite/preload-helper.js";
const preloadMarkerRE = new RegExp(preloadMarker, "g");
function toRelativePath(filename, importer) {
	const relPath = path.posix.relative(path.posix.dirname(importer), filename);
	return relPath[0] === "." ? relPath : `./${relPath}`;
}
function findPreloadMarker(str, pos = 0) {
	preloadMarkerRE.lastIndex = pos;
	return preloadMarkerRE.exec(str)?.index ?? -1;
}
/**
* Pairs each dynamic `import()` with the `__VITE_PRELOAD__` marker that belongs to it.
*
* Each import is wrapped as `__vitePreload(factory, __VITE_PRELOAD__)`, so its marker
* comes right after it. Nested imports nest the wrappers, so the imports and markers
* form balanced brackets. For example, in `import('a').then(() => import('b'))`, b's
* marker ends up before a's. Pairing each import with the next marker would give b's
* marker to both imports and drop a's CSS to `void 0` (#22700). Instead the markers are
* matched with a stack in one pass, and each marker closes the innermost import that is
* still open.
*
* The returned array is parallel to `imports`. Entry `i` holds the start position of
* import `i`'s marker, or -1 when the import has no marker.
*/
function matchImportsToPreloadMarkers(code, imports) {
	const importMarkerPos = new Array(imports.length).fill(-1);
	if (imports.length === 0) return importMarkerPos;
	const openImports = [];
	let nextImport = 0;
	for (let markerStartPos = findPreloadMarker(code, imports[0].e); markerStartPos !== -1; markerStartPos = findPreloadMarker(code, markerStartPos + preloadMarker.length)) {
		while (nextImport < imports.length && imports[nextImport].e <= markerStartPos) openImports.push(nextImport++);
		if (openImports.length) importMarkerPos[openImports.pop()] = markerStartPos;
	}
	if (imports.length === 1 && importMarkerPos[0] === -1) importMarkerPos[0] = findPreloadMarker(code);
	return importMarkerPos;
}
/**
* Helper for preloading CSS and direct imports of async chunks in parallel to
* the async chunk itself.
*/
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 promise = 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?.nonce || cspNonceMeta?.getAttribute("nonce");
		function allSettled(promises) {
			return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
				status: "fulfilled",
				value
			}), (reason) => ({
				status: "rejected",
				reason
			}))));
		}
		function importMetaResolve(specifier) {
			if (import.meta.resolve) return import.meta.resolve(specifier);
			return new URL(specifier, new URL("../../../src/node/plugins/importAnalysisBuild.ts", import.meta.url)).href;
		}
		promise = allSettled(deps.map((dep) => {
			dep = assetsURL(dep, importerUrl);
			dep = importMetaResolve(dep);
			if (dep in seen) return;
			seen[dep] = true;
			const isCss = dep.endsWith(".css");
			for (let i = links.length - 1; i >= 0; i--) {
				const link = links[i];
				if (link.href === dep && (!isCss || link.rel === "stylesheet")) 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(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
			});
		}));
	}
	function handlePreloadError(err) {
		const e = new Event("vite:preloadError", { cancelable: true });
		e.payload = err;
		window.dispatchEvent(e);
		if (!e.defaultPrevented) throw err;
	}
	return promise.then((res) => {
		for (const item of res || []) {
			if (item.status !== "rejected") continue;
			handlePreloadError(item.reason);
		}
		return baseModule().catch(handlePreloadError);
	});
}
function getPreloadCode(environment, renderBuiltUrlBoolean, isRelativeBase) {
	const { modulePreload } = environment.config.build;
	return `const scriptRel = ${modulePreload && modulePreload.polyfill ? `'modulepreload'` : `/* @__PURE__ */ (${detectScriptRel.toString()})()`};const assetsURL = ${renderBuiltUrlBoolean || isRelativeBase ? `function(dep, importerUrl) { return new URL(dep, importerUrl).href }` : `function(dep) { return ${JSON.stringify(environment.config.base)}+dep }`};const seen = {};export const ${preloadMethod} = ${preload.toString()}`;
}
/**
* Build only. During serve this is performed as part of ./importAnalysis.
*/
function buildImportAnalysisPlugin(config) {
	const getInsertPreload = (environment) => environment.config.consumer === "client" && !config.isWorker && !config.build.lib;
	const renderBuiltUrl = config.experimental.renderBuiltUrl;
	const isRelativeBase = config.base === "./" || config.base === "";
	return [{
		name: "vite:build-import-analysis",
		renderChunk(code, _, { format }) {
			if (code.includes(isModernFlag)) {
				const re = new RegExp(isModernFlag, "g");
				const isModern = String(format === "es");
				const isModernWithPadding = isModern + " ".repeat(isModernFlag.length - isModern.length);
				return {
					code: code.replace(re, isModernWithPadding),
					map: null
				};
			}
			return null;
		},
		async generateBundle(opts, bundle) {
			const { format } = opts;
			if (format !== "es") return;
			await init;
			if (!getInsertPreload(this.environment)) {
				const removedPureCssFiles = removedPureCssFilesCache.get(config);
				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$2(code)[0].filter((i) => i.d > -1);
						} catch (e) {
							const loc = numberToPos(code, e.idx);
							this.error({
								name: e.name,
								message: e.message,
								stack: e.stack,
								cause: e.cause,
								pos: e.idx,
								loc: {
									...loc,
									file: chunk.fileName
								},
								frame: generateCodeFrame(code, loc)
							});
						}
						for (const imp of imports) {
							const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imp;
							let url = name;
							if (!url) {
								const rawUrl = code.slice(start, end);
								if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
							}
							if (!url) continue;
							const normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
							if (removedPureCssFiles.has(normalizedFile)) chunk.code = chunk.code.slice(0, expStart) + `Promise.resolve({${"".padEnd(expEnd - expStart - 19, " ")}})` + chunk.code.slice(expEnd);
						}
					}
				}
				return;
			}
			const buildSourcemap = this.environment.config.build.sourcemap;
			const { modulePreload } = this.environment.config.build;
			let importMapMapping;
			let importMapReverseMapping;
			if (config.build.chunkImportMap) {
				const decoder = new TextDecoder();
				const importMap = bundle[getImportMapFilename(config)];
				const importMapContent = JSON.parse(typeof importMap.source === "string" ? importMap.source : decoder.decode(importMap.source));
				importMapMapping = Object.fromEntries(Object.entries(importMapContent.imports).map(([k, v]) => [k.slice(config.base.length), v.slice(config.base.length)]));
				importMapReverseMapping = Object.fromEntries(Object.entries(importMapMapping).map(([k, v]) => [v, k]));
				if (config.isOutputOptionsForLegacyChunks?.(opts)) {
					this.emitFile({
						type: "asset",
						fileName: "importmap.legacy.json",
						source: importMap.source
					});
					delete bundle[getImportMapFilename(config)];
				}
			}
			for (const file in bundle) {
				const chunk = bundle[file];
				if (chunk.type === "chunk" && chunk.code.includes(preloadMarker)) {
					const code = chunk.code;
					let imports;
					try {
						imports = parse$2(code)[0].filter((i) => i.d > -1);
					} catch (e) {
						const loc = numberToPos(code, e.idx);
						this.error({
							name: e.name,
							message: e.message,
							stack: e.stack,
							cause: e.cause,
							pos: e.idx,
							loc: {
								...loc,
								file: chunk.fileName
							},
							frame: generateCodeFrame(code, loc)
						});
					}
					const s = new MagicString(code);
					const rewroteMarkerStartPos = /* @__PURE__ */ new Set();
					const fileDeps = [];
					const addFileDep = (url, runtime = false) => {
						const index = fileDeps.findIndex((dep) => dep.url === url);
						if (index === -1) return fileDeps.push({
							url,
							runtime
						}) - 1;
						else return index;
					};
					if (imports.length) {
						const importMarkerPos = matchImportsToPreloadMarkers(code, imports);
						for (let index = 0; index < imports.length; index++) {
							const { n: name, s: start, e: end, ss: expStart, se: expEnd } = imports[index];
							let url = name;
							if (!url) {
								const rawUrl = code.slice(start, end);
								if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"` || rawUrl[0] === "`" && rawUrl[rawUrl.length - 1] === "`") url = rawUrl.slice(1, -1);
							}
							const deps = /* @__PURE__ */ new Set();
							let hasRemovedPureCssChunk = false;
							let normalizedFile = void 0;
							if (url) {
								normalizedFile = path.posix.join(path.posix.dirname(chunk.fileName), url);
								const ownerFilename = chunk.fileName;
								const analyzed = /* @__PURE__ */ new Set();
								const addDeps = (rawFilename) => {
									const filename = importMapMapping?.[rawFilename] ?? rawFilename;
									if (filename === ownerFilename) return;
									if (analyzed.has(filename)) return;
									analyzed.add(filename);
									const chunk = bundle[filename];
									if (chunk) {
										deps.add(chunk.fileName);
										if (chunk.type === "chunk") {
											chunk.imports.forEach(addDeps);
											chunk.viteMetadata.importedCss.forEach((file) => {
												deps.add(file);
											});
										}
									} else {
										const chunk = removedPureCssFilesCache.get(config).get(filename);
										if (chunk) {
											if (chunk.viteMetadata.importedCss.size) {
												chunk.viteMetadata.importedCss.forEach((file) => {
													deps.add(file);
												});
												hasRemovedPureCssChunk = true;
											}
											s.update(expStart, expEnd, "Promise.resolve({})");
										}
									}
								};
								addDeps(normalizedFile);
							}
							const markerStartPos = importMarkerPos[index];
							if (markerStartPos > 0) {
								let depsArray = deps.size > 1 || hasRemovedPureCssChunk && deps.size > 0 ? modulePreload === false ? [...deps].filter((d) => d.endsWith(".css")) : [...deps] : [];
								const resolveDependencies = modulePreload ? modulePreload.resolveDependencies : void 0;
								if (resolveDependencies && normalizedFile) {
									const cssDeps = [];
									const otherDeps = [];
									for (const dep of depsArray) (dep.endsWith(".css") ? cssDeps : otherDeps).push(dep);
									depsArray = [...resolveDependencies(normalizedFile, otherDeps, {
										hostId: file,
										hostType: "js"
									}), ...cssDeps];
								}
								depsArray = depsArray.map((dep) => importMapReverseMapping?.[dep] ?? dep);
								let renderedDeps;
								if (renderBuiltUrl) renderedDeps = depsArray.map((dep) => {
									const replacement = toOutputFilePathInJS(this.environment, dep, "asset", chunk.fileName, "js", toRelativePath);
									if (typeof replacement === "string") return addFileDep(replacement);
									return addFileDep(replacement.runtime, true);
								});
								else renderedDeps = depsArray.map((d) => isRelativeBase ? addFileDep(toRelativePath(d, file)) : addFileDep(d));
								s.update(markerStartPos, markerStartPos + preloadMarker.length, renderedDeps.length > 0 ? `__vite__mapDeps([${renderedDeps.join(",")}])` : `[]`);
								rewroteMarkerStartPos.add(markerStartPos);
							}
						}
					}
					if (fileDeps.length > 0) {
						const mapDepsCode = `const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=${`[${fileDeps.map((fileDep) => fileDep.runtime ? fileDep.url : JSON.stringify(fileDep.url)).join(",")}]`})))=>i.map(i=>d[i]);\n`;
						if (code.startsWith("#!")) s.prependLeft(code.indexOf("\n") + 1, mapDepsCode);
						else s.prepend(mapDepsCode);
					}
					let markerStartPos = findPreloadMarker(code);
					while (markerStartPos >= 0) {
						if (!rewroteMarkerStartPos.has(markerStartPos)) s.update(markerStartPos, markerStartPos + preloadMarker.length, "void 0");
						markerStartPos = findPreloadMarker(code, markerStartPos + preloadMarker.length);
					}
					if (s.hasChanged()) {
						chunk.code = s.toString();
						if (buildSourcemap && chunk.map) {
							const nextMap = s.generateMap({
								source: chunk.fileName,
								hires: "boundary"
							});
							const originalFile = chunk.map.file;
							const map = combineSourcemaps(chunk.fileName, [nextMap, chunk.map]);
							map.toUrl = () => genSourceMapUrl(map);
							if (originalFile) map.file = originalFile;
							const originalDebugId = chunk.map.debugId;
							chunk.map = map;
							if (buildSourcemap === "inline") {
								chunk.code = chunk.code.replace(import_convert_source_map.default.mapFileCommentRegex, "");
								chunk.code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`;
							} else {
								if (originalDebugId) map.debugId = originalDebugId;
								const mapAsset = bundle[chunk.fileName + ".map"];
								if (mapAsset && mapAsset.type === "asset") mapAsset.source = map.toString();
							}
						}
					}
				}
			}
		}
	}, perEnvironmentPlugin("native:import-analysis-build", (environment) => {
		return viteBuildImportAnalysisPlugin({
			preloadCode: getPreloadCode(environment, !!renderBuiltUrl, isRelativeBase),
			insertPreload: getInsertPreload(environment),
			optimizeModulePreloadRelativePaths: false,
			renderBuiltUrl: !!renderBuiltUrl,
			isRelativeBase
		});
	})];
}
//#endregion
//#region src/node/plugins/assetImportMetaUrl.ts
/**
* Convert `new URL('./foo.png', import.meta.url)` to its resolved built URL
*
* Supports template string with dynamic segments:
* ```
* new URL(`./dir/${name}.png`, import.meta.url)
* // transformed to
* import.meta.glob('./dir/**.png', { eager: true, import: 'default' })[`./dir/${name}.png`]
* ```
*/
const assetImportMetaUrlRE = /\bnew\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*(?:,\s*)?\)/dg;
function assetImportMetaUrlPlugin(config) {
	const { publicDir } = config;
	let assetResolver;
	const fsResolveOptions = {
		...config.resolve,
		root: config.root,
		isProduction: config.isProduction,
		isBuild: config.command === "build",
		packageCache: config.packageCache,
		asSrc: true
	};
	return {
		name: "vite:asset-import-meta-url",
		applyToEnvironment(environment) {
			return environment.config.consumer === "client";
		},
		transform: {
			filter: {
				id: { exclude: [exactRegex(preloadHelperId), exactRegex(CLIENT_ENTRY)] },
				code: assetImportMetaUrlRE
			},
			async handler(code, id) {
				let s;
				const re = new RegExp(assetImportMetaUrlRE);
				const cleanString = stripLiteral(code);
				let match;
				while (match = re.exec(cleanString)) {
					const [[startIndex, endIndex], [urlStart, urlEnd]] = match.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 templateLiteral = this.parse(pureUrl).body[0].expression;
						if (templateLiteral.expressions.length) {
							const pattern = buildGlobPattern(templateLiteral);
							if (pattern[0] === "*") continue;
							const globOptions = {
								eager: true,
								import: "default",
								query: injectQuery(queryString, "url")
							};
							s.update(startIndex, endIndex, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
							continue;
						}
					}
					const url = rawUrl.slice(1, -1);
					if (isDataUrl(url)) continue;
					let file;
					if (url[0] === ".") {
						file = slash(path.resolve(path.dirname(id), url));
						file = tryFsResolve(file, fsResolveOptions) ?? file;
					} else {
						assetResolver ??= createBackCompatIdResolver(config, {
							extensions: [],
							mainFields: [],
							tryIndex: false,
							preferRelative: true
						});
						file = await assetResolver(this.environment, url, id);
						file ??= url[0] === "/" ? slash(path.join(publicDir, url)) : slash(path.resolve(path.dirname(id), url));
					}
					let builtUrl;
					if (file) try {
						if (publicDir && isParentDirectory(publicDir, file)) {
							const publicPath = "/" + path.posix.relative(publicDir, file);
							builtUrl = await fileToUrl$1(this, publicPath);
						} else {
							builtUrl = await fileToUrl$1(this, file);
							if (tryStatSync(file)?.isFile()) this.addWatchFile(file);
						}
					} catch {}
					if (!builtUrl) {
						const rawExp = code.slice(startIndex, endIndex);
						config.logger.warnOnce(`\n${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 = url;
					}
					s.update(startIndex, endIndex, `new URL(${JSON.stringify(builtUrl)}, '' + import.meta.url)`);
				}
				if (s) return transformStableResult(s, id, config);
			}
		}
	};
}
function buildGlobPattern(ast) {
	let pattern = "";
	let lastIsGlob = false;
	for (let i = 0; i < ast.quasis.length; i++) {
		const str = ast.quasis[i].value.raw;
		if (str) {
			pattern += str;
			lastIsGlob = false;
		}
		if (ast.expressions[i] && !lastIsGlob) {
			pattern += "*";
			lastIsGlob = true;
		}
	}
	return pattern;
}
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;
}
//#endregion
//#region ../../node_modules/.pnpm/@rollup+plugin-dynamic-import-vars@2.1.4_rollup@4.59.0/node_modules/@rollup/plugin-dynamic-import-vars/dist/es/index.js
var VariableDynamicImportError = class extends Error {};
const 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 escapePath(str);
}
function templateLiteralToGlob(node) {
	let glob = "";
	for (let i = 0; i < node.quasis.length; i += 1) {
		glob += sanitizeString(node.quasis[i].value.raw);
		if (node.expressions[i]) glob += expressionToGlob(node.expressions[i]);
	}
	return glob;
}
function callExpressionToGlob(node) {
	const { callee } = node;
	if (callee.type === "MemberExpression" && callee.property.type === "Identifier" && callee.property.name === "concat") return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join("")}`;
	return "*";
}
function binaryExpressionToGlob(node) {
	if (node.operator !== "+") throw new VariableDynamicImportError(`${node.operator} operator is not supported.`);
	return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`;
}
function expressionToGlob(node) {
	switch (node.type) {
		case "TemplateLiteral": return templateLiteralToGlob(node);
		case "CallExpression": return callExpressionToGlob(node);
		case "BinaryExpression": return binaryExpressionToGlob(node);
		case "Literal": return sanitizeString(node.value);
		default: return "*";
	}
}
const defaultProtocol = "file:";
const ignoredProtocols = [
	"data:",
	"http:",
	"https:"
];
function shouldIgnore(glob) {
	const containsAsterisk = glob.includes("*");
	const globURL = new URL(glob, defaultProtocol);
	const containsIgnoredProtocol = ignoredProtocols.some((ignoredProtocol) => ignoredProtocol === globURL.protocol);
	return !containsAsterisk || containsIgnoredProtocol;
}
function dynamicImportToGlob(node, sourceString) {
	let glob = expressionToGlob(node);
	if (shouldIgnore(glob)) return null;
	glob = glob.replace(/\*\*/g, "*");
	if (glob.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 (glob.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 (!glob.startsWith("./") && !glob.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}`);
	if (/^\.\/\*\.\w+$/.test(glob)) 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 (path$1.extname(glob) === "") throw new VariableDynamicImportError(`invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}`);
	return glob;
}
//#endregion
//#region src/node/plugins/dynamicImportVars.ts
const dynamicImportHelperId = "\0vite/dynamic-import-helper.js";
const relativePathRE = /^\.{1,2}\//;
const hasDynamicImportRE = /\bimport\s*[(/]/;
const dynamicImportHelper = (glob, path, segs) => {
	const v = glob[path];
	if (v) return typeof v === "function" ? v() : Promise.resolve(v);
	return new Promise((_, reject) => {
		(typeof queueMicrotask === "function" ? queueMicrotask : setTimeout)(reject.bind(null, /* @__PURE__ */ new Error("Unknown variable dynamic import: " + path + (path.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(requestQueryMaybeEscapedSplitRE, 2);
	let [rawPattern, search] = filename.split(requestQuerySplitRE, 2);
	let globParams = null;
	if (search) {
		search = "?" + search;
		if (workerOrSharedWorkerRE.test(search) || urlRE$1.test(search) || rawRE$1.test(search)) globParams = {
			query: search,
			import: "*"
		};
		else globParams = { query: search };
	}
	return {
		globParams,
		userPattern,
		rawPattern
	};
}
async function transformDynamicImport(importSource, importer, resolve, root) {
	if (importSource[1] !== "." && importSource[1] !== "/") {
		const resolvedFileName = await resolve(importSource.slice(1, -1), importer);
		if (!resolvedFileName) return null;
		const relativeFileName = normalizePath(posix.relative(posix.dirname(normalizePath(importer)), normalizePath(resolvedFileName)));
		importSource = "`" + (relativeFileName[0] === "." ? "" : "./") + relativeFileName + "`";
	}
	const dynamicImportPattern = parseDynamicImportPattern(importSource);
	if (!dynamicImportPattern) return null;
	const { globParams, rawPattern, userPattern } = dynamicImportPattern;
	const params = globParams ? `, ${JSON.stringify(globParams)}` : "";
	const dir = importer ? posix.dirname(importer) : root;
	const normalized = rawPattern[0] === "/" ? posix.join(root, rawPattern.slice(1)) : posix.join(dir, rawPattern);
	let newRawPattern = posix.relative(posix.dirname(importer), normalized);
	if (!relativePathRE.test(newRawPattern)) newRawPattern = `./${newRawPattern}`;
	const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`;
	return {
		rawPattern: newRawPattern,
		pattern: userPattern,
		glob: exp
	};
}
function dynamicImportVarsPlugin(config) {
	const resolve = createBackCompatIdResolver(config, {
		preferRelative: true,
		tryIndex: false,
		extensions: []
	});
	const getFilter = perEnvironmentState((environment) => {
		const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
		return createFilter$1(include, exclude);
	});
	return {
		name: "vite:dynamic-import-vars",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) {
				const { include, exclude } = environment.config.build.dynamicImportVarsOptions;
				return viteDynamicImportVarsPlugin({
					include,
					exclude,
					resolver(id, importer) {
						return resolve(environment, id, importer);
					},
					sourcemap: !!environment.config.build.sourcemap
				});
			}
			return true;
		},
		resolveId: {
			filter: { id: exactRegex(dynamicImportHelperId) },
			handler(id) {
				return id;
			}
		},
		load: {
			filter: { id: exactRegex(dynamicImportHelperId) },
			handler(_id) {
				return `export default ${dynamicImportHelper.toString()}`;
			}
		},
		transform: {
			filter: {
				id: { exclude: exactRegex(CLIENT_ENTRY) },
				code: hasDynamicImportRE
			},
			async handler(source, importer) {
				const { environment } = this;
				if (!getFilter(this)(importer)) return;
				await init;
				let imports = [];
				try {
					imports = parse$2(source)[0];
				} catch {
					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 ||= new MagicString(source);
					let result;
					try {
						result = await transformDynamicImport(source.slice(start, end), importer, (id, importer) => resolve(environment, id, importer), config.root);
					} catch (error) {
						this.warn(error);
					}
					if (!result) continue;
					const { rawPattern, glob } = result;
					needDynamicImportHelper = true;
					s.overwrite(expStart, expEnd, `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`, ${rawPattern.split("/").length})`);
				}
				if (s) {
					if (needDynamicImportHelper) s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
					return transformStableResult(s, importer, config);
				}
			}
		}
	};
}
//#endregion
//#region src/node/plugins/importMetaGlob.ts
function importGlobPlugin(config) {
	const importGlobMaps = /* @__PURE__ */ new Map();
	return {
		name: "vite:import-glob",
		applyToEnvironment(environment) {
			if (environment.config.isBundled) return viteImportGlobPlugin({
				root: environment.config.root,
				sourcemap: !!environment.config.build.sourcemap,
				restoreQueryExtension: environment.config.experimental.importGlobRestoreExtension
			});
			return true;
		},
		buildStart() {
			importGlobMaps.clear();
		},
		transform: {
			filter: { code: "import.meta.glob" },
			async handler(code, id) {
				const result = await transformGlobImport(code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.experimental.importGlobRestoreExtension, config.logger);
				if (result) {
					if (!importGlobMaps.has(this.environment)) importGlobMaps.set(this.environment, /* @__PURE__ */ new Map());
					const globMatchers = result.matches.map((i) => {
						const affirmed = [];
						const negated = [];
						for (const glob of i.globsResolved) if (glob[0] === "!") negated.push(glob.slice(1));
						else affirmed.push(glob);
						const affirmedMatcher = pm(affirmed, {
							noextglob: true,
							dot: !!i.options.exhaustive,
							nocase: !(i.options.caseSensitive ?? true),
							ignore: i.options.exhaustive ? [] : ["**/node_modules/**"]
						});
						const negatedMatcher = pm(negated, {
							noextglob: true,
							dot: !!i.options.exhaustive,
							nocase: !(i.options.caseSensitive ?? true),
							ignore: i.options.exhaustive ? [] : ["**/node_modules/**"]
						});
						return (file) => {
							return (affirmed.length === 0 || affirmedMatcher(file)) && !(negated.length > 0 && negatedMatcher(file));
						};
					});
					importGlobMaps.get(this.environment).set(id, globMatchers);
					return transformStableResult(result.s, id, config);
				}
			}
		},
		hotUpdate({ type, file, modules: oldModules }) {
			if (type === "update") return;
			const importGlobMap = importGlobMaps.get(this.environment);
			if (!importGlobMap) return;
			const modules = [];
			for (const [id, globMatchers] of importGlobMap) if (globMatchers.some((matcher) => matcher(file))) {
				const mod = this.environment.moduleGraph.getModuleById(id);
				if (mod) modules.push(mod);
			}
			return modules.length > 0 ? [...oldModules, ...modules] : void 0;
		}
	};
}
const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
const objectKeysRE = /\bObject\.keys\(\s*$/;
const objectValuesRE = /\bObject\.values\(\s*$/;
const knownOptions = {
	as: ["string"],
	eager: ["boolean"],
	import: ["string"],
	exhaustive: ["boolean"],
	query: ["object", "string"],
	base: ["string"],
	caseSensitive: ["boolean"]
};
const forceDefaultAs = ["raw", "url"];
function err(e, pos) {
	const error = new Error(e);
	error.pos = pos;
	return error;
}
function parseGlobOptions(rawOpts, optsStartIndex, logger) {
	let opts = {};
	try {
		opts = evalValue(rawOpts);
	} catch {
		throw err("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(`Unknown glob option "${key}"`, optsStartIndex);
		const allowedTypes = knownOptions[key];
		const valueType = typeof opts[key];
		if (!allowedTypes.includes(valueType)) throw err(`Expected glob option "${key}" to be of type ${allowedTypes.join(" or ")}, but got ${valueType}`, optsStartIndex);
	}
	if (opts.base) {
		if (opts.base[0] === "!") throw err("Option \"base\" cannot start with \"!\"", optsStartIndex);
		else if (opts.base[0] !== "/" && !opts.base.startsWith("./") && !opts.base.startsWith("../")) throw err(`Option "base" must start with '/', './' or '../', but got "${opts.base}"`, optsStartIndex);
	}
	if (typeof opts.query === "object") {
		for (const key in opts.query) {
			const value = opts.query[key];
			if (![
				"string",
				"number",
				"boolean"
			].includes(typeof value)) throw err(`Expected glob option "query.${key}" to be of type string, number, or boolean, but got ${typeof value}`, optsStartIndex);
		}
		opts.query = stringifyQuery(opts.query);
	}
	if (opts.as && logger) {
		const importSuggestion = forceDefaultAs.includes(opts.as) ? `, import: 'default'` : "";
		logger.warn(import_picocolors.default.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(`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("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 {
		return [];
	}
	const tasks = Array.from(cleanCode.matchAll(importGlobRE)).map(async (match, index) => {
		const start = match.index;
		const err = (msg) => {
			const e = /* @__PURE__ */ new Error(`Invalid glob import syntax: ${msg}`);
			e.pos = start;
			return e;
		};
		const end = findCorrespondingCloseParenthesisPosition(cleanCode, start + match[0].length) + 1;
		if (end <= 0) throw err("Close parenthesis not found");
		const rootAst = (await parseAstAsync(code.slice(start, end))).body[0];
		if (rootAst.type !== "ExpressionStatement") throw err(`Expect CallExpression, got ${rootAst.type}`);
		const ast = rootAst.expression;
		if (ast.type !== "CallExpression") throw err(`Expect CallExpression, got ${ast.type}`);
		if (ast.arguments.length < 1 || ast.arguments.length > 2) throw err(`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 err(`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 err(`Expected glob to be a string, but got dynamic template literal`);
				globs.push(element.quasis[0].value.raw);
			} else throw err("Could only use literals");
		};
		if (arg1.type === "ArrayExpression") for (const element of arg1.elements) validateLiteral(element);
		else validateLiteral(arg1);
		let options = {};
		if (arg2) {
			if (arg2.type !== "ObjectExpression") throw err(`Expected the second argument to be an object literal, but got "${arg2.type}"`);
			options = parseGlobOptions(code.slice(start + arg2.start, start + arg2.end), start + arg2.start, logger);
		}
		const globsResolved = await Promise.all(globs.map((glob) => toAbsoluteGlob(glob, root, importer, resolveId, options.base)));
		const isRelative = globs.every((i) => ".!".includes(i[0]));
		const sliceCode = cleanCode.slice(0, start);
		const onlyKeys = objectKeysRE.test(sliceCode);
		let onlyValues = false;
		if (!onlyKeys) onlyValues = objectValuesRE.test(sliceCode);
		return {
			index,
			globs,
			globsResolved,
			isRelative,
			options,
			start,
			end,
			onlyKeys,
			onlyValues
		};
	});
	return (await Promise.all(tasks)).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;
}
const importPrefix = "__vite_glob_";
const { basename: basename$1, dirname: dirname$1, relative: relative$1 } = posix;
/**
* @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
*/
async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false, logger) {
	id = slash(id);
	root = slash(root);
	const isVirtual = isVirtualModule(id);
	const dir = isVirtual ? void 0 : dirname$1(id);
	const matches = await parseImportGlob(code, isVirtual ? void 0 : id, root, resolveId, logger);
	const matchedFiles = /* @__PURE__ */ new Set();
	if (!matches.length) return null;
	const s = new MagicString(code);
	const staticImports = (await Promise.all(matches.map(async ({ globsResolved, isRelative, options, index, start, end, onlyKeys, onlyValues }) => {
		if (!dir && !options.base && isRelative) throw new Error("In virtual modules, all globs must start with '/'");
		const files = (await glob(globsResolved, {
			absolute: true,
			cwd: getCommonBase(globsResolved) ?? root,
			dot: !!options.exhaustive,
			expandDirectories: false,
			caseSensitiveMatch: options.caseSensitive ?? true,
			ignore: options.exhaustive ? [] : ["**/node_modules/**"],
			extglob: false
		})).filter((file) => file !== id).sort();
		const objectProps = [];
		const staticImports = [];
		const resolvePaths = (file) => {
			if (!dir) {
				const importPath = `/${relative$1(root, file)}`;
				let filePath = options.base ? `${relative$1(posix.join(root, options.base), file)}` : importPath;
				if (options.base && !filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
				return {
					filePath,
					importPath
				};
			}
			let importPath = relative$1(dir, file);
			if (!importPath.startsWith("./") && !importPath.startsWith("../")) importPath = `./${importPath}`;
			let filePath;
			if (options.base) {
				filePath = relative$1(posix.join(options.base[0] === "/" ? root : dir, options.base), file);
				if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `./${filePath}`;
			} else if (isRelative) filePath = importPath;
			else {
				filePath = relative$1(root, file);
				if (!filePath.startsWith("./") && !filePath.startsWith("../")) filePath = `/${filePath}`;
			}
			return {
				filePath,
				importPath
			};
		};
		files.forEach((file, i) => {
			const paths = resolvePaths(file);
			const filePath = paths.filePath;
			let importPath = paths.importPath;
			let importQuery = options.query ?? "";
			if (onlyKeys) {
				objectProps.push(`${JSON.stringify(filePath)}: 0`);
				return;
			}
			if (importQuery && importQuery !== "?raw") {
				const fileExtension = basename$1(file).split(".").slice(-1)[0];
				if (fileExtension && restoreQueryExtension) importQuery = `${importQuery}&lang.${fileExtension}`;
			}
			importPath = `${importPath}${importQuery}`;
			const importKey = options.import && options.import !== "*" ? options.import : void 0;
			if (options.eager) {
				const variableName = `${importPrefix}${index}_${i}`;
				const expression = importKey ? `{ ${importKey} as ${variableName} }` : `* as ${variableName}`;
				staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
				objectProps.push(onlyValues ? `${variableName}` : `${JSON.stringify(filePath)}: ${variableName}`);
			} else {
				let importStatement = `import(${JSON.stringify(importPath)})`;
				if (importKey) importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
				objectProps.push(onlyValues ? `() => ${importStatement}` : `${JSON.stringify(filePath)}: () => ${importStatement}`);
			}
		});
		files.forEach((i) => matchedFiles.add(i));
		const originalLineBreakCount = code.slice(start, end).match(/\n/g)?.length ?? 0;
		const lineBreaks = originalLineBreakCount > 0 ? "\n".repeat(originalLineBreakCount) : "";
		let replacement = "";
		if (onlyKeys) replacement = `{${objectProps.join(",")}${lineBreaks}}`;
		else if (onlyValues) replacement = `[${objectProps.join(",")}${lineBreaks}]`;
		else replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(",")}${lineBreaks}})`;
		s.overwrite(start, end, replacement);
		return staticImports;
	}))).flat();
	if (staticImports.length) s.prepend(`${staticImports.join(";")};`);
	return {
		s,
		matches,
		files: matchedFiles
	};
}
function globSafePath(path) {
	return escapePath(normalizePath(path));
}
function lastNthChar(str, n) {
	return str.charAt(str.length - 1 - n);
}
function globSafeResolvedPath(resolved, glob) {
	let numEqual = 0;
	const maxEqual = Math.min(resolved.length, glob.length);
	while (numEqual < maxEqual && lastNthChar(resolved, numEqual) === lastNthChar(glob, 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(glob, root, importer, resolveId, base) {
	let pre = "";
	if (glob[0] === "!") {
		pre = "!";
		glob = glob.slice(1);
	}
	root = globSafePath(root);
	let dir;
	if (base) if (base[0] === "/") dir = posix.join(root, base);
	else dir = posix.resolve(importer ? globSafePath(dirname$1(importer)) : root, base);
	else dir = importer ? globSafePath(dirname$1(importer)) : root;
	if (glob[0] === "/") return pre + posix.join(root, glob.slice(1));
	if (glob.startsWith("./")) return pre + posix.join(dir, glob.slice(2));
	if (glob.startsWith("../")) return pre + posix.join(dir, glob);
	if (glob.startsWith("**")) return pre + glob;
	const isSubImportsPattern = glob[0] === "#" && glob.includes("*");
	const resolved = normalizePath(await resolveId(glob, importer, { custom: { "vite:import-glob": { isSubImportsPattern } } }) || glob);
	if (isAbsolute(resolved)) return pre + globSafeResolvedPath(resolved, glob);
	throw new Error(`Invalid glob: "${glob}" (resolved: "${resolved}"). It must start with '/' or './'`);
}
function getCommonBase(globsResolved) {
	const bases = globsResolved.filter((g) => g[0] !== "!").map((glob) => {
		let { base } = pm.scan(glob);
		if (posix.basename(base).includes(".")) base = 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 === candidate || base.startsWith(`${candidate}/`))) commonAncestor = candidate;
		else break;
	}
	if (!commonAncestor) commonAncestor = "/";
	return commonAncestor;
}
function isVirtualModule(id) {
	return id.startsWith("virtual:") || id[0] === "\0" || !id.includes("/");
}
//#endregion
//#region src/node/plugins/pluginFilter.ts
function getMatcherString(glob, cwd) {
	if (glob.startsWith("**") || path.isAbsolute(glob)) return slash(glob);
	return slash(path.join(cwd, glob));
}
function patternToIdFilter(pattern, cwd) {
	if (pattern instanceof RegExp) return (id) => {
		const normalizedId = slash(id);
		const result = pattern.test(normalizedId);
		pattern.lastIndex = 0;
		return result;
	};
	const matcher = pm(getMatcherString(pattern, cwd), { dot: true });
	return (id) => {
		return matcher(slash(id));
	};
}
function patternToCodeFilter(pattern) {
	if (pattern instanceof RegExp) return (code) => {
		const result = pattern.test(code);
		pattern.lastIndex = 0;
		return result;
	};
	return (code) => code.includes(pattern);
}
function createFilter(exclude, include) {
	if (!exclude && !include) return;
	return (input) => {
		if (exclude?.some((filter) => filter(input))) return false;
		if (include?.some((filter) => filter(input))) return true;
		return !(include && include.length > 0);
	};
}
function normalizeFilter(filter) {
	if (typeof filter === "string" || filter instanceof RegExp) return { include: [filter] };
	if (Array.isArray(filter)) return { include: filter };
	return {
		include: filter.include ? arraify(filter.include) : void 0,
		exclude: filter.exclude ? arraify(filter.exclude) : void 0
	};
}
function createIdFilter(filter, cwd = process.cwd()) {
	if (!filter) return;
	const { exclude, include } = normalizeFilter(filter);
	const excludeFilter = exclude?.map((p) => patternToIdFilter(p, cwd));
	const includeFilter = include?.map((p) => patternToIdFilter(p, cwd));
	return createFilter(excludeFilter, includeFilter);
}
function createCodeFilter(filter) {
	if (!filter) return;
	const { exclude, include } = normalizeFilter(filter);
	const excludeFilter = exclude?.map(patternToCodeFilter);
	const includeFilter = include?.map(patternToCodeFilter);
	return createFilter(excludeFilter, includeFilter);
}
function createModuleTypeFilter(filter) {
	if (!filter) return;
	const include = Array.isArray(filter) ? filter : filter.include ?? [];
	return (moduleType) => include.includes(moduleType);
}
function createFilterForTransform(idFilter, codeFilter, moduleTypeFilter, cwd) {
	if (!idFilter && !codeFilter && !moduleTypeFilter) return;
	const idFilterFn = createIdFilter(idFilter, cwd);
	const codeFilterFn = createCodeFilter(codeFilter);
	const moduleTypeFilterFn = createModuleTypeFilter(moduleTypeFilter);
	return (id, code, moduleType) => {
		let fallback = moduleTypeFilterFn?.(moduleType) ?? true;
		if (!fallback) return false;
		if (idFilterFn) fallback &&= idFilterFn(id);
		if (!fallback) return false;
		if (codeFilterFn) fallback &&= codeFilterFn(code);
		return fallback;
	};
}
//#endregion
//#region ../../node_modules/.pnpm/@vitest+utils@4.1.9/node_modules/@vitest/utils/dist/helpers.js
function notNullish(v) {
	return v != null;
}
function isPrimitive(value) {
	return value === null || typeof value !== "function" && typeof value !== "object";
}
//#endregion
//#region ../../node_modules/.pnpm/@vitest+utils@4.1.9/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
	if (!input) return input;
	return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
function cwd() {
	if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
	return "/";
}
const resolve$2 = function(...arguments_) {
	arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
	let resolvedPath = "";
	let resolvedAbsolute = false;
	for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
		const path = index >= 0 ? arguments_[index] : cwd();
		if (!path || path.length === 0) continue;
		resolvedPath = `${path}/${resolvedPath}`;
		resolvedAbsolute = isAbsolute$2(path);
	}
	resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
	if (resolvedAbsolute && !isAbsolute$2(resolvedPath)) return `/${resolvedPath}`;
	return resolvedPath.length > 0 ? resolvedPath : ".";
};
function normalizeString(path, allowAboveRoot) {
	let res = "";
	let lastSegmentLength = 0;
	let lastSlash = -1;
	let dots = 0;
	let char = null;
	for (let index = 0; index <= path.length; ++index) {
		if (index < path.length) char = path[index];
		else if (char === "/") break;
		else char = "/";
		if (char === "/") {
			if (lastSlash === index - 1 || dots === 1);
			else if (dots === 2) {
				if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
					if (res.length > 2) {
						const lastSlashIndex = res.lastIndexOf("/");
						if (lastSlashIndex === -1) {
							res = "";
							lastSegmentLength = 0;
						} else {
							res = res.slice(0, lastSlashIndex);
							lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
						}
						lastSlash = index;
						dots = 0;
						continue;
					} else if (res.length > 0) {
						res = "";
						lastSegmentLength = 0;
						lastSlash = index;
						dots = 0;
						continue;
					}
				}
				if (allowAboveRoot) {
					res += res.length > 0 ? "/.." : "..";
					lastSegmentLength = 2;
				}
			} else {
				if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
				else res = path.slice(lastSlash + 1, index);
				lastSegmentLength = index - lastSlash - 1;
			}
			lastSlash = index;
			dots = 0;
		} else if (char === "." && dots !== -1) ++dots;
		else dots = -1;
	}
	return res;
}
const isAbsolute$2 = function(p) {
	return _IS_ABSOLUTE_RE.test(p);
};
//#endregion
//#region ../../node_modules/.pnpm/@vitest+utils@4.1.9/node_modules/@vitest/utils/dist/source-map.js
var comma = ",".charCodeAt(0);
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = /* @__PURE__ */ new Uint8Array(64);
var charToInt = /* @__PURE__ */ new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
	const c = chars.charCodeAt(i);
	intToChar[i] = c;
	charToInt[c] = i;
}
function decodeInteger(reader, relative) {
	let value = 0;
	let shift = 0;
	let integer = 0;
	do {
		integer = charToInt[reader.next()];
		value |= (integer & 31) << shift;
		shift += 5;
	} while (integer & 32);
	const shouldNegate = value & 1;
	value >>>= 1;
	if (shouldNegate) value = -2147483648 | -value;
	return relative + value;
}
function hasMoreVlq(reader, max) {
	if (reader.pos >= max) return false;
	return reader.peek() !== comma;
}
var StringReader = class {
	constructor(buffer) {
		this.pos = 0;
		this.buffer = buffer;
	}
	next() {
		return this.buffer.charCodeAt(this.pos++);
	}
	peek() {
		return this.buffer.charCodeAt(this.pos);
	}
	indexOf(char) {
		const { buffer, pos } = this;
		const idx = buffer.indexOf(char, pos);
		return idx === -1 ? buffer.length : idx;
	}
};
function decode(mappings) {
	const { length } = mappings;
	const reader = new StringReader(mappings);
	const decoded = [];
	let genColumn = 0;
	let sourcesIndex = 0;
	let sourceLine = 0;
	let sourceColumn = 0;
	let namesIndex = 0;
	do {
		const semi = reader.indexOf(";");
		const line = [];
		let sorted = true;
		let lastCol = 0;
		genColumn = 0;
		while (reader.pos < semi) {
			let seg;
			genColumn = decodeInteger(reader, genColumn);
			if (genColumn < lastCol) sorted = false;
			lastCol = genColumn;
			if (hasMoreVlq(reader, semi)) {
				sourcesIndex = decodeInteger(reader, sourcesIndex);
				sourceLine = decodeInteger(reader, sourceLine);
				sourceColumn = decodeInteger(reader, sourceColumn);
				if (hasMoreVlq(reader, semi)) {
					namesIndex = decodeInteger(reader, namesIndex);
					seg = [
						genColumn,
						sourcesIndex,
						sourceLine,
						sourceColumn,
						namesIndex
					];
				} else seg = [
					genColumn,
					sourcesIndex,
					sourceLine,
					sourceColumn
				];
			} else seg = [genColumn];
			line.push(seg);
			reader.pos++;
		}
		if (!sorted) sort(line);
		decoded.push(line);
		reader.pos = semi + 1;
	} while (reader.pos <= length);
	return decoded;
}
function sort(line) {
	line.sort(sortComparator);
}
function sortComparator(a, b) {
	return a[0] - b[0];
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var found = false;
function binarySearch(haystack, needle, low, high) {
	while (low <= high) {
		const mid = low + (high - low >> 1);
		const cmp = haystack[mid][COLUMN] - 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] !== needle) break;
	return index;
}
function lowerBound(haystack, needle, index) {
	for (let i = index - 1; i >= 0; index = i--) if (haystack[i][COLUMN] !== needle) break;
	return index;
}
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] === 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;
function cast(map) {
	return map;
}
function decodedMappings(map) {
	var _a;
	return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
}
function originalPositionFor(map, 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(map);
	if (line >= decoded.length) return OMapping(null, null, null, null);
	const segments = decoded[line];
	const index = traceSegmentInternal(segments, cast(map)._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 } = map;
	return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
}
function OMapping(source, line, column, name) {
	return {
		source,
		line,
		column,
		name
	};
}
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;
}
const CHROME_IE_STACK_REGEXP = /^\s*at .*(?:\S:\d+|\(native\))/m;
const SAFARI_NATIVE_CODE_REGEXP = /^(?:eval@)?(?:\[native code\])?$/;
const stackIgnorePatterns = [
	"node:internal",
	/\/packages\/\w+\/dist\//,
	/\/@vitest\/\w+\/dist\//,
	"/vitest/dist/",
	"/vitest/src/",
	"/node_modules/chai/",
	"/node_modules/tinyspy/",
	"/vite/dist/node/module-runner",
	"/rolldown-vite/dist/node/module-runner",
	"/deps/chunk-",
	"/deps/@vitest",
	"/deps/loupe",
	"/deps/chai",
	"/browser-playwright/dist/locators.js",
	"/browser-webdriverio/dist/locators.js",
	"/browser-preview/dist/locators.js",
	/node:\w+/,
	/__vitest_test__/,
	/__vitest_browser__/,
	"/@id/__x00__vitest/browser",
	/\/deps\/vitest_/
];
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`vitest=\\d{${NOW_LENGTH}}`);
function extractLocation(urlLike) {
	if (!urlLike.includes(":")) return [urlLike];
	const parts = /(.+?)(?::(\d+))?(?::(\d+))?$/.exec(urlLike.replace(/^\(|\)$/g, ""));
	if (!parts) return [urlLike];
	let url = parts[1];
	if (url.startsWith("async ")) url = url.slice(6);
	if (url.startsWith("http:") || url.startsWith("https:")) {
		const urlObj = new URL(url);
		urlObj.searchParams.delete("import");
		urlObj.searchParams.delete("browserv");
		url = urlObj.pathname + urlObj.hash + urlObj.search;
	}
	if (url.startsWith("/@fs/")) {
		const isWindows = /^\/@fs\/[a-zA-Z]:\//.test(url);
		url = url.slice(isWindows ? 5 : 4);
	}
	if (url.includes("vitest=")) url = url.replace(REGEXP_VITEST, "").replace(/[?&]$/, "");
	return [
		url,
		parts[2] || void 0,
		parts[3] || void 0
	];
}
function parseSingleFFOrSafariStack(raw) {
	let line = raw.trim();
	if (SAFARI_NATIVE_CODE_REGEXP.test(line)) return null;
	if (line.includes(" > eval")) line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g, ":$1");
	if (!line.includes("@")) return null;
	let atIndex = -1;
	let locationPart = "";
	let functionName;
	for (let i = 0; i < line.length; i++) if (line[i] === "@") {
		const candidateLocation = line.slice(i + 1);
		if (candidateLocation.includes(":") && candidateLocation.length >= 3) {
			atIndex = i;
			locationPart = candidateLocation;
			functionName = i > 0 ? line.slice(0, i) : void 0;
			break;
		}
	}
	if (atIndex === -1 || !locationPart.includes(":") || locationPart.length < 3) return null;
	const [url, lineNumber, columnNumber] = extractLocation(locationPart);
	if (!url || !lineNumber || !columnNumber) return null;
	return {
		file: url,
		method: functionName || "",
		line: Number.parseInt(lineNumber),
		column: Number.parseInt(columnNumber)
	};
}
function parseSingleV8Stack(raw) {
	let line = raw.trim();
	if (!CHROME_IE_STACK_REGEXP.test(line)) return null;
	if (line.includes("(eval ")) line = line.replace(/eval code/g, "eval").replace(/(\(eval at [^()]*)|(,.*$)/g, "");
	let sanitizedLine = line.replace(/^\s+/, "").replace(/\(eval code/g, "(").replace(/^.*?\s+/, "");
	const location = sanitizedLine.match(/ (\(.+\)$)/);
	sanitizedLine = location ? sanitizedLine.replace(location[0], "") : sanitizedLine;
	const [url, lineNumber, columnNumber] = extractLocation(location ? location[1] : sanitizedLine);
	let method = location && sanitizedLine || "";
	let file = url && ["eval", "<anonymous>"].includes(url) ? void 0 : url;
	if (!file || !lineNumber || !columnNumber) return null;
	if (method.startsWith("async ")) method = method.slice(6);
	if (file.startsWith("file://")) file = file.slice(7);
	file = file.startsWith("node:") || file.startsWith("internal:") ? file : resolve$2(file);
	if (method) method = method.replace(/\(0\s?,\s?__vite_ssr_import_\d+__.(\w+)\)/g, "$1").replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "").replace(/(Object\.)?__vite_ssr_export_default__\s?/g, "");
	return {
		method,
		file,
		line: Number.parseInt(lineNumber),
		column: Number.parseInt(columnNumber)
	};
}
function parseStacktrace(stack, options = {}) {
	const { ignoreStackEntries = stackIgnorePatterns } = options;
	let stacks = !CHROME_IE_STACK_REGEXP.test(stack) ? parseFFOrSafariStackTrace(stack) : parseV8Stacktrace(stack);
	const helperIndex = stacks.findLastIndex((s) => s.method.includes("__VITEST_HELPER__"));
	if (helperIndex >= 0) stacks = stacks.slice(helperIndex + 1);
	return stacks.map((stack) => {
		if (options.getUrlId) stack.file = options.getUrlId(stack.file);
		const map = options.getSourceMap?.(stack.file);
		if (!map || typeof map !== "object" || !map.version) return shouldFilter(ignoreStackEntries, stack.file) ? null : stack;
		const position = getOriginalPosition(new DecodedMap(map, stack.file), stack);
		if (!position) return stack;
		const { line, column, source, name } = position;
		let file = source || stack.file;
		if (file.match(/\/\w:\//)) file = file.slice(1);
		if (shouldFilter(ignoreStackEntries, file)) return null;
		if (line != null && column != null) return {
			line,
			column,
			file,
			method: name || stack.method
		};
		return stack;
	}).filter((s) => s != null);
}
function shouldFilter(ignoreStackEntries, file) {
	return ignoreStackEntries.some((p) => file.match(p));
}
function parseFFOrSafariStackTrace(stack) {
	return stack.split("\n").map((line) => parseSingleFFOrSafariStack(line)).filter(notNullish);
}
function parseV8Stacktrace(stack) {
	return stack.split("\n").map((line) => parseSingleV8Stack(line)).filter(notNullish);
}
function parseErrorStacktrace(e, options = {}) {
	if (!e || isPrimitive(e)) return [];
	if ("stacks" in e && e.stacks) return e.stacks;
	const stackStr = e.stack || "";
	let stackFrames = typeof stackStr === "string" ? parseStacktrace(stackStr, options) : [];
	if (!stackFrames.length) {
		const e_ = e;
		if (e_.fileName != null && e_.lineNumber != null && e_.columnNumber != null) stackFrames = parseStacktrace(`${e_.fileName}:${e_.lineNumber}:${e_.columnNumber}`, options);
		if (e_.sourceURL != null && e_.line != null && e_._column != null) stackFrames = parseStacktrace(`${e_.sourceURL}:${e_.line}:${e_.column}`, options);
	}
	if (options.frameFilter) stackFrames = stackFrames.filter((f) => options.frameFilter(e, f) !== false);
	e.stacks = stackFrames;
	return stackFrames;
}
var DecodedMap = class {
	_encoded;
	_decoded;
	_decodedMemo;
	url;
	version;
	names = [];
	resolvedSources;
	constructor(map, from) {
		this.map = map;
		const { mappings, names, sources } = map;
		this.version = map.version;
		this.names = names || [];
		this._encoded = mappings || "";
		this._decodedMemo = memoizedState();
		this.url = from;
		this.resolvedSources = (sources || []).map((s) => resolve$2(from, "..", s || ""));
	}
};
function memoizedState() {
	return {
		lastKey: -1,
		lastNeedle: -1,
		lastIndex: -1
	};
}
function getOriginalPosition(map, needle) {
	const result = originalPositionFor(map, needle);
	if (result.column == null) return null;
	return result;
}
//#endregion
//#region src/node/plugins/forwardConsole.ts
function forwardConsolePlugin(pluginOpts) {
	const sourceMapCache = /* @__PURE__ */ new Map();
	return {
		name: "vite:forward-console",
		apply: "serve",
		configureServer(server) {
			for (const name of pluginOpts.environments) {
				const environment = server.environments[name];
				environment.hot.on("vite:forward-console", (payload) => {
					if (payload.type === "error" || payload.type === "unhandled-rejection") {
						const output = formatError(payload, environment, sourceMapCache);
						environment.config.logger.error(output, { timestamp: true });
					} else {
						const output = import_picocolors.default.dim(`[console.${payload.data.level}] `) + payload.data.message;
						if (payload.data.level === "error") environment.config.logger.error(output, { timestamp: true });
						else if (payload.data.level === "warn") environment.config.logger.warn(output, { timestamp: true });
						else environment.config.logger.info(output, { timestamp: true });
					}
				});
			}
		}
	};
}
function formatError(payload, environment, sourceMapCache) {
	const error = payload.data;
	const stacks = parseErrorStacktrace(error, {
		getUrlId(id) {
			const moduleGraph = environment.moduleGraph;
			if (moduleGraph.getModuleById(id)) return id;
			const resolvedPath = normalizePath(path.resolve(environment.config.root, id.slice(1)));
			if (moduleGraph.getModuleById(resolvedPath)) return resolvedPath;
			const files = moduleGraph.getModulesByFile(resolvedPath);
			if (files && files.size) return files.values().next().value.id;
			return id;
		},
		getSourceMap(id) {
			if (sourceMapCache.has(id)) return sourceMapCache.get(id);
			const result = environment.moduleGraph.getModuleById(id)?.transformResult;
			if (result && !result.map) try {
				const filePath = id.split("?")[0];
				const extracted = extractSourcemapFromFile(result.code, filePath, environment.config.logger);
				sourceMapCache.set(id, extracted?.map);
				return extracted?.map;
			} catch {
				sourceMapCache.set(id, null);
				return null;
			}
			sourceMapCache.set(id, result?.map);
			return result?.map;
		},
		ignoreStackEntries: []
	});
	const nearest = stacks.find((stack) => {
		return [...environment.moduleGraph.getModulesByFile(stack.file) || []].some((m) => m.transformResult) && fs.existsSync(stack.file);
	});
	let output = "";
	output += import_picocolors.default.red(`${payload.type === "unhandled-rejection" ? "[Unhandled rejection]" : "[Unhandled error]"} ${import_picocolors.default.bold(error.name)}: ${error.message}\n`);
	for (const stack of stacks) {
		const file = normalizePath(path.relative(environment.config.root, stack.file));
		output += ` > ${[stack.method, `${file}:${stack.line}:${stack.column}`].filter(Boolean).join(" ")}\n`;
		if (stack === nearest) {
			const code = fs.readFileSync(stack.file, "utf-8");
			output += generateCodeFrame(code, stack).replace(/^/gm, "    ");
			output += "\n";
		}
	}
	return output;
}
//#endregion
//#region src/node/plugins/esbuildBannerFooterCompatPlugin.ts
/**
* This plugin supports `esbuild.banner` and `esbuild.footer` options.
* esbuild supported these options and Vite exposed them.
* But this should be done by plugin with transform hook.
* This plugin makes these options work in rolldown-vite as a backward compat for now.
*/
function esbuildBannerFooterCompatPlugin(config) {
	const options = config.esbuild;
	if (!options) return;
	const { include, exclude, banner, footer } = options;
	if (!banner && !footer) return;
	const filter = createFilter$1(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
	return {
		name: "vite:esbuild-banner-footer-compat",
		transform(code, id) {
			if (filter(id) || filter(cleanUrl(id))) {
				if (!(this.environment.mode === "dev" || this.environment.mode === "build" && this.environment.config.build.sourcemap)) {
					if (banner) code = `${banner}\n${code}`;
					if (footer) code = `${code}\n${footer}`;
					return code;
				}
				let s;
				const str = () => s || (s = new MagicString(code));
				if (banner) str().prepend(`${banner}\n`);
				if (footer) str().append(`${footer}\n`);
				if (s) return {
					code: s.toString(),
					map: s.generateMap({ hires: "boundary" })
				};
			}
		}
	};
}
//#endregion
//#region src/node/plugins/index.ts
async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
	const isBuild = config.command === "build";
	const isWorker = config.isWorker;
	const buildPlugins = isBuild || Object.values(config.environments).some((env) => env.isBundled) ? (await Promise.resolve().then(() => build_exports)).resolveBuildPlugins(config) : {
		pre: [],
		post: []
	};
	const devtoolsIntegrationPlugin = config.devtools.enabled && !isWorker ? await loadDevToolsIntegrationPlugin(config) : null;
	const { modulePreload } = config.build;
	return [
		optimizedDepsPlugin(),
		!isWorker ? watchPackageDataPlugin(config.packageCache) : null,
		preAliasPlugin(config),
		{
			...alias$1({
				entries: config.resolve.alias,
				customResolver: viteAliasCustomResolver
			}),
			applyToEnvironment(environment) {
				if (environment.config.isBundled && !environment.config.resolve.alias.some((v) => v.customResolver)) return viteAliasPlugin({ entries: config.resolve.alias.map((item) => {
					return {
						find: item.find,
						replacement: item.replacement
					};
				}) });
				return true;
			}
		},
		...prePlugins,
		modulePreload !== false && modulePreload.polyfill ? modulePreloadPolyfillPlugin() : null,
		...oxcResolvePlugin({
			root: config.root,
			isProduction: config.isProduction,
			isBuild,
			packageCache: config.packageCache,
			asSrc: true,
			optimizeDeps: true,
			externalize: true,
			legacyInconsistentCjsInterop: config.legacy?.inconsistentCjsInterop
		}, isWorker ? {
			...config,
			consumer: "client",
			isBundled: true,
			optimizeDepsPluginNames: []
		} : void 0),
		htmlInlineProxyPlugin(config),
		cssPlugin(config),
		esbuildBannerFooterCompatPlugin(config),
		config.oxc !== false ? {
			...oxcRuntimePlugin(),
			applyToEnvironment(environment) {
				return !environment.config.isBundled;
			}
		} : null,
		config.oxc !== false ? oxcPlugin(config) : null,
		viteJsonPlugin({
			...config.json,
			minify: isBuild
		}),
		wasmHelperPlugin(),
		webWorkerPlugin(config),
		assetPlugin(config),
		config.server.forwardConsole.enabled && forwardConsolePlugin({ environments: ["client"] }),
		...normalPlugins,
		definePlugin(config),
		cssPostPlugin(config),
		buildHtmlPlugin(config),
		workerImportMetaUrlPlugin(config),
		assetImportMetaUrlPlugin(config),
		...buildPlugins.pre,
		dynamicImportVarsPlugin(config),
		importGlobPlugin(config),
		...postPlugins,
		...buildPlugins.post,
		devtoolsIntegrationPlugin,
		clientInjectionsPlugin(config),
		cssAnalysisPlugin(config),
		importAnalysisPlugin(config)
	].filter(Boolean);
}
async function loadDevToolsIntegrationPlugin(config) {
	try {
		const { DevToolsIntegration } = await import("@vitejs/devtools/integration");
		return DevToolsIntegration({ config });
	} catch (error) {
		config.logger.error(import_picocolors.default.red(`Failed to load Vite DevTools integration: ${error?.message || error?.stack}`), { error });
		return null;
	}
}
function createPluginHookUtils(plugins) {
	const sortedPluginsCache = /* @__PURE__ */ new Map();
	function getSortedPlugins(hookName) {
		if (sortedPluginsCache.has(hookName)) return sortedPluginsCache.get(hookName);
		const sorted = getSortedPluginsByHook(hookName, plugins);
		sortedPluginsCache.set(hookName, sorted);
		return sorted;
	}
	function getSortedPluginHooks(hookName) {
		return getSortedPlugins(hookName).map((p) => getHookHandler(p[hookName])).filter(Boolean);
	}
	return {
		getSortedPlugins,
		getSortedPluginHooks
	};
}
function getSortedPluginsByHook(hookName, plugins) {
	const sortedPlugins = [];
	let pre = 0, normal = 0, post = 0;
	for (const plugin of plugins) {
		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;
}
const filterForPlugin = /* @__PURE__ */ new WeakMap();
function getCachedFilterForPlugin(plugin, hookName) {
	let filters = filterForPlugin.get(plugin);
	if (filters && hookName in filters) return filters[hookName];
	if (!filters) {
		filters = {};
		filterForPlugin.set(plugin, filters);
	}
	let filter;
	switch (hookName) {
		case "resolveId": {
			const rawFilter = extractFilter(plugin.resolveId)?.id;
			filters.resolveId = createIdFilter(rawFilter);
			filter = filters.resolveId;
			break;
		}
		case "load": {
			const rawFilter = extractFilter(plugin.load)?.id;
			filters.load = createIdFilter(rawFilter);
			filter = filters.load;
			break;
		}
		case "transform": {
			const rawFilters = extractFilter(plugin.transform);
			filters.transform = createFilterForTransform(rawFilters?.id, rawFilters?.code, rawFilters?.moduleType);
			filter = filters.transform;
			break;
		}
	}
	return filter;
}
function extractFilter(hook) {
	return hook && "filter" in hook && hook.filter ? hook.filter : void 0;
}
const viteAliasCustomResolver = async function(id, importer, options) {
	return await this.resolve(id, importer, options) || {
		id,
		meta: { "vite:alias": { noResolved: true } }
	};
};
//#endregion
//#region src/node/server/pluginContainer.ts
/**
* This file is refactored into TypeScript based on
* https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/rollup-plugin-container.js
*/
/**
https://github.com/preactjs/wmr/blob/master/LICENSE

MIT License

Copyright (c) 2020 The Preact Authors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const EMPTY_OBJECT = Object.freeze({});
const debugSourcemapCombineFilter = process.env.DEBUG_VITE_SOURCEMAP_COMBINE_FILTER;
const debugSourcemapCombine = createDebugger("vite:sourcemap-combine", { onlyWhenFocused: true });
const debugResolve = createDebugger("vite:resolve");
const debugPluginResolve = createDebugger("vite:plugin-resolve", { onlyWhenFocused: "vite:plugin" });
const debugPluginTransform = createDebugger("vite:plugin-transform", { onlyWhenFocused: "vite:plugin" });
const debugPluginContainerContext = createDebugger("vite:plugin-container-context");
const ERR_CLOSED_SERVER = "ERR_CLOSED_SERVER";
function throwClosedServerError() {
	const err = /* @__PURE__ */ new Error("The server is being restarted or closed. Request is outdated");
	err.code = ERR_CLOSED_SERVER;
	throw err;
}
/**
* Create a plugin container with a set of plugins. We pass them as a parameter
* instead of using environment.plugins to allow the creation of different
* pipelines working with the same environment (used for createIdResolver).
*/
async function createEnvironmentPluginContainer(environment, plugins, watcher, autoStart = true) {
	const container = new EnvironmentPluginContainer(environment, plugins, watcher, autoStart);
	await container.resolveRolldownOptions();
	return container;
}
var EnvironmentPluginContainer = class {
	environment;
	plugins;
	watcher;
	_pluginContextMap = /* @__PURE__ */ new Map();
	_resolvedRolldownOptions;
	_processesing = /* @__PURE__ */ new Set();
	_seenResolves = {};
	_moduleNodeToLoadAddedImports = /* @__PURE__ */ new WeakMap();
	getSortedPluginHooks;
	getSortedPlugins;
	moduleGraph;
	watchFiles = /* @__PURE__ */ new Set();
	minimalContext;
	_started = false;
	_buildStartPromise;
	_closed = false;
	/**
	* @internal use `createEnvironmentPluginContainer` instead
	*/
	constructor(environment, plugins, watcher, autoStart = true) {
		this.environment = environment;
		this.plugins = plugins;
		this.watcher = watcher;
		this._started = !autoStart;
		this.minimalContext = new MinimalPluginContext({
			...basePluginContextMeta,
			watchMode: true
		}, environment);
		const utils = createPluginHookUtils(plugins);
		this.getSortedPlugins = utils.getSortedPlugins;
		this.getSortedPluginHooks = utils.getSortedPluginHooks;
		this.moduleGraph = environment.mode === "dev" ? environment.moduleGraph : void 0;
	}
	_updateModuleLoadAddedImports(id, addedImports) {
		const module = this.moduleGraph?.getModuleById(id);
		if (module) this._moduleNodeToLoadAddedImports.set(module, addedImports);
	}
	_getAddedImports(id) {
		const module = this.moduleGraph?.getModuleById(id);
		return module ? this._moduleNodeToLoadAddedImports.get(module) || null : null;
	}
	getModuleInfo(id) {
		const module = this.moduleGraph?.getModuleById(id);
		if (!module) return null;
		if (!module.info) module.info = new Proxy({
			id,
			meta: module.meta || EMPTY_OBJECT
		}, { get(info, key) {
			if (key in info) return info[key];
			if (key === "then") return;
			throw Error(`[vite] The "${key}" property of ModuleInfo is not supported.`);
		} });
		return module.info ?? null;
	}
	handleHookPromise(maybePromise) {
		if (!maybePromise?.then) return maybePromise;
		const promise = maybePromise;
		this._processesing.add(promise);
		return promise.finally(() => this._processesing.delete(promise));
	}
	get options() {
		return this._resolvedRolldownOptions;
	}
	async resolveRolldownOptions() {
		if (!this._resolvedRolldownOptions) {
			let options = this.environment.config.build.rolldownOptions;
			for (const optionsHook of this.getSortedPluginHooks("options")) {
				if (this._closed) throwClosedServerError();
				options = await this.handleHookPromise(optionsHook.call(this.minimalContext, options)) || options;
			}
			this._resolvedRolldownOptions = options;
		}
		return this._resolvedRolldownOptions;
	}
	_getPluginContext(plugin) {
		if (!this._pluginContextMap.has(plugin)) this._pluginContextMap.set(plugin, new PluginContext(plugin, this));
		return this._pluginContextMap.get(plugin);
	}
	async hookParallel(hookName, context, args, condition) {
		const parallelPromises = [];
		for (const plugin of this.getSortedPlugins(hookName)) {
			if (condition && !condition(plugin)) continue;
			const hook = plugin[hookName];
			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(_options) {
		if (this._started) {
			if (this._buildStartPromise) await this._buildStartPromise;
			return;
		}
		this._started = true;
		const config = this.environment.getTopLevelConfig();
		this._buildStartPromise = this.handleHookPromise(this.hookParallel("buildStart", (plugin) => this._getPluginContext(plugin), () => [this.options], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev));
		await this._buildStartPromise;
		this._buildStartPromise = void 0;
	}
	async resolveId(rawId, importer = join(this.environment.config.root, "index.html"), options) {
		if (!this._started) {
			this.buildStart();
			await this._buildStartPromise;
		}
		const skip = options?.skip;
		const skipCalls = options?.skipCalls;
		const scan = !!options?.scan;
		const ssr = this.environment.config.consumer === "server";
		const ctx = new ResolveIdContext(this, skip, skipCalls, scan);
		const topLevelConfig = this.environment.getTopLevelConfig();
		const mergedSkip = new Set(skip);
		for (const call of skipCalls ?? []) if (call.called || call.id === rawId && call.importer === importer) mergedSkip.add(call.plugin);
		const resolveStart = debugResolve ? performance$1.now() : 0;
		let id = null;
		const partial = {};
		for (const plugin of this.getSortedPlugins("resolveId")) {
			if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
			if (mergedSkip?.has(plugin)) continue;
			const filter = getCachedFilterForPlugin(plugin, "resolveId");
			if (filter && !filter(rawId)) continue;
			ctx._plugin = plugin;
			const normalizedOptions = {
				kind: options?.kind,
				attributes: options?.attributes ?? {},
				custom: options?.custom,
				isEntry: !!options?.isEntry,
				ssr,
				scan
			};
			if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) {
				let ssrTemp = ssr;
				Object.defineProperty(normalizedOptions, "ssr", {
					get() {
						warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
						return ssrTemp;
					},
					set(v) {
						ssrTemp = v;
					}
				});
			}
			const pluginResolveStart = debugPluginResolve ? performance$1.now() : 0;
			const handler = getHookHandler(plugin.resolveId);
			const result = await this.handleHookPromise(handler.call(ctx, rawId, importer, normalizedOptions));
			if (!result) continue;
			if (typeof result === "string") id = result;
			else {
				id = result.id;
				Object.assign(partial, result);
			}
			debugPluginResolve?.(timeFrom(pluginResolveStart), plugin.name, prettifyUrl(id, this.environment.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)} ${import_picocolors.default.cyan(rawId)} -> ${import_picocolors.default.dim(id)}`);
			}
		}
		if (id) {
			partial.id = isExternalUrl(id) || id[0] === "\0" ? id : normalizePath(id);
			return partial;
		} else return null;
	}
	async load(id) {
		let ssr = this.environment.config.consumer === "server";
		const topLevelConfig = this.environment.getTopLevelConfig();
		const options = { ssr };
		const ctx = new LoadPluginContext(this);
		for (const plugin of this.getSortedPlugins("load")) {
			if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
			const filter = getCachedFilterForPlugin(plugin, "load");
			if (filter && !filter(id)) continue;
			ctx._plugin = plugin;
			if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(options, "ssr", {
				get() {
					warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
					return ssr;
				},
				set(v) {
					ssr = v;
				}
			});
			const handler = getHookHandler(plugin.load);
			const result = await this.handleHookPromise(handler.call(ctx, id, options));
			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, options) {
		let ssr = this.environment.config.consumer === "server";
		const topLevelConfig = this.environment.getTopLevelConfig();
		const optionsWithSSR = options ? {
			...options,
			ssr,
			moduleType: options.moduleType ?? "js"
		} : {
			ssr,
			moduleType: "js"
		};
		const inMap = options?.inMap;
		const ctx = new TransformPluginContext(this, id, code, inMap);
		ctx._addedImports = this._getAddedImports(id);
		for (const plugin of this.getSortedPlugins("transform")) {
			if (this._closed && this.environment.config.dev.recoverable) throwClosedServerError();
			const filter = getCachedFilterForPlugin(plugin, "transform");
			if (filter && !filter(id, code, optionsWithSSR.moduleType)) continue;
			if (isFutureDeprecationEnabled(topLevelConfig, "removePluginHookSsrArgument")) Object.defineProperty(optionsWithSSR, "ssr", {
				get() {
					warnFutureDeprecation(topLevelConfig, "removePluginHookSsrArgument", `Used in plugin "${plugin.name}".`);
					return ssr;
				},
				set(v) {
					ssr = v;
				}
			});
			ctx._updateActiveInfo(plugin, id, code);
			const start = debugPluginTransform ? performance$1.now() : 0;
			let result;
			const handler = getHookHandler(plugin.transform);
			try {
				result = await this.handleHookPromise(handler.call(ctx, code, id, optionsWithSSR));
			} catch (e) {
				ctx.error(e);
			}
			if (!result) continue;
			debugPluginTransform?.(timeFrom(start), plugin.name, prettifyUrl(id, this.environment.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);
					}
				}
				if (result.moduleType !== void 0) optionsWithSSR.moduleType = result.moduleType;
				ctx._updateModuleInfo(id, result);
			} else code = result;
		}
		return {
			code,
			map: ctx._getCombinedSourcemap(),
			moduleType: optionsWithSSR.moduleType
		};
	}
	async watchChange(id, change) {
		const config = this.environment.getTopLevelConfig();
		await this.hookParallel("watchChange", (plugin) => this._getPluginContext(plugin), () => [id, change], (plugin) => this.environment.name === "client" || config.server.perEnvironmentWatchChangeDuringDev || plugin.perEnvironmentWatchChangeDuringDev);
	}
	async close() {
		if (this._closed) return;
		this._closed = true;
		await Promise.allSettled(Array.from(this._processesing));
		const config = this.environment.getTopLevelConfig();
		await this.hookParallel("buildEnd", (plugin) => this._getPluginContext(plugin), () => [], (plugin) => this.environment.name === "client" || config.server.perEnvironmentStartEndDuringDev || plugin.perEnvironmentStartEndDuringDev);
		await this.hookParallel("closeBundle", (plugin) => this._getPluginContext(plugin), () => []);
	}
};
const basePluginContextMeta = {
	viteVersion: VERSION,
	rollupVersion,
	rolldownVersion
};
var BasicMinimalPluginContext = class {
	meta;
	_logger;
	constructor(meta, _logger) {
		this.meta = meta;
		this._logger = _logger;
	}
	get pluginName() {
		return "";
	}
	debug(rawLog) {
		const log = this._normalizeRawLog(rawLog);
		const msg = buildErrorMessage(log, [`debug: ${log.message}`], false);
		debugPluginContainerContext?.(msg);
	}
	info(rawLog) {
		const log = this._normalizeRawLog(rawLog);
		const msg = buildErrorMessage(log, [`info: ${log.message}`], false);
		this._logger.info(msg, {
			clear: true,
			timestamp: true
		});
	}
	warn(rawLog) {
		const log = this._normalizeRawLog(rawLog);
		const msg = buildErrorMessage(log, [import_picocolors.default.yellow(`warning: ${log.message}`)], false);
		this._logger.warn(msg, {
			clear: true,
			timestamp: true
		});
	}
	error(e) {
		throw typeof e === "string" ? new Error(e) : e;
	}
	_normalizeRawLog(rawLog) {
		const logValue = typeof rawLog === "function" ? rawLog() : rawLog;
		return typeof logValue === "string" ? new Error(logValue) : logValue;
	}
};
var MinimalPluginContext = class extends BasicMinimalPluginContext {
	environment;
	constructor(meta, environment) {
		super(meta, environment.logger);
		this.environment = environment;
	}
};
const fsModule = {
	appendFile: fsp.appendFile,
	copyFile: fsp.copyFile,
	mkdir: fsp.mkdir,
	mkdtemp: fsp.mkdtemp,
	readdir: fsp.readdir,
	readFile: fsp.readFile,
	realpath: fsp.realpath,
	rename: fsp.rename,
	rmdir: fsp.rmdir,
	stat: fsp.stat,
	lstat: fsp.lstat,
	unlink: fsp.unlink,
	writeFile: fsp.writeFile
};
var PluginContext = class extends MinimalPluginContext {
	_plugin;
	_container;
	ssr = false;
	_scan = false;
	_activeId = null;
	_activeCode = null;
	_resolveSkips;
	_resolveSkipCalls;
	get pluginName() {
		return this._plugin.name;
	}
	constructor(_plugin, _container) {
		super(_container.minimalContext.meta, _container.environment);
		this._plugin = _plugin;
		this._container = _container;
	}
	fs = fsModule;
	parse(code, opts) {
		return parseAst(code, opts);
	}
	async resolve(id, importer, options) {
		let skipCalls;
		if (options?.skipSelf === false) skipCalls = this._resolveSkipCalls;
		else if (this._resolveSkipCalls) {
			const skipCallsTemp = [...this._resolveSkipCalls];
			const sameCallIndex = this._resolveSkipCalls.findIndex((c) => c.id === id && c.importer === importer && c.plugin === this._plugin);
			if (sameCallIndex !== -1) skipCallsTemp[sameCallIndex] = {
				...skipCallsTemp[sameCallIndex],
				called: true
			};
			else skipCallsTemp.push({
				id,
				importer,
				plugin: this._plugin
			});
			skipCalls = skipCallsTemp;
		} else skipCalls = [{
			id,
			importer,
			plugin: this._plugin
		}];
		let out = await this._container.resolveId(id, importer, {
			attributes: options?.attributes,
			custom: options?.custom,
			isEntry: !!options?.isEntry,
			skip: this._resolveSkips,
			skipCalls,
			scan: this._scan
		});
		if (typeof out === "string") out = { id: out };
		return out;
	}
	async load(options) {
		await this._container.moduleGraph?.ensureEntryFromUrl(unwrapId(options.id));
		this._updateModuleInfo(options.id, options);
		const loadResult = await this._container.load(options.id);
		const code = typeof loadResult === "object" ? loadResult?.code : loadResult;
		if (code != null) await this._container.transform(code, options.id);
		const moduleInfo = this.getModuleInfo(options.id);
		if (!moduleInfo) throw Error(`Failed to load module with id ${options.id}`);
		return moduleInfo;
	}
	getModuleInfo(id) {
		return this._container.getModuleInfo(id);
	}
	_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.environment.config.root);
	}
	getWatchFiles() {
		return [...this._container.watchFiles];
	}
	emitFile(_assetOrFile) {
		this._warnIncompatibleMethod(`emitFile`);
		return "";
	}
	setAssetSource() {
		this._warnIncompatibleMethod(`setAssetSource`);
	}
	getFileName() {
		this._warnIncompatibleMethod(`getFileName`);
		return "";
	}
	debug(log) {
		const err = this._formatLog(typeof log === "function" ? log() : log);
		super.debug(err);
	}
	info(log) {
		const err = this._formatLog(typeof log === "function" ? log() : log);
		super.info(err);
	}
	warn(log, position) {
		const err = this._formatLog(typeof log === "function" ? log() : log, position);
		super.warn(err);
	}
	error(e, position) {
		throw this._formatLog(e, position);
	}
	_formatLog(e, position) {
		const err = typeof e === "string" ? new Error(e) : e;
		if (err.pluginCode) return err;
		err.plugin = this._plugin.name;
		if (this._activeId && !err.id) err.id = this._activeId;
		if (this._activeCode) {
			err.pluginCode = this._activeCode;
			const pos = position ?? err.pos ?? err.position;
			if (pos != null) {
				let errLocation;
				try {
					errLocation = numberToPos(this._activeCode, pos);
				} catch (err2) {
					this.environment.logger.error(import_picocolors.default.red(`Error in error handler:\n${err2.stack || err2.message}\n`), { error: err2 });
					throw err;
				}
				err.loc = err.loc || {
					file: err.id,
					...errLocation
				};
				err.frame = err.frame || generateCodeFrame(this._activeCode, pos);
			} else if (err.loc) {
				if (!err.frame) {
					let code = this._activeCode;
					if (err.loc.file) {
						err.id = normalizePath(err.loc.file);
						try {
							code = fs.readFileSync(err.loc.file, "utf-8");
						} catch {}
					}
					err.frame = generateCodeFrame(code, err.loc);
				}
			} else if (err.line && err.column) {
				err.loc = {
					file: err.id,
					line: err.line,
					column: err.column
				};
				err.frame = err.frame || generateCodeFrame(this._activeCode, err.loc);
			}
			if (this instanceof TransformPluginContext && typeof err.loc?.line === "number" && typeof err.loc.column === "number") {
				const rawSourceMap = this._getCombinedSourcemap();
				if (rawSourceMap && "version" in rawSourceMap) {
					const { source, line, column } = originalPositionFor$2(new TraceMap(rawSourceMap), {
						line: Number(err.loc.line),
						column: Number(err.loc.column)
					});
					if (source) err.loc = {
						file: source,
						line,
						column
					};
				}
			}
		} else if (err.loc) {
			if (!err.frame) {
				let code = err.pluginCode;
				if (err.loc.file) {
					err.id = normalizePath(err.loc.file);
					if (!code) try {
						code = fs.readFileSync(err.loc.file, "utf-8");
					} catch {}
				}
				if (code) err.frame = generateCodeFrame(`${code}`, err.loc);
			}
		}
		if (typeof err.loc?.column !== "number" && typeof err.loc?.line !== "number" && !err.loc?.file) delete err.loc;
		return err;
	}
	_warnIncompatibleMethod(method) {
		this.environment.logger.warn(import_picocolors.default.cyan(`[plugin:${this._plugin.name}] `) + import_picocolors.default.yellow(`context method ${import_picocolors.default.bold(`${method}()`)} is not supported in serve mode. This plugin is likely not vite-compatible.`));
	}
};
var ResolveIdContext = class extends PluginContext {
	constructor(container, skip, skipCalls, scan) {
		super(null, container);
		this._resolveSkips = skip;
		this._resolveSkipCalls = skipCalls;
		this._scan = scan;
	}
};
var LoadPluginContext = class extends PluginContext {
	_addedImports = null;
	constructor(container) {
		super(null, container);
	}
	addWatchFile(id) {
		if (!this._addedImports) this._addedImports = /* @__PURE__ */ new Set();
		this._addedImports.add(id);
		super.addWatchFile(id);
	}
};
var TransformPluginContext = class extends LoadPluginContext {
	filename;
	originalCode;
	originalSourcemap = null;
	sourcemapChain = [];
	combinedMap = null;
	constructor(container, id, code, inMap) {
		super(container);
		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 map = this._getCombinedSourcemap();
		if (!map || !("version" in map) && map.mappings === "") return new MagicString(this.originalCode).generateMap({
			includeContent: true,
			hires: "boundary",
			source: cleanUrl(this.filename)
		});
		return map;
	}
	_updateActiveInfo(plugin, id, code) {
		this._plugin = plugin;
		this._activeId = id;
		this._activeCode = code;
	}
};
var PluginContainer = class {
	environments;
	constructor(environments) {
		this.environments = environments;
	}
	_getEnvironment(options) {
		return options?.environment ? options.environment : this.environments[options?.ssr ? "ssr" : "client"];
	}
	_getPluginContainer(options) {
		return this._getEnvironment(options).pluginContainer;
	}
	getModuleInfo(id) {
		const clientModuleInfo = this.environments.client.pluginContainer.getModuleInfo(id);
		const ssrModuleInfo = this.environments.ssr.pluginContainer.getModuleInfo(id);
		if (clientModuleInfo == null && ssrModuleInfo == null) return null;
		return new Proxy({}, { get: (_, key) => {
			if (key === "meta") {
				const meta = {};
				if (ssrModuleInfo) Object.assign(meta, ssrModuleInfo.meta);
				if (clientModuleInfo) Object.assign(meta, clientModuleInfo.meta);
				return meta;
			}
			if (clientModuleInfo) {
				if (key in clientModuleInfo) return clientModuleInfo[key];
			}
			if (ssrModuleInfo) {
				if (key in ssrModuleInfo) return ssrModuleInfo[key];
			}
		} });
	}
	get options() {
		return this.environments.client.pluginContainer.options;
	}
	async buildStart(_options) {
		return this.environments.client.pluginContainer.buildStart(_options);
	}
	async watchChange(id, change) {
		return this.environments.client.pluginContainer.watchChange(id, change);
	}
	async resolveId(rawId, importer, options) {
		return this._getPluginContainer(options).resolveId(rawId, importer, options);
	}
	async load(id, options) {
		return this._getPluginContainer(options).load(id);
	}
	async transform(code, id, options) {
		return this._getPluginContainer(options).transform(code, id, options);
	}
	async close() {}
};
/**
* server.pluginContainer compatibility
*
* The default environment is in buildStart, buildEnd, watchChange, and closeBundle hooks,
* which are called once for all environments, or when no environment is passed in other hooks.
* The ssrEnvironment is needed for backward compatibility when the ssr flag is passed without
* an environment. The defaultEnvironment in the main pluginContainer in the server should be
* the client environment for backward compatibility.
**/
function createPluginContainer(environments) {
	return new PluginContainer(environments);
}
//#endregion
//#region src/node/optimizer/scan.ts
var ScanEnvironment = class extends BaseEnvironment {
	mode = "scan";
	get pluginContainer() {
		if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
		return this._pluginContainer;
	}
	/**
	* @internal
	*/
	_pluginContainer;
	async init() {
		if (this._initiated) return;
		this._initiated = true;
		this._pluginContainer = await createEnvironmentPluginContainer(this, this.plugins, void 0, false);
	}
};
function devToScanEnvironment(environment) {
	return {
		mode: "scan",
		get name() {
			return environment.name;
		},
		getTopLevelConfig() {
			return environment.getTopLevelConfig();
		},
		get config() {
			return environment.config;
		},
		get logger() {
			return environment.logger;
		},
		get pluginContainer() {
			return environment.pluginContainer;
		},
		get plugins() {
			return environment.plugins;
		}
	};
}
const debug$5 = createDebugger("vite:deps");
const htmlTypesRE = /\.(?:html|vue|svelte|astro|imba)$/;
const importsRE = /(?<!\/\/.*)(?<=^|;|\*\/)\s*import(?!\s+type)(?:[\w*{}\n\r\t, ]+from)?\s*("[^"]+"|'[^']+')\s*(?=$|;|\/\/|\/\*)/gm;
function scanImports(environment) {
	const start = performance$1.now();
	const { config } = environment;
	const scanContext = { cancelled: false };
	async function cancel() {
		scanContext.cancelled = true;
	}
	async function scan() {
		const entries = await computeEntries(environment);
		if (!entries.length) {
			if (!config.optimizeDeps.entries && !config.optimizeDeps.include) environment.logger.warn(import_picocolors.default.yellow("(!) Could not auto-determine entry point from rolldownOptions or html files and there are no explicit optimizeDeps.include patterns. Skipping dependency pre-bundling."));
			return;
		}
		if (scanContext.cancelled) return;
		debug$5?.(`Crawling dependencies using entries: ${entries.map((entry) => `\n  ${import_picocolors.default.dim(entry)}`).join("")}`);
		const deps = {};
		const missing = {};
		const context = await prepareRolldownScanner(environment, entries, deps, missing);
		if (scanContext.cancelled) return;
		try {
			await context.build();
			return {
				deps: orderedDependencies(deps),
				missing
			};
		} catch (e) {
			if (e.errors?.some((error) => error.pluginCode === "ERR_CLOSED_SERVER")) return;
			e.message = import_picocolors.default.red(`\
  Failed to scan for dependencies from entries:
  ${entries.join("\n")}

  `) + e.message;
			throw e;
		} finally {
			if (debug$5) debug$5(`Scan completed in ${(performance$1.now() - start).toFixed(2)}ms: ${Object.keys(orderedDependencies(deps)).sort().map((id) => `\n  ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(deps[id])}`).join("") || import_picocolors.default.dim("no dependencies found")}`);
		}
	}
	return {
		cancel,
		result: scan().then((res) => res ?? {
			deps: {},
			missing: {}
		})
	};
}
async function computeEntries(environment) {
	let entries = [];
	const explicitEntryPatterns = environment.config.optimizeDeps.entries;
	const buildInput = environment.config.build.rolldownOptions.input;
	if (explicitEntryPatterns) entries = await globEntries(explicitEntryPatterns, environment);
	else if (buildInput) {
		const resolvePath = async (p) => {
			const id = (await environment.pluginContainer.resolveId(p, void 0, {
				isEntry: true,
				scan: true
			}))?.id;
			if (id === void 0) throw new Error(`failed to resolve rolldownOptions.input value: ${JSON.stringify(p)}.`);
			return id;
		};
		if (typeof buildInput === "string") entries = [await resolvePath(buildInput)];
		else if (Array.isArray(buildInput)) entries = await Promise.all(buildInput.map(resolvePath));
		else if (isObject$1(buildInput)) entries = await Promise.all(Object.values(buildInput).map(resolvePath));
		else throw new Error("invalid rolldownOptions.input value.");
	} else entries = await globEntries("**/*.html", environment);
	entries = entries.filter((entry) => isScannable(entry, environment.config.optimizeDeps.extensions) && fs.existsSync(entry));
	return entries;
}
async function prepareRolldownScanner(environment, entries, deps, missing) {
	const { plugins: pluginsFromConfig = [], ...rolldownOptions } = environment.config.optimizeDeps.rolldownOptions ?? {};
	const transformOptions = deepClone(rolldownOptions.transform) ?? {};
	if (transformOptions.jsx === void 0) transformOptions.jsx = {};
	else if (transformOptions.jsx === "react" || transformOptions.jsx === "react-jsx") transformOptions.jsx = getRollupJsxPresets(transformOptions.jsx);
	if (typeof transformOptions.jsx === "object") transformOptions.jsx.development ??= !environment.config.isProduction;
	const transformSyncJsxOptions = transformOptions.jsx === false ? void 0 : transformOptions.jsx;
	const plugins = await asyncFlatten(arraify(pluginsFromConfig));
	plugins.push(...rolldownScanPlugin(environment, deps, missing, entries, transformSyncJsxOptions));
	async function build() {
		await scan({
			...rolldownOptions,
			transform: transformOptions,
			input: entries,
			logLevel: "silent",
			plugins
		});
	}
	return { build };
}
function orderedDependencies(deps) {
	const depsList = Object.entries(deps);
	depsList.sort((a, b) => a[0].localeCompare(b[0]));
	return Object.fromEntries(depsList);
}
async function globEntries(patterns, environment) {
	const nodeModulesPatterns = [];
	const regularPatterns = [];
	for (const pattern of arraify(patterns)) if (pattern.includes("node_modules")) nodeModulesPatterns.push(pattern);
	else regularPatterns.push(pattern);
	const sharedOptions = {
		absolute: true,
		cwd: environment.config.root,
		ignore: [`**/${environment.config.build.outDir}/**`, ...environment.config.optimizeDeps.entries ? [] : [`**/__tests__/**`, `**/coverage/**`]]
	};
	return (await Promise.all([glob(nodeModulesPatterns, sharedOptions), glob(regularPatterns, {
		...sharedOptions,
		ignore: [...sharedOptions.ignore, "**/node_modules/**"]
	})])).flat();
}
const scriptRE = /(<script(?:\s+[a-z_:][-\w:]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^"'<>=\s]+))?)*\s*>)(.*?)<\/script>/gis;
const commentRE = /<!--.*?-->/gs;
const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
const typeRE = /\btype\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
const svelteScriptModuleRE = /\bcontext\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/i;
const svelteModuleRE = /\smodule\b/i;
function rolldownScanPlugin(environment, depImports, missing, entries, jsxOptions) {
	const seen = /* @__PURE__ */ new Map();
	async function resolveId(id, importer, options) {
		return environment.pluginContainer.resolveId(id, importer && normalizePath(importer), {
			scan: true,
			...options
		});
	}
	const resolve = async (id, importer, options) => {
		const key = JSON.stringify([
			id,
			importer && path.dirname(importer),
			options
		]);
		if (seen.has(key)) return seen.get(key);
		const res = (await resolveId(id, importer, options))?.id;
		seen.set(key, res);
		return res;
	};
	const optimizeDepsOptions = environment.config.optimizeDeps;
	const include = optimizeDepsOptions.include;
	const exclude = [
		...optimizeDepsOptions.exclude ?? [],
		"@vite/client",
		"@vite/env"
	];
	const externalUnlessEntry = ({ path }) => ({
		id: path,
		external: !entries.includes(path)
	});
	const doTransformGlobImport = async (contents, id, loader) => {
		let transpiledContents;
		if (loader !== "js") {
			const result = transformSync(id, contents, {
				...jsxOptions !== void 0 ? { jsx: jsxOptions } : {},
				lang: loader,
				tsconfig: false
			});
			if (result.errors.length > 0) throw new AggregateError(result.errors, "oxc transform error");
			transpiledContents = result.code;
		} else transpiledContents = contents;
		return (await transformGlobImport(transpiledContents, id, environment.config.root, resolve))?.s.toString() || transpiledContents;
	};
	const scripts = {};
	const htmlTypeOnLoadCallback = async (id) => {
		let raw = await fsp.readFile(id, "utf-8");
		raw = raw.replace(commentRE, "<!---->");
		const isHtml = id.endsWith(".html");
		let js = "";
		let scriptId = 0;
		const matches = raw.matchAll(scriptRE);
		for (const [, openTag, content] of matches) {
			const typeMatch = typeRE.exec(openTag);
			const type = typeMatch && (typeMatch[1] || typeMatch[2] || typeMatch[3]);
			const langMatch = langRE.exec(openTag);
			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 (id.endsWith(".astro")) loader = "ts";
			const srcMatch = srcRE.exec(openTag);
			if (srcMatch) js += `import ${JSON.stringify(srcMatch[1] || srcMatch[2] || srcMatch[3])}\n`;
			else if (content.trim()) {
				const contents = content + (loader.startsWith("ts") ? extractImportPaths(content) : "");
				const key = `${id}?id=${scriptId++}`;
				if (contents.includes("import.meta.glob")) scripts[key] = {
					loader: "js",
					contents: await doTransformGlobImport(contents, id, loader)
				};
				else scripts[key] = {
					loader,
					contents
				};
				const virtualModulePath = JSON.stringify(virtualModulePrefix + key);
				let addedImport = false;
				if (id.endsWith(".svelte")) {
					let isModule = svelteModuleRE.test(openTag);
					if (!isModule) {
						const contextMatch = svelteScriptModuleRE.exec(openTag);
						isModule = (contextMatch && (contextMatch[1] || contextMatch[2] || contextMatch[3])) === "module";
					}
					if (!isModule) {
						addedImport = true;
						js += `import ${virtualModulePath}\n`;
					}
				}
				if (!addedImport) js += `export * from ${virtualModulePath}\n`;
			}
		}
		if (!id.endsWith(".vue") || !js.includes("export default")) js += "\nexport default {}";
		return js;
	};
	const ASSET_TYPE_RE = new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
	return [
		{
			name: "vite:dep-scan:resolve-external-url",
			resolveId: {
				filter: { id: externalRE },
				handler: (id) => ({
					id,
					external: true
				})
			}
		},
		{
			name: "vite:dep-scan:resolve-data-url",
			resolveId: {
				filter: { id: dataUrlRE },
				handler: (id) => ({
					id,
					external: true
				})
			}
		},
		{
			name: "vite:dep-scan:local-scripts",
			resolveId: {
				filter: { id: virtualModuleRE },
				handler: (id) => ({ id })
			},
			load: {
				filter: { id: virtualModuleRE },
				handler(id) {
					const script = scripts[id.replace(virtualModulePrefix, "")];
					return {
						code: script.contents,
						moduleType: script.loader
					};
				}
			}
		},
		{
			name: "vite:dep-scan:resolve",
			async resolveId(id, importer) {
				importer = importer && virtualModuleRE.test(importer) ? importer.replace(virtualModulePrefix, "") : importer;
				if (htmlTypesRE.test(id)) {
					const resolved = await resolve(id, importer);
					if (!resolved) return;
					if (isInNodeModules(resolved) && isOptimizable(resolved, optimizeDepsOptions)) return;
					if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
					return resolved;
				}
				if (/^[\w@][^:]/.test(id)) {
					if (moduleListContains(exclude, id)) return externalUnlessEntry({ path: id });
					if (depImports[id]) return externalUnlessEntry({ path: id });
					const resolved = await resolve(id, importer);
					if (resolved) {
						if (shouldExternalizeDep(resolved, id)) return externalUnlessEntry({ path: id });
						if (isInNodeModules(resolved) || include?.includes(id)) {
							if (isOptimizable(resolved, optimizeDepsOptions)) depImports[id] = resolved;
							return externalUnlessEntry({ path: id });
						} else if (isScannable(resolved, optimizeDepsOptions.extensions)) return path.resolve(resolved);
						else return externalUnlessEntry({ path: id });
					} else missing[id] = normalizePath(importer);
				}
				if (CSS_LANGS_RE.test(id)) return externalUnlessEntry({ path: id });
				if (/\.(?:json|json5|wasm)$/.test(id)) return externalUnlessEntry({ path: id });
				if (ASSET_TYPE_RE.test(id)) return externalUnlessEntry({ path: id });
				if (SPECIAL_QUERY_RE.test(id)) return {
					id,
					external: true
				};
				const resolved = await resolve(id, importer);
				if (resolved) {
					if (shouldExternalizeDep(resolved, id) || !isScannable(resolved, optimizeDepsOptions.extensions)) return externalUnlessEntry({ path: id });
					return path.resolve(cleanUrl(resolved));
				}
				return externalUnlessEntry({ path: id });
			}
		},
		{
			name: "vite:dep-scan:load:html",
			load: {
				filter: { id: htmlTypesRE },
				async handler(id) {
					return {
						code: await htmlTypeOnLoadCallback(id),
						moduleType: "js"
					};
				}
			}
		},
		...environment.config.esbuild && environment.config.esbuild.jsxInject ? [{
			name: "vite:dep-scan:transform:jsx-inject",
			transform: {
				filter: { id: /\.[jt]sx$/ },
				handler(code) {
					const esbuildConfig = environment.config.esbuild;
					if (esbuildConfig && esbuildConfig.jsxInject) code = esbuildConfig.jsxInject + `\n` + code;
					return code;
				}
			}
		}] : [],
		{
			name: "vite:dep-scan:transform:js-glob",
			transform: {
				filter: { code: "import.meta.glob" },
				async handler(code, id) {
					if (JS_TYPES_RE.test(id)) {
						let ext = path.extname(id).slice(1);
						if (ext === "mjs") ext = "js";
						return {
							moduleType: "js",
							code: await doTransformGlobImport(code, id, ext)
						};
					}
				}
			}
		}
	];
}
/**
* when using TS + (Vue + `<script setup>`) or Svelte, imports may seem
* unused to esbuild and dropped in the build output, which prevents
* esbuild from crawling further.
* the solution is to add `import 'x'` for every source to force
* esbuild to keep crawling due to potential side effects.
*/
function extractImportPaths(code) {
	code = code.replace(multilineCommentsRE, "/* */").replace(singlelineCommentsRE, "");
	let js = "";
	let m;
	importsRE.lastIndex = 0;
	while ((m = importsRE.exec(code)) != null) js += `\nimport ${m[1]}`;
	return js;
}
function shouldExternalizeDep(resolvedId, rawId) {
	if (!path.isAbsolute(resolvedId)) return true;
	if (resolvedId === rawId || resolvedId.includes("\0")) return true;
	return false;
}
function isScannable(id, extensions) {
	return JS_TYPES_RE.test(id) || htmlTypesRE.test(id) || extensions?.includes(path.extname(id)) || false;
}
//#endregion
//#region src/node/optimizer/resolve.ts
function createOptimizeDepsIncludeResolver(environment) {
	const topLevelConfig = environment.getTopLevelConfig();
	const resolve = createBackCompatIdResolver(topLevelConfig, {
		asSrc: false,
		scan: true,
		packageCache: /* @__PURE__ */ new Map()
	});
	return async (id) => {
		const lastArrowIndex = id.lastIndexOf(">");
		if (lastArrowIndex === -1) return await resolve(environment, id, void 0);
		const nestedRoot = id.substring(0, lastArrowIndex).trim();
		const nestedPath = id.substring(lastArrowIndex + 1).trim();
		const basedir = nestedResolveBasedir(nestedRoot, topLevelConfig.root, topLevelConfig.resolve.preserveSymlinks);
		return await resolve(environment, nestedPath, path.resolve(basedir, "package.json"));
	};
}
/**
* Expand the glob syntax in `optimizeDeps.include` to proper import paths
*/
function expandGlobIds(id, config) {
	const pkgName = getNpmPackageName(id);
	if (!pkgName) return [];
	const pkgData = resolvePackageData(pkgName, config.root, config.resolve.preserveSymlinks, config.packageCache);
	if (!pkgData) return [];
	const pattern = "." + id.slice(pkgName.length);
	const exports = pkgData.data.exports;
	if (exports) {
		if (typeof exports === "string" || Array.isArray(exports)) return [pkgName];
		const possibleExportPaths = [];
		for (const key in exports) if (key[0] === ".") if (key.includes("*")) {
			const exportsValue = getFirstExportStringValue(exports[key]);
			if (!exportsValue) continue;
			const exportValuePattern = exportsValue.replace(/\*/g, "**/*");
			const exportsValueGlobRe = new RegExp(exportsValue.split("*").map(escapeRegex).join("(.*)"));
			possibleExportPaths.push(...globSync(exportValuePattern, {
				cwd: pkgData.dir,
				expandDirectories: false,
				ignore: ["node_modules"]
			}).map((filePath) => {
				if (exportsValue.startsWith("./")) filePath = "./" + filePath;
				const matched = exportsValueGlobRe.exec(slash(filePath));
				if (matched) {
					let allGlobSame = matched.length === 2;
					if (!allGlobSame) {
						allGlobSame = true;
						for (let i = 2; i < matched.length; i++) if (matched[i] !== matched[i - 1]) {
							allGlobSame = false;
							break;
						}
					}
					if (allGlobSame) return key.replace("*", matched[1]).slice(2);
				}
				return "";
			}).filter(Boolean));
		} else {
			if (exports[key] == null) continue;
			possibleExportPaths.push(key.slice(2));
		}
		const isMatch = pm(pattern);
		const matched = possibleExportPaths.filter((p) => isMatch(p)).map((match) => path.posix.join(pkgName, match));
		matched.unshift(pkgName);
		return matched;
	} else {
		const matched = globSync(pattern, {
			cwd: pkgData.dir,
			expandDirectories: false,
			ignore: ["node_modules"]
		}).map((match) => path.posix.join(pkgName, slash(match)));
		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]);
}
/**
* Continuously resolve the basedir of packages separated by '>'
*/
function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
	const pkgs = id.split(">").map((pkg) => pkg.trim());
	for (const pkg of pkgs) basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir;
	return basedir;
}
//#endregion
//#region src/node/optimizer/rolldownDepPlugin.ts
const externalWithConversionNamespace = "vite:dep-pre-bundle:external-conversion";
const convertedExternalPrefix = "vite-dep-pre-bundle-external:";
const cjsExternalFacadeNamespace = "vite:cjs-external-facade";
const nonFacadePrefix = "vite-cjs-external-facade:";
const externalTypes = [
	"css",
	"less",
	"sass",
	"scss",
	"styl",
	"stylus",
	"pcss",
	"postcss",
	"wasm",
	"vue",
	"svelte",
	"marko",
	"astro",
	"imba",
	"jsx",
	"tsx",
	...KNOWN_ASSET_TYPES
];
const optionalPeerDepNamespace = "optional-peer-dep:";
const browserExternalNamespace = "browser-external:";
function rolldownDepPlugin(environment, qualified, external) {
	const { isProduction } = environment.config;
	const { extensions } = environment.config.optimizeDeps;
	const allExternalTypes = extensions ? externalTypes.filter((type) => !extensions.includes("." + type)) : externalTypes;
	const esmPackageCache = /* @__PURE__ */ new Map();
	const cjsPackageCache = /* @__PURE__ */ new Map();
	const resolveAssets = (resolved, kind) => {
		if (kind === "require-call") return { id: externalWithConversionNamespace + resolved };
		return {
			id: resolved,
			external: "absolute"
		};
	};
	const _resolve = createBackCompatIdResolver(environment.getTopLevelConfig(), {
		asSrc: false,
		scan: true,
		packageCache: esmPackageCache
	});
	const _resolveRequire = createBackCompatIdResolver(environment.getTopLevelConfig(), {
		asSrc: false,
		isRequire: true,
		scan: true,
		packageCache: cjsPackageCache
	});
	const resolve = (id, importer, kind) => {
		const _importer = importer && importer in qualified ? qualified[importer] : importer;
		return (kind.startsWith("require") ? _resolveRequire : _resolve)(environment, id, _importer);
	};
	const resolveResult = (id, resolved, kind) => {
		if (resolved.startsWith("__vite-browser-external")) return { id: browserExternalNamespace + id };
		if (resolved.startsWith("__vite-optional-peer-dep")) return { id: optionalPeerDepNamespace + resolved };
		if (allExternalTypesReg.test(resolved)) return resolveAssets(resolved, kind);
		if (isBuiltin(environment.config.resolve.builtins, resolved)) return;
		if (isExternalUrl(resolved)) return {
			id: resolved,
			external: "absolute"
		};
		return { id: path.resolve(resolved) };
	};
	const allExternalTypesReg = new RegExp(`\\.(` + allExternalTypes.join("|") + `)(\\?.*)?$`);
	function resolveEntry(id) {
		const flatId = flattenId(id);
		if (flatId in qualified) return { id: qualified[flatId] };
	}
	const bundleOutputDir = path.join(environment.config.cacheDir, "deps");
	return [{
		name: "vite:dep-pre-bundle-assets",
		resolveId: {
			filter: { id: allExternalTypesReg },
			async handler(id, importer, options) {
				const kind = options.kind;
				if (id.startsWith(convertedExternalPrefix)) return {
					id: id.slice(29),
					external: "absolute"
				};
				const resolved = await resolve(id, importer, kind);
				if (resolved) {
					if (JS_TYPES_RE.test(resolved)) return {
						id: isWindows ? resolved.replaceAll("/", "\\") : resolved,
						external: false
					};
					return resolveAssets(resolved, kind);
				}
			}
		},
		load: {
			filter: { id: prefixRegex(externalWithConversionNamespace) },
			handler(id) {
				const path = id.slice(39);
				const modulePath = `"${convertedExternalPrefix}${path}"`;
				return { code: isCSSRequest(path) && !isModuleCSSRequest(path) ? `import ${modulePath};` : `export { default } from ${modulePath};export * from ${modulePath};` };
			}
		}
	}, {
		name: "vite:dep-pre-bundle",
		buildEnd() {
			esmPackageCache.clear();
			cjsPackageCache.clear();
		},
		resolveId: {
			filter: { id: /^[\w@][^:]/ },
			async handler(id, importer, options) {
				const kind = options.kind;
				if (moduleListContains(external, id)) return {
					id,
					external: "absolute"
				};
				let entry;
				if (!importer) {
					if (entry = resolveEntry(id)) return entry;
					const aliased = await _resolve(environment, id, void 0, true);
					if (aliased && (entry = resolveEntry(aliased))) return entry;
				}
				const resolved = await resolve(id, importer, kind);
				if (resolved) return resolveResult(id, resolved, kind);
			}
		},
		load: {
			filter: { id: [prefixRegex(browserExternalNamespace), prefixRegex(optionalPeerDepNamespace)] },
			handler(id) {
				if (id.startsWith(browserExternalNamespace)) {
					const path = id.slice(17);
					if (isProduction) return { code: "module.exports = {}" };
					else return { code: `\
    module.exports = Object.create(new Proxy({}, {
        get(_, key) {
        if (
            key !== '__esModule' &&
            key !== '__proto__' &&
            key !== 'constructor' &&
            key !== 'splice'
        ) {
            console.warn(\`Module "${path}" has been externalized for browser compatibility. Cannot access "${path}.\${key}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.\`)
        }
        }
    }))` };
				}
				if (id.startsWith(optionalPeerDepNamespace)) {
					const [, peerDep, parentDep] = id.slice(18).split(":");
					return { code: `module.exports = {};throw new Error(\`Could not resolve "${peerDep}" imported by "${parentDep}". Is it installed?\`)` };
				}
			}
		},
		transform: {
			filter: { code: assetImportMetaUrlRE },
			handler(code, id) {
				let s;
				const re = new RegExp(assetImportMetaUrlRE);
				const cleanString = stripLiteral(code);
				let match;
				while (match = re.exec(cleanString)) {
					const [[startIndex, endIndex], [urlStart, urlEnd]] = match.indices;
					if (hasViteIgnoreRE.test(code.slice(startIndex, urlStart))) continue;
					const rawUrl = code.slice(urlStart, urlEnd);
					if (rawUrl[0] === "`" && rawUrl.includes("${")) continue;
					const url = rawUrl.slice(1, -1);
					if (isDataUrl(url) || isExternalUrl(url) || url.startsWith("/")) continue;
					if (!s) s = new MagicString(code);
					const absolutePath = path.resolve(path.dirname(id), url);
					const normalizedRelativePath = normalizePath(path.relative(bundleOutputDir, absolutePath));
					s.update(startIndex, endIndex, `new URL('' + ${JSON.stringify(normalizedRelativePath)}, import.meta.url)`);
				}
				if (s) return {
					code: s.toString(),
					map: s.generateMap({ hires: "boundary" })
				};
			}
		}
	}];
}
const matchesEntireLine = (text) => `^${escapeRegex(text)}$`;
function rolldownCjsExternalPlugin(externals, platform) {
	if (platform === "node") return;
	if (platform === "neutral") return;
	const filter = new RegExp(externals.map(matchesEntireLine).join("|"));
	return {
		name: "cjs-external",
		resolveId: {
			filter: { id: [prefixRegex(nonFacadePrefix), filter] },
			handler(id, _importer, options) {
				if (id.startsWith(nonFacadePrefix)) return {
					id: id.slice(25),
					external: "absolute"
				};
				if (options.kind === "require-call") return { id: cjsExternalFacadeNamespace + id };
				return {
					id,
					external: "absolute"
				};
			}
		},
		load: {
			filter: { id: prefixRegex(cjsExternalFacadeNamespace) },
			handler(id) {
				const idWithoutNamespace = id.slice(24);
				return { code: `\
import * as m from ${JSON.stringify(nonFacadePrefix + idWithoutNamespace)};
module.exports = ${isNodeBuiltin(idWithoutNamespace) ? "m.default" : "{ ...m }"};
` };
			}
		}
	};
}
//#endregion
//#region src/node/optimizer/index.ts
var optimizer_exports = /* @__PURE__ */ __exportAll({
	addManuallyIncludedOptimizeDeps: () => addManuallyIncludedOptimizeDeps,
	addOptimizedDepInfo: () => addOptimizedDepInfo,
	cleanupDepsCacheStaleDirs: () => cleanupDepsCacheStaleDirs,
	createIsOptimizedDepFile: () => createIsOptimizedDepFile,
	createIsOptimizedDepUrl: () => createIsOptimizedDepUrl,
	depsFromOptimizedDepInfo: () => depsFromOptimizedDepInfo,
	depsLogString: () => depsLogString,
	discoverProjectDependencies: () => discoverProjectDependencies,
	extractExportsData: () => extractExportsData,
	getDepsCacheDir: () => getDepsCacheDir,
	getOptimizedDepPath: () => getOptimizedDepPath,
	initDepsOptimizerMetadata: () => initDepsOptimizerMetadata,
	isDepOptimizationDisabled: () => isDepOptimizationDisabled,
	loadCachedDepOptimizationMetadata: () => loadCachedDepOptimizationMetadata,
	optimizeDeps: () => optimizeDeps,
	optimizeExplicitEnvironmentDeps: () => optimizeExplicitEnvironmentDeps,
	optimizedDepInfoFromFile: () => optimizedDepInfoFromFile,
	optimizedDepInfoFromId: () => optimizedDepInfoFromId,
	optimizedDepNeedsInterop: () => optimizedDepNeedsInterop,
	runOptimizeDeps: () => runOptimizeDeps,
	toDiscoveredDependencies: () => toDiscoveredDependencies
});
const debug$4 = createDebugger("vite:deps");
const jsExtensionRE = /\.js$/i;
function isDepOptimizationDisabled(optimizeDeps) {
	return optimizeDeps.disabled === true || optimizeDeps.disabled === "dev" || !!optimizeDeps.noDiscovery && !optimizeDeps.include?.length;
}
/**
* Scan and optimize dependencies within a project.
* Used by Vite CLI when running `vite optimize`.
*
* @deprecated the optimization process runs automatically and does not need to be called
*/
async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
	const log = asCommand ? config.logger.info : debug$4;
	config.logger.warn(import_picocolors.default.yellow("manually calling optimizeDeps is deprecated. This is done automatically and does not need to be called manually."));
	const environment = new ScanEnvironment("client", config);
	await environment.init();
	const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, force, asCommand);
	if (cachedMetadata) return cachedMetadata;
	const deps = await discoverProjectDependencies(environment).result;
	await addManuallyIncludedOptimizeDeps(environment, deps);
	const depsString = depsLogString(Object.keys(deps));
	log?.(import_picocolors.default.green(`Optimizing dependencies:\n  ${depsString}`));
	const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
	await result.commit();
	return result.metadata;
}
async function optimizeExplicitEnvironmentDeps(environment) {
	const cachedMetadata = await loadCachedDepOptimizationMetadata(environment, environment.config.optimizeDeps.force ?? false, false);
	if (cachedMetadata) return cachedMetadata;
	const deps = {};
	await addManuallyIncludedOptimizeDeps(environment, deps);
	const result = await runOptimizeDeps(environment, toDiscoveredDependencies(environment, deps)).result;
	await result.commit();
	return result.metadata;
}
function initDepsOptimizerMetadata(environment, timestamp) {
	const { lockfileHash, configHash, hash } = getDepHash(environment);
	return {
		hash,
		lockfileHash,
		configHash,
		browserHash: getOptimizedBrowserHash(hash, {}, timestamp),
		optimized: {},
		chunks: {},
		discovered: {},
		depInfoList: []
	};
}
function addOptimizedDepInfo(metadata, type, depInfo) {
	metadata[type][depInfo.id] = depInfo;
	metadata.depInfoList.push(depInfo);
	return depInfo;
}
let firstLoadCachedDepOptimizationMetadata = true;
/**
* Creates the initial dep optimization metadata, loading it from the deps cache
* if it exists and pre-bundling isn't forced
*/
async function loadCachedDepOptimizationMetadata(environment, force = environment.config.optimizeDeps.force ?? false, asCommand = false) {
	const log = asCommand ? environment.logger.info : debug$4;
	if (firstLoadCachedDepOptimizationMetadata) {
		firstLoadCachedDepOptimizationMetadata = false;
		setTimeout(() => cleanupDepsCacheStaleDirs(environment.getTopLevelConfig()), 0).unref();
	}
	const depsCacheDir = getDepsCacheDir(environment);
	ignoreInput(depsCacheDir);
	ignoreOutput(depsCacheDir);
	if (!force) {
		let cachedMetadata;
		try {
			const cachedMetadataPath = path.join(depsCacheDir, METADATA_FILENAME);
			cachedMetadata = parseDepsOptimizerMetadata(await fsp.readFile(cachedMetadataPath, "utf-8"), depsCacheDir);
		} catch {}
		if (cachedMetadata) if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) environment.logger.info("Re-optimizing dependencies because lockfile has changed", { timestamp: true });
		else if (cachedMetadata.configHash !== getConfigHash(environment)) environment.logger.info("Re-optimizing dependencies because vite config has changed", { timestamp: true });
		else {
			log?.(`(${environment.name}) Hash is consistent. Skipping. Use --force to override.`);
			return cachedMetadata;
		}
	} else environment.logger.info("Forced re-optimization of dependencies", { timestamp: true });
	debug$4?.(`(${environment.name}) ${import_picocolors.default.green(`removing old cache dir ${depsCacheDir}`)}`);
	await fsp.rm(depsCacheDir, {
		recursive: true,
		force: true
	});
}
/**
* Initial optimizeDeps at server start. Perform a fast scan using esbuild to
* find deps to pre-bundle and include user hard-coded dependencies
*/
function discoverProjectDependencies(environment) {
	const { cancel, result } = scanImports(environment);
	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:\n\n  ${missingIds.map((id) => `${import_picocolors.default.cyan(id)} ${import_picocolors.default.white(import_picocolors.default.dim(`(imported by ${missing[id]})`))}`).join(`\n  `)}\n\nAre they installed?`);
			return deps;
		})
	};
}
function toDiscoveredDependencies(environment, deps, timestamp) {
	const browserHash = getOptimizedBrowserHash(getDepHash(environment).hash, deps, timestamp);
	const discovered = {};
	for (const id in deps) {
		const src = deps[id];
		discovered[id] = {
			id,
			file: getOptimizedDepPath(environment, id),
			src,
			browserHash,
			exportsData: extractExportsData(environment, src)
		};
	}
	return discovered;
}
function depsLogString(qualifiedIds) {
	return import_picocolors.default.yellow(qualifiedIds.join(`, `));
}
/**
* Internally, Vite uses this function to prepare a optimizeDeps run. When Vite starts, we can get
* the metadata and start the server without waiting for the optimizeDeps processing to be completed
*/
function runOptimizeDeps(environment, depsInfo) {
	const optimizerContext = { cancelled: false };
	const depsCacheDir = getDepsCacheDir(environment);
	const processingCacheDir = getProcessingDepsCacheDir(environment);
	fs.mkdirSync(processingCacheDir, { recursive: true });
	debug$4?.(import_picocolors.default.green(`creating package.json in ${processingCacheDir}`));
	fs.writeFileSync(path.resolve(processingCacheDir, "package.json"), `{\n  "type": "module"\n}\n`);
	const metadata = initDepsOptimizerMetadata(environment);
	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$4?.(import_picocolors.default.green(`removing cache dir ${processingCacheDir}`));
			try {
				fs.rmSync(processingCacheDir, {
					recursive: true,
					force: true
				});
			} catch {}
		}
	};
	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 = path.join(processingCacheDir, METADATA_FILENAME);
			debug$4?.(import_picocolors.default.green(`creating ${METADATA_FILENAME} in ${processingCacheDir}`));
			fs.writeFileSync(dataPath, stringifyDepsOptimizerMetadata(metadata, depsCacheDir));
			const temporaryPath = depsCacheDir + getTempSuffix();
			const depsCacheDirPresent = fs.existsSync(depsCacheDir);
			if (isWindows) {
				if (depsCacheDirPresent) {
					debug$4?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
					await safeRename(depsCacheDir, temporaryPath);
				}
				debug$4?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
				await safeRename(processingCacheDir, depsCacheDir);
			} else {
				if (depsCacheDirPresent) {
					debug$4?.(import_picocolors.default.green(`renaming ${depsCacheDir} to ${temporaryPath}`));
					fs.renameSync(depsCacheDir, temporaryPath);
				}
				debug$4?.(import_picocolors.default.green(`renaming ${processingCacheDir} to ${depsCacheDir}`));
				fs.renameSync(processingCacheDir, depsCacheDir);
			}
			if (depsCacheDirPresent) {
				debug$4?.(import_picocolors.default.green(`removing cache temp dir ${temporaryPath}`));
				fsp.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 = performance$1.now();
	const bundleTimer = setTimeout(() => {
		environment.logger.info("[optimizer] bundling dependencies...", { timestamp: true });
	}, 1e3);
	const preparedRun = prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext);
	const runResult = preparedRun.then(({ context, idToExports }) => {
		if (!context || optimizerContext.cancelled) {
			clearTimeout(bundleTimer);
			return cancelledResult;
		}
		return context.build().then((result) => {
			const depForEntryFileName = {};
			for (const dep of Object.values(depsInfo)) {
				const entryFileName = flattenId(dep.id) + ".js";
				depForEntryFileName[entryFileName] = dep;
			}
			for (const chunk of result.output) {
				if (chunk.type !== "chunk") continue;
				if (chunk.isEntry) {
					const { exportsData, file, id, ...info } = depForEntryFileName[chunk.fileName];
					addOptimizedDepInfo(metadata, "optimized", {
						id,
						file,
						...info,
						fileHash: getHash(metadata.hash + file + JSON.stringify(chunk.imports)),
						browserHash: metadata.browserHash,
						needsInterop: needsInterop(environment, id, idToExports[id], chunk)
					});
				} else {
					const id = chunk.fileName.replace(jsExtensionRE, "");
					const file = normalizePath(path.resolve(getDepsCacheDir(environment), chunk.fileName));
					if (!findOptimizedDepInfoInRecord(metadata.optimized, (depInfo) => depInfo.file === file)) addOptimizedDepInfo(metadata, "chunks", {
						id,
						file,
						needsInterop: false,
						browserHash: metadata.browserHash,
						isDynamicEntry: chunk.isDynamicEntry
					});
				}
			}
			clearTimeout(bundleTimer);
			debug$4?.(`Dependencies bundled in ${(performance$1.now() - start).toFixed(2)}ms`);
			return successfulResult;
		}).catch((e) => {
			clearTimeout(bundleTimer);
			if (e.errors && e.message.includes("The build was canceled")) return cancelledResult;
			e.message = import_picocolors.default.red("Error during dependency optimization:\n\n") + e.message;
			throw e;
		});
	});
	runResult.catch(() => {
		cleanUp();
	});
	return {
		async cancel() {
			optimizerContext.cancelled = true;
			const { context } = await preparedRun;
			context?.cancel();
			cleanUp();
		},
		result: runResult
	};
}
async function prepareRolldownOptimizerRun(environment, depsInfo, processingCacheDir, optimizerContext) {
	const flatIdDeps = {};
	const idToExports = {};
	const { optimizeDeps } = environment.config;
	const { plugins: pluginsFromConfig = [], ...rolldownOptions } = optimizeDeps.rolldownOptions ?? {};
	let jsxLoader = false;
	await Promise.all(Object.keys(depsInfo).map(async (id) => {
		const src = depsInfo[id].src;
		const exportsData = await (depsInfo[id].exportsData ?? extractExportsData(environment, src));
		if (exportsData.jsxLoader) jsxLoader = true;
		const flatId = flattenId(id);
		flatIdDeps[flatId] = isWindows ? src.replaceAll("/", "\\") : src;
		idToExports[id] = exportsData;
	}));
	if (optimizerContext.cancelled) return {
		context: void 0,
		idToExports
	};
	const define = {
		"process.env.NODE_ENV": environment.config.keepProcessEnv ? "process.env.NODE_ENV" : JSON.stringify(process.env.NODE_ENV || environment.config.mode),
		...rolldownOptions.transform?.define
	};
	const platform = optimizeDeps.rolldownOptions?.platform ?? (environment.config.consumer === "client" || environment.config.ssr.target === "webworker" ? "browser" : "node");
	const external = [...optimizeDeps.exclude ?? []];
	const plugins = await asyncFlatten(arraify(pluginsFromConfig));
	if (external.length) plugins.push(rolldownCjsExternalPlugin(external, platform));
	plugins.push(...rolldownDepPlugin(environment, flatIdDeps, external));
	let canceled = false;
	async function build() {
		const bundle = await rolldown({
			...rolldownOptions,
			input: flatIdDeps,
			logLevel: "silent",
			plugins,
			platform,
			transform: {
				target: ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET,
				...rolldownOptions.transform,
				define
			},
			resolve: {
				extensions: [
					".tsx",
					".ts",
					".jsx",
					".js",
					".css",
					".json"
				],
				...rolldownOptions.resolve
			},
			moduleTypes: {
				".css": "js",
				...rolldownOptions.moduleTypes,
				...jsxLoader ? { ".js": "jsx" } : {}
			}
		});
		if (canceled) {
			await bundle.close();
			throw new Error("The build was canceled");
		}
		try {
			return await bundle.write({
				...rolldownOptions.output,
				format: "esm",
				sourcemap: "hidden",
				dir: processingCacheDir,
				entryFileNames: "[name].js"
			});
		} finally {
			await bundle.close();
		}
	}
	function cancel() {
		canceled = true;
	}
	return {
		context: {
			build,
			cancel
		},
		idToExports
	};
}
async function addManuallyIncludedOptimizeDeps(environment, deps) {
	const { logger } = environment;
	const { optimizeDeps } = environment.config;
	const optimizeDepsInclude = optimizeDeps.include ?? [];
	if (optimizeDepsInclude.length) {
		const unableToOptimize = (id, msg) => {
			if (optimizeDepsInclude.includes(id)) logger.warn(`${msg}: ${import_picocolors.default.cyan(id)}, present in ${environment.name} 'optimizeDeps.include'`);
		};
		const includes = [...optimizeDepsInclude];
		for (let i = 0; i < includes.length; i++) {
			const id = includes[i];
			if (isDynamicPattern(id)) {
				const globIds = expandGlobIds(id, environment.getTopLevelConfig());
				includes.splice(i, 1, ...globIds);
				i += globIds.length - 1;
			}
		}
		const resolve = createOptimizeDepsIncludeResolver(environment);
		for (const id of includes) {
			const normalizedId = normalizeId(id);
			if (!deps[normalizedId]) {
				const entry = await resolve(id);
				if (entry) if (isOptimizable(entry, optimizeDeps)) deps[normalizedId] = entry;
				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(environment, id) {
	return normalizePath(path.resolve(getDepsCacheDir(environment), flattenId(id) + ".js"));
}
function getDepsCacheSuffix(environment) {
	return environment.name === "client" ? "" : `_${environment.name}`;
}
function getDepsCacheDir(environment) {
	return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment);
}
function getProcessingDepsCacheDir(environment) {
	return getDepsCacheDirPrefix(environment) + getDepsCacheSuffix(environment) + getTempSuffix();
}
function getTempSuffix() {
	return "_temp_" + getHash(`${process.pid}:${Date.now().toString()}:${Math.random().toString(16).slice(2)}`);
}
function getDepsCacheDirPrefix(environment) {
	return normalizePath(path.resolve(environment.config.cacheDir, "deps"));
}
function createIsOptimizedDepFile(environment) {
	const depsCacheDirPrefix = getDepsCacheDirPrefix(environment);
	return (id) => id.startsWith(depsCacheDirPrefix);
}
function createIsOptimizedDepUrl(environment) {
	const { root } = environment.config;
	const depsCacheDir = getDepsCacheDirPrefix(environment);
	const depsCacheDirRelative = normalizePath(path.relative(root, depsCacheDir));
	const depsCacheDirPrefix = depsCacheDirRelative.startsWith("../") ? `/@fs/${removeLeadingSlash(normalizePath(depsCacheDir))}` : `/${depsCacheDirRelative}`;
	return function isOptimizedDepUrl(url) {
		return url.startsWith(depsCacheDirPrefix);
	};
}
function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
	const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
		if (key === "file" || key === "src") return normalizePath(path.resolve(depsCacheDir, value));
		return value;
	});
	if (!chunks || Object.values(optimized).some((depInfo) => !depInfo.fileHash)) return;
	const metadata = {
		hash,
		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;
}
/**
* Stringify metadata for deps cache. Remove processing promises
* and individual dep info browserHash. Once the cache is reload
* the next time the server start we need to use the global
* browserHash to allow long term caching
*/
function stringifyDepsOptimizerMetadata(metadata, depsCacheDir) {
	const { hash, configHash, lockfileHash, browserHash, optimized, chunks } = metadata;
	return JSON.stringify({
		hash,
		configHash,
		lockfileHash,
		browserHash,
		optimized: Object.fromEntries(Object.values(optimized).map(({ id, src, file, fileHash, needsInterop, isDynamicEntry }) => [id, {
			src,
			file,
			fileHash,
			needsInterop,
			isDynamicEntry
		}])),
		chunks: Object.fromEntries(Object.values(chunks).map(({ id, file, isDynamicEntry }) => [id, {
			file,
			isDynamicEntry
		}]))
	}, (key, value) => {
		if (key === "file" || key === "src") return normalizePath(path.relative(depsCacheDir, value));
		return value;
	}, 2);
}
async function extractExportsData(environment, filePath) {
	await init;
	const { optimizeDeps } = environment.config;
	const rolldownOptions = optimizeDeps.rolldownOptions ?? {};
	if (optimizeDeps.extensions?.some((ext) => filePath.endsWith(ext))) {
		const { plugins: pluginsFromConfig = [], ...remainingRolldownOptions } = rolldownOptions;
		const plugins = await asyncFlatten(arraify(pluginsFromConfig));
		plugins.unshift({
			name: "externalize",
			resolveId(id, importer) {
				if (importer !== void 0) return {
					id,
					external: true
				};
			}
		});
		const [, exports, , hasModuleSyntax] = parse$2((await (await rolldown({
			...remainingRolldownOptions,
			plugins,
			input: [filePath],
			moduleTypes: {
				".css": "js",
				...remainingRolldownOptions.moduleTypes
			}
		})).generate({
			...rolldownOptions.output,
			format: "esm",
			sourcemap: false
		})).output[0].code);
		return {
			hasModuleSyntax,
			exports: exports.map((e) => e.n)
		};
	}
	let parseResult;
	let usedJsxLoader = false;
	const entryContent = fs.readFileSync(filePath, "utf-8");
	try {
		parseResult = parse$2(entryContent);
	} catch {
		const lang = rolldownOptions.moduleTypes?.[path.extname(filePath)] || "jsx";
		debug$4?.(`Unable to parse: ${filePath}.\n Trying again with a ${lang} transform.`);
		if (lang !== "jsx" && lang !== "tsx" && lang !== "ts") throw new Error(`Unable to parse: ${filePath}.`);
		parseResult = parse$2((await transformWithOxc(entryContent, filePath, { lang }, void 0, environment.config)).code);
		usedJsxLoader = true;
	}
	const [, exports, , hasModuleSyntax] = parseResult;
	return {
		hasModuleSyntax,
		exports: exports.map((e) => e.n),
		jsxLoader: usedJsxLoader
	};
}
function needsInterop(environment, id, exportsData, output) {
	if (environment.config.optimizeDeps.needsInterop?.includes(id)) return true;
	const { hasModuleSyntax, exports } = exportsData;
	if (!hasModuleSyntax) return true;
	if (output) {
		const generatedExports = output.exports;
		if (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports)) return true;
	}
	return false;
}
function isSingleDefaultExport(exports) {
	return exports.length === 1 && exports[0] === "default";
}
const lockfileFormats = [
	{
		path: "node_modules/.package-lock.json",
		checkPatchesDir: "patches",
		manager: "npm"
	},
	{
		path: "node_modules/.yarn-state.yml",
		checkPatchesDir: false,
		manager: "yarn"
	},
	{
		path: ".pnp.cjs",
		checkPatchesDir: ".yarn/patches",
		manager: "yarn"
	},
	{
		path: ".pnp.js",
		checkPatchesDir: ".yarn/patches",
		manager: "yarn"
	},
	{
		path: "node_modules/.yarn-integrity",
		checkPatchesDir: "patches",
		manager: "yarn"
	},
	{
		path: "node_modules/.pnpm/lock.yaml",
		checkPatchesDir: false,
		manager: "pnpm"
	},
	{
		path: ".rush/temp/shrinkwrap-deps.json",
		checkPatchesDir: false,
		manager: "pnpm"
	},
	{
		path: "bun.lock",
		checkPatchesDir: "patches",
		manager: "bun"
	},
	{
		path: "bun.lockb",
		checkPatchesDir: "patches",
		manager: "bun"
	}
].sort((_, { manager }) => {
	return process.env.npm_config_user_agent?.startsWith(manager) ? 1 : -1;
});
const lockfilePaths = lockfileFormats.map((l) => l.path);
function getConfigHash(environment) {
	const { config } = environment;
	const { optimizeDeps } = config;
	return getHash(JSON.stringify({
		define: !config.keepProcessEnv ? process.env.NODE_ENV || config.mode : null,
		root: config.root,
		resolve: config.resolve,
		assetsInclude: config.assetsInclude,
		plugins: config.plugins.map((p) => p.name),
		optimizeDeps: {
			include: optimizeDeps.include ? unique(optimizeDeps.include).sort() : void 0,
			exclude: optimizeDeps.exclude ? unique(optimizeDeps.exclude).sort() : void 0,
			rolldownOptions: {
				...optimizeDeps.rolldownOptions,
				plugins: void 0,
				onLog: void 0,
				onwarn: void 0,
				checks: void 0,
				output: {
					...optimizeDeps.rolldownOptions?.output,
					plugins: void 0
				}
			}
		},
		optimizeDepsPluginNames: config.optimizeDepsPluginNames
	}, (_, value) => {
		if (typeof value === "function" || value instanceof RegExp) return value.toString();
		return value;
	}));
}
function getLockfileHash(environment) {
	const lockfilePath = lookupFile(environment.config.root, lockfilePaths);
	let content = lockfilePath ? fs.readFileSync(lockfilePath, "utf-8") : "";
	if (lockfilePath) {
		const normalizedLockfilePath = lockfilePath.replaceAll("\\", "/");
		const lockfileFormat = lockfileFormats.find((f) => normalizedLockfilePath.endsWith(f.path));
		if (lockfileFormat.checkPatchesDir) {
			const baseDir = lockfilePath.slice(0, -lockfileFormat.path.length);
			const stat = tryStatSync(path.join(baseDir, lockfileFormat.checkPatchesDir));
			if (stat?.isDirectory()) content += stat.mtimeMs.toString();
		}
	}
	return getHash(content);
}
function getDepHash(environment) {
	const lockfileHash = getLockfileHash(environment);
	const configHash = getConfigHash(environment);
	return {
		hash: getHash(lockfileHash + configHash),
		lockfileHash,
		configHash
	};
}
function getOptimizedBrowserHash(hash, deps, timestamp = "") {
	return getHash(hash + JSON.stringify(deps) + timestamp);
}
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 o of Object.keys(dependenciesInfo)) {
		const info = dependenciesInfo[o];
		if (callbackFn(info, o)) return info;
	}
}
async function optimizedDepNeedsInterop(environment, metadata, file) {
	const depInfo = optimizedDepInfoFromFile(metadata, file);
	if (depInfo?.src && depInfo.needsInterop === void 0) {
		depInfo.exportsData ??= extractExportsData(environment, depInfo.src);
		depInfo.needsInterop = needsInterop(environment, depInfo.id, await depInfo.exportsData);
	}
	return depInfo?.needsInterop;
}
const MAX_TEMP_DIR_AGE_MS = 1440 * 60 * 1e3;
async function cleanupDepsCacheStaleDirs(config) {
	try {
		const cacheDir = path.resolve(config.cacheDir);
		if (fs.existsSync(cacheDir)) {
			const dirents = await fsp.readdir(cacheDir, { withFileTypes: true });
			for (const dirent of dirents) if (dirent.isDirectory() && dirent.name.includes("_temp_")) {
				const tempDirPath = path.resolve(config.cacheDir, dirent.name);
				const stats = await fsp.stat(tempDirPath).catch(() => null);
				if (stats?.mtime && Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS) {
					debug$4?.(`removing stale cache temp dir ${tempDirPath}`);
					await fsp.rm(tempDirPath, {
						recursive: true,
						force: true
					});
				}
			}
		}
	} catch (err) {
		config.logger.error(err);
	}
}
const GRACEFUL_RENAME_TIMEOUT = 5e3;
const safeRename = promisify(function gracefulRename(from, to, cb) {
	const start = Date.now();
	let backoff = 0;
	fs.rename(from, to, function CB(er) {
		if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < GRACEFUL_RENAME_TIMEOUT) {
			setTimeout(function() {
				fs.stat(to, function(stater, _st) {
					if (stater && stater.code === "ENOENT") fs.rename(from, to, CB);
					else CB(er);
				});
			}, backoff);
			if (backoff < 100) backoff += 10;
			return;
		}
		cb(er);
	});
});
//#endregion
//#region src/node/plugins/resolve.ts
const normalizedClientEntry = normalizePath(CLIENT_ENTRY);
const normalizedEnvEntry = normalizePath(ENV_ENTRY);
const ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
const browserExternalId = "__vite-browser-external";
const optionalPeerDepId = "__vite-optional-peer-dep";
const subpathImportsPrefix = "#";
const relativePrefixRE = /^\.\.?(?:[/\\]|$)/;
const startsWithWordCharRE = /^\w/;
const debug$3 = createDebugger("vite:resolve-details", { onlyWhenFocused: true });
const perEnvironmentOrWorkerPlugin = (name, overrideEnvConfig, f) => {
	const envs = {};
	const getEnvironmentPlugin = {
		name: `${name}:get-environment`,
		buildStart() {
			envs[this.environment.name] = this.environment;
		},
		perEnvironmentStartEndDuringDev: true
	};
	const createGetEnvironment = (name) => () => envs[name];
	if (overrideEnvConfig) return [getEnvironmentPlugin, f({
		name: "client",
		config: overrideEnvConfig
	}, createGetEnvironment("client"))];
	return [getEnvironmentPlugin, {
		name,
		applyToEnvironment(environment) {
			return f(environment, createGetEnvironment(environment.name));
		}
	}];
};
function oxcResolvePlugin(resolveOptions, overrideEnvConfig, isJsPluginContainer = false) {
	return [...resolveOptions.optimizeDeps && !resolveOptions.isBuild ? [optimizerResolvePlugin(resolveOptions)] : [], ...perEnvironmentOrWorkerPlugin("vite:resolve-builtin", overrideEnvConfig, (partialEnv, getEnv) => {
		const depsOptimizerEnabled = resolveOptions.optimizeDeps && !resolveOptions.isBuild && !partialEnv.config.isBundled && !isDepOptimizationDisabled(partialEnv.config.optimizeDeps);
		const getDepsOptimizer = () => {
			const env = getEnv();
			if (env.mode !== "dev") throw new Error("The environment mode should be dev");
			if (!env.depsOptimizer) throw new Error("The environment should have a depsOptimizer");
			return env.depsOptimizer;
		};
		const options = {
			...partialEnv.config.resolve,
			...resolveOptions
		};
		const noExternal = Array.isArray(options.noExternal) || options.noExternal === true ? options.noExternal : [options.noExternal];
		const plugin = viteResolvePlugin({
			resolveOptions: {
				isBuild: options.isBuild,
				isProduction: options.isProduction,
				asSrc: options.asSrc ?? false,
				preferRelative: options.preferRelative ?? false,
				isRequire: options.isRequire,
				root: options.root,
				scan: options.scan ?? false,
				mainFields: options.skipMainField ? options.mainFields : options.mainFields.concat(["main"]),
				conditions: options.conditions,
				externalConditions: options.externalConditions,
				extensions: options.extensions,
				tryIndex: options.tryIndex ?? true,
				tryPrefix: options.tryPrefix,
				preserveSymlinks: options.preserveSymlinks,
				tsconfigPaths: options.tsconfigPaths
			},
			environmentConsumer: partialEnv.config.consumer,
			environmentName: partialEnv.name,
			builtins: partialEnv.config.resolve.builtins,
			external: options.external,
			noExternal,
			dedupe: options.dedupe,
			disableCache: partialEnv.config.command === "serve" && partialEnv.config.server.watch === null,
			legacyInconsistentCjsInterop: options.legacyInconsistentCjsInterop,
			finalizeBareSpecifier: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId, importer) => {
				const depsOptimizer = getDepsOptimizer();
				const isJsType = isOptimizable(resolvedId, depsOptimizer.options);
				const exclude = depsOptimizer?.options.exclude;
				const deepMatch = deepImportRE.exec(rawId);
				const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(rawId);
				const skipOptimization = depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(rawId) || SPECIAL_QUERY_RE.test(resolvedId);
				let newId = resolvedId;
				if (skipOptimization) {
					const versionHash = depsOptimizer.metadata.browserHash;
					if (versionHash && isJsType) newId = injectQuery(newId, `v=${versionHash}`);
				} else {
					const optimizedInfo = depsOptimizer.registerMissingImport(rawId, newId);
					newId = depsOptimizer.getOptimizedDepId(optimizedInfo);
				}
				return newId;
			},
			finalizeOtherSpecifiers: !depsOptimizerEnabled ? void 0 : (resolvedId, rawId) => {
				const newResolvedId = ensureVersionQuery(resolvedId, rawId, options, getDepsOptimizer());
				return newResolvedId === resolvedId ? void 0 : newResolvedId;
			},
			resolveSubpathImports(id, importer, isRequire, scan) {
				return resolveSubpathImports(id, importer, {
					...options,
					isRequire: resolveOptions.isRequire ?? isRequire,
					scan
				});
			},
			...partialEnv.config.command === "serve" || isJsPluginContainer ? { async onWarn(msg) {
				partialEnv.config.logger.warn(`warning: ${msg}`, {
					clear: true,
					timestamp: true
				});
			} } : {},
			...debug$3 ? { async onDebug(message) {
				debug$3(message);
			} } : {}
		});
		plugin.perEnvironmentWatchChangeDuringDev = true;
		return plugin;
	})];
}
function optimizerResolvePlugin(resolveOptions) {
	const { root, asSrc } = resolveOptions;
	return {
		name: "vite:resolve-dev",
		applyToEnvironment(environment) {
			return !environment.config.isBundled && !isDepOptimizationDisabled(environment.config.optimizeDeps);
		},
		resolveId: {
			filter: { id: { exclude: [
				/^\0/,
				/^virtual:/,
				/^\/virtual:/,
				/^__vite-/
			] } },
			async handler(id, importer, resolveOpts) {
				const depsOptimizer = resolveOptions.optimizeDeps && this.environment.mode === "dev" ? this.environment.depsOptimizer : void 0;
				if (!depsOptimizer) return;
				const options = {
					isRequire: resolveOpts.kind === "require-call",
					...this.environment.config.resolve,
					...resolveOptions,
					scan: resolveOpts.scan ?? resolveOptions.scan
				};
				options.preferRelative ||= importer?.endsWith(".html");
				if (asSrc && depsOptimizer.isOptimizedDepUrl(id)) return id.startsWith(FS_PREFIX) ? fsPathFromId(id) : normalizePath(path.resolve(root, id.slice(1)));
				if (!isDataUrl(id) && !isExternalUrl(id)) {
					if (id[0] === "." || options.preferRelative && startsWithWordCharRE.test(id)) {
						const basedir = importer ? path.dirname(importer) : root;
						const normalizedFsPath = normalizePath(path.resolve(basedir, id));
						if (depsOptimizer.isOptimizedDepFile(normalizedFsPath)) {
							if (!DEP_VERSION_RE.test(normalizedFsPath)) {
								const browserHash = optimizedDepInfoFromFile(depsOptimizer.metadata, normalizedFsPath)?.browserHash;
								if (browserHash) return injectQuery(normalizedFsPath, `v=${browserHash}`);
							}
							return normalizedFsPath;
						}
					}
					if (bareImportRE.test(id)) {
						let res;
						if (asSrc && !options.scan && (res = await tryOptimizedResolve(depsOptimizer, id, importer, options.preserveSymlinks, options.packageCache))) return res;
					}
				}
			}
		}
	};
}
function resolveSubpathImports(id, importer, options) {
	if (!importer || !id.startsWith(subpathImportsPrefix)) return;
	const basedir = path.dirname(importer);
	const pkgData = findNearestPackageData(basedir, options.packageCache);
	if (!pkgData) return;
	let { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id.slice(1));
	idWithoutPostfix = "#" + idWithoutPostfix;
	let importsPath = resolveExportsOrImports(pkgData.data, idWithoutPostfix, options, "imports");
	if (importsPath?.[0] === ".") {
		importsPath = path.relative(basedir, path.join(pkgData.dir, importsPath));
		if (!relativePrefixRE.test(importsPath)) importsPath = `./${importsPath}`;
	}
	if (importsPath == null) return;
	return importsPath + postfix;
}
function ensureVersionQuery(resolved, id, options, depsOptimizer) {
	if (!options.isBuild && !options.scan && depsOptimizer && !(resolved === normalizedClientEntry || resolved === normalizedEnvEntry)) {
		if ((isInNodeModules(id) || isInNodeModules(resolved)) && !DEP_VERSION_RE.test(resolved)) {
			const versionHash = depsOptimizer.metadata.browserHash;
			if (versionHash && isOptimizable(resolved, depsOptimizer.options)) resolved = injectQuery(resolved, `v=${versionHash}`);
		}
	}
	return resolved;
}
function tryFsResolve(fsPath, options, tryIndex = true, skipPackageJson = false) {
	const hashIndex = fsPath.indexOf("#");
	if (hashIndex >= 0 && isInNodeModules(fsPath)) {
		const queryIndex = fsPath.indexOf("?");
		if (queryIndex < 0 || queryIndex > hashIndex) {
			const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath;
			const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
			if (res) return res + fsPath.slice(file.length);
		}
	}
	const { file, postfix } = splitFileAndPostfix(fsPath);
	const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson);
	if (res) return res + postfix;
}
const knownTsOutputRE = /\.(?:js|mjs|cjs|jsx)$/;
const isPossibleTsOutput = (url) => knownTsOutputRE.test(url);
function tryCleanFsResolve(file, options, tryIndex = true, skipPackageJson = false) {
	const { tryPrefix, extensions, preserveSymlinks } = options;
	const fileResult = tryResolveRealFileOrType(file, options.preserveSymlinks);
	if (fileResult?.path) return fileResult.path;
	let res;
	const possibleJsToTs = isPossibleTsOutput(file);
	if (possibleJsToTs || options.extensions.length || tryPrefix) {
		const dirPath = path.dirname(file);
		if (isDirectory(dirPath)) {
			if (possibleJsToTs) {
				const fileExt = path.extname(file);
				const fileName = file.slice(0, -fileExt.length);
				if (res = tryResolveRealFile(fileName + fileExt.replace("js", "ts"), preserveSymlinks)) return res;
				if (fileExt === ".js" && (res = tryResolveRealFile(fileName + ".tsx", preserveSymlinks))) return res;
			}
			if (res = tryResolveRealFileWithExtensions(file, extensions, preserveSymlinks)) return res;
			if (tryPrefix) {
				const prefixed = `${dirPath}/${options.tryPrefix}${path.basename(file)}`;
				if (res = tryResolveRealFile(prefixed, preserveSymlinks)) return res;
				if (res = tryResolveRealFileWithExtensions(prefixed, extensions, preserveSymlinks)) return res;
			}
		}
	}
	if (tryIndex && fileResult?.type === "directory") {
		const dirPath = file;
		if (!skipPackageJson) {
			let pkgPath = `${dirPath}/package.json`;
			try {
				if (fs.existsSync(pkgPath)) {
					if (!options.preserveSymlinks) pkgPath = safeRealpathSync(pkgPath);
					return resolvePackageEntry(dirPath, loadPackageData(pkgPath), options);
				}
			} catch (e) {
				if (e.code !== ERR_RESOLVE_PACKAGE_ENTRY_FAIL && e.code !== "ENOENT") throw e;
			}
		}
		if (res = tryResolveRealFileWithExtensions(`${dirPath}/index`, extensions, preserveSymlinks)) return res;
		if (tryPrefix) {
			if (res = tryResolveRealFileWithExtensions(`${dirPath}/${options.tryPrefix}index`, extensions, preserveSymlinks)) return res;
		}
	}
}
function tryNodeResolve(id, importer, options, depsOptimizer, externalize) {
	const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
	const deepMatch = deepImportRE.exec(id);
	const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
	let basedir;
	if (dedupe.includes(pkgId)) basedir = root;
	else if (importer && path.isAbsolute(importer) && (importer.endsWith("*") || fs.existsSync(cleanUrl(importer)))) basedir = path.dirname(importer);
	else basedir = root;
	const isModuleBuiltin = (id) => isBuiltin(options.builtins, id);
	let selfPkg = null;
	if (!isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
		const selfPackageData = findNearestPackageData(basedir, packageCache);
		selfPkg = selfPackageData?.data.exports && selfPackageData.data.name === pkgId ? selfPackageData : null;
	}
	const pkg = selfPkg || resolvePackageData(pkgId, basedir, preserveSymlinks, packageCache);
	if (!pkg) {
		if (!options.disableOptionalPeerDepHandling && basedir !== root && !isModuleBuiltin(id) && !id.includes("\0") && bareImportRE.test(id)) {
			const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data;
			if (mainPkg) {
				const pkgName = getNpmPackageName(id);
				if (pkgName != null && mainPkg.peerDependencies?.[pkgName] && mainPkg.peerDependenciesMeta?.[pkgName]?.optional) return { id: `${optionalPeerDepId}:${id}:${mainPkg.name}` };
			}
		}
		return;
	}
	let resolved = (deepMatch ? resolveDeepImport : resolvePackageEntry)(deepMatch ? "." + id.slice(pkgId.length) : id, pkg, options, externalize);
	if (!resolved) return;
	const processResult = (resolved) => {
		if (!externalize) return resolved;
		if (!canExternalizeFile(resolved.id)) return resolved;
		let resolvedId = id;
		if (deepMatch && !pkg.data.exports && path.extname(id) !== path.extname(resolved.id)) {
			const index = resolved.id.indexOf(id);
			if (index > -1) {
				resolvedId = resolved.id.slice(index);
				debug$3?.(`[processResult] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolvedId)}`);
			}
		}
		return {
			...resolved,
			id: resolvedId,
			external: true
		};
	};
	if (!options.idOnly && (!options.scan && isBuild || externalize)) return processResult({
		id: resolved,
		moduleSideEffects: pkg.hasSideEffects(resolved),
		packageJsonPath: findNearestPackagePath(resolved, options.legacyInconsistentCjsInterop, options.packageCache, isBuild)
	});
	if (!isInNodeModules(resolved) || !depsOptimizer || options.scan) return { id: resolved };
	const isJsType = isOptimizable(resolved, depsOptimizer.options);
	const exclude = depsOptimizer.options.exclude;
	if (depsOptimizer.options.noDiscovery || !isJsType || importer && isInNodeModules(importer) || exclude?.includes(pkgId) || exclude?.includes(id) || SPECIAL_QUERY_RE.test(resolved)) {
		const versionHash = depsOptimizer.metadata.browserHash;
		if (versionHash && isJsType) resolved = injectQuery(resolved, `v=${versionHash}`);
	} else {
		const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
		resolved = depsOptimizer.getOptimizedDepId(optimizedInfo);
	}
	return { id: resolved };
}
async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks, packageCache) {
	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 = resolvePackageData(pkgName, importer, preserveSymlinks, packageCache)?.dir;
			if (idPkgDir == null) break;
			idPkgDir = normalizePath(idPkgDir);
		}
		if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) return depsOptimizer.getOptimizedDepId(optimizedData);
	}
}
function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, options, externalize) {
	const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
	const cached = getResolvedCache(".", options);
	if (cached) return cached + postfix;
	try {
		let entryPoint;
		if (data.exports) entryPoint = resolveExportsOrImports(data, ".", options, "exports", externalize);
		if (!entryPoint) {
			for (const field of options.mainFields) if (typeof data[field] === "string") {
				entryPoint = data[field];
				break;
			} else if (field === "browser") {
				const browser = data[field];
				if (isObject$1(browser) && browser["."]) {
					entryPoint = browser["."];
					break;
				}
			}
		}
		entryPoint ||= data.main;
		const entryPoints = entryPoint ? [entryPoint] : [
			"index.js",
			"index.json",
			"index.node"
		];
		for (let entry of entryPoints) {
			let skipPackageJson = false;
			if (options.mainFields[0] === "sass" && !options.extensions.includes(path.extname(entry))) {
				entry = "";
				skipPackageJson = true;
			} else {
				const { browser: browserField } = data;
				if (options.mainFields.includes("browser") && isObject$1(browserField)) entry = mapWithBrowserField(entry, browserField) || entry;
			}
			const resolvedEntryPoint = tryFsResolve(path.join(dir, entry), options, true, skipPackageJson);
			if (resolvedEntryPoint) {
				debug$3?.(`[package entry] ${import_picocolors.default.cyan(idWithoutPostfix)} -> ${import_picocolors.default.dim(resolvedEntryPoint)}${postfix !== "" ? ` (postfix: ${postfix})` : ""}`);
				setResolvedCache(".", resolvedEntryPoint, options);
				return resolvedEntryPoint + postfix;
			}
		}
	} catch (e) {
		packageEntryFailure(id, e.message);
	}
	packageEntryFailure(id);
}
function packageEntryFailure(id, details) {
	const err = /* @__PURE__ */ new Error(`Failed to resolve entry for package "${id}". The package may have incorrect main/module/exports specified in its package.json` + (details ? ": " + details : "."));
	err.code = ERR_RESOLVE_PACKAGE_ENTRY_FAIL;
	throw err;
}
function getConditions(conditions, isProduction, isRequire) {
	const resolvedConditions = conditions.map((condition) => {
		if (condition === DEV_PROD_CONDITION) return isProduction ? "production" : "development";
		return condition;
	});
	if (isRequire) resolvedConditions.push("require");
	else resolvedConditions.push("import");
	return resolvedConditions;
}
function resolveExportsOrImports(pkg, key, options, type, externalize) {
	const conditions = getConditions(externalize ? options.externalConditions : options.conditions, options.isProduction, options.isRequire);
	const result = (type === "imports" ? f : o)(pkg, key, {
		conditions,
		unsafe: true
	});
	return result ? result[0] : void 0;
}
function resolveDeepImport(id, { setResolvedCache, getResolvedCache, dir, data }, options, externalize) {
	const cache = getResolvedCache(id, options);
	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, options, "exports", externalize);
			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 ${path.join(dir, "package.json")}.`);
	} else if (options.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) {
			setResolvedCache(id, browserExternalId, options);
			return browserExternalId;
		}
	}
	if (relativeId) {
		const resolved = tryFsResolve(path.join(dir, relativeId), options, !exportsField);
		if (resolved) {
			debug$3?.(`[node/deep-import] ${import_picocolors.default.cyan(id)} -> ${import_picocolors.default.dim(resolved)}`);
			setResolvedCache(id, resolved, options);
			return resolved;
		}
	}
}
/**
* given a relative path in pkg dir,
* return a relative path in pkg dir,
* mapped with the "map" object
*
* - Returning `undefined` means there is no browser mapping for this id
* - Returning `false` means this id is explicitly externalized for browser
*/
function mapWithBrowserField(relativePathInPkgDir, map) {
	const normalizedPath = path.posix.normalize(relativePathInPkgDir);
	for (const key in map) {
		const normalizedKey = path.posix.normalize(key);
		if (normalizedPath === normalizedKey || equalWithoutSuffix(normalizedPath, normalizedKey, ".js") || equalWithoutSuffix(normalizedPath, normalizedKey, "/index.js")) return map[key];
	}
}
function equalWithoutSuffix(path, key, suffix) {
	return key.endsWith(suffix) && key.slice(0, -suffix.length) === path;
}
function tryResolveRealFile(file, preserveSymlinks) {
	if (tryStatSync(file)?.isFile()) return getRealPath(file, preserveSymlinks);
}
function tryResolveRealFileWithExtensions(filePath, extensions, preserveSymlinks) {
	for (const ext of extensions) {
		const res = tryResolveRealFile(filePath + ext, preserveSymlinks);
		if (res) return res;
	}
}
function tryResolveRealFileOrType(file, preserveSymlinks) {
	const fileStat = tryStatSync(file);
	if (fileStat?.isFile()) return {
		path: getRealPath(file, preserveSymlinks),
		type: "file"
	};
	if (fileStat?.isDirectory()) return { type: "directory" };
}
function getRealPath(resolved, preserveSymlinks) {
	if (!preserveSymlinks) resolved = safeRealpathSync(resolved);
	return normalizePath(resolved);
}
function isDirectory(path) {
	return tryStatSync(path)?.isDirectory() ?? false;
}
function findNearestPackagePath(file, legacyInconsistentCjsInterop, packageCache, isBuild) {
	if (!isBuild || legacyInconsistentCjsInterop) return;
	const pkgData = findNearestPackageData(file, packageCache);
	return pkgData ? path.join(pkgData.dir, "package.json") : null;
}
//#endregion
//#region src/node/nodeResolve.ts
/**
* Resolve like Node.js using Vite's resolution algorithm with preconfigured options.
*/
function nodeResolveWithVite(id, importer, options) {
	return tryNodeResolve(id, importer, {
		root: options.root,
		isBuild: true,
		isProduction: true,
		preferRelative: false,
		tryIndex: true,
		mainFields: [],
		conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []],
		externalConditions: [],
		external: [],
		noExternal: [],
		dedupe: [],
		extensions: DEFAULT_EXTENSIONS,
		preserveSymlinks: false,
		tsconfigPaths: false,
		packageCache: void 0,
		isRequire: options.isRequire,
		builtins: nodeLikeBuiltins,
		disableOptionalPeerDepHandling: true
	})?.id;
}
//#endregion
//#region src/node/plugins/terser.ts
let terserPath;
function loadTerserPath(root) {
	if (terserPath) return terserPath;
	const resolved = nodeResolveWithVite("terser", void 0, { root }) ?? nodeResolveWithVite("terser", _dirname, { root });
	if (resolved) return terserPath = resolved;
	throw new Error("terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.");
}
function terserPlugin(config) {
	const { maxWorkers, ...terserOptions } = config.build.terserOptions;
	const makeWorker = () => new WorkerWithFallback(() => async (terserPath, code, options) => {
		const terser = await import(terserPath);
		try {
			return await terser.minify(code, options);
		} catch (e) {
			throw {
				stack: e.stack,
				...e
			};
		}
	}, {
		shouldUseFake(_terserPath, _code, options) {
			return !!(typeof options.mangle === "object" && (options.mangle.nth_identifier?.get || typeof options.mangle.properties === "object" && options.mangle.properties.nth_identifier?.get) || typeof options.format?.comments === "function" || typeof options.output?.comments === "function" || options.nameCache);
		},
		max: maxWorkers
	});
	let worker;
	return {
		name: "vite:terser",
		applyToEnvironment(environment) {
			return !!environment.config.build.minify;
		},
		async renderChunk(code, chunk, outputOptions) {
			if (config.build.minify !== "terser" && !this.environment.config.isOutputOptionsForLegacyChunks?.(outputOptions)) return null;
			worker ||= makeWorker();
			const terserPath = pathToFileURL(loadTerserPath(config.root)).href;
			try {
				const res = await worker.run(terserPath, code, {
					safari10: true,
					...terserOptions,
					format: {
						...terserOptions.format,
						preserve_annotations: config.build.lib && outputOptions.format === "es" ? true : terserOptions.format?.preserve_annotations
					},
					sourceMap: !!outputOptions.sourcemap,
					module: outputOptions.format.startsWith("es"),
					toplevel: outputOptions.format === "cjs"
				});
				return {
					code: res.code,
					map: res.map
				};
			} catch (e) {
				if (e.line !== void 0 && e.col !== void 0) e.loc = {
					file: chunk.fileName,
					line: e.line,
					column: e.col
				};
				if (e.pos !== void 0) e.frame = generateCodeFrame(code, e.pos);
				throw e;
			}
		},
		closeBundle() {
			worker?.stop();
		}
	};
}
//#endregion
//#region src/node/ssr/ssrManifestPlugin.ts
function ssrManifestPlugin() {
	const getSsrManifest = perEnvironmentState(() => {
		return {};
	});
	return {
		name: "vite:ssr-manifest",
		applyToEnvironment(environment) {
			return !!environment.config.build.ssrManifest;
		},
		generateBundle(_options, bundle) {
			const config = this.environment.config;
			const ssrManifest = getSsrManifest(this);
			const { base } = config;
			for (const file in bundle) {
				const chunk = bundle[file];
				if (chunk.type === "chunk") {
					for (const id in chunk.modules) {
						const normalizedId = normalizePath(relative(config.root, id));
						const mappedChunks = ssrManifest[normalizedId] ?? (ssrManifest[normalizedId] = []);
						if (!chunk.isEntry) {
							mappedChunks.push(joinUrlSegments(base, chunk.fileName));
							chunk.viteMetadata.importedCss.forEach((file) => {
								mappedChunks.push(joinUrlSegments(base, file));
							});
						}
						chunk.viteMetadata.importedAssets.forEach((file) => {
							mappedChunks.push(joinUrlSegments(base, file));
						});
					}
					if (chunk.code.includes(preloadMethod)) {
						const code = chunk.code;
						let imports = [];
						try {
							imports = parse$2(code)[0].filter((i) => i.n && i.d > -1);
						} catch (_e) {
							const e = _e;
							const loc = numberToPos(code, e.idx);
							this.error({
								name: e.name,
								message: e.message,
								stack: e.stack,
								cause: e.cause,
								pos: e.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: name } = imports[index];
							const url = 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 chunk = bundle[filename];
								if (chunk) {
									chunk.viteMetadata.importedCss.forEach((file) => {
										deps.push(joinUrlSegments(base, file));
									});
									chunk.imports.forEach(addDeps);
								}
							};
							addDeps(normalizePath(join(dirname(chunk.fileName), url.slice(1, -1))));
							ssrManifest[basename(name)] = deps;
						}
					}
				}
			}
			this.emitFile({
				fileName: typeof config.build.ssrManifest === "string" ? config.build.ssrManifest : ".vite/ssr-manifest.json",
				type: "asset",
				source: JSON.stringify(sortObjectKeys(ssrManifest), void 0, 2)
			});
		}
	};
}
//#endregion
//#region src/node/plugins/license.ts
const licenseConfigDefaults = Object.freeze({ fileName: ".vite/license.md" });
const licenseFiles = [
	/^license/i,
	/^licence/i,
	/^copying/i
];
function licensePlugin() {
	return {
		name: "vite:license",
		generateBundle(_, bundle) {
			const licenseOption = this.environment.config.build.license;
			if (licenseOption === false) return;
			const packageCache = /* @__PURE__ */ new Map();
			const licenses = {};
			for (const file in bundle) {
				const chunk = bundle[file];
				if (chunk.type === "asset") continue;
				for (const moduleId of chunk.moduleIds) {
					if (moduleId.startsWith("\0") || !isInNodeModules(moduleId)) continue;
					const pkgData = findNearestMainPackageData(path.dirname(moduleId), packageCache);
					if (!pkgData) continue;
					const { name, version = "0.0.0", license } = pkgData.data;
					const key = `${name}@${version}`;
					if (licenses[key]) continue;
					const entry = {
						name,
						version
					};
					if (license) entry.identifier = license.trim();
					const licenseFile = findLicenseFile(pkgData.dir);
					if (licenseFile) entry.text = fs.readFileSync(licenseFile, "utf-8").trim();
					licenses[key] = entry;
				}
			}
			const licenseEntries = Object.values(sortObjectKeys(licenses));
			const licenseOutputFileName = typeof licenseOption === "object" ? licenseOption.fileName : licenseConfigDefaults.fileName;
			if (licenseOutputFileName.endsWith(".json")) {
				this.emitFile({
					fileName: licenseOutputFileName,
					type: "asset",
					source: JSON.stringify(licenseEntries, null, 2)
				});
				return;
			}
			const markdown = licenseEntryToMarkdown(licenseEntries);
			this.emitFile({
				fileName: licenseOutputFileName,
				type: "asset",
				source: markdown
			});
		}
	};
}
function licenseEntryToMarkdown(licenses) {
	if (licenses.length === 0) return `\
# Licenses

The app does not bundle any dependencies with licenses.
`;
	let text = `\
# Licenses

The app bundles dependencies which contain the following licenses:
`;
	for (const license of licenses) {
		const nameAndVersionText = `${license.name} - ${license.version}`;
		const identifierText = license.identifier ? ` (${license.identifier})` : "";
		text += `\n## ${nameAndVersionText}${identifierText}\n`;
		if (license.text) text += `\n${license.text}\n`;
	}
	return text;
}
function findLicenseFile(pkgDir) {
	const matchedFile = fs.readdirSync(pkgDir).find((file) => licenseFiles.some((re) => re.test(file)));
	if (matchedFile) return path.join(pkgDir, matchedFile);
}
//#endregion
//#region src/node/plugins/prepareOutDir.ts
function prepareOutDirPlugin() {
	const rendered = /* @__PURE__ */ new Set();
	return {
		name: "vite:prepare-out-dir",
		watchChange() {
			rendered.delete(this.environment);
		},
		renderStart: {
			order: "pre",
			handler() {
				if (rendered.has(this.environment)) return;
				const { config } = this.environment;
				if (config.build.write) {
					rendered.add(this.environment);
					const { root, build: options } = config;
					const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rolldownOptions.output);
					prepareOutDir(resolvedOutDirs, resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, this.environment.logger), this.environment);
				}
			}
		}
	};
}
function prepareOutDir(outDirs, emptyOutDir, environment) {
	const { publicDir } = environment.config;
	const outDirsArray = [...outDirs];
	for (const outDir of outDirs) {
		ignoreInput(outDir);
		if (emptyOutDir !== false && fs.existsSync(outDir)) emptyDir(outDir, [...outDirsArray.map((dir) => {
			const relative = path.relative(outDir, dir);
			if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) return relative;
			return "";
		}).filter(Boolean), ".git"]);
		if (environment.config.build.copyPublicDir && publicDir && fs.existsSync(publicDir)) {
			if (!areSeparateFolders(outDir, publicDir)) environment.logger.warn(import_picocolors.default.yellow(`\n${import_picocolors.default.bold(`(!)`)} The public directory feature may not work correctly. outDir ${import_picocolors.default.white(import_picocolors.default.dim(outDir))} and publicDir ${import_picocolors.default.white(import_picocolors.default.dim(publicDir))} are not separate folders.\n`));
			copyDir(publicDir, outDir);
		}
	}
}
function areSeparateFolders(a, b) {
	const na = normalizePath(a);
	const nb = normalizePath(b);
	return na !== nb && !na.startsWith(withTrailingSlash(nb)) && !nb.startsWith(withTrailingSlash(na));
}
//#endregion
//#region src/node/build.ts
var build_exports = /* @__PURE__ */ __exportAll({
	BuildEnvironment: () => BuildEnvironment,
	ChunkMetadataMap: () => ChunkMetadataMap,
	build: () => build,
	buildEnvironmentOptionsDefaults: () => buildEnvironmentOptionsDefaults,
	builderOptionsDefaults: () => builderOptionsDefaults,
	clearLine: () => clearLine,
	createBuilder: () => createBuilder,
	createToImportMetaURLBasedRelativeRuntime: () => createToImportMetaURLBasedRelativeRuntime,
	enhanceRollupError: () => enhanceRollupError,
	injectEnvironmentToHooks: () => injectEnvironmentToHooks,
	onRollupLog: () => onRollupLog,
	resolveBuildEnvironmentOptions: () => resolveBuildEnvironmentOptions,
	resolveBuildOutputs: () => resolveBuildOutputs,
	resolveBuildPlugins: () => resolveBuildPlugins,
	resolveBuilderOptions: () => resolveBuilderOptions,
	resolveLibFilename: () => resolveLibFilename,
	resolveRolldownOptions: () => resolveRolldownOptions,
	resolveUserExternal: () => resolveUserExternal,
	toOutputFilePathInCss: () => toOutputFilePathInCss,
	toOutputFilePathInHtml: () => toOutputFilePathInHtml,
	toOutputFilePathInJS: () => toOutputFilePathInJS,
	toOutputFilePathWithoutRuntime: () => toOutputFilePathWithoutRuntime
});
const _buildEnvironmentOptionsDefaults = Object.freeze({
	target: "baseline-widely-available",
	/** @deprecated */
	polyfillModulePreload: true,
	modulePreload: true,
	outDir: "dist",
	assetsDir: "assets",
	assetsInlineLimit: DEFAULT_ASSETS_INLINE_LIMIT,
	sourcemap: false,
	terserOptions: {},
	chunkImportMap: false,
	rolldownOptions: {},
	commonjsOptions: {
		include: [/node_modules/],
		extensions: [".js", ".cjs"]
	},
	dynamicImportVarsOptions: { exclude: [/node_modules/] },
	write: true,
	emptyOutDir: null,
	copyPublicDir: true,
	license: false,
	manifest: false,
	lib: false,
	ssrManifest: false,
	ssrEmitAssets: false,
	reportCompressedSize: true,
	chunkSizeWarningLimit: 500,
	watch: null
});
const buildEnvironmentOptionsDefaults = _buildEnvironmentOptionsDefaults;
function resolveBuildEnvironmentOptions(raw, logger, consumer, isBundledDev, isSsrTargetWebworkerEnvironment) {
	const deprecatedPolyfillModulePreload = raw.polyfillModulePreload;
	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 merged = mergeWithDefaults({
		..._buildEnvironmentOptionsDefaults,
		cssCodeSplit: !raw.lib,
		minify: consumer === "server" || isBundledDev ? false : "oxc",
		rollupOptions: {},
		rolldownOptions: void 0,
		ssr: consumer === "server",
		emitAssets: consumer === "client",
		createEnvironment: (name, config) => new BuildEnvironment(name, config)
	}, raw);
	setupRollupOptionCompat(merged, "build");
	merged.rolldownOptions = {
		platform: consumer === "client" || isSsrTargetWebworkerEnvironment ? "browser" : "node",
		...merged.rolldownOptions
	};
	if (merged.target === "baseline-widely-available") merged.target = ESBUILD_BASELINE_WIDELY_AVAILABLE_TARGET;
	if (Array.isArray(merged.target)) merged.target = unique(merged.target);
	if (merged.minify === "false") merged.minify = false;
	else if (merged.minify === true) merged.minify = "oxc";
	const defaultModulePreload = { polyfill: true };
	const resolved = {
		...merged,
		cssTarget: merged.cssTarget ?? merged.target,
		cssMinify: merged.cssMinify ?? (consumer === "server" ? "lightningcss" : !!merged.minify),
		modulePreload: merged.modulePreload === false ? false : merged.modulePreload === true ? defaultModulePreload : {
			...defaultModulePreload,
			...merged.modulePreload
		}
	};
	setupRollupOptionCompat(resolved, "build");
	return resolved;
}
function resolveBuildPlugins(config) {
	const isBuild = config.command === "build";
	return {
		pre: [
			...isBuild && !config.isWorker ? [prepareOutDirPlugin()] : [],
			perEnvironmentPlugin("vite:rollup-options-plugins", async (environment) => {
				if (!isBuild && !environment.config.isBundled) return false;
				return (await asyncFlatten(arraify(environment.config.build.rolldownOptions.plugins))).filter(Boolean);
			}),
			...config.isWorker ? [webWorkerPostPlugin(config)] : []
		],
		post: [
			...isBuild ? buildImportAnalysisPlugin(config) : [],
			...isBuild && config.build.minify === "esbuild" ? [buildEsbuildPlugin()] : [],
			...isBuild ? [terserPlugin(config)] : [],
			...isBuild && !config.isWorker ? [
				licensePlugin(),
				manifestPlugin(),
				ssrManifestPlugin(),
				buildReporterPlugin(config)
			] : [],
			viteLoadFallbackPlugin()
		]
	};
}
/**
* Bundles a single environment for production.
* Returns a Promise containing the build result.
*/
async function build(inlineConfig = {}) {
	const builder = await createBuilder(inlineConfig, true);
	const environment = Object.values(builder.environments)[0];
	if (!environment) throw new Error("No environment found");
	return builder.build(environment);
}
function resolveConfigToBuild(inlineConfig = {}, patchConfig, patchPlugins) {
	return resolveConfig(inlineConfig, "build", "production", "production", false, patchConfig, patchPlugins);
}
function resolveRolldownOptions(environment, chunkMetadataMap) {
	const { root, packageCache, base, build: options } = environment.config;
	const libOptions = options.lib;
	const { logger } = environment;
	const ssr = environment.config.consumer === "server";
	const resolve = (p) => path.resolve(root, p);
	const input = libOptions ? options.rolldownOptions.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [alias, resolve(file)]))) : typeof options.ssr === "string" ? resolve(options.ssr) : options.rolldownOptions.input || resolve("index.html");
	if (ssr && typeof input === "string" && input.endsWith(".html")) throw new Error("rolldownOptions.input should not be an html file when building for SSR. Please specify a dedicated SSR entry.");
	if (options.cssCodeSplit === false) {
		if ((typeof input === "string" ? [input] : Array.isArray(input) ? input : Object.values(input)).some((input) => input.endsWith(".css"))) throw new Error(`When "build.cssCodeSplit: false" is set, "rolldownOptions.input" should not include CSS files.`);
	}
	const outDir = resolve(options.outDir);
	const plugins = environment.plugins.map((p) => injectEnvironmentToHooks(environment, chunkMetadataMap, p));
	const rolldownOptions = {
		preserveEntrySignatures: ssr ? "allow-extension" : libOptions ? "strict" : false,
		...options.rolldownOptions,
		output: options.rolldownOptions.output,
		input,
		plugins,
		external: options.rolldownOptions.external,
		onLog(level, log) {
			onRollupLog(level, log, environment);
		},
		transform: {
			target: options.target === false ? void 0 : options.target,
			...options.rolldownOptions.transform,
			define: {
				...options.rolldownOptions.transform?.define,
				"process.env.NODE_ENV": "process.env.NODE_ENV"
			}
		},
		moduleTypes: {
			...options.rolldownOptions.moduleTypes,
			".css": "js"
		},
		experimental: {
			...options.rolldownOptions.experimental,
			viteMode: true,
			chunkImportMap: options.chunkImportMap ? { baseUrl: base } : options.rolldownOptions.experimental?.chunkImportMap
		}
	};
	const isSsrTargetWebworkerEnvironment = environment.name === "ssr" && environment.getTopLevelConfig().ssr?.target === "webworker";
	if (isSsrTargetWebworkerEnvironment) plugins.push(esmExternalRequirePlugin());
	const buildOutputOptions = (output = {}) => {
		if (output.output) logger.warn("You've set \"rolldownOptions.output.output\" in your config. This is deprecated and will override all Vite.js default output options. Please use \"rolldownOptions.output\" instead.");
		if (output.file) throw new Error("Vite does not support \"rolldownOptions.output.file\". Please use \"rolldownOptions.output.dir\" and \"rolldownOptions.output.entryFileNames\" instead.");
		if (output.sourcemap) logger.warnOnce(import_picocolors.default.yellow("Vite does not support \"rolldownOptions.output.sourcemap\". Please use \"build.sourcemap\" instead."));
		const format = output.format || "es";
		const jsExt = ssr && !isSsrTargetWebworkerEnvironment || libOptions ? resolveOutputJsExtension(format, findNearestPackageData(root, packageCache)?.data.type) : "js";
		return {
			dir: outDir,
			format,
			exports: "auto",
			sourcemap: options.sourcemap,
			name: libOptions ? libOptions.name : void 0,
			generatedCode: { preset: "es2015" },
			entryFileNames: ssr ? `[name].${jsExt}` : libOptions ? ({ name }) => resolveLibFilename(libOptions, format, name, root, jsExt, packageCache) : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
			chunkFileNames: libOptions ? `[name]-[hash].${jsExt}` : path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
			assetFileNames: libOptions ? `[name].[ext]` : path.posix.join(options.assetsDir, `[name]-[hash].[ext]`),
			codeSplitting: output.codeSplitting ?? (output.format === "umd" || output.format === "iife" || isSsrTargetWebworkerEnvironment && (typeof input === "string" || Object.keys(input).length === 1) ? false : void 0),
			comments: typeof output.comments === "boolean" ? output.comments : {
				annotation: !options.minify || libOptions && (format === "es" || format === "esm"),
				jsdoc: !options.minify,
				legal: !options.minify,
				...output.comments
			},
			minify: options.minify === "oxc" ? libOptions && (format === "es" || format === "esm") ? {
				compress: true,
				mangle: true,
				codegen: false
			} : true : options.minify === false ? "dce-only" : false,
			topLevelVar: true,
			...output
		};
	};
	const outputs = resolveBuildOutputs(options.rolldownOptions.output, libOptions, logger);
	if (Array.isArray(outputs)) rolldownOptions.output = outputs.map(buildOutputOptions);
	else rolldownOptions.output = buildOutputOptions(outputs);
	return rolldownOptions;
}
/**
* Build an App environment, or a App library (if libraryOptions is provided)
**/
async function buildEnvironment(environment) {
	const { logger, config } = environment;
	const { root, build: options } = config;
	logger.info(import_picocolors.default.cyan(`vite v${VERSION} ${import_picocolors.default.green(`building ${environment.name} environment for ${environment.config.mode}...`)}`));
	let bundle;
	let startTime;
	try {
		const chunkMetadataMap = new ChunkMetadataMap();
		const rolldownOptions = resolveRolldownOptions(environment, chunkMetadataMap);
		if (options.watch) {
			logger.info(import_picocolors.default.cyan(`\nwatching for file changes...`));
			const resolvedOutDirs = getResolvedOutDirs(root, options.outDir, options.rolldownOptions.output);
			const emptyOutDir = resolveEmptyOutDir(options.emptyOutDir, root, resolvedOutDirs, logger);
			const resolvedChokidarOptions = resolveChokidarOptions({
				...(rolldownOptions.watch || {}).chokidar,
				...options.watch.chokidar
			}, resolvedOutDirs, emptyOutDir, environment.config.cacheDir);
			const { watch } = await import("rolldown");
			const watcher = watch({
				...rolldownOptions,
				watch: {
					...rolldownOptions.watch,
					...options.watch,
					watcher: convertToWatcherOptions(resolvedChokidarOptions)
				}
			});
			watcher.on("event", (event) => {
				if (event.code === "BUNDLE_START") {
					logger.info(import_picocolors.default.cyan(`\nbuild started...`));
					chunkMetadataMap.clearResetChunks();
				} else if (event.code === "BUNDLE_END") {
					event.result.close();
					logger.info(import_picocolors.default.cyan(`built in ${event.duration}ms.`));
				} else if (event.code === "ERROR") {
					const e = event.error;
					enhanceRollupError(e);
					clearLine();
					logger.error(e.message, { error: e });
				}
			});
			return watcher;
		}
		const { rolldown } = await import("rolldown");
		startTime = Date.now();
		bundle = await rolldown(rolldownOptions);
		const res = [];
		for (const output of arraify(rolldownOptions.output)) res.push(await bundle[options.write ? "write" : "generate"](output));
		for (const output of res) for (const chunk of output.output) injectChunkMetadata(chunkMetadataMap, chunk);
		logger.info(`${import_picocolors.default.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`);
		return Array.isArray(rolldownOptions.output) ? res : res[0];
	} catch (e) {
		enhanceRollupError(e);
		clearLine();
		if (startTime) {
			logger.error(`${import_picocolors.default.red("✗")} Build failed in ${displayTime(Date.now() - startTime)}`);
			startTime = void 0;
		}
		throw e;
	} finally {
		if (bundle) await bundle.close();
	}
}
function enhanceRollupError(e) {
	const stackOnly = extractStack(e);
	let msg = import_picocolors.default.red((e.plugin ? `[${e.plugin}] ` : "") + e.message);
	if (e.loc && e.loc.file && e.loc.file !== e.id) msg += `\nfile: ${import_picocolors.default.cyan(`${e.loc.file}:${e.loc.line}:${e.loc.column}` + (e.id ? ` (${e.id})` : ""))}`;
	else if (e.id) msg += `\nfile: ${import_picocolors.default.cyan(e.id + (e.loc ? `:${e.loc.line}:${e.loc.column}` : ""))}`;
	if (e.frame) msg += `\n` + import_picocolors.default.yellow(normalizeCodeFrame(e.frame));
	e.message = msg;
	if (stackOnly !== void 0) e.stack = `${e.message}\n${stackOnly}`;
}
/**
* The stack string usually contains a copy of the message at the start of the stack.
* If the stack starts with the message, we remove it and just return the stack trace
* portion. Otherwise the original stack trace is used.
*/
function extractStack(e) {
	const { stack, name = "Error", message } = e;
	if (!stack) return stack;
	const expectedPrefix = `${name}: ${message}\n`;
	if (stack.startsWith(expectedPrefix)) return stack.slice(expectedPrefix.length);
	return stack;
}
/**
* Esbuild code frames have newlines at the start and end of the frame, rollup doesn't
* This function normalizes the frame to match the esbuild format which has more pleasing padding
*/
function normalizeCodeFrame(frame) {
	return `\n${frame.replace(/^\n|\n$/g, "")}\n`;
}
function resolveOutputJsExtension(format, type = "commonjs") {
	if (type === "module") return format === "cjs" || format === "umd" ? "cjs" : "js";
	else return format === "es" ? "mjs" : "js";
}
function resolveLibFilename(libOptions, format, entryName, root, extension, packageCache) {
	if (typeof libOptions.fileName === "function") return libOptions.fileName(format, entryName);
	const packageJson = findNearestMainPackageData(root, packageCache)?.data;
	const name = libOptions.fileName || (packageJson && typeof libOptions.entry === "string" ? getPkgName(packageJson.name) : entryName);
	if (!name) throw new Error("Name in package.json is required if option \"build.lib.fileName\" is not provided.");
	extension ??= resolveOutputJsExtension(format, packageJson?.type);
	if (format === "cjs" || format === "es") return `${name}.${extension}`;
	return `${name}.${format}.${extension}`;
}
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((format) => ({
				...outputs,
				format
			}));
		}
		if (libOptions.formats) logger.warn(import_picocolors.default.yellow("\"build.lib.formats\" will be ignored because \"build.rolldownOptions.output\" is already an array format."));
		outputs.forEach((output) => {
			if ((output.format === "umd" || output.format === "iife") && !output.name) throw new Error("Entries in \"build.rolldownOptions.output\" must specify \"name\" when the format is \"umd\" or \"iife\".");
		});
	}
	return outputs;
}
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
const dynamicImportWarningIgnoreList = [`Unsupported expression`, `statically analyzed`];
function clearLine() {
	if (process.stdout.isTTY && !process.env.CI) {
		process.stdout.clearLine(0);
		process.stdout.cursorTo(0);
	}
}
function onRollupLog(level, log, environment) {
	const debugLogger = createDebugger("vite:build");
	const viteLog = (logLeveling, rawLogging) => {
		const logging = typeof rawLogging === "object" ? rawLogging : { message: rawLogging };
		if (logging.code === "UNRESOLVED_IMPORT") {
			const id = logging.id;
			const exporter = logging.exporter;
			if (!id || !id.endsWith("?commonjs-external")) throw new Error(`[vite]: Rolldown failed to resolve import "${exporter}" from "${id}".\nThis is most likely unintended because it can break your application at runtime.\nIf you do want to externalize this module explicitly add it to\n\`build.rolldownOptions.external\``);
		}
		if (logLeveling === "warn") {
			if (logging.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some((msg) => logging.message.includes(msg))) return;
			if (warningIgnoreList.includes(logging.code)) return;
		}
		let message = logging.message;
		if (logging.plugin) message = `[plugin ${logging.plugin}] ${message}`;
		switch (logLeveling) {
			case "info":
				environment.logger.info(message);
				return;
			case "warn":
				environment.logger.warn(import_picocolors.default.yellow(message));
				return;
			case "error":
				environment.logger.error(import_picocolors.default.red(message));
				return;
			case "debug":
				debugLogger?.(message);
				return;
			default:
				environment.logger.info(message);
				return;
		}
	};
	clearLine();
	const userOnLog = environment.config.build.rolldownOptions?.onLog;
	const userOnWarn = environment.config.build.rolldownOptions?.onwarn;
	if (userOnLog) if (userOnWarn) userOnLog(level, log, normalizeUserOnWarn(userOnWarn, viteLog));
	else userOnLog(level, log, viteLog);
	else if (userOnWarn) normalizeUserOnWarn(userOnWarn, viteLog)(level, log);
	else viteLog(level, log);
}
function normalizeUserOnWarn(userOnWarn, defaultHandler) {
	return (logLevel, logging) => {
		if (logLevel === "warn") userOnWarn(normalizeLog(logging), (log) => defaultHandler("warn", typeof log === "function" ? log() : log));
		else defaultHandler(logLevel, logging);
	};
}
const normalizeLog = (log) => typeof log === "string" ? { message: log } : log;
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);
}
var ChunkMetadataMap = class {
	_inner = /* @__PURE__ */ new Map();
	_resetChunks = /* @__PURE__ */ new Set();
	_getKey(chunk) {
		return "preliminaryFileName" in chunk ? chunk.preliminaryFileName : chunk.fileName;
	}
	_getDefaultValue(chunk) {
		return chunk.type === "chunk" ? {
			importedAssets: /* @__PURE__ */ new Set(),
			importedCss: /* @__PURE__ */ new Set(),
			__modules: chunk.modules
		} : {
			importedAssets: /* @__PURE__ */ new Set(),
			importedCss: /* @__PURE__ */ new Set()
		};
	}
	get(chunk) {
		const key = this._getKey(chunk);
		if (!this._inner.has(key)) this._inner.set(key, this._getDefaultValue(chunk));
		return this._inner.get(key);
	}
	reset(chunk) {
		const key = this._getKey(chunk);
		if (this._resetChunks.has(key)) return;
		this._resetChunks.add(key);
		this._inner.set(key, this._getDefaultValue(chunk));
	}
	clearResetChunks() {
		this._resetChunks.clear();
	}
};
function injectEnvironmentToHooks(environment, chunkMetadataMap, plugin) {
	const { resolveId, load, transform } = plugin;
	const clone = Object.assign(Object.create(Object.getPrototypeOf(plugin)), plugin);
	for (const hook of Object.keys(clone)) switch (hook) {
		case "resolveId":
			clone[hook] = wrapEnvironmentResolveId(environment, resolveId, plugin.name);
			break;
		case "load":
			clone[hook] = wrapEnvironmentLoad(environment, load, plugin.name);
			break;
		case "transform":
			clone[hook] = wrapEnvironmentTransform(environment, transform, plugin.name);
			break;
		default:
			if (ROLLUP_HOOKS.includes(hook)) clone[hook] = wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hook);
			break;
	}
	return clone;
}
const wrappedHookMap = /* @__PURE__ */ new WeakMap();
function wrapHookObject(hook, handler) {
	const newHook = {
		...hook,
		handler
	};
	if (!wrappedHookMap.has(hook)) {
		wrappedHookMap.set(hook, []);
		Object.defineProperty(hook, "filter", {
			get() {
				return wrappedHookMap.get(hook)[0].filter;
			},
			set(v) {
				for (const h of wrappedHookMap.get(hook)) h.filter = v;
			}
		});
		Object.defineProperty(hook, "order", {
			get() {
				return wrappedHookMap.get(hook)[0].order;
			},
			set(v) {
				for (const h of wrappedHookMap.get(hook)) h.order = v;
			}
		});
	}
	wrappedHookMap.get(hook).push(newHook);
	return newHook;
}
function wrapEnvironmentResolveId(environment, hook, pluginName) {
	if (!hook) return;
	const fn = getHookHandler(hook);
	const handler = function(id, importer, options) {
		return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options, environment, pluginName));
	};
	if ("handler" in hook) return wrapHookObject(hook, handler);
	else return handler;
}
function wrapEnvironmentLoad(environment, hook, pluginName) {
	if (!hook) return;
	const fn = getHookHandler(hook);
	const handler = function(id, ...args) {
		return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment, pluginName));
	};
	if ("handler" in hook) return wrapHookObject(hook, handler);
	else return handler;
}
function wrapEnvironmentTransform(environment, hook, pluginName) {
	if (!hook) return;
	const fn = getHookHandler(hook);
	const handler = function(code, importer, ...args) {
		return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment, pluginName));
	};
	if ("handler" in hook) return wrapHookObject(hook, handler);
	else return handler;
}
function wrapEnvironmentHook(environment, chunkMetadataMap, plugin, hookName) {
	const hook = plugin[hookName];
	if (!hook) return;
	const fn = getHookHandler(hook);
	if (typeof fn !== "function") return hook;
	const handler = function(...args) {
		if (hookName === "renderChunk") injectChunkMetadata(chunkMetadataMap, args[1], true);
		if (hookName === "augmentChunkHash") injectChunkMetadata(chunkMetadataMap, args[0]);
		if (hookName === "generateBundle" || hookName === "writeBundle") {
			const bundle = args[1];
			for (const chunk of Object.values(bundle)) injectChunkMetadata(chunkMetadataMap, chunk);
		}
		return fn.call(injectEnvironmentInContext(this, environment), ...args);
	};
	if ("handler" in hook) return wrapHookObject(hook, handler);
	else return handler;
}
function injectChunkMetadata(chunkMetadataMap, chunk, resetChunkMetadata = false) {
	if (resetChunkMetadata) chunkMetadataMap.reset(chunk);
	Object.defineProperty(chunk, "viteMetadata", {
		value: chunkMetadataMap.get(chunk),
		enumerable: true
	});
	if (chunk.type === "chunk") Object.defineProperty(chunk, "modules", {
		get() {
			return chunk.viteMetadata.__modules;
		},
		enumerable: true
	});
}
function injectEnvironmentInContext(context, environment) {
	context.meta.viteVersion ??= VERSION;
	context.environment ??= environment;
	return context;
}
function injectSsrFlag(options, environment, pluginName) {
	let ssr = environment.config.consumer === "server";
	const newOptions = {
		...options ?? {},
		ssr
	};
	if (isFutureDeprecationEnabled(environment?.getTopLevelConfig(), "removePluginHookSsrArgument")) Object.defineProperty(newOptions, "ssr", {
		get() {
			warnFutureDeprecation(environment?.getTopLevelConfig(), "removePluginHookSsrArgument", `Used in plugin "${pluginName}".`);
			return ssr;
		},
		set(v) {
			ssr = v;
		}
	});
	return newOptions;
}
const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
const backSlashRegEx = /\\/g;
function escapeId(id) {
	if (!needsEscapeRegEx.test(id)) return id;
	return id.replace(backSlashRegEx, "\\\\").replace(quoteNewlineRegEx, "\\$1");
}
const getResolveUrl = (path, URL = "URL") => `new ${URL}(${path}).href`;
const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ""}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
const customRelativeUrlMechanisms = {
	cjs: (relativePath) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
	es: (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
	iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
	umd: (relativePath) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`,
	"worker-iife": (relativePath) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
};
function toOutputFilePathInJS(environment, filename, type, hostId, hostType, toRelative) {
	const { experimental, base, decodedBase } = environment.config;
	const ssr = environment.config.consumer === "server";
	const { renderBuiltUrl } = experimental;
	let relative = base === "" || base === "./";
	if (renderBuiltUrl) {
		const result = renderBuiltUrl(filename, {
			hostId,
			hostType,
			type,
			ssr
		});
		if (typeof result === "object") {
			if (result.runtime) return { runtime: result.runtime };
			if (typeof result.relative === "boolean") relative = result.relative;
		} else if (result) return result;
	}
	if (relative && !ssr) return toRelative(filename, hostId);
	return joinUrlSegments(decodedBase, filename);
}
function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
	const toRelativePath = customRelativeUrlMechanisms[isWorker && format === "iife" ? "worker-iife" : format];
	return (filename, importer) => ({ runtime: toRelativePath(path.posix.relative(path.dirname(importer), filename)) });
}
function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
	const { renderBuiltUrl } = config.experimental;
	let relative = config.base === "" || config.base === "./";
	if (renderBuiltUrl) {
		const result = renderBuiltUrl(filename, {
			hostId,
			hostType,
			type,
			ssr: !!config.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") relative = result.relative;
		} else if (result) return result;
	}
	if (relative && !config.build.ssr) return toRelative(filename, hostId);
	else return joinUrlSegments(config.decodedBase, filename);
}
const toOutputFilePathInCss = toOutputFilePathWithoutRuntime;
const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
var BuildEnvironment = class extends BaseEnvironment {
	mode = "build";
	isBuilt = false;
	constructor(name, config, setup) {
		let options = config.environments[name];
		if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
		if (setup?.options) options = mergeConfig(options, setup.options);
		super(name, config, options);
	}
	async init() {
		if (this._initiated) return;
		this._initiated = true;
	}
};
const _builderOptionsDefaults = Object.freeze({
	sharedConfigBuild: false,
	sharedPlugins: false
});
const builderOptionsDefaults = _builderOptionsDefaults;
function resolveBuilderOptions(options) {
	if (!options) return;
	return mergeWithDefaults({
		..._builderOptionsDefaults,
		buildApp: async () => {}
	}, options);
}
/**
* Creates a ViteBuilder to orchestrate building multiple environments.
* @experimental
*/
async function createBuilder(inlineConfig = {}, useLegacyBuilder = false) {
	const patchConfig = (resolved) => {
		if (!(useLegacyBuilder ?? !resolved.builder)) return;
		resolved.build = { ...resolved.environments[resolved.build.ssr ? "ssr" : "client"].build };
	};
	const config = await resolveConfigToBuild(inlineConfig, patchConfig);
	useLegacyBuilder ??= !config.builder;
	const configBuilder = config.builder ?? resolveBuilderOptions({});
	const environments = {};
	const builder = {
		environments,
		config,
		async buildApp() {
			const pluginContext = new BasicMinimalPluginContext({
				...basePluginContextMeta,
				watchMode: false
			}, config.logger);
			let configBuilderBuildAppCalled = false;
			for (const p of config.getSortedPlugins("buildApp")) {
				const hook = p.buildApp;
				if (!configBuilderBuildAppCalled && typeof hook === "object" && hook.order === "post") {
					configBuilderBuildAppCalled = true;
					await configBuilder.buildApp(builder);
				}
				await getHookHandler(hook).call(pluginContext, builder);
			}
			if (!configBuilderBuildAppCalled) await configBuilder.buildApp(builder);
			if (Object.values(builder.environments).every((environment) => !environment.isBuilt)) for (const environment of Object.values(builder.environments)) await builder.build(environment);
		},
		async build(environment) {
			const output = await buildEnvironment(environment);
			environment.isBuilt = true;
			return output;
		},
		async runDevTools() {
			if (config.devtools.enabled) try {
				const { runDevTools } = await import("@vitejs/devtools/integration");
				await runDevTools(builder);
			} catch (e) {
				config.logger.error(import_picocolors.default.red(`Failed to run Vite DevTools: ${e?.message || e?.stack}`), { error: e });
			}
		}
	};
	async function setupEnvironment(name, config) {
		const environment = await config.build.createEnvironment(name, config);
		await environment.init();
		environments[name] = environment;
	}
	if (useLegacyBuilder) await setupEnvironment(config.build.ssr ? "ssr" : "client", config);
	else {
		const environmentConfigs = [];
		for (const environmentName of Object.keys(config.environments)) {
			let environmentConfig = config;
			if (!configBuilder.sharedConfigBuild) {
				const patchConfig = (resolved) => {
					resolved.build = { ...resolved.environments[environmentName].build };
				};
				const patchPlugins = (resolvedPlugins) => {
					let j = 0;
					for (let i = 0; i < resolvedPlugins.length; i++) {
						const environmentPlugin = resolvedPlugins[i];
						if (configBuilder.sharedPlugins || environmentPlugin.sharedDuringBuild) {
							for (let k = j; k < config.plugins.length; k++) if (environmentPlugin.name === config.plugins[k].name) {
								resolvedPlugins[i] = config.plugins[k];
								j = k + 1;
								break;
							}
						}
					}
				};
				environmentConfig = await resolveConfigToBuild(inlineConfig, patchConfig, patchPlugins);
			}
			environmentConfigs.push([environmentName, environmentConfig]);
		}
		await Promise.all(environmentConfigs.map(async ([environmentName, environmentConfig]) => await setupEnvironment(environmentName, environmentConfig)));
	}
	return builder;
}
//#endregion
//#region src/node/ssr/fetchModule.ts
/**
* Fetch module information for Vite module runner.
* @experimental
*/
async function fetchModule(environment, url, importer, options = {}) {
	if (url.startsWith("data:") || isBuiltin(environment.config.resolve.builtins, url)) return {
		externalize: url,
		type: "builtin"
	};
	const isFileUrl = url.startsWith("file://");
	if (isExternalUrl(url) && !isFileUrl) return {
		externalize: url,
		type: "network"
	};
	if (!isFileUrl && importer && url[0] !== "." && url[0] !== "/") {
		const { isProduction, root } = environment.config;
		const { externalConditions, dedupe, preserveSymlinks } = environment.config.resolve;
		const resolved = tryNodeResolve(url, importer, {
			mainFields: ["main"],
			conditions: externalConditions,
			externalConditions,
			external: [],
			noExternal: [],
			extensions: [
				".js",
				".cjs",
				".json"
			],
			dedupe,
			preserveSymlinks,
			tsconfigPaths: false,
			isBuild: false,
			isProduction,
			root,
			packageCache: environment.config.packageCache,
			builtins: environment.config.resolve.builtins
		});
		if (!resolved) {
			const err = /* @__PURE__ */ new Error(`Cannot find module '${url}' imported from '${importer}'`);
			err.code = "ERR_MODULE_NOT_FOUND";
			throw err;
		}
		return {
			externalize: pathToFileURL(resolved.id).toString(),
			type: isFilePathESM(resolved.id, environment.config.packageCache) ? "module" : "commonjs"
		};
	}
	url = unwrapId(url);
	const mod = await environment.moduleGraph.ensureEntryFromUrl(url);
	const cached = !!mod.transformResult;
	if (options.cached && cached) return { cache: true };
	let result = await environment.transformRequest(url);
	if (!result) throw new Error(`[vite] transform failed for module '${url}'${importer ? ` imported from '${importer}'` : ""}.`);
	if (options.inlineSourceMap !== false) result = inlineSourceMap(mod, result, options.startOffset);
	if (result.code[0] === "#") result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length));
	return {
		code: result.code,
		file: mod.file,
		id: mod.id,
		url: mod.url,
		invalidate: !cached
	};
}
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
function inlineSourceMap(mod, result, startOffset) {
	const map = result.map;
	let code = result.code;
	if (!map || !("version" in map) || code.includes("//# sourceMappingSource=vite-generated")) return result;
	OTHER_SOURCE_MAP_REGEXP.lastIndex = 0;
	if (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
	const sourceMap = startOffset ? Object.assign({}, map, { mappings: ";".repeat(startOffset) + map.mappings }) : map;
	result.code = `${code.trimEnd()}\n//# sourceURL=${mod.id}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`;
	return result;
}
//#endregion
//#region src/node/optimizer/optimizer.ts
const debug$2 = createDebugger("vite:deps");
/**
* The amount to wait for requests to register newly found dependencies before triggering
* a re-bundle + page reload
*/
const debounceMs = 100;
function createDepsOptimizer(environment) {
	const { logger } = environment;
	const sessionTimestamp = Date.now().toString();
	let debounceProcessingHandle;
	let closed = false;
	const options = environment.config.optimizeDeps;
	const { noDiscovery, holdUntilCrawlEnd } = options;
	let metadata = initDepsOptimizerMetadata(environment, sessionTimestamp);
	const depsOptimizer = {
		init,
		metadata,
		registerMissingImport,
		run: () => debouncedProcessing(0),
		isOptimizedDepFile: createIsOptimizedDepFile(environment),
		isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
		getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
		close,
		options
	};
	let newDepsDiscovered = false;
	let newDepsToLog = [];
	let newDepsToLogHandle;
	const logNewlyDiscoveredDeps = () => {
		if (newDepsToLog.length) {
			logger.info(import_picocolors.default.green(`${newDepsToLog.length === 1 ? "dependency" : "dependencies"} optimized: ${depsLogString(newDepsToLog)}`), { timestamp: true });
			newDepsToLog = [];
		}
	};
	let discoveredDepsWhileScanning = [];
	const logOptimizeDepsIncludeSuggestion = (reason) => {
		if (discoveredDepsWhileScanning.length) {
			logger.info(import_picocolors.default.magenta(`tip: consider adding ${depsLogString(discoveredDepsWhileScanning)} to optimizeDeps.include to ${reason}`) + import_picocolors.default.dim(`\n  See https://vite.dev/guide/dep-pre-bundling.html#customizing-the-behavior`), { 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 = false;
	let warnAboutMissedDependencies = false;
	let waitingForCrawlEnd = false;
	let optimizationResult;
	let discover;
	async function close() {
		closed = true;
		await Promise.allSettled([
			discover?.cancel(),
			depsOptimizer.scanProcessing,
			optimizationResult?.cancel()
		]);
	}
	let inited = false;
	async function init() {
		if (inited) return;
		inited = true;
		const cachedMetadata = await loadCachedDepOptimizationMetadata(environment);
		firstRunCalled = !!cachedMetadata;
		metadata = depsOptimizer.metadata = cachedMetadata || initDepsOptimizerMetadata(environment, sessionTimestamp);
		if (!cachedMetadata) {
			waitingForCrawlEnd = true;
			currentlyProcessing = true;
			const manuallyIncludedDeps = {};
			await addManuallyIncludedOptimizeDeps(environment, manuallyIncludedDeps);
			const manuallyIncludedDepsInfo = toDiscoveredDependencies(environment, manuallyIncludedDeps, sessionTimestamp);
			for (const depInfo of Object.values(manuallyIncludedDepsInfo)) {
				addOptimizedDepInfo(metadata, "discovered", {
					...depInfo,
					processing: depOptimizationProcessing.promise
				});
				newDepsDiscovered = true;
			}
			environment.waitForRequestsIdle().then(onCrawlEnd);
			if (noDiscovery) runOptimizer();
			else depsOptimizer.scanProcessing = new Promise((resolve) => {
				(async () => {
					try {
						debug$2?.(import_picocolors.default.green(`scanning for dependencies...`));
						const scanTimer = setTimeout(() => {
							logger.info("[optimizer] scanning dependencies...", { timestamp: true });
						}, 1e3);
						let deps;
						try {
							discover = discoverProjectDependencies(devToScanEnvironment(environment));
							deps = await discover.result;
							discover = void 0;
						} catch (e) {
							environment.logger.error(import_picocolors.default.red("(!) Failed to run dependency scan. Skipping dependency pre-bundling. " + e.stack));
							return;
						} finally {
							clearTimeout(scanTimer);
						}
						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(environment, knownDeps);
						if (!holdUntilCrawlEnd) optimizationResult.result.then((result) => {
							if (!waitingForCrawlEnd) return;
							optimizationResult = void 0;
							runOptimizer(result);
						});
					} catch (e) {
						logger.error(e.stack || e.message);
					} finally {
						resolve();
						depsOptimizer.scanProcessing = void 0;
					}
				})();
			});
		}
	}
	function startNextDiscoveredBatch() {
		newDepsDiscovered = false;
		depOptimizationProcessingQueue.push(depOptimizationProcessing);
		depOptimizationProcessing = promiseWithResolvers();
	}
	function prepareKnownDeps() {
		const knownDeps = {};
		const metadata = depsOptimizer.metadata;
		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;
			depOptimizationProcessing.resolve();
			resolveEnqueuedProcessingPromises();
			return;
		}
		currentlyProcessing = true;
		try {
			let processingResult;
			if (preRunResult) processingResult = preRunResult;
			else {
				const knownDeps = prepareKnownDeps();
				startNextDiscoveredBatch();
				optimizationResult = runOptimizeDeps(environment, knownDeps);
				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 o in newData.optimized) {
					const discovered = metadata.discovered[o];
					if (discovered) {
						const optimized = newData.optimized[o];
						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$2) {
					if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
					newDepsToLogHandle = setTimeout(() => {
						newDepsToLogHandle = void 0;
						logNewlyDiscoveredDeps();
						if (warnAboutMissedDependencies) {
							logOptimizeDepsIncludeSuggestion("speed up cold start");
							warnAboutMissedDependencies = false;
						}
					}, 2 * debounceMs);
				} else debug$2(import_picocolors.default.green(!isRerun ? `dependencies optimized` : `optimized dependencies unchanged`));
			} else if (newDepsDiscovered) {
				processingResult.cancel();
				debug$2?.(import_picocolors.default.green(`delaying reload as new dependencies have been found...`));
			} else {
				await commitProcessing();
				if (!debug$2) {
					if (newDepsToLogHandle) clearTimeout(newDepsToLogHandle);
					newDepsToLogHandle = void 0;
					logNewlyDiscoveredDeps();
					if (warnAboutMissedDependencies) {
						logOptimizeDepsIncludeSuggestion("avoid a full page reload during cold start");
						warnAboutMissedDependencies = false;
					}
				}
				logger.info(import_picocolors.default.green(`optimized dependencies changed. reloading`), { timestamp: true });
				if (needsInteropMismatch.length > 0) logger.warn(`Mixed ESM and CJS detected in ${import_picocolors.default.yellow(needsInteropMismatch.join(", "))}, add ${needsInteropMismatch.length === 1 ? "it" : "them"} to optimizeDeps.needsInterop to speed up cold start`, { timestamp: true });
				fullReload();
			}
		} catch (e) {
			logger.error(import_picocolors.default.red(`error while updating dependencies:\n${e.stack}`), {
				timestamp: true,
				error: e
			});
			resolveEnqueuedProcessingPromises();
			metadata.discovered = {};
		}
		currentlyProcessing = false;
		enqueuedRerun?.();
	}
	function fullReload() {
		environment.moduleGraph.invalidateAll();
		environment.hot.send({
			type: "full-reload",
			path: "*"
		});
	}
	function rerun() {
		const depsString = depsLogString(Object.keys(metadata.discovered));
		debug$2?.(import_picocolors.default.green(`new dependencies found: ${depsString}`));
		runOptimizer();
	}
	function getDiscoveredBrowserHash(hash, deps, missing) {
		return getHash(hash + 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(environment, id),
			src: resolved,
			browserHash: getDiscoveredBrowserHash(metadata.hash, depsFromOptimizedDepInfo(metadata.optimized), depsFromOptimizedDepInfo(metadata.discovered)),
			processing: depOptimizationProcessing.promise,
			exportsData: extractExportsData(environment, resolved)
		});
	}
	function debouncedProcessing(timeout = 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();
		}, timeout);
	}
	async function onCrawlEnd() {
		waitingForCrawlEnd = false;
		debug$2?.(import_picocolors.default.green(`static imports crawl ended`));
		if (closed) return;
		await depsOptimizer.scanProcessing;
		if (optimizationResult && !options.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$2?.(import_picocolors.default.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));
			if (needsInteropMismatch.length > 0 || scannerMissedDeps) {
				result.cancel();
				for (const dep of scanDeps) if (!crawlDeps.includes(dep)) addMissingDep(dep, result.metadata.optimized[dep].src);
				if (scannerMissedDeps) debug$2?.(import_picocolors.default.yellow(`new dependencies were found while crawling that weren't detected by the scanner`));
				debug$2?.(import_picocolors.default.green(`re-running optimizer`));
				debouncedProcessing(0);
			} else {
				debug$2?.(import_picocolors.default.green(`using post-scan optimizer result, the scanner found every used dependency`));
				startNextDiscoveredBatch();
				runOptimizer(result);
			}
		} else if (!holdUntilCrawlEnd) {
			if (newDepsDiscovered) {
				debug$2?.(import_picocolors.default.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$2?.(import_picocolors.default.green(`no dependencies found while crawling the static imports`));
				firstRunCalled = true;
			}
			debouncedProcessing(0);
		}
	}
	return depsOptimizer;
}
function createExplicitDepsOptimizer(environment) {
	const depsOptimizer = {
		metadata: initDepsOptimizerMetadata(environment),
		isOptimizedDepFile: createIsOptimizedDepFile(environment),
		isOptimizedDepUrl: createIsOptimizedDepUrl(environment),
		getOptimizedDepId: (depInfo) => `${depInfo.file}?v=${depInfo.browserHash}`,
		registerMissingImport: () => {
			throw new Error(`Vite Internal Error: registerMissingImport is not supported in dev ${environment.name}`);
		},
		init,
		run: () => {},
		close: async () => {},
		options: environment.config.optimizeDeps
	};
	let inited = false;
	async function init() {
		if (inited) return;
		inited = true;
		depsOptimizer.metadata = await optimizeExplicitEnvironmentDeps(environment);
	}
	return 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$2?.(import_picocolors.default.cyan(`needsInterop mismatch detected for ${dep}`));
		}
	}
	return needsInteropMismatch;
}
//#endregion
//#region src/node/server/moduleGraph.ts
var EnvironmentModuleNode = class {
	environment;
	/**
	* Public served url path, starts with /
	*/
	url;
	/**
	* Resolved file system path + query
	*/
	id = null;
	file = null;
	type;
	info;
	meta;
	importers = /* @__PURE__ */ new Set();
	importedModules = /* @__PURE__ */ new Set();
	acceptedHmrDeps = /* @__PURE__ */ new Set();
	acceptedHmrExports = null;
	importedBindings = null;
	isSelfAccepting;
	transformResult = null;
	ssrModule = null;
	ssrError = null;
	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
	*/
	lastHMRInvalidationReceived = false;
	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
	*/
	invalidationState;
	/**
	* 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
	*/
	staticImportedUrls;
	/**
	* @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870
	*/
	constructor(url, environment, setIsSelfAccepting = true) {
		this.environment = environment;
		this.url = url;
		this.type = isDirectCSSRequest(url) ? "css" : "js";
		if (setIsSelfAccepting) this.isSelfAccepting = false;
	}
};
var EnvironmentModuleGraph = class {
	environment;
	urlToModuleMap = /* @__PURE__ */ new Map();
	idToModuleMap = /* @__PURE__ */ new Map();
	etagToModuleMap = /* @__PURE__ */ new Map();
	fileToModulesMap = /* @__PURE__ */ new Map();
	/**
	* @internal
	*/
	_unresolvedUrlToModuleMap = /* @__PURE__ */ new Map();
	/**
	* @internal
	*/
	_resolveId;
	/** @internal */
	_hasResolveFailedErrorModules = /* @__PURE__ */ new Set();
	constructor(environment, resolveId) {
		this.environment = environment;
		this._resolveId = resolveId;
	}
	async getModuleByUrl(rawUrl) {
		rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
		const mod = this._getUnresolvedUrlToModule(rawUrl);
		if (mod) return mod;
		const [url] = await this._resolveUrl(rawUrl);
		return this.urlToModuleMap.get(url);
	}
	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 seen = /* @__PURE__ */ new Set();
			mods.forEach((mod) => {
				this.invalidateModule(mod, seen);
			});
		}
	}
	onFileDelete(file) {
		const mods = this.getModulesByFile(file);
		if (mods) mods.forEach((mod) => {
			mod.importedModules.forEach((importedMod) => {
				importedMod.importers.delete(mod);
			});
		});
	}
	invalidateModule(mod, seen = /* @__PURE__ */ new Set(), timestamp = monotonicDateNow(), isHmr = false, softInvalidate = false) {
		const prevInvalidationState = mod.invalidationState;
		if (softInvalidate) mod.invalidationState ??= mod.transformResult ?? "HARD_INVALIDATED";
		else mod.invalidationState = "HARD_INVALIDATED";
		if (seen.has(mod) && prevInvalidationState === mod.invalidationState) return;
		seen.add(mod);
		if (isHmr) {
			mod.lastHMRTimestamp = timestamp;
			mod.lastHMRInvalidationReceived = false;
		} else mod.lastInvalidationTimestamp = timestamp;
		const etag = mod.transformResult?.etag;
		if (etag) this.etagToModuleMap.delete(etag);
		mod.transformResult = null;
		mod.ssrModule = null;
		mod.ssrError = null;
		mod.importers.forEach((importer) => {
			if (!importer.acceptedHmrDeps.has(mod)) {
				const shouldSoftInvalidateImporter = (importer.staticImportedUrls?.has(mod.url) || softInvalidate) && importer.type === "js";
				this.invalidateModule(importer, seen, timestamp, isHmr, shouldSoftInvalidateImporter);
			}
		});
		this._hasResolveFailedErrorModules.delete(mod);
	}
	invalidateAll() {
		const timestamp = monotonicDateNow();
		const seen = /* @__PURE__ */ new Set();
		this.idToModuleMap.forEach((mod) => {
			this.invalidateModule(mod, seen, timestamp);
		});
	}
	/**
	* 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, staticImportedUrls) {
		mod.isSelfAccepting = isSelfAccepting;
		const prevImports = mod.importedModules;
		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).then((dep) => {
				dep.importers.add(mod);
				resolveResults[nextIndex] = dep;
			}));
			else {
				imported.importers.add(mod);
				resolveResults[nextIndex] = imported;
			}
		}
		if (resolvePromises.length) await Promise.all(resolvePromises);
		mod.importedModules = new Set(resolveResults);
		prevImports.forEach((dep) => {
			if (!mod.importedModules.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).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, setIsSelfAccepting = true) {
		return this._ensureEntryFromUrl(rawUrl, setIsSelfAccepting);
	}
	/**
	* @internal
	*/
	async _ensureEntryFromUrl(rawUrl, setIsSelfAccepting = true, resolved) {
		rawUrl = removeImportQuery(removeTimestampQuery(rawUrl));
		let mod = this._getUnresolvedUrlToModule(rawUrl);
		if (mod) return mod;
		const modPromise = (async () => {
			const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, resolved);
			mod = this.idToModuleMap.get(resolvedId);
			if (!mod) {
				mod = new EnvironmentModuleNode(url, this.environment, setIsSelfAccepting);
				if (meta) mod.meta = meta;
				this.urlToModuleMap.set(url, 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(url)) this.urlToModuleMap.set(url, mod);
			this._setUnresolvedUrlToModule(rawUrl, mod);
			return mod;
		})();
		this._setUnresolvedUrlToModule(rawUrl, modPromise);
		return modPromise;
	}
	createFileOnlyEntry(file) {
		file = normalizePath(file);
		let fileMappedModules = this.fileToModulesMap.get(file);
		if (!fileMappedModules) {
			fileMappedModules = /* @__PURE__ */ new Set();
			this.fileToModulesMap.set(file, fileMappedModules);
		}
		const url = `${FS_PREFIX}${file}`;
		for (const m of fileMappedModules) if ((m.url === url || m.id === file) && m.type === "asset") return m;
		const mod = new EnvironmentModuleNode(url, this.environment);
		mod.type = "asset";
		mod.file = file;
		fileMappedModules.add(mod);
		return mod;
	}
	async resolveUrl(url) {
		url = removeImportQuery(removeTimestampQuery(url));
		const mod = await this._getUnresolvedUrlToModule(url);
		if (mod?.id) return [
			mod.url,
			mod.id,
			mod.meta
		];
		return this._resolveUrl(url);
	}
	updateModuleTransformResult(mod, result) {
		if (this.environment === "client") {
			const prevEtag = mod.transformResult?.etag;
			if (prevEtag) this.etagToModuleMap.delete(prevEtag);
			if (result?.etag) this.etagToModuleMap.set(result.etag, mod);
		}
		mod.transformResult = result;
	}
	getModuleByEtag(etag) {
		return this.etagToModuleMap.get(etag);
	}
	/**
	* @internal
	*/
	_getUnresolvedUrlToModule(url) {
		return this._unresolvedUrlToModuleMap.get(url);
	}
	/**
	* @internal
	*/
	_setUnresolvedUrlToModule(url, mod) {
		this._unresolvedUrlToModuleMap.set(url, mod);
	}
	/**
	* @internal
	*/
	async _resolveUrl(url, alreadyResolved) {
		const resolved = alreadyResolved ?? await this._resolveId(url);
		const resolvedId = resolved?.id || url;
		if (url !== resolvedId && !url.includes("\0") && !url.startsWith(`virtual:`)) {
			const ext = extname(cleanUrl(resolvedId));
			if (ext) {
				const pathname = cleanUrl(url);
				if (!pathname.endsWith(ext)) url = pathname + ext + url.slice(pathname.length);
			}
		}
		return [
			url,
			resolvedId,
			resolved?.meta
		];
	}
};
//#endregion
//#region src/node/server/warmup.ts
function warmupFiles(server, environment) {
	const { root } = server.config;
	mapFiles(environment.config.dev.warmup, root).then((files) => {
		for (const file of files) warmupFile(server, environment, file);
	});
}
async function warmupFile(server, environment, file) {
	if (file.endsWith(".html")) {
		const url = htmlFileToUrl(file, server.config.root);
		if (url) try {
			const html = await fsp.readFile(file, "utf-8");
			await server.transformIndexHtml(url, html);
		} catch (e) {
			environment.logger.error(`Pre-transform error (${import_picocolors.default.cyan(file)}): ${e.message}`, {
				error: e,
				timestamp: true
			});
		}
	} else {
		const url = fileToUrl(file, server.config.root);
		await environment.warmupRequest(url);
	}
}
function htmlFileToUrl(file, root) {
	const url = path.relative(root, file);
	if (url[0] === ".") return;
	return "/" + normalizePath(url);
}
function fileToUrl(file, root) {
	const url = path.relative(root, file);
	if (url[0] === ".") return path.posix.join(FS_PREFIX, normalizePath(file));
	return "/" + normalizePath(url);
}
async function mapFiles(files, root) {
	if (!files.length) return [];
	const result = [];
	const globs = [];
	for (const file of files) if (isDynamicPattern(file)) globs.push(file);
	else if (path.isAbsolute(file)) result.push(file);
	else result.push(path.resolve(root, file));
	if (globs.length) result.push(...await glob(globs, {
		absolute: true,
		cwd: root,
		expandDirectories: false,
		ignore: ["**/.git/**", "**/node_modules/**"]
	}));
	return result;
}
//#endregion
//#region src/node/server/bundledDev.ts
const debug$1 = createDebugger("vite:full-bundle-mode");
var MemoryFiles = class {
	files = /* @__PURE__ */ new Map();
	get size() {
		return this.files.size;
	}
	get(file) {
		const result = this.files.get(file);
		if (result === void 0) return;
		if (typeof result === "function") {
			const content = result();
			this.files.set(file, content);
			return content;
		}
		return result;
	}
	set(file, content) {
		this.files.set(file, content);
	}
	has(file) {
		return this.files.has(file);
	}
	clear() {
		this.files.clear();
	}
};
var BundledDev = class {
	environment;
	_devEngine;
	initialBuildCompleted = false;
	clients = new Clients();
	invalidateCalledModules = /* @__PURE__ */ new Map();
	debouncedFullReload = debounce(20, () => {
		this.environment.hot.send({
			type: "full-reload",
			path: "*"
		});
		this.environment.logger.info(import_picocolors.default.green(`page reload`), { timestamp: true });
	});
	fullReloadPending = false;
	lastBuildError = null;
	memoryFiles = new MemoryFiles();
	constructor(environment) {
		this.environment = environment;
		if (environment.name !== "client") throw new Error("currently full bundle mode is only available for client environment");
	}
	get devEngine() {
		if (!this._devEngine) throw new Error(`dev engine was not yet initialized`);
		return this._devEngine;
	}
	async listen() {
		debug$1?.("INITIAL: setup bundle options");
		const rolldownOptions = await this.getRolldownOptions();
		if (Array.isArray(rolldownOptions.output) && rolldownOptions.output.length > 1) throw new Error("multiple output options are not supported in dev mode");
		const outputOptions = Array.isArray(rolldownOptions.output) ? rolldownOptions.output[0] : rolldownOptions.output;
		this.environment.hot.on("vite:module-loaded", (payload, client) => {
			this.clients.setupIfNeeded(client, payload.clientId);
			this.devEngine.registerModules(payload.clientId, payload.modules);
		});
		this.environment.hot.on("vite:client:connect", (_payload, client) => {
			if (this.lastBuildError) {
				debug$1?.("REPLAY: replaying last build error to newly connected client");
				client.send({
					type: "error",
					err: prepareError(this.lastBuildError)
				});
			}
		});
		this.environment.hot.on("vite:client:disconnect", (_payload, client) => {
			const clientId = this.clients.delete(client);
			if (clientId) this.devEngine.removeClient(clientId);
		});
		this._devEngine = await dev(rolldownOptions, outputOptions, {
			onHmrUpdates: (result) => {
				if (result instanceof Error) {
					for (const client of this.clients.getAll()) client.send({
						type: "error",
						err: prepareError(result)
					});
					return;
				}
				const { updates, changedFiles } = result;
				if (changedFiles.length === 0) return;
				if (updates.every((update) => update.update.type === "Noop")) {
					debug$1?.(`ignored file change for ${changedFiles.join(", ")}`);
					return;
				}
				for (const { clientId, update } of updates) {
					const client = this.clients.get(clientId);
					if (client) {
						this.invalidateCalledModules.get(client)?.clear();
						this.handleHmrOutput(client, changedFiles, update);
					}
				}
			},
			onOutput: (result) => {
				if (result instanceof Error) {
					this.environment.logger.error(import_picocolors.default.red(`✘ Build error: ${result.message}`), { error: result });
					this.lastBuildError = result;
					this.fullReloadPending = false;
					this.environment.hot.send({
						type: "error",
						err: prepareError(result)
					});
					return;
				}
				this.lastBuildError = null;
				this.storeOutputFiles(result.output);
				if (this.fullReloadPending) {
					this.fullReloadPending = false;
					this.debouncedFullReload();
				}
			},
			onAdditionalAssets: (result) => {
				this.storeOutputFiles(result.output);
			},
			watch: { skipWrite: true }
		});
		debug$1?.("INITIAL: setup dev engine");
		this.devEngine.run().then(() => {
			debug$1?.("INITIAL: run done");
		}, (e) => {
			debug$1?.("INITIAL: run error", e);
		});
		this.waitForInitialBuildFinish().then(() => {
			debug$1?.("INITIAL: build done");
			this.environment.hot.send({
				type: "full-reload",
				path: "*"
			});
			this.initialBuildCompleted = true;
		});
	}
	async waitForInitialBuildFinish() {
		await this.devEngine.ensureCurrentBuildFinish();
		let state = await this.devEngine.getBundleState();
		while (this.memoryFiles.size === 0 && !state.lastBuildErrored) {
			await setTimeout$1(10);
			await this.devEngine.ensureCurrentBuildFinish();
			state = await this.devEngine.getBundleState();
		}
	}
	async invalidateModule(m, client) {
		const invalidateCalledModules = this.invalidateCalledModules.get(client);
		if (invalidateCalledModules?.has(m.path)) {
			debug$1?.(`INVALIDATE: invalidate received from ${m.path}, but ignored because it was already invalidated`);
			return;
		}
		debug$1?.(`INVALIDATE: invalidate received from ${m.path}, re-triggering HMR`);
		if (!invalidateCalledModules) this.invalidateCalledModules.set(client, /* @__PURE__ */ new Set([]));
		this.invalidateCalledModules.get(client).add(m.path);
		let update;
		try {
			update = (await this.devEngine.invalidate(m.path, m.firstInvalidatedBy)).find((u) => this.clients.get(u.clientId) === client)?.update;
		} catch (e) {
			client.send({
				type: "error",
				err: prepareError(e)
			});
			return;
		}
		if (!update) return;
		if (update.type === "Patch") this.environment.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
		this.handleHmrOutput(client, [m.path], update, { firstInvalidatedBy: m.firstInvalidatedBy });
	}
	async triggerBundleRegenerationIfStale() {
		const bundleState = await this.devEngine.getBundleState();
		if (this.initialBuildCompleted && bundleState.lastBuildErrored && bundleState.lastErrorStage === "Hmr") {
			debug$1?.(`TRIGGER: access after HMR-stage failure, forcing full rebuild`);
			this.devEngine.triggerFullBuild();
			this.devEngine.ensureLatestBuildOutput().then(() => {
				this.debouncedFullReload();
			});
			return true;
		}
		const shouldTrigger = bundleState.hasStaleOutput && !bundleState.lastBuildErrored && this.initialBuildCompleted;
		if (shouldTrigger) {
			this.devEngine.ensureLatestBuildOutput().then(() => {
				this.debouncedFullReload();
			});
			debug$1?.(`TRIGGER: access to stale bundle, triggered bundle re-generation`);
		}
		return shouldTrigger;
	}
	async triggerLazyBundling(moduleId, clientId) {
		if (!moduleId || !clientId) return;
		debug$1?.(`TRIGGER-LAZY: trigger lazy bundling for module ${moduleId} for client ${clientId}`);
		return await this.devEngine.compileEntry(moduleId, clientId);
	}
	async close() {
		this.memoryFiles.clear();
		await this._devEngine?.close();
		this.initialBuildCompleted = false;
	}
	storeOutputFiles(output) {
		for (const outputFile of output) this.memoryFiles.set(outputFile.fileName, () => {
			const source = outputFile.type === "chunk" ? outputFile.code : outputFile.source;
			return {
				source,
				etag: (0, import_etag.default)(Buffer.from(source), { weak: true })
			};
		});
	}
	async getRolldownOptions() {
		const chunkMetadataMap = new ChunkMetadataMap();
		const rolldownOptions = resolveRolldownOptions(this.environment, chunkMetadataMap);
		rolldownOptions.experimental ??= {};
		rolldownOptions.experimental.devMode = {
			lazy: true,
			...typeof rolldownOptions.experimental.devMode === "object" ? rolldownOptions.experimental.devMode : {},
			implement: await getHmrImplementation(this.environment.getTopLevelConfig())
		};
		rolldownOptions.optimization ??= {};
		rolldownOptions.optimization.inlineConst = false;
		const plugins = await asyncFlatten([rolldownOptions.plugins]);
		for (const plugin of plugins) {
			const transform = plugin && "transform" in plugin ? plugin.transform : void 0;
			if (!transform) continue;
			const handler = typeof transform === "function" ? transform : transform.handler;
			const wrappedHandler = function(code, id, opts) {
				if (id.includes("?rolldown-lazy=")) return null;
				return handler.call(this, code, id, opts);
			};
			if (typeof transform === "function") plugin.transform = wrappedHandler;
			else transform.handler = wrappedHandler;
		}
		rolldownOptions.plugins = plugins;
		if (Array.isArray(rolldownOptions.output)) for (const output of rolldownOptions.output) {
			output.entryFileNames = "assets/[name].js";
			output.chunkFileNames = "assets/[name]-[hash].js";
			output.assetFileNames = "assets/[name]-[hash][extname]";
			output.minify = false;
			output.sourcemap = true;
		}
		else {
			rolldownOptions.output ??= {};
			rolldownOptions.output.entryFileNames = "assets/[name].js";
			rolldownOptions.output.chunkFileNames = "assets/[name]-[hash].js";
			rolldownOptions.output.assetFileNames = "assets/[name]-[hash][extname]";
			rolldownOptions.output.minify = false;
			rolldownOptions.output.sourcemap = true;
		}
		return rolldownOptions;
	}
	handleHmrOutput(client, files, hmrOutput, invalidateInformation) {
		if (hmrOutput.type === "Noop") return;
		const shortFile = files.map((file) => getShortName(file, this.environment.config.root)).join(", ");
		if (hmrOutput.type === "FullReload") {
			const reason = hmrOutput.reason ? import_picocolors.default.dim(` (${hmrOutput.reason})`) : "";
			this.environment.logger.info(import_picocolors.default.green(`trigger page reload `) + import_picocolors.default.dim(shortFile) + reason, {
				clear: !invalidateInformation,
				timestamp: true
			});
			if (invalidateInformation) this.devEngine.ensureLatestBuildOutput().then(async () => {
				this.debouncedFullReload();
			});
			else this.fullReloadPending = true;
			return;
		}
		debug$1?.(`handle hmr output for ${shortFile}`, {
			...hmrOutput,
			code: typeof hmrOutput.code === "string" ? "[code]" : hmrOutput.code
		});
		this.memoryFiles.set(hmrOutput.filename, { source: hmrOutput.code + "\n; export {}" });
		if (hmrOutput.sourcemapFilename && hmrOutput.sourcemap) this.memoryFiles.set(hmrOutput.sourcemapFilename, { source: hmrOutput.sourcemap });
		const updates = hmrOutput.hmrBoundaries.map((boundary) => {
			return {
				type: "js-update",
				url: hmrOutput.filename,
				path: boundary.boundary,
				acceptedPath: boundary.acceptedVia,
				firstInvalidatedBy: invalidateInformation?.firstInvalidatedBy,
				timestamp: Date.now()
			};
		});
		client.send({
			type: "update",
			updates
		});
		const filePaths = [...new Set(updates.map((u) => u.path))];
		const { formatted, truncated } = formatAndTruncateFileList(filePaths);
		if (truncated) debugHmr?.(`hmr update ${filePaths.join(", ")}`);
		this.environment.logger.info(import_picocolors.default.green(`hmr update `) + import_picocolors.default.dim(formatted), {
			clear: !invalidateInformation,
			timestamp: true
		});
	}
};
var Clients = class {
	clientToId = /* @__PURE__ */ new Map();
	idToClient = /* @__PURE__ */ new Map();
	setupIfNeeded(client, clientId) {
		const id = this.clientToId.get(client);
		if (id && id !== clientId) throw new Error("client ID conflict detected. Please restart the dev server.");
		this.clientToId.set(client, clientId);
		this.idToClient.set(clientId, client);
	}
	get(id) {
		return this.idToClient.get(id);
	}
	getAll() {
		return Array.from(this.idToClient.values());
	}
	delete(client) {
		const id = this.clientToId.get(client);
		if (id) {
			this.clientToId.delete(client);
			this.idToClient.delete(id);
			return id;
		}
	}
};
function debounce(time, cb) {
	let timer;
	return () => {
		if (timer) {
			globalThis.clearTimeout(timer);
			timer = null;
		}
		timer = globalThis.setTimeout(cb, time);
	};
}
//#endregion
//#region src/node/server/environment.ts
var DevEnvironment = class extends BaseEnvironment {
	mode = "dev";
	moduleGraph;
	depsOptimizer;
	/**
	* @internal
	*/
	_remoteRunnerOptions;
	/**
	* @internal
	*/
	_skipFsCheck;
	get pluginContainer() {
		if (!this._pluginContainer) throw new Error(`${this.name} environment.pluginContainer called before initialized`);
		return this._pluginContainer;
	}
	/**
	* @internal
	*/
	_pluginContainer;
	/**
	* @internal
	*/
	_closing = false;
	/**
	* @internal
	*/
	_pendingRequests;
	/**
	* @internal
	*/
	_crawlEndFinder;
	/**
	* Hot channel for this environment. If not provided or disabled,
	* it will be a noop channel that does nothing.
	*
	* @example
	* environment.hot.send({ type: 'full-reload' })
	*/
	hot;
	bundledDev;
	constructor(name, config, context) {
		let options = config.environments[name];
		if (!options) throw new Error(`Environment "${name}" is not defined in the config.`);
		if (context.options) options = mergeConfig(options, context.options);
		super(name, config, options);
		if (options.isBundled || name === "client" && config.experimental.bundledDev) {
			context.disableDepsOptimizer = true;
			this.bundledDev = new BundledDev(this);
		}
		this._pendingRequests = /* @__PURE__ */ new Map();
		this.moduleGraph = new EnvironmentModuleGraph(name, (url) => this.pluginContainer.resolveId(url, void 0));
		this._crawlEndFinder = setupOnCrawlEnd();
		this._remoteRunnerOptions = context.remoteRunner ?? {};
		this._skipFsCheck = !!(context.transport && !(isWebSocketServer in context.transport) && context.transport.skipFsCheck);
		this.hot = context.transport ? isWebSocketServer in context.transport ? context.transport : normalizeHotChannel(context.transport, context.hot) : normalizeHotChannel({}, context.hot);
		this.hot.setInvokeHandler({
			fetchModule: (id, importer, options) => {
				if (context.disableFetchModule) throw new Error("fetchModule is disabled in this environment");
				return this.fetchModule(id, importer, options);
			},
			getBuiltins: async () => {
				return this.config.resolve.builtins.map((builtin) => typeof builtin === "string" ? {
					type: "string",
					value: builtin
				} : {
					type: "RegExp",
					source: builtin.source,
					flags: builtin.flags
				});
			}
		});
		this.hot.on("vite:invalidate", ({ path, message, firstInvalidatedBy }, client) => {
			this.invalidateModule({
				path,
				message,
				firstInvalidatedBy
			}, client);
		});
		if (!context.disableDepsOptimizer) {
			const { optimizeDeps } = this.config;
			if (context.depsOptimizer) this.depsOptimizer = context.depsOptimizer;
			else if (isDepOptimizationDisabled(optimizeDeps)) this.depsOptimizer = void 0;
			else this.depsOptimizer = (optimizeDeps.noDiscovery ? createExplicitDepsOptimizer : createDepsOptimizer)(this);
		}
	}
	async init(options) {
		if (this._initiated) return;
		this._initiated = true;
		this._pluginContainer = await createEnvironmentPluginContainer(this, this.config.plugins, options?.watcher);
	}
	/**
	* When the dev server is restarted, the methods are called in the following order:
	* - new instance `init`
	* - previous instance `close`
	* - new instance `listen`
	*/
	async listen(server) {
		this.hot.listen();
		await Promise.all([this.bundledDev?.listen(), this.depsOptimizer?.init()]);
		warmupFiles(server, this);
	}
	/**
	* Called by the module runner to retrieve information about the specified
	* module. Internally calls `transformRequest` and wraps the result in the
	* format that the module runner understands.
	* This method is not meant to be called manually.
	*/
	fetchModule(id, importer, options) {
		return fetchModule(this, id, importer, {
			...this._remoteRunnerOptions,
			...options
		});
	}
	async reloadModule(module) {
		if (this.config.server.hmr !== false && module.file) updateModules(this, module.file, [module], monotonicDateNow());
	}
	transformRequest(url) {
		return transformRequest(this, url, { skipFsCheck: this._skipFsCheck });
	}
	async warmupRequest(url) {
		if (this.bundledDev) return;
		try {
			await transformRequest(this, url, { skipFsCheck: true });
		} catch (e) {
			if (e?.code === "ERR_OUTDATED_OPTIMIZED_DEP" || e?.code === "ERR_CLOSED_SERVER") return;
			this.logger.error(buildErrorMessage(e, [`Pre-transform error: ${e.message}`], false), {
				error: e,
				timestamp: true
			});
		}
	}
	invalidateModule(m, _client) {
		if (this.bundledDev) {
			this.bundledDev.invalidateModule(m, _client);
			return;
		}
		const mod = this.moduleGraph.urlToModuleMap.get(m.path);
		if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0 && !mod.lastHMRInvalidationReceived) {
			mod.lastHMRInvalidationReceived = true;
			this.logger.info(import_picocolors.default.yellow(`hmr invalidate `) + import_picocolors.default.dim(m.path) + (m.message ? ` ${m.message}` : ""), { timestamp: true });
			const file = getShortName(mod.file, this.config.root);
			updateModules(this, file, [...mod.importers].filter((imp) => imp !== mod), mod.lastHMRTimestamp, m.firstInvalidatedBy);
		}
	}
	async close() {
		this._closing = true;
		this._crawlEndFinder.cancel();
		await Promise.allSettled([
			this.pluginContainer.close(),
			this.bundledDev?.close(),
			this.depsOptimizer?.close(),
			isWebSocketServer in this.hot ? Promise.resolve() : this.hot.close(),
			(async () => {
				while (this._pendingRequests.size > 0) await Promise.allSettled([...this._pendingRequests.values()].map((pending) => pending.request));
			})()
		]);
	}
	/**
	* Calling `await environment.waitForRequestsIdle(id)` will wait until all static imports
	* are processed after the first transformRequest call. If called from a load or transform
	* plugin hook, the id needs to be passed as a parameter to avoid deadlocks.
	* Calling this function after the first static imports section of the module graph has been
	* processed will resolve immediately.
	* @experimental
	*/
	waitForRequestsIdle(ignoredId) {
		return this._crawlEndFinder.waitForRequestsIdle(ignoredId);
	}
	/**
	* @internal
	*/
	_registerRequestProcessing(id, done) {
		this._crawlEndFinder.registerRequestProcessing(id, done);
	}
};
const callCrawlEndIfIdleAfterMs = 50;
function setupOnCrawlEnd() {
	const registeredIds = /* @__PURE__ */ new Set();
	const seenIds = /* @__PURE__ */ new Set();
	const onCrawlEndPromiseWithResolvers = promiseWithResolvers();
	let timeoutHandle;
	let cancelled = false;
	function cancel() {
		cancelled = true;
	}
	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);
		} else checkIfCrawlEndAfterTimeout();
		return onCrawlEndPromiseWithResolvers.promise;
	}
	function markIdAsDone(id) {
		registeredIds.delete(id);
		checkIfCrawlEndAfterTimeout();
	}
	function checkIfCrawlEndAfterTimeout() {
		if (cancelled || registeredIds.size > 0) return;
		if (timeoutHandle) clearTimeout(timeoutHandle);
		timeoutHandle = setTimeout(callOnCrawlEndWhenIdle, callCrawlEndIfIdleAfterMs);
	}
	function callOnCrawlEndWhenIdle() {
		if (cancelled || registeredIds.size > 0) return;
		onCrawlEndPromiseWithResolvers.resolve();
	}
	return {
		registerRequestProcessing,
		waitForRequestsIdle,
		cancel
	};
}
//#endregion
//#region src/node/server/environments/runnableEnvironment.ts
function createRunnableDevEnvironment(name, config, context = {}) {
	if (context.transport == null) context.transport = createServerHotChannel();
	if (context.hot == null) context.hot = true;
	return new RunnableDevEnvironment(name, config, context);
}
function isRunnableDevEnvironment(environment) {
	return environment instanceof RunnableDevEnvironment;
}
var RunnableDevEnvironment = class extends DevEnvironment {
	_runner;
	_runnerFactory;
	_runnerOptions;
	constructor(name, config, context) {
		super(name, config, context);
		this._runnerFactory = context.runner;
		this._runnerOptions = context.runnerOptions;
	}
	get runner() {
		if (this._runner) return this._runner;
		const factory = this._runnerFactory || createServerModuleRunner;
		this._runner = factory(this, this._runnerOptions);
		return this._runner;
	}
	async close() {
		await super.close();
		if (this._runner) await this._runner.close();
	}
};
//#endregion
//#region ../../node_modules/.pnpm/@polka+compression@1.0.0-next.25/node_modules/@polka/compression/build.mjs
const NOOP = () => {};
const MIMES = /text|javascript|\/json|xml/i;
/**
* @param {any} chunk
* @param {BufferEncoding} enc
* @returns {number}
*/
function getChunkSize(chunk, enc) {
	return chunk ? Buffer.byteLength(chunk, enc) : 0;
}
/**
* @param {import('./index.d.mts').Options} [options]
* @returns {import('./index.d.mts').Middleware}
*/
function build_default({ threshold = 1024, level = -1, brotli = false, gzip = true, mimes = MIMES } = {}) {
	const brotliOpts = typeof brotli === "object" && brotli || {};
	const gzipOpts = typeof gzip === "object" && gzip || {};
	if (!zlib.createBrotliCompress) brotli = false;
	return (req, res, next = NOOP) => {
		const accept = req.headers["accept-encoding"] + "";
		const encoding = (brotli && accept.match(/\bbr\b/) || gzip && accept.match(/\bgzip\b/) || [])[0];
		if (req.method === "HEAD" || !encoding) return next();
		/** @type {zlib.Gzip | zlib.BrotliCompress} */
		let compress;
		/** @type {Array<[string, function]>?} */
		let pendingListeners = [];
		let pendingStatus = 0;
		let started = false;
		let size = 0;
		function start() {
			started = true;
			size = res.getHeader("Content-Length") | 0 || size;
			const compressible = mimes.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 = zlib.createBrotliCompress({ params: Object.assign({
					[zlib.constants.BROTLI_PARAM_QUALITY]: level,
					[zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
				}, brotliOpts) });
				else compress = zlib.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(status, reason, headers) {
			if (typeof reason !== "string") [headers, reason] = [reason, headers];
			if (headers) for (let k in headers) res.setHeader(k, headers[k]);
			pendingStatus = status;
			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, listener) {
			if (!pendingListeners) on.call(this, type, listener);
			else if (compress) compress.on(type, listener);
			else pendingListeners.push([type, listener]);
			return this;
		};
		next();
	};
}
//#endregion
//#region src/node/preview.ts
var preview_exports = /* @__PURE__ */ __exportAll({
	preview: () => preview,
	resolvePreviewOptions: () => resolvePreviewOptions
});
function resolvePreviewOptions(preview, server) {
	return {
		port: preview?.port ?? 4173,
		strictPort: preview?.strictPort ?? server.strictPort,
		host: preview?.host ?? server.host,
		allowedHosts: preview?.allowedHosts ?? server.allowedHosts,
		https: preview?.https ?? server.https,
		open: preview?.open ?? server.open,
		proxy: preview?.proxy ?? server.proxy,
		cors: preview?.cors ?? server.cors,
		headers: preview?.headers ?? server.headers
	};
}
/**
* Starts the Vite server in preview mode, to simulate a production deployment
*/
async function preview(inlineConfig = {}) {
	disableCache();
	const config = await resolveConfig(inlineConfig, "serve", "production", "production", true);
	const clientOutDir = config.environments.client.build.outDir;
	const distDir = path.resolve(config.root, clientOutDir);
	if (!fs.existsSync(distDir) && config.plugins.every((plugin) => !plugin.configurePreviewServer) && process.argv[1]?.endsWith(path.normalize("bin/vite.js")) && process.argv[2] === "preview") throw new Error(`The directory "${clientOutDir}" does not exist. Did you build your project?`);
	const httpsOptions = await resolveHttpsConfig(config.preview.https);
	const app = (0, import_connect.default)();
	const httpServer = await resolveHttpServer(app, httpsOptions);
	setClientErrorHandler(httpServer, config.logger);
	const options = config.preview;
	const logger = config.logger;
	const closeHttpServer = createServerCloseFn(httpServer);
	let closeServerPromise;
	const closeServer = async () => {
		teardownSIGTERMListener(closeServerAndExit);
		await closeHttpServer();
		server.resolvedUrls = null;
	};
	const server = {
		config,
		middlewares: app,
		httpServer,
		async close() {
			if (!closeServerPromise) closeServerPromise = closeServer();
			return closeServerPromise;
		},
		resolvedUrls: null,
		printUrls() {
			if (server.resolvedUrls) printServerUrls(server.resolvedUrls, options.host, logger.info);
			else throw new Error("Cannot print server URLs before server is listening.");
		},
		bindCLIShortcuts(options) {
			bindCLIShortcuts(server, options);
		}
	};
	const closeServerAndExit = async (_, exitCode) => {
		try {
			await server.close();
		} finally {
			process.exitCode ??= exitCode ? 128 + exitCode : void 0;
			process.exit();
		}
	};
	setupSIGTERMListener(closeServerAndExit);
	const { cors } = config.preview;
	if (cors !== false) app.use((0, import_lib.default)(typeof cors === "boolean" ? {} : cors));
	const { allowedHosts } = config.preview;
	if (allowedHosts !== true && !config.preview.https) app.use(hostValidationMiddleware(allowedHosts, true));
	const configurePreviewServerContext = new BasicMinimalPluginContext({
		...basePluginContextMeta,
		watchMode: false
	}, config.logger);
	const postHooks = [];
	for (const hook of config.getSortedPluginHooks("configurePreviewServer")) postHooks.push(await hook.call(configurePreviewServerContext, server));
	const { proxy } = config.preview;
	if (proxy) app.use(proxyMiddleware(httpServer, proxy, config));
	app.use(build_default());
	if (config.base !== "/") app.use(baseMiddleware(config.rawBase, false));
	const headers = config.preview.headers;
	const viteAssetMiddleware = (...args) => build_default$1(distDir, {
		etag: true,
		dev: true,
		extensions: [],
		ignores: false,
		setHeaders(res) {
			if (headers) for (const name in headers) res.setHeader(name, headers[name]);
		},
		shouldServe(filePath) {
			return shouldServeFile(filePath, distDir);
		}
	})(...args);
	app.use(viteAssetMiddleware);
	if (config.appType === "spa" || config.appType === "mpa") app.use(htmlFallbackMiddleware(distDir, config.appType === "spa"));
	postHooks.forEach((fn) => fn && fn());
	if (config.appType === "spa" || config.appType === "mpa") {
		const normalizedDistDir = normalizePath(distDir);
		app.use(indexHtmlMiddleware(normalizedDistDir, server));
		app.use(notFoundMiddleware());
	}
	const hostname = await resolveHostname(options.host);
	await httpServerStart(httpServer, {
		port: options.port,
		strictPort: options.strictPort,
		host: hostname.host,
		logger
	});
	server.resolvedUrls = resolveServerUrls(httpServer, config.preview, hostname, httpsOptions, config);
	if (options.open) {
		const url = getServerUrlByHost(server.resolvedUrls, options.host);
		if (url) openBrowser(typeof options.open === "string" ? new URL(options.open, url).href : url, true, logger);
	}
	return server;
}
//#endregion
//#region src/node/ssr/index.ts
const _ssrConfigDefaults = Object.freeze({
	target: "node",
	optimizeDeps: {}
});
const ssrConfigDefaults = _ssrConfigDefaults;
function resolveSSROptions(ssr, preserveSymlinks) {
	return mergeWithDefaults(mergeWithDefaults(_ssrConfigDefaults, { optimizeDeps: { esbuildOptions: { preserveSymlinks } } }), ssr ?? {});
}
//#endregion
//#region src/node/ssr/runnerImport.ts
/**
* Import any file using the default Vite environment.
* @experimental
*/
async function runnerImport(moduleId, inlineConfig) {
	const isModuleSyncConditionEnabled = (await import("#module-sync-enabled")).default;
	const environment = createRunnableDevEnvironment("inline", await resolveConfig(mergeConfig(inlineConfig || {}, {
		configFile: false,
		envDir: false,
		cacheDir: process.cwd(),
		environments: { inline: {
			consumer: "server",
			dev: { moduleRunnerTransform: true },
			resolve: {
				external: true,
				mainFields: [],
				conditions: ["node", ...isModuleSyncConditionEnabled ? ["module-sync"] : []]
			}
		} }
	}), "serve"), {
		runnerOptions: { hmr: { logger: false } },
		hot: false
	});
	await environment.init();
	try {
		const module = await environment.runner.import(moduleId);
		return {
			module,
			dependencies: [...environment.runner.evaluatedModules.urlToIdModuleMap.values()].filter((m) => {
				if (!m.meta || "externalize" in m.meta) return false;
				return m.exports !== module;
			}).map((m) => m.file)
		};
	} finally {
		await environment.close();
	}
}
//#endregion
//#region src/node/optimizer/pluginConverter.ts
function convertEsbuildPluginToRolldownPlugin(esbuildPlugin) {
	const onStartCallbacks = [];
	const onEndCallbacks = [];
	const onDisposeCallbacks = [];
	let resolveIdHandlers;
	let loadHandlers;
	let isSetupDone = false;
	const setup = async (plugins, platform) => {
		const onResolveCallbacks = [];
		const onLoadCallbacks = [];
		const pluginBuild = {
			initialOptions: new Proxy({
				platform,
				plugins: plugins?.flatMap((p) => p && "name" in p ? [{
					name: p.name,
					setup() {}
				}] : []) ?? []
			}, { get(target, p, _receiver) {
				if (p in target) return target[p];
				throw new Error("Not implemented");
			} }),
			resolve() {
				throw new Error("Not implemented");
			},
			onStart(callback) {
				onStartCallbacks.push(callback);
			},
			onEnd(callback) {
				onEndCallbacks.push(callback);
			},
			onResolve(options, callback) {
				onResolveCallbacks.push([options, callback]);
			},
			onLoad(options, callback) {
				onLoadCallbacks.push([options, callback]);
			},
			onDispose(callback) {
				onDisposeCallbacks.push(callback);
			},
			get esbuild() {
				throw new Error("Not implemented");
			},
			set esbuild(_) {
				throw new Error("Not implemented");
			}
		};
		await esbuildPlugin.setup(pluginBuild);
		resolveIdHandlers = onResolveCallbacks.map(([options, callback]) => createResolveIdHandler(options, callback));
		loadHandlers = onLoadCallbacks.map(([options, callback]) => createLoadHandler(options, callback));
		isSetupDone = true;
	};
	const usedNamespaces = /* @__PURE__ */ new Set();
	return {
		name: esbuildPlugin.name,
		async options(inputOptions) {
			await setup(inputOptions.plugins, inputOptions.platform ?? "node");
		},
		async buildStart(inputOptions) {
			if (!isSetupDone) await setup([{ name: "vite:dep-scan" }], inputOptions.platform ?? "node");
			for (const cb of onStartCallbacks) cb();
		},
		generateBundle(_outputOpts, _bundle, isWrite) {
			const buildResult = new Proxy({
				metafile: void 0,
				mangleCache: void 0,
				...isWrite ? { outputFiles: void 0 } : {}
			}, { get(_target, prop) {
				if (prop in _target || typeof prop === "symbol") return _target[prop];
				throw new Error("Not implemented property: " + prop);
			} });
			for (const cb of onEndCallbacks) cb(buildResult);
		},
		async resolveId(id, importer, opts) {
			for (const handler of resolveIdHandlers) {
				const result = await handler.call(this, id, importer, opts);
				if (result) {
					if (typeof result === "object" && result.namespace) usedNamespaces.add(result.namespace);
					return result;
				}
			}
			if (usedNamespaces.size) {
				const [importerWithoutNamespace, namespaceFromImporter] = idToPathAndNamespace(importer);
				if (usedNamespaces.has(namespaceFromImporter)) return await this.resolve(id, importerWithoutNamespace, opts);
			}
		},
		async load(id) {
			for (const handler of loadHandlers) {
				const result = await handler.call(this, id);
				if (result) return result;
			}
		},
		closeBundle() {
			if (!this.meta.watchMode) for (const cb of onDisposeCallbacks) cb();
		},
		closeWatcher() {
			for (const cb of onDisposeCallbacks) cb();
		}
	};
}
function createResolveIdHandler(options, callback) {
	return async function(id, importer, opts) {
		const [importerWithoutNamespace, importerNamespace] = idToPathAndNamespace(importer);
		if (options.namespace !== void 0 && options.namespace !== importerNamespace) return;
		if (options.filter !== void 0 && !options.filter.test(id)) return;
		const result = await callback({
			path: id,
			importer: importerWithoutNamespace ?? "",
			namespace: importerNamespace,
			resolveDir: dirname(importerWithoutNamespace ?? ""),
			kind: importerWithoutNamespace === void 0 ? "entry-point" : opts.kind === "new-url" || opts.kind === "hot-accept" ? "dynamic-import" : opts.kind,
			pluginData: {},
			with: {}
		});
		if (!result) return;
		if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
		if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || !result.path) throw new Error("not implemented");
		for (const file of result.watchFiles ?? []) this.addWatchFile(file);
		return {
			id: result.namespace ? `${result.namespace}:${result.path}` : result.path,
			external: result.external,
			moduleSideEffects: result.sideEffects,
			namespace: result.namespace
		};
	};
}
function createLoadHandler(options, callback) {
	const textDecoder = new TextDecoder();
	return async function(id) {
		const [idWithoutNamespace, idNamespace] = idToPathAndNamespace(id);
		if (options.namespace !== void 0 && options.namespace !== "file" && options.namespace !== idNamespace) return;
		if (options.filter !== void 0 && !options.filter.test(id)) return;
		const result = await callback.call(this, {
			path: idWithoutNamespace,
			namespace: idNamespace,
			suffix: "",
			pluginData: {},
			with: {}
		});
		if (!result) return;
		if (result.errors && result.errors.length > 0) throw new AggregateError(result.errors);
		if (result.warnings && result.warnings.length > 0 || result.watchDirs && result.watchDirs.length > 0 || result.contents == null) throw new Error("not implemented");
		for (const file of result.watchFiles ?? []) this.addWatchFile(file);
		return {
			code: typeof result.contents === "string" ? result.contents : textDecoder.decode(result.contents),
			moduleType: result.loader
		};
	};
}
function idToPathAndNamespace(id) {
	if (id === void 0) return [void 0, "file"];
	const namespaceIndex = id.indexOf(":");
	if (namespaceIndex >= 0) return [id.slice(namespaceIndex + 1), id.slice(0, namespaceIndex)];
	else return [id, "file"];
}
//#endregion
//#region src/node/config.ts
var config_exports = /* @__PURE__ */ __exportAll({
	defineConfig: () => defineConfig,
	getDefaultEnvironmentOptions: () => getDefaultEnvironmentOptions,
	isResolvedConfig: () => isResolvedConfig,
	loadConfigFromFile: () => loadConfigFromFile,
	resolveBaseUrl: () => resolveBaseUrl,
	resolveConfig: () => resolveConfig,
	resolveDevEnvironmentOptions: () => resolveDevEnvironmentOptions,
	resolveDevToolsConfig: () => resolveDevToolsConfig,
	sortUserPlugins: () => sortUserPlugins
});
const debug = createDebugger("vite:config", { depth: 10 });
const promisifiedRealpath = promisify(fs.realpath);
const SYMBOL_RESOLVED_CONFIG = Symbol("vite:resolved-config");
function defineConfig(config) {
	return config;
}
function defaultCreateClientDevEnvironment(name, config, context) {
	return new DevEnvironment(name, config, {
		hot: true,
		transport: context.ws,
		disableFetchModule: true
	});
}
function defaultCreateDevEnvironment(name, config) {
	return createRunnableDevEnvironment(name, config);
}
async function resolveDevToolsConfig(config, host, logger) {
	const isEnabled = config === true || !!(config && config.enabled);
	const fallbackHostname = (await resolveHostname(host)).host ?? "localhost";
	const fallbackConfig = {
		config: { host: fallbackHostname },
		enabled: false
	};
	if (!isEnabled) return fallbackConfig;
	try {
		const { normalizeDevToolsConfig } = await import("@vitejs/devtools/config");
		return normalizeDevToolsConfig(config, fallbackHostname);
	} catch (e) {
		logger.error(import_picocolors.default.red(`Failed to load Vite DevTools config: ${e.message || e.stack}`), { error: e });
		return fallbackConfig;
	}
}
const configDefaults = Object.freeze({
	define: {},
	dev: {
		warmup: [],
		/** @experimental */
		sourcemap: { js: true },
		sourcemapIgnoreList: void 0
	},
	build: buildEnvironmentOptionsDefaults,
	resolve: {
		externalConditions: [...DEFAULT_EXTERNAL_CONDITIONS],
		extensions: DEFAULT_EXTENSIONS,
		dedupe: [],
		/** @experimental */
		noExternal: [],
		external: [],
		preserveSymlinks: false,
		tsconfigPaths: false,
		alias: []
	},
	base: "/",
	publicDir: "public",
	plugins: [],
	html: { cspNonce: void 0 },
	css: cssConfigDefaults,
	json: {
		namedExports: true,
		stringify: "auto"
	},
	assetsInclude: void 0,
	/** @experimental */
	builder: builderOptionsDefaults,
	server: serverConfigDefaults,
	preview: { port: DEFAULT_PREVIEW_PORT },
	/** @experimental */
	experimental: {
		importGlobRestoreExtension: false,
		renderBuiltUrl: void 0,
		hmrPartialAccept: false,
		bundledDev: false
	},
	future: {
		removePluginHookHandleHotUpdate: void 0,
		removePluginHookSsrArgument: void 0,
		removeServerModuleGraph: void 0,
		removeServerHot: void 0,
		removeServerTransformRequest: void 0,
		removeServerWarmupRequest: void 0,
		removeSsrLoadModule: void 0
	},
	legacy: { skipWebSocketTokenCheck: false },
	logLevel: "info",
	customLogger: void 0,
	clearScreen: true,
	envDir: void 0,
	envPrefix: "VITE_",
	worker: {
		format: "iife",
		plugins: () => []
	},
	optimizeDeps: {
		include: [],
		exclude: [],
		needsInterop: [],
		rolldownOptions: {},
		/** @experimental */
		extensions: [],
		/** @deprecated @experimental */
		disabled: "build",
		/** @experimental */
		holdUntilCrawlEnd: true,
		/** @experimental */
		force: false,
		/** @experimental */
		ignoreOutdatedRequests: false
	},
	ssr: ssrConfigDefaults,
	environments: {},
	appType: "spa"
});
function resolveDevEnvironmentOptions(dev, environmentName, consumer, preTransformRequest) {
	const resolved = mergeWithDefaults({
		...configDefaults.dev,
		sourcemapIgnoreList: isInNodeModules,
		preTransformRequests: preTransformRequest ?? consumer === "client",
		createEnvironment: environmentName === "client" ? defaultCreateClientDevEnvironment : defaultCreateDevEnvironment,
		recoverable: consumer === "client",
		moduleRunnerTransform: consumer === "server"
	}, dev ?? {});
	return {
		...resolved,
		sourcemapIgnoreList: resolved.sourcemapIgnoreList === false ? () => false : resolved.sourcemapIgnoreList
	};
}
function resolveEnvironmentOptions(options, alias, preserveSymlinks, forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, isSsrTargetWebworkerSet, preTransformRequests) {
	const isClientEnvironment = environmentName === "client";
	const consumer = options.consumer ?? (isClientEnvironment ? "client" : "server");
	const isSsrTargetWebworkerEnvironment = isSsrTargetWebworkerSet && environmentName === "ssr";
	const isBundled = options.isBundled ?? (isBuild || isClientEnvironment && isBundledDev);
	if (options.define?.["process.env"]) {
		const processEnvDefine = options.define["process.env"];
		if (typeof processEnvDefine === "object") {
			const pathKey = Object.entries(processEnvDefine).find(([key, value]) => key.toLowerCase() === "path" && !!value)?.[0];
			if (pathKey) logger.warnOnce(import_picocolors.default.yellow(`The \`define\` option contains an object with ${JSON.stringify(pathKey)} for "process.env" key. It looks like you may have passed the entire \`process.env\` object to \`define\`, which can unintentionally expose all environment variables. This poses a security risk and is discouraged.`));
		}
	}
	const resolve = resolveEnvironmentResolveOptions(options.resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment);
	return {
		define: options.define,
		resolve,
		keepProcessEnv: options.keepProcessEnv ?? (isSsrTargetWebworkerEnvironment ? false : consumer === "server"),
		consumer,
		optimizeDeps: resolveDepOptimizationOptions(options.optimizeDeps, resolve.preserveSymlinks, forceOptimizeDeps, consumer, logger),
		dev: resolveDevEnvironmentOptions(options.dev, environmentName, consumer, preTransformRequests),
		build: resolveBuildEnvironmentOptions(options.build ?? {}, logger, consumer, isBundled && !isBuild, isSsrTargetWebworkerEnvironment),
		isBundled,
		plugins: void 0,
		optimizeDepsPluginNames: void 0
	};
}
function getDefaultEnvironmentOptions(config) {
	return {
		define: config.define,
		resolve: {
			...config.resolve,
			mainFields: void 0,
			conditions: void 0
		},
		dev: config.dev,
		build: config.build
	};
}
/**
* Check and warn if `path` includes characters that don't work well in Vite,
* such as `#` and `?` and `*`.
*/
function checkBadCharactersInPath(name, type, path, logger) {
	const badChars = [];
	if (path.includes("#")) badChars.push("#");
	if (path.includes("?")) badChars.push("?");
	if (path.includes("*")) badChars.push("*");
	if (badChars.length > 0) {
		const charString = badChars.map((c) => `"${c}"`).join(" and ");
		logger.warn(import_picocolors.default.yellow(`${name} contains the ${charString} ${badChars.length > 1 ? "characters" : "character"} (${import_picocolors.default.cyan(path)}), which may not work when running Vite. Consider renaming the ${type} without the characters.`));
	}
}
const clientAlias = [{
	find: /^\/?@vite\/env/,
	replacement: path.posix.join(FS_PREFIX, normalizePath(ENV_ENTRY))
}, {
	find: /^\/?@vite\/client/,
	replacement: path.posix.join(FS_PREFIX, normalizePath(CLIENT_ENTRY))
}];
/**
* alias and preserveSymlinks are not per-environment options, but they are
* included in the resolved environment options for convenience.
*/
function resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, consumer, isSsrTargetWebworkerEnvironment) {
	const resolvedResolve = mergeWithDefaults({
		...configDefaults.resolve,
		mainFields: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_MAIN_FIELDS : DEFAULT_SERVER_MAIN_FIELDS,
		conditions: consumer === void 0 || consumer === "client" || isSsrTargetWebworkerEnvironment ? DEFAULT_CLIENT_CONDITIONS : DEFAULT_SERVER_CONDITIONS.filter((c) => c !== "browser"),
		builtins: resolve?.builtins ?? (consumer === "server" ? isSsrTargetWebworkerEnvironment && resolve?.noExternal === true ? [] : nodeLikeBuiltins : [])
	}, resolve ?? {});
	resolvedResolve.preserveSymlinks = preserveSymlinks;
	resolvedResolve.alias = alias;
	if (resolve?.browserField === false && resolvedResolve.mainFields.includes("browser")) logger.warn(import_picocolors.default.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."));
	return resolvedResolve;
}
function resolveResolveOptions(resolve, logger) {
	const alias = normalizeAlias(mergeAlias(clientAlias, resolve?.alias || configDefaults.resolve.alias));
	const preserveSymlinks = resolve?.preserveSymlinks ?? configDefaults.resolve.preserveSymlinks;
	if (alias.some((a) => a.find === "/")) logger.warn(import_picocolors.default.yellow("`resolve.alias` contains an alias that maps `/`. This is not recommended as it can cause unexpected behavior when resolving paths."));
	if (alias.some((a) => a.customResolver)) logger.warn(import_picocolors.default.yellow("`resolve.alias` contains an alias with `customResolver` option. This is deprecated and will be removed in Vite 9. Please use a custom plugin with a resolveId hook and `enforce: 'pre'` instead."));
	return resolveEnvironmentResolveOptions(resolve, alias, preserveSymlinks, logger, void 0);
}
function resolveDepOptimizationOptions(optimizeDeps, preserveSymlinks, forceOptimizeDeps, consumer, logger) {
	if (optimizeDeps?.rolldownOptions && optimizeDeps?.rolldownOptions === optimizeDeps?.rollupOptions) delete optimizeDeps?.rollupOptions;
	const merged = mergeWithDefaults({
		...configDefaults.optimizeDeps,
		disabled: void 0,
		noDiscovery: consumer !== "client",
		force: forceOptimizeDeps ?? configDefaults.optimizeDeps.force
	}, optimizeDeps ?? {});
	setupRollupOptionCompat(merged, "optimizeDeps");
	const rolldownOptions = merged.rolldownOptions;
	if (merged.esbuildOptions && Object.keys(merged.esbuildOptions).length > 0) {
		logger.warn(import_picocolors.default.yellow("You or a plugin you are using have set `optimizeDeps.esbuildOptions` but this option is now deprecated. Vite now uses Rolldown to optimize the dependencies. Please use `optimizeDeps.rolldownOptions` instead."));
		rolldownOptions.resolve ??= {};
		rolldownOptions.output ??= {};
		rolldownOptions.transform ??= {};
		const setResolveOptions = (key, value) => {
			if (value !== void 0 && rolldownOptions.resolve[key] === void 0) rolldownOptions.resolve[key] = value;
		};
		if (merged.esbuildOptions.minify !== void 0 && rolldownOptions.output.minify === void 0) rolldownOptions.output.minify = merged.esbuildOptions.minify;
		if (merged.esbuildOptions.treeShaking !== void 0 && rolldownOptions.treeshake === void 0) rolldownOptions.treeshake = merged.esbuildOptions.treeShaking;
		if (merged.esbuildOptions.define !== void 0 && rolldownOptions.transform.define === void 0) rolldownOptions.transform.define = merged.esbuildOptions.define;
		if (merged.esbuildOptions.loader !== void 0) {
			const loader = merged.esbuildOptions.loader;
			rolldownOptions.moduleTypes ??= {};
			for (const [key, value] of Object.entries(loader)) if (rolldownOptions.moduleTypes[key] === void 0 && value !== "copy" && value !== "css" && value !== "default" && value !== "file" && value !== "local-css") rolldownOptions.moduleTypes[key] = value;
		}
		if (merged.esbuildOptions.preserveSymlinks !== void 0 && rolldownOptions.resolve.symlinks === void 0) rolldownOptions.resolve.symlinks = !merged.esbuildOptions.preserveSymlinks;
		setResolveOptions("extensions", merged.esbuildOptions.resolveExtensions);
		setResolveOptions("mainFields", merged.esbuildOptions.mainFields);
		setResolveOptions("conditionNames", merged.esbuildOptions.conditions);
		if (merged.esbuildOptions.keepNames !== void 0 && rolldownOptions.output.keepNames === void 0) rolldownOptions.output.keepNames = merged.esbuildOptions.keepNames;
		if (merged.esbuildOptions.platform !== void 0 && rolldownOptions.platform === void 0) rolldownOptions.platform = merged.esbuildOptions.platform;
	}
	merged.esbuildOptions ??= {};
	merged.esbuildOptions.preserveSymlinks ??= preserveSymlinks;
	rolldownOptions.resolve ??= {};
	rolldownOptions.resolve.symlinks ??= !preserveSymlinks;
	rolldownOptions.output ??= {};
	rolldownOptions.output.topLevelVar ??= true;
	return merged;
}
async function setOptimizeDepsPluginNames(resolvedConfig) {
	await Promise.all(Object.values(resolvedConfig.environments).map(async (environment) => {
		const flattenedPlugins = await asyncFlatten([environment.optimizeDeps.rolldownOptions?.plugins ?? [], environment.optimizeDeps.rolldownOptions?.output?.plugins ?? []]);
		const pluginNames = [];
		for (const plugin of flattenedPlugins) if (plugin && "name" in plugin) pluginNames.push(plugin.name);
		environment.optimizeDepsPluginNames = pluginNames;
	}));
}
function applyDepOptimizationOptionCompat(resolvedConfig) {
	if (resolvedConfig.optimizeDeps.esbuildOptions?.plugins && resolvedConfig.optimizeDeps.esbuildOptions.plugins.length > 0) {
		resolvedConfig.optimizeDeps.rolldownOptions ??= {};
		resolvedConfig.optimizeDeps.rolldownOptions.plugins ||= [];
		resolvedConfig.optimizeDeps.rolldownOptions.plugins.push(...resolvedConfig.optimizeDeps.esbuildOptions.plugins.map((plugin) => convertEsbuildPluginToRolldownPlugin(plugin)));
	}
}
function isResolvedConfig(inlineConfig) {
	return SYMBOL_RESOLVED_CONFIG in inlineConfig && inlineConfig[SYMBOL_RESOLVED_CONFIG];
}
async function resolveConfig(inlineConfig, command, defaultMode = "development", defaultNodeEnv = "development", isPreview = false, patchConfig = void 0, patchPlugins = void 0) {
	let config = inlineConfig;
	config.build ??= {};
	setupRollupOptionCompat(config.build, "build");
	config.worker ??= {};
	setupRollupOptionCompat(config.worker, "worker");
	config.optimizeDeps ??= {};
	setupRollupOptionCompat(config.optimizeDeps, "optimizeDeps");
	if (config.ssr) {
		config.ssr.optimizeDeps ??= {};
		setupRollupOptionCompat(config.ssr.optimizeDeps, "ssr.optimizeDeps");
	}
	let configFileDependencies = [];
	let mode = inlineConfig.mode || defaultMode;
	if (process.env.NODE_ENV === void 0) {
		const nodeEnv = getEnv("NODE_ENV");
		if (nodeEnv !== void 0) process.env.NODE_ENV = nodeEnv;
	}
	const isNodeEnvSet = !!process.env.NODE_ENV;
	const packageCache = /* @__PURE__ */ new Map();
	if (!isNodeEnvSet) process.env.NODE_ENV = defaultNodeEnv;
	const configEnv = {
		mode,
		command,
		isSsrBuild: command === "build" && !!config.build?.ssr,
		isPreview
	};
	let { configFile } = config;
	if (configFile !== false) {
		const loadResult = await loadConfigFromFile(configEnv, configFile, config.root, config.logLevel, config.customLogger, config.configLoader);
		if (loadResult) {
			config = mergeConfig(loadResult.config, config);
			configFile = loadResult.path;
			configFileDependencies = loadResult.dependencies;
		}
	}
	mode = inlineConfig.mode || config.mode || mode;
	configEnv.mode = mode;
	const filterPlugin = (p) => {
		if (!p) return false;
		else if (!p.apply) return true;
		else if (typeof p.apply === "function") return p.apply({
			...config,
			mode
		}, configEnv);
		else return p.apply === command;
	};
	const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins((await asyncFlatten(config.plugins || [])).filter(filterPlugin));
	const isBuild = command === "build";
	const userPlugins = [
		...prePlugins,
		...normalPlugins,
		...postPlugins
	];
	config = await runConfigHook(config, userPlugins, configEnv);
	config.environments ??= {};
	if (!config.environments.ssr && (!isBuild || config.ssr || config.build?.ssr)) config.environments = {
		ssr: {},
		...config.environments
	};
	if (!config.environments.client) config.environments = {
		client: {},
		...config.environments
	};
	const logger = createLogger(config.logLevel, {
		allowClearScreen: config.clearScreen,
		customLogger: config.customLogger
	});
	const tsconfigPathsPlugin = userPlugins.find((p) => p.name === "vite-tsconfig-paths" || p.name === "vite-plugin-tsconfig-paths");
	if (tsconfigPathsPlugin) logger.warnOnce(import_picocolors.default.yellow(`The plugin ${JSON.stringify(tsconfigPathsPlugin.name)} is detected. Vite now supports tsconfig paths resolution natively via the ${import_picocolors.default.bold("resolve.tsconfigPaths")} option. You can remove the plugin and set ${import_picocolors.default.bold("resolve.tsconfigPaths: true")} in your Vite config instead.`));
	if (process.versions.pnp) logger.warnOnce(import_picocolors.default.yellow(`Using Yarn PnP with Vite is discouraged and PnP-specific bugs will no longer be actively worked on. Please switch to a different ${import_picocolors.default.bold("nodeLinker")} mode or to a different package manager.`));
	const resolvedRoot = normalizePath(config.root ? path.resolve(config.root) : process.cwd());
	checkBadCharactersInPath("The project root", "directory", resolvedRoot, logger);
	const configEnvironmentsClient = config.environments.client;
	configEnvironmentsClient.dev ??= {};
	const deprecatedSsrOptimizeDepsConfig = config.ssr?.optimizeDeps ?? {};
	let configEnvironmentsSsr = config.environments.ssr;
	const warmupOptions = config.server?.warmup;
	if (warmupOptions?.clientFiles) configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles;
	if (warmupOptions?.ssrFiles) {
		configEnvironmentsSsr ??= {};
		configEnvironmentsSsr.dev ??= {};
		configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles;
	}
	if (configEnvironmentsSsr) {
		configEnvironmentsSsr.optimizeDeps = mergeConfig(deprecatedSsrOptimizeDepsConfig, configEnvironmentsSsr.optimizeDeps ?? {});
		configEnvironmentsSsr.resolve = mergeConfig({ resolve: {
			conditions: config.ssr?.resolve?.conditions,
			externalConditions: config.ssr?.resolve?.externalConditions,
			mainFields: config.ssr?.resolve?.mainFields,
			external: config.ssr?.external,
			noExternal: config.ssr?.noExternal
		} }, { resolve: configEnvironmentsSsr.resolve ?? {} }).resolve;
	}
	if (config.build?.ssrEmitAssets !== void 0) {
		configEnvironmentsSsr ??= {};
		configEnvironmentsSsr.build ??= {};
		configEnvironmentsSsr.build.emitAssets = config.build.ssrEmitAssets;
	}
	if (!config.environments.client || !config.environments.ssr && !isBuild) throw new Error("Required environments configuration were stripped out in the config hook");
	const defaultEnvironmentOptions = getDefaultEnvironmentOptions(config);
	const defaultClientEnvironmentOptions = {
		...defaultEnvironmentOptions,
		resolve: config.resolve,
		optimizeDeps: config.optimizeDeps
	};
	const defaultNonClientEnvironmentOptions = {
		...defaultEnvironmentOptions,
		dev: {
			...defaultEnvironmentOptions.dev,
			createEnvironment: void 0,
			warmup: void 0
		},
		build: {
			...defaultEnvironmentOptions.build,
			createEnvironment: void 0
		}
	};
	for (const name of Object.keys(config.environments)) config.environments[name] = mergeConfig(name === "client" ? defaultClientEnvironmentOptions : deepClone(defaultNonClientEnvironmentOptions), config.environments[name]);
	await runConfigEnvironmentHook(config.environments, userPlugins, logger, configEnv, config.ssr?.target === "webworker");
	const isBundledDev = command === "serve" && !!config.experimental?.bundledDev;
	config.resolve ??= {};
	config.resolve.conditions = config.environments.client.resolve?.conditions;
	config.resolve.mainFields = config.environments.client.resolve?.mainFields;
	const resolvedDefaultResolve = resolveResolveOptions(config.resolve, logger);
	const resolvedEnvironments = {};
	for (const environmentName of Object.keys(config.environments)) resolvedEnvironments[environmentName] = resolveEnvironmentOptions(config.environments[environmentName], resolvedDefaultResolve.alias, resolvedDefaultResolve.preserveSymlinks, inlineConfig.forceOptimizeDeps, logger, environmentName, isBuild, isBundledDev, config.ssr?.target === "webworker", config.server?.preTransformRequests);
	const backwardCompatibleOptimizeDeps = resolvedEnvironments.client.optimizeDeps;
	const resolvedDevEnvironmentOptions = resolveDevEnvironmentOptions(config.dev, void 0, void 0);
	const resolvedBuildOptions = resolveBuildEnvironmentOptions(config.build ?? {}, logger, void 0, isBundledDev);
	const ssr = resolveSSROptions({
		...config.ssr,
		external: resolvedEnvironments.ssr?.resolve.external,
		noExternal: resolvedEnvironments.ssr?.resolve.noExternal,
		optimizeDeps: resolvedEnvironments.ssr?.optimizeDeps,
		resolve: {
			...config.ssr?.resolve,
			conditions: resolvedEnvironments.ssr?.resolve.conditions,
			externalConditions: resolvedEnvironments.ssr?.resolve.externalConditions
		}
	}, resolvedDefaultResolve.preserveSymlinks);
	if (config.envFile === false) logger.warn(import_picocolors.default.yellow("The `envFile` option is deprecated, please use `envDir: false` instead."));
	let envDir = config.envFile === false ? false : config.envDir;
	if (envDir !== false) envDir = config.envDir ? normalizePath(path.resolve(resolvedRoot, config.envDir)) : resolvedRoot;
	const userEnv = loadEnv(mode, envDir, resolveEnvPrefix(config));
	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 = process.env.NODE_ENV === "production";
	const resolvedBase = config.base === "" || config.base === "./" ? !isBuild || config.build?.ssr ? "/" : "./" : resolveBaseUrl(config.base, isBuild, logger);
	const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir;
	let cacheDir;
	if (config.cacheDir) cacheDir = path.resolve(resolvedRoot, config.cacheDir);
	else if (pkgDir) cacheDir = path.join(pkgDir, `node_modules/.vite`);
	else {
		const nodeModulesDir = path.join(resolvedRoot, "node_modules");
		cacheDir = fs.existsSync(nodeModulesDir) ? path.join(nodeModulesDir, `.vite`) : path.join(resolvedRoot, `.vite`);
	}
	cacheDir = normalizePath(cacheDir);
	const assetsFilter = config.assetsInclude && (!Array.isArray(config.assetsInclude) || config.assetsInclude.length) ? createFilter$1(config.assetsInclude) : () => false;
	const { publicDir } = config;
	const resolvedPublicDir = publicDir !== false && publicDir !== "" ? normalizePath(path.resolve(resolvedRoot, typeof publicDir === "string" ? publicDir : configDefaults.publicDir)) : "";
	const server = await resolveServerOptions(resolvedRoot, config.server, logger);
	const builder = resolveBuilderOptions(config.builder);
	const BASE_URL = resolvedBase;
	const resolvedConfigContext = new BasicMinimalPluginContext({
		...basePluginContextMeta,
		watchMode: command === "serve" && !isPreview || command === "build" && !!resolvedBuildOptions.watch
	}, logger);
	let resolved;
	let createUserWorkerPlugins = config.worker?.plugins;
	if (Array.isArray(createUserWorkerPlugins)) {
		createUserWorkerPlugins = () => config.worker?.plugins;
		logger.warn(import_picocolors.default.yellow("worker.plugins is now a function that returns an array of plugins. Please update your Vite config accordingly.\n"));
	}
	const createWorkerPlugins = async function(bundleChain) {
		const rawWorkerUserPlugins = (await asyncFlatten(createUserWorkerPlugins?.() || [])).filter(filterPlugin);
		let workerConfig = mergeConfig({}, config);
		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
		};
		workerResolved.plugins = await resolvePlugins(workerResolved, workerPrePlugins, workerNormalPlugins, workerPostPlugins);
		await Promise.all(createPluginHookUtils(workerResolved.plugins).getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, workerResolved)));
		workerResolved.environments = {
			...workerResolved.environments,
			client: {
				...workerResolved.environments.client,
				plugins: await resolveEnvironmentPlugins(new PartialEnvironment("client", workerResolved))
			}
		};
		return workerResolved;
	};
	const resolvedWorkerOptions = {
		format: config.worker?.format || "iife",
		plugins: createWorkerPlugins,
		rollupOptions: config.worker?.rollupOptions || {},
		rolldownOptions: config.worker?.rolldownOptions
	};
	setupRollupOptionCompat(resolvedWorkerOptions, "worker");
	const base = withTrailingSlash(resolvedBase);
	const preview = resolvePreviewOptions(config.preview, server);
	const additionalAllowedHosts = getAdditionalAllowedHosts(server, preview);
	if (Array.isArray(server.allowedHosts)) server.allowedHosts.push(...additionalAllowedHosts);
	if (Array.isArray(preview.allowedHosts)) preview.allowedHosts.push(...additionalAllowedHosts);
	let oxc = config.oxc;
	if (config.esbuild) if (config.oxc) logger.warn(import_picocolors.default.yellow(`Both esbuild and oxc options were set. oxc options will be used and esbuild options will be ignored.`) + ` The following esbuild options were set: \`${inspect(config.esbuild)}\``);
	else oxc = convertEsbuildConfigToOxcConfig(config.esbuild, logger);
	else if (config.esbuild === false && config.oxc !== false) logger.warn(import_picocolors.default.yellow("`esbuild` option is set to false, but `oxc` option was not set to false. `esbuild: false` does not have effect any more. If you want to disable the default transformation, which is now handled by Oxc, please set `oxc: false` instead."));
	const experimental = mergeWithDefaults(configDefaults.experimental, config.experimental ?? {});
	if (command === "serve" && experimental.bundledDev) experimental.renderBuiltUrl = void 0;
	const resolvedDevToolsConfig = await resolveDevToolsConfig(config.devtools, server.host, logger);
	resolved = {
		configFile: configFile ? normalizePath(configFile) : void 0,
		configFileDependencies: configFileDependencies.map((name) => normalizePath(path.resolve(name))),
		inlineConfig,
		root: resolvedRoot,
		base,
		decodedBase: decodeBase(base),
		rawBase: resolvedBase,
		publicDir: resolvedPublicDir,
		cacheDir,
		command,
		mode,
		isWorker: false,
		mainConfig: null,
		bundleChain: [],
		isProduction,
		plugins: userPlugins,
		css: resolveCSSOptions(config.css),
		json: mergeWithDefaults(configDefaults.json, config.json ?? {}),
		esbuild: config.esbuild === false ? false : {
			jsxDev: !isProduction,
			charset: "utf8",
			legalComments: "none",
			...config.esbuild
		},
		oxc: oxc === false ? false : {
			...oxc,
			jsx: typeof oxc?.jsx === "string" ? oxc.jsx : {
				development: oxc?.jsx?.development ?? !isProduction,
				...oxc?.jsx
			}
		},
		server,
		builder,
		preview,
		envDir,
		env: {
			...userEnv,
			BASE_URL,
			MODE: mode,
			DEV: !isProduction,
			PROD: isProduction
		},
		assetsInclude(file) {
			return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file);
		},
		rawAssetsInclude: config.assetsInclude ? arraify(config.assetsInclude) : [],
		logger,
		packageCache,
		worker: resolvedWorkerOptions,
		appType: config.appType ?? "spa",
		experimental,
		future: config.future === "warn" ? {
			removePluginHookHandleHotUpdate: "warn",
			removePluginHookSsrArgument: "warn",
			removeServerModuleGraph: "warn",
			removeServerReloadModule: "warn",
			removeServerPluginContainer: "warn",
			removeServerHot: "warn",
			removeServerTransformRequest: "warn",
			removeServerWarmupRequest: "warn",
			removeSsrLoadModule: "warn"
		} : config.future,
		ssr,
		optimizeDeps: backwardCompatibleOptimizeDeps,
		resolve: resolvedDefaultResolve,
		dev: resolvedDevEnvironmentOptions,
		build: resolvedBuildOptions,
		devtools: resolvedDevToolsConfig,
		environments: resolvedEnvironments,
		webSocketToken: Buffer.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(9))).toString("base64url"),
		getSortedPlugins: void 0,
		getSortedPluginHooks: void 0,
		createResolver(options) {
			const resolve = createIdResolver(this, options);
			const clientEnvironment = new PartialEnvironment("client", this);
			let ssrEnvironment;
			return async (id, importer, aliasOnly, ssr) => {
				if (ssr) ssrEnvironment ??= new PartialEnvironment("ssr", this);
				return await resolve(ssr ? ssrEnvironment : clientEnvironment, id, importer, aliasOnly);
			};
		},
		fsDenyGlob: pm(server.fs.deny.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`), {
			matchBase: false,
			nocase: true,
			dot: true
		}),
		safeModulePaths: /* @__PURE__ */ new Set(),
		[SYMBOL_RESOLVED_CONFIG]: true
	};
	resolved = {
		...config,
		...resolved
	};
	patchConfig?.(resolved);
	const resolvedPlugins = await resolvePlugins(resolved, prePlugins, normalPlugins, postPlugins);
	patchPlugins?.(resolvedPlugins);
	resolved.plugins = resolvedPlugins;
	Object.assign(resolved, createPluginHookUtils(resolved.plugins));
	await Promise.all(resolved.getSortedPluginHooks("configResolved").map((hook) => hook.call(resolvedConfigContext, resolved)));
	for (const name of Object.keys(resolved.environments)) resolved.environments[name].plugins = await resolveEnvironmentPlugins(new PartialEnvironment(name, resolved));
	optimizeDepsDisabledBackwardCompatibility(resolved, resolved.optimizeDeps);
	optimizeDepsDisabledBackwardCompatibility(resolved, resolved.ssr.optimizeDeps, "ssr.");
	if (!resolved.builder?.sharedConfigBuild && resolved.environments.ssr) resolved.environments.ssr.build.emitAssets = resolved.build.ssrEmitAssets || resolved.build.emitAssets;
	applyDepOptimizationOptionCompat(resolved);
	await setOptimizeDepsPluginNames(resolved);
	debug?.(`using resolved config: %O`, {
		...resolved,
		plugins: resolved.plugins.map((p) => p.name),
		worker: {
			...resolved.worker,
			plugins: `() => plugins`
		}
	});
	const outputOption = config.build?.rolldownOptions?.output ?? [];
	if (Array.isArray(outputOption)) {
		const assetFileNamesList = outputOption.map((output) => output.assetFileNames);
		if (assetFileNamesList.length > 1) {
			const firstAssetFileNames = assetFileNamesList[0];
			if (assetFileNamesList.some((assetFileNames) => assetFileNames !== firstAssetFileNames)) resolved.logger.warn(import_picocolors.default.yellow(`
assetFileNames isn't equal for every build.rolldownOptions.output. A single pattern across all outputs is supported by Vite.
`));
		}
	}
	if (config.experimental?.renderBuiltUrl && config.build?.chunkImportMap) resolved.logger.warn(import_picocolors.default.yellow("The `build.chunkImportMap` option and the `experimental.renderBuiltUrl` option are both enabled. The combination of these two options is not supported and may result in unexpected behavior."));
	if (config.legacy?.buildSsrCjsExternalHeuristics || config.ssr?.format === "cjs") resolved.logger.warn(import_picocolors.default.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(path.resolve(resolved.root, resolved.build.outDir));
	if (isParentDirectory(resolvedBuildOutDir, resolved.root) || resolvedBuildOutDir === resolved.root) resolved.logger.warn(import_picocolors.default.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;
}
/**
* Resolve base url. Note that some users use Vite to build for non-web targets like
* electron or expects to deploy
*/
function resolveBaseUrl(base = configDefaults.base, isBuild, logger) {
	if (base[0] === ".") {
		logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) invalid "base" option: "${base}". The value can only be an absolute URL, "./", or an empty string.`)));
		return "/";
	}
	const isExternal = isExternalUrl(base);
	if (!isExternal && base[0] !== "/") logger.warn(import_picocolors.default.yellow(import_picocolors.default.bold(`(!) "base" option should start with a slash.`)));
	if (!isBuild || !isExternal) {
		base = new URL(base, "http://vite.dev").pathname;
		if (base[0] !== "/") base = "/" + base;
	}
	return base;
}
function decodeBase(base) {
	try {
		return decodeURI(base);
	} catch {
		throw new Error("The value passed to \"base\" option was malformed. It should be a valid URL.");
	}
}
function sortUserPlugins(plugins) {
	const prePlugins = [];
	const postPlugins = [];
	const normalPlugins = [];
	if (plugins) plugins.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, configLoader = "bundle") {
	if (configLoader !== "bundle" && configLoader !== "runner" && configLoader !== "native") throw new Error(`Unsupported configLoader: ${configLoader}. Accepted values are 'bundle', 'runner', and 'native'.`);
	const start = performance$1.now();
	const getTime = () => `${(performance$1.now() - start).toFixed(2)}ms`;
	let resolvedPath;
	if (configFile) resolvedPath = path.resolve(configFile);
	else for (const filename of DEFAULT_CONFIG_FILES) {
		const filePath = path.resolve(configRoot, filename);
		if (!fs.existsSync(filePath)) continue;
		resolvedPath = filePath;
		break;
	}
	if (!resolvedPath) {
		debug?.("no config file found.");
		return null;
	}
	try {
		const { configExport, dependencies } = await (configLoader === "bundle" ? bundleAndLoadConfigFile : configLoader === "runner" ? runnerImportConfigFile : nativeImportConfigFile)(resolvedPath);
		debug?.(`config file loaded in ${getTime()}`);
		const config = await (typeof configExport === "function" ? configExport(configEnv) : configExport);
		if (!isObject$1(config)) throw new Error(`config must export or return an object.`);
		return {
			path: normalizePath(resolvedPath),
			config,
			dependencies
		};
	} catch (e) {
		const logger = createLogger(logLevel, { customLogger });
		checkBadCharactersInPath("The config path", "file", resolvedPath, logger);
		logger.error(import_picocolors.default.red(`failed to load config from ${resolvedPath}`), { error: e });
		throw e;
	}
}
async function nativeImportConfigFile(resolvedPath) {
	const freshImported = freshImport(pathToFileURL(resolvedPath).href);
	if (freshImported) {
		const { result, dependencies } = await freshImported;
		return {
			configExport: result.default,
			dependencies
		};
	}
	return {
		configExport: (await import(pathToFileURL(resolvedPath).href + "?t=" + Date.now())).default,
		dependencies: []
	};
}
async function runnerImportConfigFile(resolvedPath) {
	const { module, dependencies } = await runnerImport(resolvedPath);
	return {
		configExport: module.default,
		dependencies
	};
}
async function bundleAndLoadConfigFile(resolvedPath) {
	const isESM = typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
	const bundled = await bundleConfigFile(resolvedPath, isESM);
	return {
		configExport: await loadConfigFromBundledFile(resolvedPath, bundled.code, isESM),
		dependencies: bundled.dependencies
	};
}
async function bundleConfigFile(fileName, isESM) {
	let importMetaResolverRegistered = false;
	const root = path.dirname(fileName);
	const dirnameVarName = "__vite_injected_original_dirname";
	const filenameVarName = "__vite_injected_original_filename";
	const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
	const importMetaResolveVarName = "__vite_injected_original_import_meta_resolve";
	const importMetaResolveRegex = /import\.meta\s*\.\s*resolve/;
	const bundle = await rolldown({
		input: fileName,
		platform: "node",
		resolve: { mainFields: ["main"] },
		transform: { define: {
			__dirname: dirnameVarName,
			__filename: filenameVarName,
			"import.meta.url": importMetaUrlVarName,
			"import.meta.dirname": dirnameVarName,
			"import.meta.filename": filenameVarName,
			"import.meta.resolve": importMetaResolveVarName,
			"import.meta.main": "false"
		} },
		treeshake: false,
		tsconfig: false,
		plugins: [{
			name: "externalize-deps",
			resolveId: {
				filter: { id: /^[^.#].*/ },
				handler(id, importer, { kind }) {
					if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
					if (isNodeLikeBuiltin(id) || id.startsWith("npm:")) return {
						id,
						external: true
					};
					const isImport = isESM || kind === "dynamic-import";
					let idFsPath;
					try {
						idFsPath = nodeResolveWithVite(id, importer, {
							root,
							isRequire: !isImport
						});
					} catch (e) {
						if (!isImport) {
							let canResolveWithImport = false;
							try {
								canResolveWithImport = !!nodeResolveWithVite(id, importer, { root });
							} 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://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`);
						}
						throw e;
					}
					if (!idFsPath) return;
					if (idFsPath.endsWith(".json")) return idFsPath;
					if (idFsPath && isImport) idFsPath = pathToFileURL(idFsPath).href;
					return {
						id: idFsPath,
						external: true
					};
				}
			}
		}, {
			name: "inject-file-scope-variables",
			transform: {
				filter: { id: /\.[cm]?[jt]s$/ },
				handler(code, id) {
					let injectValues = `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};`;
					if (importMetaResolveRegex.test(code)) if (isESM) {
						if (!importMetaResolverRegistered) {
							importMetaResolverRegistered = true;
							createImportMetaResolver();
						}
						injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`;
					} else injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`;
					let injectedContents;
					if (code.startsWith("#!")) {
						let firstLineEndIndex = code.indexOf("\n");
						if (firstLineEndIndex < 0) firstLineEndIndex = code.length;
						injectedContents = code.slice(0, firstLineEndIndex + 1) + injectValues + code.slice(firstLineEndIndex + 1);
					} else injectedContents = injectValues + code;
					return {
						code: injectedContents,
						map: null
					};
				}
			}
		}]
	});
	const result = await bundle.generate({
		format: isESM ? "esm" : "cjs",
		sourcemap: "inline",
		sourcemapPathTransform(relative) {
			return path.resolve(fileName, relative);
		},
		codeSplitting: false
	});
	await bundle.close();
	const entryChunk = result.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
	const bundleChunks = Object.fromEntries(result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : []));
	const allModules = /* @__PURE__ */ new Set();
	collectAllModules(bundleChunks, entryChunk.fileName, allModules);
	return {
		code: entryChunk.code,
		dependencies: [...allModules].filter((m) => !m.startsWith("\0"))
	};
}
function collectAllModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
	if (analyzedModules.has(fileName)) return;
	analyzedModules.add(fileName);
	const chunk = bundle[fileName];
	if (!chunk) return;
	for (const mod of chunk.moduleIds) allModules.add(mod);
	for (const i of chunk.imports) collectAllModules(bundle, i, allModules, analyzedModules);
	for (const i of chunk.dynamicImports) collectAllModules(bundle, i, allModules, analyzedModules);
}
const _require = createRequire(
	/** #__KEEP__ */
	import.meta.url
);
async function loadConfigFromBundledFile(fileName, bundledCode, isESM) {
	if (isESM) {
		const nodeModulesDir = typeof process.versions.deno === "string" ? void 0 : findNearestNodeModules(path.dirname(fileName));
		let viteTempDir = nodeModulesDir ? path.resolve(nodeModulesDir, ".vite-temp") : void 0;
		if (viteTempDir) try {
			await fsp.mkdir(viteTempDir, { recursive: true });
		} catch (e) {
			if (e.code === "EACCES") viteTempDir = void 0;
			else throw e;
		}
		const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
		const tempFileName = viteTempDir ? path.resolve(viteTempDir, `${path.basename(fileName)}.${hash}.mjs`) : `${fileName}.${hash}.mjs`;
		const pathToIgnore = viteTempDir ?? tempFileName;
		ignoreInput(pathToIgnore);
		ignoreOutput(pathToIgnore);
		await fsp.writeFile(tempFileName, bundledCode);
		try {
			return (await import(pathToFileURL(tempFileName).href)).default;
		} finally {
			fs.unlink(tempFileName, () => {});
		}
	} else {
		const extension = path.extname(fileName);
		const realFileName = await promisifiedRealpath(fileName);
		const loaderExt = extension in _require.extensions ? extension : ".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(config, plugins, configEnv) {
	let conf = config;
	const context = new BasicMinimalPluginContext(basePluginContextMeta, createLogger(config.logLevel, {
		allowClearScreen: config.clearScreen,
		customLogger: config.customLogger
	}));
	for (const p of getSortedPluginsByHook("config", plugins)) {
		const hook = p.config;
		const res = await getHookHandler(hook).call(context, conf, configEnv);
		if (res && res !== conf) {
			if (hasBothRollupOptionsAndRolldownOptions(res)) context.warn(`Both \`rollupOptions\` and \`rolldownOptions\` were specified by ${JSON.stringify(p.name)} plugin. \`rollupOptions\` specified by that plugin will be ignored.`);
			if (res.esbuild) context.warn(`\`esbuild\` option was specified by ${JSON.stringify(p.name)} plugin. This option is deprecated, please use \`oxc\` instead.`);
			if (res.optimizeDeps?.esbuildOptions) context.warn(`\`optimizeDeps.esbuildOptions\` option was specified by ${JSON.stringify(p.name)} plugin. This option is deprecated, please use \`optimizeDeps.rolldownOptions\` instead.`);
			conf = mergeConfig(conf, res);
		}
	}
	return conf;
}
async function runConfigEnvironmentHook(environments, plugins, logger, configEnv, isSsrTargetWebworkerSet) {
	const context = new BasicMinimalPluginContext(basePluginContextMeta, logger);
	const environmentNames = Object.keys(environments);
	for (const p of getSortedPluginsByHook("configEnvironment", plugins)) {
		const hook = p.configEnvironment;
		const handler = getHookHandler(hook);
		for (const name of environmentNames) {
			const res = await handler.call(context, name, environments[name], {
				...configEnv,
				isSsrTargetWebworker: isSsrTargetWebworkerSet && name === "ssr"
			});
			if (res) environments[name] = mergeConfig(environments[name], res);
		}
	}
}
function optimizeDepsDisabledBackwardCompatibility(resolved, optimizeDeps, optimizeDepsPath = "") {
	const optimizeDepsDisabled = optimizeDeps.disabled;
	if (optimizeDepsDisabled !== void 0) {
		if (optimizeDepsDisabled === true || optimizeDepsDisabled === "dev") {
			const commonjsOptionsInclude = resolved.build.commonjsOptions.include;
			const commonjsPluginDisabled = Array.isArray(commonjsOptionsInclude) && commonjsOptionsInclude.length === 0;
			optimizeDeps.noDiscovery = true;
			optimizeDeps.include = void 0;
			if (commonjsPluginDisabled) resolved.build.commonjsOptions.include = void 0;
			resolved.logger.warn(import_picocolors.default.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(import_picocolors.default.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.
  `));
	}
}
//#endregion
//#region src/node/server/environments/fetchableEnvironments.ts
function createFetchableDevEnvironment(name, config, context) {
	if (typeof Request === "undefined" || typeof Response === "undefined") throw new TypeError("FetchableDevEnvironment requires a global `Request` and `Response` object.");
	if (!context.handleRequest) throw new TypeError("FetchableDevEnvironment requires a `handleRequest` method during initialisation.");
	return new FetchableDevEnvironment(name, config, context);
}
function isFetchableDevEnvironment(environment) {
	return environment instanceof FetchableDevEnvironment;
}
var FetchableDevEnvironment = class extends DevEnvironment {
	_handleRequest;
	constructor(name, config, context) {
		super(name, config, context);
		this._handleRequest = context.handleRequest;
	}
	async dispatchFetch(request) {
		if (!(request instanceof Request)) throw new TypeError("FetchableDevEnvironment `dispatchFetch` must receive a `Request` object.");
		const response = await this._handleRequest(request);
		if (!(response instanceof Response)) throw new TypeError("FetchableDevEnvironment `context.handleRequest` must return a `Response` object.");
		return response;
	}
};
//#endregion
//#region src/node/index.ts
/** @deprecated - use `parseSync` instead */
const parseAst$1 = parseAst;
/** @deprecated - use `parse` instead */
const parseAstAsync$1 = parseAstAsync;
const esbuildVersion = "0.25.0";
//#endregion
export { mergeConfig as $, createServerHotChannel as A, send$1 as B, fetchModule as C, createBuilder as D, build_exports as E, searchForWorkspaceRoot as F, loadEnv as G, createServerModuleRunner as H, createIdResolver as I, transformWithEsbuild as J, resolveEnvPrefix as K, perEnvironmentState as L, server_exports as M, formatPostcssSourceMap as N, optimizeDeps as O, preprocessCSS as P, mergeAlias as Q, isFileLoadingAllowed as R, DevEnvironment as S, build as T, createServerModuleRunnerTransport as U, ssrTransform as V, buildErrorMessage as W, createFilter$1 as X, perEnvironmentPlugin as Y, isCSSRequest as Z, runnerImport as _, minifySync as a, createRunnableDevEnvironment as b, parseAstAsync$1 as c, isFetchableDevEnvironment as d, normalizePath as et, config_exports as f, sortUserPlugins as g, resolveConfig as h, minify as i, createServer$2 as j, optimizer_exports as k, parseSync as l, loadConfigFromFile as m, esbuildVersion as n, rollupVersion as nt, parse as o, defineConfig as p, transformWithOxc as q, esmExternalRequirePlugin$1 as r, withFilter as rt, parseAst$1 as s, Visitor as t, rolldownVersion as tt, createFetchableDevEnvironment as u, preview as v, BuildEnvironment as w, isRunnableDevEnvironment as x, preview_exports as y, isFileServingAllowed as z };
