module-runner.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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.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 SyntaxError(moduleType === "module" ? `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'` : `\
  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.7/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) {
  752. if (runner.isClosed()) break;
  753. try {
  754. await runner.import(url);
  755. } catch (err) {
  756. if (runner.isClosed()) break;
  757. err.code !== "ERR_OUTDATED_OPTIMIZED_DEP" && hmrClient.logger.error(`An error happened during full reload\n${err.message}\n${err.stack}`);
  758. }
  759. }
  760. break;
  761. }
  762. case "prune":
  763. await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
  764. break;
  765. case "error": {
  766. await hmrClient.notifyListeners("vite:error", payload);
  767. let err = payload.err;
  768. hmrClient.logger.error(`Internal Server Error\n${err.message}\n${err.stack}`);
  769. break;
  770. }
  771. case "ping": break;
  772. default: return payload;
  773. }
  774. });
  775. }
  776. function getModulesByFile(runner, file) {
  777. let nodes = runner.evaluatedModules.getModulesByFile(file);
  778. return nodes ? [...nodes].map((node) => node.id) : [];
  779. }
  780. function getModulesEntrypoints(runner, modules, visited = /* @__PURE__ */ new Set(), entrypoints = /* @__PURE__ */ new Set()) {
  781. for (let moduleId of modules) {
  782. if (visited.has(moduleId)) continue;
  783. visited.add(moduleId);
  784. let module = runner.evaluatedModules.getModuleById(moduleId);
  785. if (module) {
  786. if (!module.importers.size) {
  787. entrypoints.add(module.url);
  788. continue;
  789. }
  790. for (let importer of module.importers) getModulesEntrypoints(runner, [importer], visited, entrypoints);
  791. }
  792. }
  793. return entrypoints;
  794. }
  795. function findAllEntrypoints(runner, entrypoints = /* @__PURE__ */ new Set()) {
  796. for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
  797. return entrypoints;
  798. }
  799. //#endregion
  800. //#region src/module-runner/sourcemap/interceptor.ts
  801. const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => ((...args) => {
  802. for (let handler of handlers) {
  803. let result = handler(...args);
  804. if (result) return result;
  805. }
  806. return null;
  807. }), retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
  808. let overridden = !1;
  809. const originalPrepare = Error.prepareStackTrace;
  810. function resetInterceptor(runner, options) {
  811. evaluatedModulesCache.delete(runner.evaluatedModules), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), evaluatedModulesCache.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
  812. }
  813. function interceptStackTrace(runner, options = {}) {
  814. 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);
  815. }
  816. function supportRelativeURL(file, url) {
  817. if (!file) return url;
  818. let dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir), protocol = match ? match[0] : "", startPath = dir.slice(protocol.length);
  819. return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
  820. }
  821. function getRunnerSourceMap(position) {
  822. for (let moduleGraph of evaluatedModulesCache) {
  823. let sourceMap = moduleGraph.getModuleSourceMapById(position.source);
  824. if (sourceMap) return {
  825. url: position.source,
  826. map: sourceMap,
  827. vite: !0
  828. };
  829. }
  830. return null;
  831. }
  832. function retrieveFile(path) {
  833. if (path in fileContentsCache) return fileContentsCache[path];
  834. let content = retrieveFileFromHandlers(path);
  835. return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
  836. }
  837. function retrieveSourceMapURL(source) {
  838. let fileData = retrieveFile(source);
  839. if (!fileData) return null;
  840. let re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm, lastMatch, match;
  841. for (; match = re.exec(fileData);) lastMatch = match;
  842. return lastMatch ? lastMatch[1] : null;
  843. }
  844. const reSourceMap = /^data:application\/json[^,]+base64,/;
  845. function retrieveSourceMap(source) {
  846. let urlAndMap = retrieveSourceMapFromHandlers(source);
  847. if (urlAndMap) return urlAndMap;
  848. let sourceMappingURL = retrieveSourceMapURL(source);
  849. if (!sourceMappingURL) return null;
  850. let sourceMapData;
  851. if (reSourceMap.test(sourceMappingURL)) {
  852. let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  853. sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
  854. } else sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
  855. return sourceMapData ? {
  856. url: sourceMappingURL,
  857. map: sourceMapData
  858. } : null;
  859. }
  860. function mapSourcePosition(position) {
  861. if (!position.source) return position;
  862. let sourceMap = getRunnerSourceMap(position);
  863. if (sourceMap ||= sourceMapCache[position.source], !sourceMap) {
  864. let urlAndMap = retrieveSourceMap(position.source);
  865. if (urlAndMap && urlAndMap.map) {
  866. let url = urlAndMap.url;
  867. sourceMap = sourceMapCache[position.source] = {
  868. url,
  869. map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
  870. };
  871. let contents = sourceMap.map?.map.sourcesContent;
  872. sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
  873. let content = contents[i];
  874. if (content && source && url) {
  875. let contentUrl = supportRelativeURL(url, source);
  876. fileContentsCache[contentUrl] = content;
  877. }
  878. });
  879. } else sourceMap = sourceMapCache[position.source] = {
  880. url: null,
  881. map: null
  882. };
  883. }
  884. if (sourceMap.map && sourceMap.url) {
  885. let originalPosition = getOriginalPosition(sourceMap.map, position);
  886. if (originalPosition && originalPosition.source != null) return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
  887. }
  888. return position;
  889. }
  890. function mapEvalOrigin(origin) {
  891. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  892. if (match) {
  893. let position = mapSourcePosition({
  894. name: null,
  895. source: match[2],
  896. line: +match[3],
  897. column: match[4] - 1
  898. });
  899. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  900. }
  901. return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
  902. }
  903. function CallSiteToString() {
  904. let fileName, fileLocation = "";
  905. if (this.isNative()) fileLocation = "native";
  906. else {
  907. fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
  908. let lineNumber = this.getLineNumber();
  909. if (lineNumber != null) {
  910. fileLocation += `:${lineNumber}`;
  911. let columnNumber = this.getColumnNumber();
  912. columnNumber && (fileLocation += `:${columnNumber}`);
  913. }
  914. }
  915. let line = "", functionName = this.getFunctionName(), addSuffix = !0, isConstructor = this.isConstructor();
  916. if (this.isToplevel() || isConstructor) isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
  917. else {
  918. let typeName = this.getTypeName();
  919. typeName === "[object Object]" && (typeName = "null");
  920. let methodName = this.getMethodName();
  921. 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>"}`;
  922. }
  923. return addSuffix && (line += ` (${fileLocation})`), line;
  924. }
  925. function cloneCallSite(frame) {
  926. let object = {};
  927. return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  928. let key = name;
  929. object[key] = /^(?:is|get)/.test(name) ? function() {
  930. return frame[key].call(frame);
  931. } : frame[key];
  932. }), object.toString = CallSiteToString, object;
  933. }
  934. function wrapCallSite(frame, state) {
  935. if (state === void 0 && (state = {
  936. nextPosition: null,
  937. curPosition: null
  938. }), frame.isNative()) return state.curPosition = null, frame;
  939. let source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  940. if (source) {
  941. let position = mapSourcePosition({
  942. name: null,
  943. source,
  944. line: frame.getLineNumber() ?? 0,
  945. column: (frame.getColumnNumber() ?? 1) - 1
  946. });
  947. state.curPosition = position, frame = cloneCallSite(frame);
  948. let originalFunctionName = frame.getFunctionName;
  949. return frame.getFunctionName = function() {
  950. let name = state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName();
  951. return name === "eval" && "_vite" in position ? null : name;
  952. }, frame.getFileName = function() {
  953. return position.source ?? null;
  954. }, frame.getLineNumber = function() {
  955. return position.line;
  956. }, frame.getColumnNumber = function() {
  957. return position.column + 1;
  958. }, frame.getScriptNameOrSourceURL = function() {
  959. return position.source;
  960. }, frame;
  961. }
  962. let origin = frame.isEval() && frame.getEvalOrigin();
  963. return origin ? (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
  964. return origin || void 0;
  965. }, frame) : frame;
  966. }
  967. function prepareStackTrace(error, stack) {
  968. let errorString = `${error.name || "Error"}: ${error.message || ""}`, state = {
  969. nextPosition: null,
  970. curPosition: null
  971. }, processedStack = [];
  972. for (let i = stack.length - 1; i >= 0; i--) processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
  973. return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
  974. }
  975. //#endregion
  976. //#region src/module-runner/sourcemap/index.ts
  977. function enableSourceMapSupport(runner) {
  978. if (runner.options.sourcemapInterceptor === "node") {
  979. if (typeof process > "u") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because global \"process\" variable is not available.");
  980. if (typeof process.setSourceMapsEnabled != "function") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because \"process.setSourceMapsEnabled\" function is not available. Please use Node >= 16.6.0.");
  981. let isEnabledAlready = process.sourceMapsEnabled ?? !1;
  982. return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
  983. }
  984. return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
  985. }
  986. //#endregion
  987. //#region src/module-runner/esmEvaluator.ts
  988. var ESModulesEvaluator = class {
  989. startOffset = getAsyncFunctionDeclarationPaddingLineCount();
  990. async runInlinedModule(context, code) {
  991. 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]);
  992. }
  993. runExternalModule(filepath) {
  994. return import(filepath);
  995. }
  996. };
  997. //#endregion
  998. //#region src/module-runner/importMetaResolver.ts
  999. const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/", customizationHooksModule = `
  1000. export async function resolve(specifier, context, nextResolve) {
  1001. if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
  1002. const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
  1003. const [parsedSpecifier, parsedImporter] = JSON.parse(data)
  1004. specifier = parsedSpecifier
  1005. context.parentURL = parsedImporter
  1006. }
  1007. return nextResolve(specifier, context)
  1008. }
  1009. `;
  1010. function customizationHookResolve(specifier, context, nextResolve) {
  1011. if (specifier.startsWith(customizationHookNamespace)) {
  1012. let data = specifier.slice(42), [parsedSpecifier, parsedImporter] = JSON.parse(data);
  1013. specifier = parsedSpecifier, context.parentURL = parsedImporter;
  1014. }
  1015. return nextResolve(specifier, context);
  1016. }
  1017. let isHookRegistered = !1;
  1018. function createImportMetaResolver() {
  1019. if (isHookRegistered) return importMetaResolveWithCustomHook;
  1020. let module;
  1021. try {
  1022. module = typeof process < "u" ? process.getBuiltinModule("node:module").Module : void 0;
  1023. } catch {
  1024. return;
  1025. }
  1026. if (module) {
  1027. if (module.registerHooks) return module.registerHooks({ resolve: customizationHookResolve }), isHookRegistered = !0, importMetaResolveWithCustomHook;
  1028. if (module.register) {
  1029. try {
  1030. let hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
  1031. module.register(hookModuleContent);
  1032. } catch (e) {
  1033. if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
  1034. throw e;
  1035. }
  1036. return isHookRegistered = !0, importMetaResolveWithCustomHook;
  1037. }
  1038. }
  1039. }
  1040. function importMetaResolveWithCustomHook(specifier, importer) {
  1041. return import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
  1042. }
  1043. `${customizationHookNamespace}`;
  1044. //#endregion
  1045. //#region src/module-runner/createImportMeta.ts
  1046. const envProxy = new Proxy({}, { get(_, p) {
  1047. throw Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
  1048. } });
  1049. function createDefaultImportMeta(modulePath) {
  1050. let href = posixPathToFileHref(modulePath), filename = modulePath, dirname = posixDirname(modulePath);
  1051. return {
  1052. filename: isWindows ? toWindowsPath(filename) : filename,
  1053. dirname: isWindows ? toWindowsPath(dirname) : dirname,
  1054. url: href,
  1055. env: envProxy,
  1056. resolve(_id, _parent) {
  1057. throw Error("[module runner] \"import.meta.resolve\" is not supported.");
  1058. },
  1059. glob() {
  1060. throw Error("[module runner] \"import.meta.glob\" is statically replaced during file transformation. Make sure to reference it by the full name.");
  1061. }
  1062. };
  1063. }
  1064. /**
  1065. * Create import.meta object for Node.js.
  1066. */
  1067. function createNodeImportMeta(modulePath) {
  1068. let defaultMeta = createDefaultImportMeta(modulePath), href = defaultMeta.url, importMetaResolver = createImportMetaResolver();
  1069. return {
  1070. ...defaultMeta,
  1071. main: !1,
  1072. resolve(id, parent) {
  1073. return (importMetaResolver ?? defaultMeta.resolve)(id, parent ?? href);
  1074. }
  1075. };
  1076. }
  1077. //#endregion
  1078. //#region src/module-runner/runner.ts
  1079. var ModuleRunner = class {
  1080. evaluatedModules;
  1081. hmrClient;
  1082. transport;
  1083. resetSourceMapSupport;
  1084. concurrentModuleNodePromises = /* @__PURE__ */ new Map();
  1085. isBuiltin;
  1086. builtinsPromise;
  1087. closed = !1;
  1088. constructor(options, evaluator = new ESModulesEvaluator(), debug) {
  1089. if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
  1090. let optionsHmr = options.hmr ?? !0;
  1091. 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");
  1092. this.transport.connect(createHMRHandlerForRunner(this));
  1093. } else this.transport.connect?.();
  1094. options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
  1095. }
  1096. /**
  1097. * URL to execute. Accepts file path, server path or id relative to the root.
  1098. */
  1099. async import(url) {
  1100. let fetchedModule = await this.cachedModule(url);
  1101. return await this.cachedRequest(url, fetchedModule);
  1102. }
  1103. /**
  1104. * Clear all caches including HMR listeners.
  1105. */
  1106. clearCache() {
  1107. this.evaluatedModules.clear(), this.hmrClient?.clear();
  1108. }
  1109. /**
  1110. * Clears all caches, removes all HMR listeners, and resets source map support.
  1111. * This method doesn't stop the HMR connection.
  1112. */
  1113. async close() {
  1114. this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
  1115. }
  1116. /**
  1117. * Returns `true` if the runtime has been closed by calling `close()` method.
  1118. */
  1119. isClosed() {
  1120. return this.closed;
  1121. }
  1122. processImport(exports, fetchResult, metadata) {
  1123. if (!("externalize" in fetchResult)) return exports;
  1124. let { url, type } = fetchResult;
  1125. return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
  1126. }
  1127. isCircularModule(mod) {
  1128. for (let importedFile of mod.imports) if (mod.importers.has(importedFile)) return !0;
  1129. return !1;
  1130. }
  1131. isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
  1132. for (let importer of importers) {
  1133. if (visited.has(importer)) continue;
  1134. if (visited.add(importer), importer === moduleUrl) return !0;
  1135. let mod = this.evaluatedModules.getModuleById(importer);
  1136. if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited)) return !0;
  1137. }
  1138. return !1;
  1139. }
  1140. async cachedRequest(url, mod, callstack = [], metadata) {
  1141. let meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
  1142. if (importee && importers.add(importee), mod.evaluated && mod.promise) return this.processImport(await mod.promise, meta, metadata);
  1143. if ((callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports) return this.processImport(mod.exports, meta, metadata);
  1144. let debugTimer;
  1145. this.debug && (debugTimer = setTimeout(() => {
  1146. this.debug(`[module runner] module ${moduleId} takes over 2s to load.\n${`stack:\n${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join("\n")}`}`);
  1147. }, 2e3));
  1148. try {
  1149. if (mod.promise) return this.processImport(await mod.promise, meta, metadata);
  1150. let promise = this.directRequest(url, mod, callstack);
  1151. return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
  1152. } finally {
  1153. mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
  1154. }
  1155. }
  1156. async cachedModule(url, importer) {
  1157. let cached = this.concurrentModuleNodePromises.get(url);
  1158. if (cached) this.debug?.("[module runner] using cached module info for", url);
  1159. else {
  1160. let cachedModule = this.evaluatedModules.getModuleByUrl(url);
  1161. cached = this.getModuleInformation(url, importer, cachedModule).finally(() => {
  1162. this.concurrentModuleNodePromises.delete(url);
  1163. }), this.concurrentModuleNodePromises.set(url, cached);
  1164. }
  1165. return cached;
  1166. }
  1167. ensureBuiltins() {
  1168. if (!this.isBuiltin) return this.builtinsPromise ??= (async () => {
  1169. try {
  1170. this.debug?.("[module runner] fetching builtins from server");
  1171. 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);
  1172. this.isBuiltin = createIsBuiltin(builtins), this.debug?.("[module runner] builtins loaded:", builtins);
  1173. } finally {
  1174. this.builtinsPromise = void 0;
  1175. }
  1176. })(), this.builtinsPromise;
  1177. }
  1178. async getModuleInformation(url, importer, cachedModule) {
  1179. if (this.closed) throw Error("Vite module runner has been closed.");
  1180. await this.ensureBuiltins(), this.debug?.("[module runner] fetching", url);
  1181. let isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = url.startsWith("data:") || this.isBuiltin?.(url) ? {
  1182. externalize: url,
  1183. type: "builtin"
  1184. } : await this.transport.invoke("fetchModule", [
  1185. url,
  1186. importer,
  1187. {
  1188. cached: isCached,
  1189. startOffset: this.evaluator.startOffset
  1190. }
  1191. ]);
  1192. if ("cache" in fetchedModule) {
  1193. if (!cachedModule || !cachedModule.meta) throw Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
  1194. return cachedModule;
  1195. }
  1196. let moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
  1197. return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
  1198. }
  1199. async directRequest(url, mod, _callstack) {
  1200. let fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
  1201. let importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
  1202. return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
  1203. }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
  1204. if ("externalize" in fetchResult) {
  1205. let { externalize } = fetchResult;
  1206. this.debug?.("[module runner] externalizing", externalize);
  1207. let exports = await this.evaluator.runExternalModule(externalize);
  1208. return mod.exports = exports, exports;
  1209. }
  1210. let { code, file } = fetchResult;
  1211. if (code == null) {
  1212. let importer = callstack[callstack.length - 2];
  1213. throw Error(`[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`);
  1214. }
  1215. let createImportMeta = this.options.createImportMeta ?? createDefaultImportMeta, modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), meta = await createImportMeta(modulePath), exports = Object.create(null);
  1216. Object.defineProperty(exports, Symbol.toStringTag, {
  1217. value: "Module",
  1218. enumerable: !1,
  1219. configurable: !1
  1220. }), mod.exports = exports;
  1221. let hotContext;
  1222. this.hmrClient && Object.defineProperty(meta, "hot", {
  1223. enumerable: !0,
  1224. get: () => {
  1225. if (!this.hmrClient) throw Error("[module runner] HMR client was closed.");
  1226. return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
  1227. },
  1228. set: (value) => {
  1229. hotContext = value;
  1230. }
  1231. });
  1232. let context = {
  1233. [ssrImportKey]: request,
  1234. [ssrDynamicImportKey]: dynamicRequest,
  1235. [ssrModuleExportsKey]: exports,
  1236. [ssrExportAllKey]: (obj) => exportAll(exports, obj),
  1237. [ssrExportNameKey]: (name, getter) => Object.defineProperty(exports, name, {
  1238. enumerable: !0,
  1239. configurable: !0,
  1240. get: getter
  1241. }),
  1242. [ssrImportMetaKey]: meta
  1243. };
  1244. return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
  1245. }
  1246. };
  1247. function exportAll(exports, sourceModule) {
  1248. if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
  1249. for (let key in sourceModule) if (key !== "default" && key !== "__esModule" && !(key in exports)) try {
  1250. Object.defineProperty(exports, key, {
  1251. enumerable: !0,
  1252. configurable: !0,
  1253. get: () => sourceModule[key]
  1254. });
  1255. } catch {}
  1256. }
  1257. }
  1258. //#endregion
  1259. export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };