import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk.js"; import { A as OPTIMIZABLE_ENTRY_RE, C as ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR, D as JS_TYPES_RE, E as FS_PREFIX, F as defaultAllowedOrigins, 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, _ 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 } from "./logger.js"; import { builtinModules, createRequire } from "node:module"; import { parseAst, parseAstAsync } from "rolldown/parseAst"; import { esmExternalRequirePlugin } from "rolldown/plugins"; import { TsconfigCache, Visitor, minify, minifySync, parse, parseSync, transformSync } from "rolldown/utils"; import * as fs$1 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, { randomUUID } from "node:crypto"; import picomatch from "picomatch"; 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, viteWasmFallbackPlugin, viteWebWorkerPostPlugin } from "rolldown/experimental"; import readline from "node:readline"; import { MessageChannel, Worker } from "node:worker_threads"; import isModuleSyncConditionEnabled from "#module-sync-enabled"; import assert from "node:assert"; import process$1 from "node:process"; import v8 from "node:v8"; import { escapePath, glob, globSync, isDynamicPattern } from "tinyglobby"; 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 { setTimeout as setTimeout$1 } from "node:timers/promises"; import * as qs from "node:querystring"; //#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 = new Uint8Array(64); var charToInt$1 = 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]); } assert$2(sourceLine); assert$2(sourceColumn); 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 assert$2(_val) {} 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$36, inspectOpts, humanize$1, createDebug, node_default; var init_node = __esmMin((() => { init_core(); require$1 = createRequire(import.meta.url); colors$36 = 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$36, 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.3.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 picomatch(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 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 (options.includeArbitraryNames && isWellFormedString(key)) { const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`; arbitraryNameExportRows.push(`${variableName} as ${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 replaceSlashOrColonRE = /[/:]/g; const replaceDotRE = /\./g; const replaceNestedIdRE = /\s*>\s*/g; const replaceHashRE = /#/g; const replacePlusRE = /\+/g; const flattenId = (id) => { return limitFlattenIdLength(id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____").replace(replacePlusRE, "_____")); }; const FLATTEN_ID_HASH_LENGTH = 8; 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 - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + 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", (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|(?<=,))(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\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 = /^[A-Z]:/; const replaceWindowsDriveRE = /^([A-Z]):\//; const linuxAbsolutePathRE = /^\/[^/]/; function escapeToLinuxLikePath(path) { if (windowsDriveRE.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. */ async function getLocalhostAddressIfDiffersFromDNS() { const [nodeResult, dnsResult] = await Promise.all([promises.lookup("localhost"), promises.lookup("localhost", { verbatim: true })]); 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 = 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 = new Set(["optimizeDeps", "ssr.optimizeDeps"]); const rollupOptionsDeprecationCall = () => { 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 = 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) return true; return false; } function mergeConfigRecursively(defaults, overrides, rootPath) { const merged = { ...defaults }; if (rollupOptionsRootPaths.has(rootPath)) setupRollupOptionCompat(merged, rootPath); 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") { 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; } //#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; } async 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.2/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(); const resArgs = receive(syncPort).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$1 = args.id; if (resolvers.has(id$1)) { const { resolve, reject } = resolvers.get(id$1); resolvers.delete(id$1); 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 = 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); } //#endregion //#region ../../node_modules/.pnpm/ufo@1.6.3/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 = 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} 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} */ 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} 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} */ const types = []; /** @type {Array} */ const instances = []; /** @type {Array} */ 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) => 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} parameters */ function NodeError(...parameters) { const limit = Error.stackTraceLimit; if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; const error = new Base(); if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; const message = getMessage(key, parameters, error); Object.defineProperties(error, { message: { value: message, enumerable: false, writable: true, configurable: true }, toString: { value() { return `${this.name} [${key}]: ${this.message}`; }, enumerable: false, writable: true, configurable: true } }); captureLargerStackTrace(error); error.code = key; return error; } } /** * @returns {boolean} */ function isErrorStackTraceLimitWritable() { try { if (v8.startupSnapshot.isBuildingSnapshot()) return false; } catch {} const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); if (desc === void 0) return Object.isExtensible(Error); return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0; } /** * This function removes unnecessary frames from Node.js core errors. * @template {(...parameters: unknown[]) => unknown} T * @param {T} wrappedFunction * @returns {T} */ function hideStackFrames(wrappedFunction) { const hidden = nodeInternalPrefix + wrappedFunction.name; Object.defineProperty(wrappedFunction, "name", { value: hidden }); return wrappedFunction; } const captureLargerStackTrace = hideStackFrames( /** * @param {Error} error * @returns {Error} */ function(error) { const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); if (stackTraceLimitIsWritable) { userStackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = Number.POSITIVE_INFINITY; } Error.captureStackTrace(error); if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; return error; } ); /** * @param {string} key * @param {Array} 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"']*(?[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?(?<="\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 }; } const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m; const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g; function hasESMSyntax(code, opts = {}) { if (opts.stripComments) code = code.replace(COMMENT_RE, ""); return ESM_RE.test(code); } //#endregion //#region ../../node_modules/.pnpm/es-module-lexer@1.7.0/node_modules/es-module-lexer/dist/lexer.js var ImportType; (function(A) { 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"; })(ImportType || (ImportType = {})); const A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0]; function parse$2(E, g = "@") { if (!C) return init.then((() => parse$2(E))); const I = E.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength; w > 0 && C.memory.grow(Math.ceil(w / 65536)); const K = C.sa(I - 1); if ((A ? B : Q)(E, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(/* @__PURE__ */ new Error(`Parse error ${g}:${E.slice(0, C.e()).split("\n").length}:${C.e() - E.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() }); const o = [], D = []; for (; C.ri();) { const A = C.is(), Q = C.ie(), B = C.it(), g = C.ai(), I = C.id(), w = C.ss(), K = C.se(); let D; C.ip() && (D = k(E.slice(-1 === I ? A - 1 : A, -1 === I ? Q + 1 : Q))), o.push({ n: D, t: B, s: A, e: Q, ss: w, se: K, d: I, a: g }); } for (; C.re();) { const A = C.es(), Q = C.ee(), B = C.els(), g = C.ele(), I = E.slice(A, Q), w = I[0], K = B < 0 ? void 0 : E.slice(B, g), o = K ? K[0] : ""; D.push({ s: A, e: Q, ls: B, le: g, n: "\"" === w || "'" === w ? k(I) : I, ln: "\"" === o || "'" === o ? k(K) : K }); } function k(A) { try { return (0, eval)(A); } catch (A) {} } return [ o, D, !!C.f(), !!C.ms() ]; } function Q(A, Q) { const B = A.length; let C = 0; for (; C < B;) { const B = A.charCodeAt(C); Q[C++] = (255 & B) << 8 | B >>> 8; } } function B(A, Q) { const B = A.length; let C = 0; for (; C < B;) Q[C] = A.charCodeAt(C++); } let C; const E = () => { return A = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1Akh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wCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(A, "base64") : Uint8Array.from(atob(A), ((A) => A.charCodeAt(0))); var A; }; const init = WebAssembly.compile(E()).then(WebAssembly.instantiate).then((({ exports: A }) => { C = 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) { if (config.isBundled) return perEnvironmentPlugin("native:transform", (environment) => { const { jsxInject, include = /\.(m?ts|[jt]sx)$/, exclude = /\.js$/, jsxRefreshInclude, jsxRefreshExclude, ..._transformOptions } = 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 }); }); 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", 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) { 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 { return await fsp.readFile(file, "utf-8"); } 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 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 = /(? normalizePath(path.join(envDir, file))); return []; } 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 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(` Error