module-runner.js 53 KB

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