module-runner.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. let SOURCEMAPPING_URL = "sourceMa";
  2. SOURCEMAPPING_URL += "ppingURL";
  3. //#endregion
  4. //#region src/shared/utils.ts
  5. const isWindows = typeof process < "u" && process.platform === "win32";
  6. /**
  7. * Undo {@link wrapId}'s `/@id/` and null byte replacements.
  8. */
  9. function unwrapId(id) {
  10. return id.startsWith("/@id/") ? id.slice(5).replace("__x00__", "\0") : id;
  11. }
  12. const windowsSlashRE = /\\/g;
  13. function slash(p) {
  14. return p.replace(windowsSlashRE, "/");
  15. }
  16. const postfixRE = /[?#].*$/;
  17. function cleanUrl(url) {
  18. return url.replace(postfixRE, "");
  19. }
  20. function isPrimitive(value) {
  21. return !value || typeof value != "object" && typeof value != "function";
  22. }
  23. const AsyncFunction = async function() {}.constructor;
  24. let asyncFunctionDeclarationPaddingLineCount;
  25. function getAsyncFunctionDeclarationPaddingLineCount() {
  26. if (asyncFunctionDeclarationPaddingLineCount === void 0) {
  27. let body = "/*code*/", source = new AsyncFunction("a", "b", body).toString();
  28. asyncFunctionDeclarationPaddingLineCount = source.slice(0, source.indexOf(body)).split("\n").length - 1;
  29. }
  30. return asyncFunctionDeclarationPaddingLineCount;
  31. }
  32. function promiseWithResolvers() {
  33. let resolve, reject;
  34. return {
  35. promise: new Promise((_resolve, _reject) => {
  36. resolve = _resolve, reject = _reject;
  37. }),
  38. resolve,
  39. reject
  40. };
  41. }
  42. //#endregion
  43. //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
  44. const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
  45. function normalizeWindowsPath(input = "") {
  46. return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
  47. }
  48. const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
  49. function cwd() {
  50. return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
  51. }
  52. const resolve = function(...arguments_) {
  53. arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
  54. let resolvedPath = "", resolvedAbsolute = !1;
  55. for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
  56. let path = index >= 0 ? arguments_[index] : cwd();
  57. !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
  58. }
  59. return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
  60. };
  61. function normalizeString(path, allowAboveRoot) {
  62. let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
  63. for (let index = 0; index <= path.length; ++index) {
  64. if (index < path.length) char = path[index];
  65. else if (char === "/") break;
  66. else char = "/";
  67. if (char === "/") {
  68. if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
  69. if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
  70. if (res.length > 2) {
  71. let lastSlashIndex = res.lastIndexOf("/");
  72. lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
  73. continue;
  74. } else if (res.length > 0) {
  75. res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
  76. continue;
  77. }
  78. }
  79. allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
  80. } else res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
  81. lastSlash = index, dots = 0;
  82. } else char === "." && dots !== -1 ? ++dots : dots = -1;
  83. }
  84. return res;
  85. }
  86. const isAbsolute = function(p) {
  87. return _IS_ABSOLUTE_RE.test(p);
  88. }, dirname = function(p) {
  89. let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
  90. return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
  91. }, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
  92. function encodePathChars(filepath) {
  93. return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf("\n") !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
  94. }
  95. const posixDirname = dirname, posixResolve = resolve;
  96. function posixPathToFileHref(posixPath) {
  97. let resolved = posixResolve(posixPath), filePathLast = posixPath.charCodeAt(posixPath.length - 1);
  98. return (filePathLast === 47 || isWindows && filePathLast === 92) && resolved[resolved.length - 1] !== "/" && (resolved += "/"), resolved = encodePathChars(resolved), resolved.indexOf("?") !== -1 && (resolved = resolved.replace(questionRegex, "%3F")), resolved.indexOf("#") !== -1 && (resolved = resolved.replace(hashRegex, "%23")), new URL(`file://${resolved}`).href;
  99. }
  100. function toWindowsPath(path) {
  101. return path.replace(/\//g, "\\");
  102. }
  103. //#endregion
  104. //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
  105. var comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
  106. for (let i = 0; i < chars.length; i++) {
  107. let c = chars.charCodeAt(i);
  108. intToChar[i] = c, charToInt[c] = i;
  109. }
  110. function decodeInteger(reader, relative) {
  111. let value = 0, shift = 0, integer = 0;
  112. do
  113. integer = charToInt[reader.next()], value |= (integer & 31) << shift, shift += 5;
  114. while (integer & 32);
  115. let shouldNegate = value & 1;
  116. return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
  117. }
  118. function hasMoreVlq(reader, max) {
  119. return reader.pos >= max ? !1 : reader.peek() !== comma;
  120. }
  121. var StringReader = class {
  122. constructor(buffer) {
  123. this.pos = 0, this.buffer = buffer;
  124. }
  125. next() {
  126. return this.buffer.charCodeAt(this.pos++);
  127. }
  128. peek() {
  129. return this.buffer.charCodeAt(this.pos);
  130. }
  131. indexOf(char) {
  132. let { buffer, pos } = this, idx = buffer.indexOf(char, pos);
  133. return idx === -1 ? buffer.length : idx;
  134. }
  135. };
  136. function decode(mappings) {
  137. let { length } = mappings, reader = new StringReader(mappings), decoded = [], genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
  138. do {
  139. let semi = reader.indexOf(";"), line = [], sorted = !0, lastCol = 0;
  140. for (genColumn = 0; reader.pos < semi;) {
  141. let seg;
  142. genColumn = decodeInteger(reader, genColumn), genColumn < lastCol && (sorted = !1), lastCol = genColumn, hasMoreVlq(reader, semi) ? (sourcesIndex = decodeInteger(reader, sourcesIndex), sourceLine = decodeInteger(reader, sourceLine), sourceColumn = decodeInteger(reader, sourceColumn), hasMoreVlq(reader, semi) ? (namesIndex = decodeInteger(reader, namesIndex), seg = [
  143. genColumn,
  144. sourcesIndex,
  145. sourceLine,
  146. sourceColumn,
  147. namesIndex
  148. ]) : seg = [
  149. genColumn,
  150. sourcesIndex,
  151. sourceLine,
  152. sourceColumn
  153. ]) : seg = [genColumn], line.push(seg), reader.pos++;
  154. }
  155. sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
  156. } while (reader.pos <= length);
  157. return decoded;
  158. }
  159. function sort(line) {
  160. line.sort(sortComparator);
  161. }
  162. function sortComparator(a, b) {
  163. return a[0] - b[0];
  164. }
  165. //#endregion
  166. //#region ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
  167. var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4, found = !1;
  168. function binarySearch(haystack, needle, low, high) {
  169. for (; low <= high;) {
  170. let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
  171. if (cmp === 0) return found = !0, mid;
  172. cmp < 0 ? low = mid + 1 : high = mid - 1;
  173. }
  174. return found = !1, low - 1;
  175. }
  176. function upperBound(haystack, needle, index) {
  177. for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++);
  178. return index;
  179. }
  180. function lowerBound(haystack, needle, index) {
  181. for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--);
  182. return index;
  183. }
  184. function memoizedBinarySearch(haystack, needle, state, key) {
  185. let { lastKey, lastNeedle, lastIndex } = state, low = 0, high = haystack.length - 1;
  186. if (key === lastKey) {
  187. if (needle === lastNeedle) return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
  188. needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
  189. }
  190. return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
  191. }
  192. var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)", COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
  193. function cast(map) {
  194. return map;
  195. }
  196. function decodedMappings(map) {
  197. var _a;
  198. return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
  199. }
  200. function originalPositionFor(map, needle) {
  201. let { line, column, bias } = needle;
  202. if (line--, line < 0) throw Error(LINE_GTR_ZERO);
  203. if (column < 0) throw Error(COL_GTR_EQ_ZERO);
  204. let decoded = decodedMappings(map);
  205. if (line >= decoded.length) return OMapping(null, null, null, null);
  206. let segments = decoded[line], index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || 1);
  207. if (index === -1) return OMapping(null, null, null, null);
  208. let segment = segments[index];
  209. if (segment.length === 1) return OMapping(null, null, null, null);
  210. let { names, resolvedSources } = map;
  211. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  212. }
  213. function OMapping(source, line, column, name) {
  214. return {
  215. source,
  216. line,
  217. column,
  218. name
  219. };
  220. }
  221. function traceSegmentInternal(segments, memo, line, column, bias) {
  222. let index = memoizedBinarySearch(segments, column, memo, line);
  223. return found ? index = (bias === -1 ? upperBound : lowerBound)(segments, column, index) : bias === -1 && index++, index === -1 || index === segments.length ? -1 : index;
  224. }
  225. //#endregion
  226. //#region src/module-runner/sourcemap/decoder.ts
  227. var DecodedMap = class {
  228. _encoded;
  229. _decoded;
  230. _decodedMemo;
  231. url;
  232. file;
  233. version;
  234. names = [];
  235. resolvedSources;
  236. constructor(map, from) {
  237. this.map = map;
  238. let { mappings, names, sources } = map;
  239. this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.file = from;
  240. let originDir = posixDirname(from);
  241. this.resolvedSources = (sources || []).map((s) => posixResolve(originDir, s || ""));
  242. }
  243. };
  244. function memoizedState() {
  245. return {
  246. lastKey: -1,
  247. lastNeedle: -1,
  248. lastIndex: -1
  249. };
  250. }
  251. function getOriginalPosition(map, needle) {
  252. let result = originalPositionFor(map, needle);
  253. return result.column == null ? null : result;
  254. }
  255. //#endregion
  256. //#region src/module-runner/evaluatedModules.ts
  257. const MODULE_RUNNER_SOURCEMAPPING_REGEXP = RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
  258. var EvaluatedModuleNode = class {
  259. importers = /* @__PURE__ */ new Set();
  260. imports = /* @__PURE__ */ new Set();
  261. evaluated = !1;
  262. meta;
  263. promise;
  264. exports;
  265. file;
  266. map;
  267. constructor(id, url) {
  268. this.id = id, this.url = url, this.file = cleanUrl(id);
  269. }
  270. }, EvaluatedModules = class {
  271. idToModuleMap = /* @__PURE__ */ new Map();
  272. fileToModulesMap = /* @__PURE__ */ new Map();
  273. urlToIdModuleMap = /* @__PURE__ */ new Map();
  274. /**
  275. * Returns the module node by the resolved module ID. Usually, module ID is
  276. * the file system path with query and/or hash. It can also be a virtual module.
  277. *
  278. * Module runner graph will have 1 to 1 mapping with the server module graph.
  279. * @param id Resolved module ID
  280. */
  281. getModuleById(id) {
  282. return this.idToModuleMap.get(id);
  283. }
  284. /**
  285. * Returns all modules related to the file system path. Different modules
  286. * might have different query parameters or hash, so it's possible to have
  287. * multiple modules for the same file.
  288. * @param file The file system path of the module
  289. */
  290. getModulesByFile(file) {
  291. return this.fileToModulesMap.get(file);
  292. }
  293. /**
  294. * Returns the module node by the URL that was used in the import statement.
  295. * Unlike module graph on the server, the URL is not resolved and is used as is.
  296. * @param url Server URL that was used in the import statement
  297. */
  298. getModuleByUrl(url) {
  299. return this.urlToIdModuleMap.get(unwrapId(url));
  300. }
  301. /**
  302. * Ensure that module is in the graph. If the module is already in the graph,
  303. * it will return the existing module node. Otherwise, it will create a new
  304. * module node and add it to the graph.
  305. * @param id Resolved module ID
  306. * @param url URL that was used in the import statement
  307. */
  308. ensureModule(id, url) {
  309. if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
  310. let moduleNode = this.idToModuleMap.get(id);
  311. return this.urlToIdModuleMap.set(url, moduleNode), moduleNode;
  312. }
  313. let moduleNode = new EvaluatedModuleNode(id, url);
  314. this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
  315. let fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
  316. return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
  317. }
  318. invalidateModule(node) {
  319. node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
  320. }
  321. /**
  322. * Extracts the inlined source map from the module code and returns the decoded
  323. * source map. If the source map is not inlined, it will return null.
  324. * @param id Resolved module ID
  325. */
  326. getModuleSourceMapById(id) {
  327. let mod = this.getModuleById(id);
  328. if (!mod) return null;
  329. if (mod.map) return mod.map;
  330. if (!mod.meta || !("code" in mod.meta)) return null;
  331. let pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`, lastIndex = mod.meta.code.lastIndexOf(pattern);
  332. if (lastIndex === -1) return null;
  333. let mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(mod.meta.code.slice(lastIndex))?.[1];
  334. return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
  335. }
  336. clear() {
  337. this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
  338. }
  339. };
  340. const prefixedBuiltins = new Set([
  341. "node:sea",
  342. "node:sqlite",
  343. "node:test",
  344. "node:test/reporters"
  345. ]);
  346. function normalizeModuleId(file) {
  347. return prefixedBuiltins.has(file) ? file : slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/").replace(/^file:\/+/, isWindows ? "" : "/");
  348. }
  349. //#endregion
  350. //#region src/shared/hmr.ts
  351. var HMRContext = class {
  352. newListeners;
  353. constructor(hmrClient, ownerPath) {
  354. this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
  355. let mod = hmrClient.hotModulesMap.get(ownerPath);
  356. mod && (mod.callbacks = []);
  357. let staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
  358. if (staleListeners) for (let [event, staleFns] of staleListeners) {
  359. let listeners = hmrClient.customListenersMap.get(event);
  360. listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
  361. }
  362. this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
  363. }
  364. get data() {
  365. return this.hmrClient.dataMap.get(this.ownerPath);
  366. }
  367. accept(deps, callback) {
  368. if (typeof deps == "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
  369. else if (typeof deps == "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
  370. else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
  371. else throw Error("invalid hot.accept() usage.");
  372. }
  373. acceptExports(_, callback) {
  374. this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
  375. }
  376. dispose(cb) {
  377. this.hmrClient.disposeMap.set(this.ownerPath, cb);
  378. }
  379. prune(cb) {
  380. this.hmrClient.pruneMap.set(this.ownerPath, cb);
  381. }
  382. decline() {}
  383. invalidate(message) {
  384. let firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
  385. this.hmrClient.notifyListeners("vite:invalidate", {
  386. path: this.ownerPath,
  387. message,
  388. firstInvalidatedBy
  389. }), this.send("vite:invalidate", {
  390. path: this.ownerPath,
  391. message,
  392. firstInvalidatedBy
  393. }), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
  394. }
  395. on(event, cb) {
  396. let addToMap = (map) => {
  397. let existing = map.get(event) || [];
  398. existing.push(cb), map.set(event, existing);
  399. };
  400. addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
  401. }
  402. off(event, cb) {
  403. let removeFromMap = (map) => {
  404. let existing = map.get(event);
  405. if (existing === void 0) return;
  406. let pruned = existing.filter((l) => l !== cb);
  407. if (pruned.length === 0) {
  408. map.delete(event);
  409. return;
  410. }
  411. map.set(event, pruned);
  412. };
  413. removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
  414. }
  415. send(event, data) {
  416. this.hmrClient.send({
  417. type: "custom",
  418. event,
  419. data
  420. });
  421. }
  422. acceptDeps(deps, callback = () => {}) {
  423. let mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
  424. id: this.ownerPath,
  425. callbacks: []
  426. };
  427. mod.callbacks.push({
  428. deps,
  429. fn: callback
  430. }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
  431. }
  432. }, HMRClient = class {
  433. hotModulesMap = /* @__PURE__ */ new Map();
  434. disposeMap = /* @__PURE__ */ new Map();
  435. pruneMap = /* @__PURE__ */ new Map();
  436. dataMap = /* @__PURE__ */ new Map();
  437. customListenersMap = /* @__PURE__ */ new Map();
  438. ctxToListenersMap = /* @__PURE__ */ new Map();
  439. currentFirstInvalidatedBy;
  440. constructor(logger, transport, importUpdatedModule) {
  441. this.logger = logger, this.transport = transport, this.importUpdatedModule = importUpdatedModule;
  442. }
  443. async notifyListeners(event, data) {
  444. let cbs = this.customListenersMap.get(event);
  445. cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
  446. }
  447. send(payload) {
  448. this.transport.send(payload).catch((err) => {
  449. this.logger.error(err);
  450. });
  451. }
  452. clear() {
  453. this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
  454. }
  455. async prunePaths(paths) {
  456. await Promise.all(paths.map((path) => {
  457. let disposer = this.disposeMap.get(path);
  458. if (disposer) return disposer(this.dataMap.get(path));
  459. })), await Promise.all(paths.map((path) => {
  460. let fn = this.pruneMap.get(path);
  461. if (fn) return fn(this.dataMap.get(path));
  462. }));
  463. }
  464. warnFailedUpdate(err, path) {
  465. (!(err instanceof Error) || !err.message.includes("fetch")) && this.logger.error(err), this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
  466. }
  467. updateQueue = [];
  468. pendingUpdateQueue = !1;
  469. /**
  470. * buffer multiple hot updates triggered by the same src change
  471. * so that they are invoked in the same order they were sent.
  472. * (otherwise the order may be inconsistent because of the http request round trip)
  473. */
  474. async queueUpdate(payload) {
  475. if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
  476. this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
  477. let loading = [...this.updateQueue];
  478. this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
  479. }
  480. }
  481. async fetchUpdate(update) {
  482. let { path, acceptedPath, firstInvalidatedBy } = update, mod = this.hotModulesMap.get(path);
  483. if (!mod) return;
  484. let fetchedModule, isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
  485. if (isSelfUpdate || qualifiedCallbacks.length > 0) {
  486. let disposer = this.disposeMap.get(acceptedPath);
  487. disposer && await disposer(this.dataMap.get(acceptedPath));
  488. try {
  489. fetchedModule = await this.importUpdatedModule(update);
  490. } catch (e) {
  491. this.warnFailedUpdate(e, acceptedPath);
  492. }
  493. }
  494. return () => {
  495. try {
  496. this.currentFirstInvalidatedBy = firstInvalidatedBy;
  497. for (let { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
  498. let loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
  499. this.logger.debug(`hot updated: ${loggedPath}`);
  500. } finally {
  501. this.currentFirstInvalidatedBy = void 0;
  502. }
  503. };
  504. }
  505. };
  506. //#endregion
  507. //#region src/shared/ssrTransform.ts
  508. /**
  509. * Vite converts `import { } from 'foo'` to `const _ = __vite_ssr_import__('foo')`.
  510. * Top-level imports and dynamic imports work slightly differently in Node.js.
  511. * This function normalizes the differences so it matches prod behaviour.
  512. */
  513. function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
  514. if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
  515. let missingBindings = metadata.importedNames.filter((s) => !(s in mod));
  516. if (missingBindings.length) {
  517. let lastBinding = missingBindings[missingBindings.length - 1];
  518. throw moduleType === "module" ? SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`) : SyntaxError(`\
  519. [vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports.
  520. CommonJS modules can always be imported via the default export, for example using:
  521. import pkg from '${rawId}';
  522. const {${missingBindings.join(", ")}} = pkg;
  523. `);
  524. }
  525. }
  526. }
  527. //#endregion
  528. //#region ../../node_modules/.pnpm/nanoid@5.1.6/node_modules/nanoid/non-secure/index.js
  529. let nanoid = (size = 21) => {
  530. let id = "", i = size | 0;
  531. for (; i--;) id += "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[Math.random() * 64 | 0];
  532. return id;
  533. };
  534. //#endregion
  535. //#region src/shared/moduleRunnerTransport.ts
  536. function reviveInvokeError(e) {
  537. let error = Error(e.message || "Unknown invoke error");
  538. return Object.assign(error, e, { runnerError: /* @__PURE__ */ Error("RunnerError") }), error;
  539. }
  540. const createInvokeableTransport = (transport) => {
  541. if (transport.invoke) return {
  542. ...transport,
  543. async invoke(name, data) {
  544. let result = await transport.invoke({
  545. type: "custom",
  546. event: "vite:invoke",
  547. data: {
  548. id: "send",
  549. name,
  550. data
  551. }
  552. });
  553. if ("error" in result) throw reviveInvokeError(result.error);
  554. return result.result;
  555. }
  556. };
  557. if (!transport.send || !transport.connect) throw Error("transport must implement send and connect when invoke is not implemented");
  558. let rpcPromises = /* @__PURE__ */ new Map();
  559. return {
  560. ...transport,
  561. connect({ onMessage, onDisconnection }) {
  562. return transport.connect({
  563. onMessage(payload) {
  564. if (payload.type === "custom" && payload.event === "vite:invoke") {
  565. let data = payload.data;
  566. if (data.id.startsWith("response:")) {
  567. let invokeId = data.id.slice(9), promise = rpcPromises.get(invokeId);
  568. if (!promise) return;
  569. promise.timeoutId && clearTimeout(promise.timeoutId), rpcPromises.delete(invokeId);
  570. let { error, result } = data.data;
  571. error ? promise.reject(error) : promise.resolve(result);
  572. return;
  573. }
  574. }
  575. onMessage(payload);
  576. },
  577. onDisconnection
  578. });
  579. },
  580. disconnect() {
  581. return rpcPromises.forEach((promise) => {
  582. promise.reject(/* @__PURE__ */ Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
  583. }), rpcPromises.clear(), transport.disconnect?.();
  584. },
  585. send(data) {
  586. return transport.send(data);
  587. },
  588. async invoke(name, data) {
  589. let promiseId = nanoid(), wrappedData = {
  590. type: "custom",
  591. event: "vite:invoke",
  592. data: {
  593. name,
  594. id: `send:${promiseId}`,
  595. data
  596. }
  597. }, sendPromise = transport.send(wrappedData), { promise, resolve, reject } = promiseWithResolvers(), timeout = transport.timeout ?? 6e4, timeoutId;
  598. timeout > 0 && (timeoutId = setTimeout(() => {
  599. rpcPromises.delete(promiseId), reject(/* @__PURE__ */ Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
  600. }, timeout), timeoutId?.unref?.()), rpcPromises.set(promiseId, {
  601. resolve,
  602. reject,
  603. name,
  604. timeoutId
  605. }), sendPromise && sendPromise.catch((err) => {
  606. clearTimeout(timeoutId), rpcPromises.delete(promiseId), reject(err);
  607. });
  608. try {
  609. return await promise;
  610. } catch (err) {
  611. throw reviveInvokeError(err);
  612. }
  613. }
  614. };
  615. }, normalizeModuleRunnerTransport = (transport) => {
  616. let invokeableTransport = createInvokeableTransport(transport), isConnected = !invokeableTransport.connect, connectingPromise;
  617. return {
  618. ...transport,
  619. ...invokeableTransport.connect ? { async connect(onMessage) {
  620. if (isConnected) return;
  621. if (connectingPromise) {
  622. await connectingPromise;
  623. return;
  624. }
  625. let maybePromise = invokeableTransport.connect({
  626. onMessage: onMessage ?? (() => {}),
  627. onDisconnection() {
  628. isConnected = !1;
  629. }
  630. });
  631. maybePromise && (connectingPromise = maybePromise, await connectingPromise, connectingPromise = void 0), isConnected = !0;
  632. } } : {},
  633. ...invokeableTransport.disconnect ? { async disconnect() {
  634. isConnected && (connectingPromise && await connectingPromise, isConnected = !1, await invokeableTransport.disconnect());
  635. } } : {},
  636. async send(data) {
  637. if (invokeableTransport.send) {
  638. if (!isConnected) if (connectingPromise) await connectingPromise;
  639. else throw Error("send was called before connect");
  640. await invokeableTransport.send(data);
  641. }
  642. },
  643. async invoke(name, data) {
  644. if (!isConnected) if (connectingPromise) await connectingPromise;
  645. else throw Error("invoke was called before connect");
  646. return invokeableTransport.invoke(name, data);
  647. }
  648. };
  649. }, createWebSocketModuleRunnerTransport = (options) => {
  650. let pingInterval = options.pingInterval ?? 3e4, ws, pingIntervalId;
  651. return {
  652. async connect({ onMessage, onDisconnection }) {
  653. let socket = options.createConnection();
  654. socket.addEventListener("message", async ({ data }) => {
  655. onMessage(JSON.parse(data));
  656. });
  657. let isOpened = socket.readyState === socket.OPEN;
  658. isOpened || await new Promise((resolve, reject) => {
  659. socket.addEventListener("open", () => {
  660. isOpened = !0, resolve();
  661. }, { once: !0 }), socket.addEventListener("close", async () => {
  662. if (!isOpened) {
  663. reject(/* @__PURE__ */ Error("WebSocket closed without opened."));
  664. return;
  665. }
  666. onMessage({
  667. type: "custom",
  668. event: "vite:ws:disconnect",
  669. data: { webSocket: socket }
  670. }), onDisconnection();
  671. });
  672. }), onMessage({
  673. type: "custom",
  674. event: "vite:ws:connect",
  675. data: { webSocket: socket }
  676. }), ws = socket, pingIntervalId = setInterval(() => {
  677. socket.readyState === socket.OPEN && socket.send(JSON.stringify({ type: "ping" }));
  678. }, pingInterval);
  679. },
  680. disconnect() {
  681. clearInterval(pingIntervalId), ws?.close();
  682. },
  683. send(data) {
  684. ws.send(JSON.stringify(data));
  685. }
  686. };
  687. };
  688. //#endregion
  689. //#region src/shared/builtin.ts
  690. function createIsBuiltin(builtins) {
  691. let plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin == "string")), regexBuiltins = builtins.filter((builtin) => typeof builtin != "string");
  692. return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
  693. }
  694. //#endregion
  695. //#region src/module-runner/constants.ts
  696. const ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrExportNameKey = "__vite_ssr_exportName__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {}, silentConsole = {
  697. debug: noop,
  698. error: noop
  699. }, hmrLogger = {
  700. debug: (...msg) => console.log("[vite]", ...msg),
  701. error: (error) => console.log("[vite]", error)
  702. };
  703. //#endregion
  704. //#region src/shared/hmrHandler.ts
  705. function createHMRHandler(handler) {
  706. let queue = new Queue();
  707. return (payload) => queue.enqueue(() => handler(payload));
  708. }
  709. var Queue = class {
  710. queue = [];
  711. pending = !1;
  712. enqueue(promise) {
  713. return new Promise((resolve, reject) => {
  714. this.queue.push({
  715. promise,
  716. resolve,
  717. reject
  718. }), this.dequeue();
  719. });
  720. }
  721. dequeue() {
  722. if (this.pending) return !1;
  723. let item = this.queue.shift();
  724. return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
  725. this.pending = !1, this.dequeue();
  726. }), !0) : !1;
  727. }
  728. };
  729. //#endregion
  730. //#region src/module-runner/hmrHandler.ts
  731. function createHMRHandlerForRunner(runner) {
  732. return createHMRHandler(async (payload) => {
  733. let hmrClient = runner.hmrClient;
  734. if (!(!hmrClient || runner.isClosed())) switch (payload.type) {
  735. case "connected":
  736. hmrClient.logger.debug("connected.");
  737. break;
  738. case "update":
  739. await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
  740. if (update.type === "js-update") return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
  741. hmrClient.logger.error("css hmr is not supported in runner mode.");
  742. })), await hmrClient.notifyListeners("vite:afterUpdate", payload);
  743. break;
  744. case "custom":
  745. await hmrClient.notifyListeners(payload.event, payload.data);
  746. break;
  747. case "full-reload": {
  748. let { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
  749. if (!clearEntrypointUrls.size) break;
  750. hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
  751. for (let url of clearEntrypointUrls) try {
  752. await runner.import(url);
  753. } catch (err) {
  754. err.code !== "ERR_OUTDATED_OPTIMIZED_DEP" && hmrClient.logger.error(`An error happened during full reload\n${err.message}\n${err.stack}`);
  755. }
  756. break;
  757. }
  758. case "prune":
  759. await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
  760. break;
  761. case "error": {
  762. await hmrClient.notifyListeners("vite:error", payload);
  763. let err = payload.err;
  764. hmrClient.logger.error(`Internal Server Error\n${err.message}\n${err.stack}`);
  765. break;
  766. }
  767. case "ping": break;
  768. default: return payload;
  769. }
  770. });
  771. }
  772. function getModulesByFile(runner, file) {
  773. let nodes = runner.evaluatedModules.getModulesByFile(file);
  774. return nodes ? [...nodes].map((node) => node.id) : [];
  775. }
  776. function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
  777. for (let moduleId of modules) {
  778. if (visited.has(moduleId)) continue;
  779. visited.add(moduleId);
  780. let module = runner.evaluatedModules.getModuleById(moduleId);
  781. if (module) {
  782. if (!module.importers.size) {
  783. entrypoints.add(module.url);
  784. continue;
  785. }
  786. for (let importer of module.importers) getModulesEntrypoints(runner, [importer], visited, entrypoints);
  787. }
  788. }
  789. return entrypoints;
  790. }
  791. function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
  792. for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
  793. return entrypoints;
  794. }
  795. //#endregion
  796. //#region src/module-runner/sourcemap/interceptor.ts
  797. const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => ((...args) => {
  798. for (let handler of handlers) {
  799. let result = handler(...args);
  800. if (result) return result;
  801. }
  802. return null;
  803. }), retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
  804. let overridden = !1;
  805. const originalPrepare = Error.prepareStackTrace;
  806. function resetInterceptor(runner, options) {
  807. evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
  808. }
  809. function interceptStackTrace(runner, options = {}) {
  810. return overridden ||= (Error.prepareStackTrace = prepareStackTrace, !0), evaluatedModulesCache.add(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runner, options);
  811. }
  812. function supportRelativeURL(file, url) {
  813. if (!file) return url;
  814. let dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir), protocol = match ? match[0] : "", startPath = dir.slice(protocol.length);
  815. return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
  816. }
  817. function getRunnerSourceMap(position) {
  818. for (let moduleGraph of evaluatedModulesCache) {
  819. let sourceMap = moduleGraph.getModuleSourceMapById(position.source);
  820. if (sourceMap) return {
  821. url: position.source,
  822. map: sourceMap,
  823. vite: !0
  824. };
  825. }
  826. return null;
  827. }
  828. function retrieveFile(path) {
  829. if (path in fileContentsCache) return fileContentsCache[path];
  830. let content = retrieveFileFromHandlers(path);
  831. return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
  832. }
  833. function retrieveSourceMapURL(source) {
  834. let fileData = retrieveFile(source);
  835. if (!fileData) return null;
  836. let re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm, lastMatch, match;
  837. for (; match = re.exec(fileData);) lastMatch = match;
  838. return lastMatch ? lastMatch[1] : null;
  839. }
  840. const reSourceMap = /^data:application\/json[^,]+base64,/;
  841. function retrieveSourceMap(source) {
  842. let urlAndMap = retrieveSourceMapFromHandlers(source);
  843. if (urlAndMap) return urlAndMap;
  844. let sourceMappingURL = retrieveSourceMapURL(source);
  845. if (!sourceMappingURL) return null;
  846. let sourceMapData;
  847. if (reSourceMap.test(sourceMappingURL)) {
  848. let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  849. sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
  850. } else sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
  851. return sourceMapData ? {
  852. url: sourceMappingURL,
  853. map: sourceMapData
  854. } : null;
  855. }
  856. function mapSourcePosition(position) {
  857. if (!position.source) return position;
  858. let sourceMap = getRunnerSourceMap(position);
  859. if (sourceMap ||= sourceMapCache[position.source], !sourceMap) {
  860. let urlAndMap = retrieveSourceMap(position.source);
  861. if (urlAndMap && urlAndMap.map) {
  862. let url = urlAndMap.url;
  863. sourceMap = sourceMapCache[position.source] = {
  864. url,
  865. map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
  866. };
  867. let contents = sourceMap.map?.map.sourcesContent;
  868. sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
  869. let content = contents[i];
  870. if (content && source && url) {
  871. let contentUrl = supportRelativeURL(url, source);
  872. fileContentsCache[contentUrl] = content;
  873. }
  874. });
  875. } else sourceMap = sourceMapCache[position.source] = {
  876. url: null,
  877. map: null
  878. };
  879. }
  880. if (sourceMap.map && sourceMap.url) {
  881. let originalPosition = getOriginalPosition(sourceMap.map, position);
  882. if (originalPosition && originalPosition.source != null) return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
  883. }
  884. return position;
  885. }
  886. function mapEvalOrigin(origin) {
  887. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  888. if (match) {
  889. let position = mapSourcePosition({
  890. name: null,
  891. source: match[2],
  892. line: +match[3],
  893. column: match[4] - 1
  894. });
  895. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  896. }
  897. return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
  898. }
  899. function CallSiteToString() {
  900. let fileName, fileLocation = "";
  901. if (this.isNative()) fileLocation = "native";
  902. else {
  903. fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
  904. let lineNumber = this.getLineNumber();
  905. if (lineNumber != null) {
  906. fileLocation += `:${lineNumber}`;
  907. let columnNumber = this.getColumnNumber();
  908. columnNumber && (fileLocation += `:${columnNumber}`);
  909. }
  910. }
  911. let line = "", functionName = this.getFunctionName(), addSuffix = !0, isConstructor = this.isConstructor();
  912. if (this.isToplevel() || isConstructor) isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
  913. else {
  914. let typeName = this.getTypeName();
  915. typeName === "[object Object]" && (typeName = "null");
  916. let methodName = this.getMethodName();
  917. functionName ? (typeName && functionName.indexOf(typeName) !== 0 && (line += `${typeName}.`), line += functionName, methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1 && (line += ` [as ${methodName}]`)) : line += `${typeName}.${methodName || "<anonymous>"}`;
  918. }
  919. return addSuffix && (line += ` (${fileLocation})`), line;
  920. }
  921. function cloneCallSite(frame) {
  922. let object = {};
  923. return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  924. let key = name;
  925. object[key] = /^(?:is|get)/.test(name) ? function() {
  926. return frame[key].call(frame);
  927. } : frame[key];
  928. }), object.toString = CallSiteToString, object;
  929. }
  930. function wrapCallSite(frame, state) {
  931. if (state === void 0 && (state = {
  932. nextPosition: null,
  933. curPosition: null
  934. }), frame.isNative()) return state.curPosition = null, frame;
  935. let source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  936. if (source) {
  937. let position = mapSourcePosition({
  938. name: null,
  939. source,
  940. line: frame.getLineNumber() ?? 0,
  941. column: (frame.getColumnNumber() ?? 1) - 1
  942. });
  943. state.curPosition = position, frame = cloneCallSite(frame);
  944. let originalFunctionName = frame.getFunctionName;
  945. return frame.getFunctionName = function() {
  946. let name = state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName();
  947. return name === "eval" && "_vite" in position ? null : name;
  948. }, frame.getFileName = function() {
  949. return position.source ?? null;
  950. }, frame.getLineNumber = function() {
  951. return position.line;
  952. }, frame.getColumnNumber = function() {
  953. return position.column + 1;
  954. }, frame.getScriptNameOrSourceURL = function() {
  955. return position.source;
  956. }, frame;
  957. }
  958. let origin = frame.isEval() && frame.getEvalOrigin();
  959. return origin ? (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
  960. return origin || void 0;
  961. }, frame) : frame;
  962. }
  963. function prepareStackTrace(error, stack) {
  964. let errorString = `${error.name || "Error"}: ${error.message || ""}`, state = {
  965. nextPosition: null,
  966. curPosition: null
  967. }, processedStack = [];
  968. for (let i = stack.length - 1; i >= 0; i--) processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
  969. return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
  970. }
  971. //#endregion
  972. //#region src/module-runner/sourcemap/index.ts
  973. function enableSourceMapSupport(runner) {
  974. if (runner.options.sourcemapInterceptor === "node") {
  975. if (typeof process > "u") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because global \"process\" variable is not available.");
  976. if (typeof process.setSourceMapsEnabled != "function") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because \"process.setSourceMapsEnabled\" function is not available. Please use Node >= 16.6.0.");
  977. let isEnabledAlready = process.sourceMapsEnabled ?? !1;
  978. return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
  979. }
  980. return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
  981. }
  982. //#endregion
  983. //#region src/module-runner/esmEvaluator.ts
  984. var ESModulesEvaluator = class {
  985. startOffset = getAsyncFunctionDeclarationPaddingLineCount();
  986. async runInlinedModule(context, code) {
  987. await new AsyncFunction(ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, "\"use strict\";" + code)(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey], context[ssrExportNameKey]), Object.seal(context[ssrModuleExportsKey]);
  988. }
  989. runExternalModule(filepath) {
  990. return import(filepath);
  991. }
  992. };
  993. //#endregion
  994. //#region src/module-runner/importMetaResolver.ts
  995. const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/", customizationHooksModule = `
  996. export async function resolve(specifier, context, nextResolve) {
  997. if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
  998. const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
  999. const [parsedSpecifier, parsedImporter] = JSON.parse(data)
  1000. specifier = parsedSpecifier
  1001. context.parentURL = parsedImporter
  1002. }
  1003. return nextResolve(specifier, context)
  1004. }
  1005. `;
  1006. function customizationHookResolve(specifier, context, nextResolve) {
  1007. if (specifier.startsWith(customizationHookNamespace)) {
  1008. let data = specifier.slice(42), [parsedSpecifier, parsedImporter] = JSON.parse(data);
  1009. specifier = parsedSpecifier, context.parentURL = parsedImporter;
  1010. }
  1011. return nextResolve(specifier, context);
  1012. }
  1013. let isHookRegistered = !1;
  1014. function createImportMetaResolver() {
  1015. if (isHookRegistered) return importMetaResolveWithCustomHook;
  1016. let module;
  1017. try {
  1018. module = typeof process < "u" ? process.getBuiltinModule("node:module").Module : void 0;
  1019. } catch {
  1020. return;
  1021. }
  1022. if (module) {
  1023. if (module.registerHooks) return module.registerHooks({ resolve: customizationHookResolve }), isHookRegistered = !0, importMetaResolveWithCustomHook;
  1024. if (module.register) {
  1025. try {
  1026. let hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
  1027. module.register(hookModuleContent);
  1028. } catch (e) {
  1029. if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
  1030. throw e;
  1031. }
  1032. return isHookRegistered = !0, importMetaResolveWithCustomHook;
  1033. }
  1034. }
  1035. }
  1036. function importMetaResolveWithCustomHook(specifier, importer) {
  1037. return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
  1038. }
  1039. `${customizationHookNamespace}`;
  1040. //#endregion
  1041. //#region src/module-runner/createImportMeta.ts
  1042. const envProxy = new Proxy({}, { get(_, p) {
  1043. throw Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
  1044. } });
  1045. function createDefaultImportMeta(modulePath) {
  1046. let href = posixPathToFileHref(modulePath), filename = modulePath, dirname = posixDirname(modulePath);
  1047. return {
  1048. filename: isWindows ? toWindowsPath(filename) : filename,
  1049. dirname: isWindows ? toWindowsPath(dirname) : dirname,
  1050. url: href,
  1051. env: envProxy,
  1052. resolve(_id, _parent) {
  1053. throw Error("[module runner] \"import.meta.resolve\" is not supported.");
  1054. },
  1055. glob() {
  1056. throw Error("[module runner] \"import.meta.glob\" is statically replaced during file transformation. Make sure to reference it by the full name.");
  1057. }
  1058. };
  1059. }
  1060. /**
  1061. * Create import.meta object for Node.js.
  1062. */
  1063. function createNodeImportMeta(modulePath) {
  1064. let defaultMeta = createDefaultImportMeta(modulePath), href = defaultMeta.url, importMetaResolver = createImportMetaResolver();
  1065. return {
  1066. ...defaultMeta,
  1067. main: !1,
  1068. resolve(id, parent) {
  1069. return (importMetaResolver ?? defaultMeta.resolve)(id, parent ?? href);
  1070. }
  1071. };
  1072. }
  1073. //#endregion
  1074. //#region src/module-runner/runner.ts
  1075. var ModuleRunner = class {
  1076. evaluatedModules;
  1077. hmrClient;
  1078. transport;
  1079. resetSourceMapSupport;
  1080. concurrentModuleNodePromises = /* @__PURE__ */ new Map();
  1081. isBuiltin;
  1082. builtinsPromise;
  1083. closed = !1;
  1084. constructor(options, evaluator = new ESModulesEvaluator(), debug) {
  1085. if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
  1086. let optionsHmr = options.hmr ?? !0;
  1087. if (this.hmrClient = new HMRClient(optionsHmr === !0 || optionsHmr.logger === void 0 ? hmrLogger : optionsHmr.logger === !1 ? silentConsole : optionsHmr.logger, this.transport, ({ acceptedPath }) => this.import(acceptedPath)), !this.transport.connect) throw Error("HMR is not supported by this runner transport, but `hmr` option was set to true");
  1088. this.transport.connect(createHMRHandlerForRunner(this));
  1089. } else this.transport.connect?.();
  1090. options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
  1091. }
  1092. /**
  1093. * URL to execute. Accepts file path, server path or id relative to the root.
  1094. */
  1095. async import(url) {
  1096. let fetchedModule = await this.cachedModule(url);
  1097. return await this.cachedRequest(url, fetchedModule);
  1098. }
  1099. /**
  1100. * Clear all caches including HMR listeners.
  1101. */
  1102. clearCache() {
  1103. this.evaluatedModules.clear(), this.hmrClient?.clear();
  1104. }
  1105. /**
  1106. * Clears all caches, removes all HMR listeners, and resets source map support.
  1107. * This method doesn't stop the HMR connection.
  1108. */
  1109. async close() {
  1110. this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
  1111. }
  1112. /**
  1113. * Returns `true` if the runtime has been closed by calling `close()` method.
  1114. */
  1115. isClosed() {
  1116. return this.closed;
  1117. }
  1118. processImport(exports, fetchResult, metadata) {
  1119. if (!("externalize" in fetchResult)) return exports;
  1120. let { url, type } = fetchResult;
  1121. return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
  1122. }
  1123. isCircularModule(mod) {
  1124. for (let importedFile of mod.imports) if (mod.importers.has(importedFile)) return !0;
  1125. return !1;
  1126. }
  1127. isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
  1128. for (let importer of importers) {
  1129. if (visited.has(importer)) continue;
  1130. if (visited.add(importer), importer === moduleUrl) return !0;
  1131. let mod = this.evaluatedModules.getModuleById(importer);
  1132. if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited)) return !0;
  1133. }
  1134. return !1;
  1135. }
  1136. async cachedRequest(url, mod, callstack = [], metadata) {
  1137. let meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
  1138. if (importee && importers.add(importee), mod.evaluated && mod.promise) return this.processImport(await mod.promise, meta, metadata);
  1139. if ((callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports) return this.processImport(mod.exports, meta, metadata);
  1140. let debugTimer;
  1141. this.debug && (debugTimer = setTimeout(() => {
  1142. this.debug(`[module runner] module ${moduleId} takes over 2s to load.\n${`stack:\n${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join("\n")}`}`);
  1143. }, 2e3));
  1144. try {
  1145. if (mod.promise) return this.processImport(await mod.promise, meta, metadata);
  1146. let promise = this.directRequest(url, mod, callstack);
  1147. return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
  1148. } finally {
  1149. mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
  1150. }
  1151. }
  1152. async cachedModule(url, importer) {
  1153. let cached = this.concurrentModuleNodePromises.get(url);
  1154. if (cached) this.debug?.("[module runner] using cached module info for", url);
  1155. else {
  1156. let cachedModule = this.evaluatedModules.getModuleByUrl(url);
  1157. cached = this.getModuleInformation(url, importer, cachedModule).finally(() => {
  1158. this.concurrentModuleNodePromises.delete(url);
  1159. }), this.concurrentModuleNodePromises.set(url, cached);
  1160. }
  1161. return cached;
  1162. }
  1163. ensureBuiltins() {
  1164. if (!this.isBuiltin) return this.builtinsPromise ??= (async () => {
  1165. try {
  1166. this.debug?.("[module runner] fetching builtins from server");
  1167. let builtins = (await this.transport.invoke("getBuiltins", [])).map((builtin) => typeof builtin == "object" && builtin && "type" in builtin ? builtin.type === "string" ? builtin.value : new RegExp(builtin.source, builtin.flags) : builtin);
  1168. this.isBuiltin = createIsBuiltin(builtins), this.debug?.("[module runner] builtins loaded:", builtins);
  1169. } finally {
  1170. this.builtinsPromise = void 0;
  1171. }
  1172. })(), this.builtinsPromise;
  1173. }
  1174. async getModuleInformation(url, importer, cachedModule) {
  1175. if (this.closed) throw Error("Vite module runner has been closed.");
  1176. await this.ensureBuiltins(), this.debug?.("[module runner] fetching", url);
  1177. let isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = url.startsWith("data:") || this.isBuiltin?.(url) ? {
  1178. externalize: url,
  1179. type: "builtin"
  1180. } : await this.transport.invoke("fetchModule", [
  1181. url,
  1182. importer,
  1183. {
  1184. cached: isCached,
  1185. startOffset: this.evaluator.startOffset
  1186. }
  1187. ]);
  1188. if ("cache" in fetchedModule) {
  1189. if (!cachedModule || !cachedModule.meta) throw Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
  1190. return cachedModule;
  1191. }
  1192. let moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
  1193. return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
  1194. }
  1195. async directRequest(url, mod, _callstack) {
  1196. let fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
  1197. let importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
  1198. return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
  1199. }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
  1200. if ("externalize" in fetchResult) {
  1201. let { externalize } = fetchResult;
  1202. this.debug?.("[module runner] externalizing", externalize);
  1203. let exports = await this.evaluator.runExternalModule(externalize);
  1204. return mod.exports = exports, exports;
  1205. }
  1206. let { code, file } = fetchResult;
  1207. if (code == null) {
  1208. let importer = callstack[callstack.length - 2];
  1209. throw Error(`[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`);
  1210. }
  1211. let createImportMeta = this.options.createImportMeta ?? createDefaultImportMeta, modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), meta = await createImportMeta(modulePath), exports = Object.create(null);
  1212. Object.defineProperty(exports, Symbol.toStringTag, {
  1213. value: "Module",
  1214. enumerable: !1,
  1215. configurable: !1
  1216. }), mod.exports = exports;
  1217. let hotContext;
  1218. this.hmrClient && Object.defineProperty(meta, "hot", {
  1219. enumerable: !0,
  1220. get: () => {
  1221. if (!this.hmrClient) throw Error("[module runner] HMR client was closed.");
  1222. return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
  1223. },
  1224. set: (value) => {
  1225. hotContext = value;
  1226. }
  1227. });
  1228. let context = {
  1229. [ssrImportKey]: request,
  1230. [ssrDynamicImportKey]: dynamicRequest,
  1231. [ssrModuleExportsKey]: exports,
  1232. [ssrExportAllKey]: (obj) => exportAll(exports, obj),
  1233. [ssrExportNameKey]: (name, getter) => Object.defineProperty(exports, name, {
  1234. enumerable: !0,
  1235. configurable: !0,
  1236. get: getter
  1237. }),
  1238. [ssrImportMetaKey]: meta
  1239. };
  1240. return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
  1241. }
  1242. };
  1243. function exportAll(exports, sourceModule) {
  1244. if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
  1245. for (let key in sourceModule) if (key !== "default" && key !== "__esModule" && !(key in exports)) try {
  1246. Object.defineProperty(exports, key, {
  1247. enumerable: !0,
  1248. configurable: !0,
  1249. get: () => sourceModule[key]
  1250. });
  1251. } catch {}
  1252. }
  1253. }
  1254. //#endregion
  1255. export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };