1 | const VALID_ID_PREFIX = "/@id/", NULL_BYTE_PLACEHOLDER = "__x00__";
|
---|
2 | let SOURCEMAPPING_URL = "sourceMa";
|
---|
3 | SOURCEMAPPING_URL += "ppingURL";
|
---|
4 | const isWindows = typeof process < "u" && process.platform === "win32";
|
---|
5 | function wrapId(id) {
|
---|
6 | return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
|
---|
7 | }
|
---|
8 | function unwrapId(id) {
|
---|
9 | return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
|
---|
10 | }
|
---|
11 | const windowsSlashRE = /\\/g;
|
---|
12 | function slash(p) {
|
---|
13 | return p.replace(windowsSlashRE, "/");
|
---|
14 | }
|
---|
15 | const postfixRE = /[?#].*$/;
|
---|
16 | function cleanUrl(url) {
|
---|
17 | return url.replace(postfixRE, "");
|
---|
18 | }
|
---|
19 | function isPrimitive(value) {
|
---|
20 | return !value || typeof value != "object" && typeof value != "function";
|
---|
21 | }
|
---|
22 | function withTrailingSlash(path) {
|
---|
23 | return path[path.length - 1] !== "/" ? `${path}/` : path;
|
---|
24 | }
|
---|
25 | const AsyncFunction = async function() {
|
---|
26 | }.constructor, _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
---|
27 | function normalizeWindowsPath(input = "") {
|
---|
28 | return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
---|
29 | }
|
---|
30 | const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
|
---|
31 | function cwd() {
|
---|
32 | return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
|
---|
33 | }
|
---|
34 | const resolve = function(...arguments_) {
|
---|
35 | arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
---|
36 | let resolvedPath = "", resolvedAbsolute = !1;
|
---|
37 | for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
---|
38 | const path = index >= 0 ? arguments_[index] : cwd();
|
---|
39 | !path || path.length === 0 || (resolvedPath = `${path}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path));
|
---|
40 | }
|
---|
41 | return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
|
---|
42 | };
|
---|
43 | function normalizeString(path, allowAboveRoot) {
|
---|
44 | let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
|
---|
45 | for (let index = 0; index <= path.length; ++index) {
|
---|
46 | if (index < path.length)
|
---|
47 | char = path[index];
|
---|
48 | else {
|
---|
49 | if (char === "/")
|
---|
50 | break;
|
---|
51 | char = "/";
|
---|
52 | }
|
---|
53 | if (char === "/") {
|
---|
54 | if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
|
---|
55 | if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
---|
56 | if (res.length > 2) {
|
---|
57 | const lastSlashIndex = res.lastIndexOf("/");
|
---|
58 | lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
|
---|
59 | continue;
|
---|
60 | } else if (res.length > 0) {
|
---|
61 | res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
|
---|
62 | continue;
|
---|
63 | }
|
---|
64 | }
|
---|
65 | allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
|
---|
66 | } else
|
---|
67 | res.length > 0 ? res += `/${path.slice(lastSlash + 1, index)}` : res = path.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
|
---|
68 | lastSlash = index, dots = 0;
|
---|
69 | } else char === "." && dots !== -1 ? ++dots : dots = -1;
|
---|
70 | }
|
---|
71 | return res;
|
---|
72 | }
|
---|
73 | const isAbsolute = function(p) {
|
---|
74 | return _IS_ABSOLUTE_RE.test(p);
|
---|
75 | }, dirname = function(p) {
|
---|
76 | const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
|
---|
77 | return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
|
---|
78 | }, decodeBase64 = typeof atob < "u" ? atob : (str) => Buffer.from(str, "base64").toString("utf-8"), CHAR_FORWARD_SLASH = 47, CHAR_BACKWARD_SLASH = 92, percentRegEx = /%/g, backslashRegEx = /\\/g, newlineRegEx = /\n/g, carriageReturnRegEx = /\r/g, tabRegEx = /\t/g, questionRegex = /\?/g, hashRegex = /#/g;
|
---|
79 | function encodePathChars(filepath) {
|
---|
80 | return filepath.indexOf("%") !== -1 && (filepath = filepath.replace(percentRegEx, "%25")), !isWindows && filepath.indexOf("\\") !== -1 && (filepath = filepath.replace(backslashRegEx, "%5C")), filepath.indexOf(`
|
---|
81 | `) !== -1 && (filepath = filepath.replace(newlineRegEx, "%0A")), filepath.indexOf("\r") !== -1 && (filepath = filepath.replace(carriageReturnRegEx, "%0D")), filepath.indexOf(" ") !== -1 && (filepath = filepath.replace(tabRegEx, "%09")), filepath;
|
---|
82 | }
|
---|
83 | const posixDirname = dirname, posixResolve = resolve;
|
---|
84 | function posixPathToFileHref(posixPath) {
|
---|
85 | let resolved = posixResolve(posixPath);
|
---|
86 | const filePathLast = posixPath.charCodeAt(posixPath.length - 1);
|
---|
87 | return (filePathLast === CHAR_FORWARD_SLASH || isWindows && filePathLast === CHAR_BACKWARD_SLASH) && 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;
|
---|
88 | }
|
---|
89 | function toWindowsPath(path) {
|
---|
90 | return path.replace(/\//g, "\\");
|
---|
91 | }
|
---|
92 | const comma = 44, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
|
---|
93 | for (let i = 0; i < chars.length; i++) {
|
---|
94 | const c = chars.charCodeAt(i);
|
---|
95 | intToChar[i] = c, charToInt[c] = i;
|
---|
96 | }
|
---|
97 | function decodeInteger(reader, relative) {
|
---|
98 | let value = 0, shift = 0, integer = 0;
|
---|
99 | do {
|
---|
100 | const c = reader.next();
|
---|
101 | integer = charToInt[c], value |= (integer & 31) << shift, shift += 5;
|
---|
102 | } while (integer & 32);
|
---|
103 | const shouldNegate = value & 1;
|
---|
104 | return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
|
---|
105 | }
|
---|
106 | function hasMoreVlq(reader, max) {
|
---|
107 | return reader.pos >= max ? !1 : reader.peek() !== comma;
|
---|
108 | }
|
---|
109 | class StringReader {
|
---|
110 | constructor(buffer) {
|
---|
111 | this.pos = 0, this.buffer = buffer;
|
---|
112 | }
|
---|
113 | next() {
|
---|
114 | return this.buffer.charCodeAt(this.pos++);
|
---|
115 | }
|
---|
116 | peek() {
|
---|
117 | return this.buffer.charCodeAt(this.pos);
|
---|
118 | }
|
---|
119 | indexOf(char) {
|
---|
120 | const { buffer, pos } = this, idx = buffer.indexOf(char, pos);
|
---|
121 | return idx === -1 ? buffer.length : idx;
|
---|
122 | }
|
---|
123 | }
|
---|
124 | function decode(mappings) {
|
---|
125 | const { length } = mappings, reader = new StringReader(mappings), decoded = [];
|
---|
126 | let genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
|
---|
127 | do {
|
---|
128 | const semi = reader.indexOf(";"), line = [];
|
---|
129 | let sorted = !0, lastCol = 0;
|
---|
130 | for (genColumn = 0; reader.pos < semi; ) {
|
---|
131 | let seg;
|
---|
132 | 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 = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]) : seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]) : seg = [genColumn], line.push(seg), reader.pos++;
|
---|
133 | }
|
---|
134 | sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
|
---|
135 | } while (reader.pos <= length);
|
---|
136 | return decoded;
|
---|
137 | }
|
---|
138 | function sort(line) {
|
---|
139 | line.sort(sortComparator);
|
---|
140 | }
|
---|
141 | function sortComparator(a, b) {
|
---|
142 | return a[0] - b[0];
|
---|
143 | }
|
---|
144 | const COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4;
|
---|
145 | let found = !1;
|
---|
146 | function binarySearch(haystack, needle, low, high) {
|
---|
147 | for (; low <= high; ) {
|
---|
148 | const mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
|
---|
149 | if (cmp === 0)
|
---|
150 | return found = !0, mid;
|
---|
151 | cmp < 0 ? low = mid + 1 : high = mid - 1;
|
---|
152 | }
|
---|
153 | return found = !1, low - 1;
|
---|
154 | }
|
---|
155 | function upperBound(haystack, needle, index) {
|
---|
156 | for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++)
|
---|
157 | ;
|
---|
158 | return index;
|
---|
159 | }
|
---|
160 | function lowerBound(haystack, needle, index) {
|
---|
161 | for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--)
|
---|
162 | ;
|
---|
163 | return index;
|
---|
164 | }
|
---|
165 | function memoizedBinarySearch(haystack, needle, state, key) {
|
---|
166 | const { lastKey, lastNeedle, lastIndex } = state;
|
---|
167 | let low = 0, high = haystack.length - 1;
|
---|
168 | if (key === lastKey) {
|
---|
169 | if (needle === lastNeedle)
|
---|
170 | return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
|
---|
171 | needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
|
---|
172 | }
|
---|
173 | return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
|
---|
174 | }
|
---|
175 | const 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)", LEAST_UPPER_BOUND = -1, GREATEST_LOWER_BOUND = 1;
|
---|
176 | function cast(map) {
|
---|
177 | return map;
|
---|
178 | }
|
---|
179 | function decodedMappings(map) {
|
---|
180 | var _a;
|
---|
181 | return (_a = map)._decoded || (_a._decoded = decode(map._encoded));
|
---|
182 | }
|
---|
183 | function originalPositionFor(map, needle) {
|
---|
184 | let { line, column, bias } = needle;
|
---|
185 | if (line--, line < 0)
|
---|
186 | throw new Error(LINE_GTR_ZERO);
|
---|
187 | if (column < 0)
|
---|
188 | throw new Error(COL_GTR_EQ_ZERO);
|
---|
189 | const decoded = decodedMappings(map);
|
---|
190 | if (line >= decoded.length)
|
---|
191 | return OMapping(null, null, null, null);
|
---|
192 | const segments = decoded[line], index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
|
---|
193 | if (index === -1)
|
---|
194 | return OMapping(null, null, null, null);
|
---|
195 | const segment = segments[index];
|
---|
196 | if (segment.length === 1)
|
---|
197 | return OMapping(null, null, null, null);
|
---|
198 | const { names, resolvedSources } = map;
|
---|
199 | return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
|
---|
200 | }
|
---|
201 | function OMapping(source, line, column, name) {
|
---|
202 | return { source, line, column, name };
|
---|
203 | }
|
---|
204 | function traceSegmentInternal(segments, memo, line, column, bias) {
|
---|
205 | let index = memoizedBinarySearch(segments, column, memo, line);
|
---|
206 | return found ? index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index) : bias === LEAST_UPPER_BOUND && index++, index === -1 || index === segments.length ? -1 : index;
|
---|
207 | }
|
---|
208 | class DecodedMap {
|
---|
209 | constructor(map, from) {
|
---|
210 | this.map = map;
|
---|
211 | const { mappings, names, sources } = map;
|
---|
212 | this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map(
|
---|
213 | (s) => posixResolve(s || "", from)
|
---|
214 | );
|
---|
215 | }
|
---|
216 | _encoded;
|
---|
217 | _decoded;
|
---|
218 | _decodedMemo;
|
---|
219 | url;
|
---|
220 | version;
|
---|
221 | names = [];
|
---|
222 | resolvedSources;
|
---|
223 | }
|
---|
224 | function memoizedState() {
|
---|
225 | return {
|
---|
226 | lastKey: -1,
|
---|
227 | lastNeedle: -1,
|
---|
228 | lastIndex: -1
|
---|
229 | };
|
---|
230 | }
|
---|
231 | function getOriginalPosition(map, needle) {
|
---|
232 | const result = originalPositionFor(map, needle);
|
---|
233 | return result.column == null ? null : result;
|
---|
234 | }
|
---|
235 | const VITE_RUNTIME_SOURCEMAPPING_REGEXP = new RegExp(
|
---|
236 | `//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`
|
---|
237 | );
|
---|
238 | class ModuleCacheMap extends Map {
|
---|
239 | root;
|
---|
240 | constructor(root, entries) {
|
---|
241 | super(entries), this.root = withTrailingSlash(root);
|
---|
242 | }
|
---|
243 | normalize(fsPath) {
|
---|
244 | return normalizeModuleId(fsPath, this.root);
|
---|
245 | }
|
---|
246 | /**
|
---|
247 | * Assign partial data to the map
|
---|
248 | */
|
---|
249 | update(fsPath, mod) {
|
---|
250 | return fsPath = this.normalize(fsPath), super.has(fsPath) ? Object.assign(super.get(fsPath), mod) : this.setByModuleId(fsPath, mod), this;
|
---|
251 | }
|
---|
252 | setByModuleId(modulePath, mod) {
|
---|
253 | return super.set(modulePath, mod);
|
---|
254 | }
|
---|
255 | set(fsPath, mod) {
|
---|
256 | return this.setByModuleId(this.normalize(fsPath), mod);
|
---|
257 | }
|
---|
258 | getByModuleId(modulePath) {
|
---|
259 | super.has(modulePath) || this.setByModuleId(modulePath, {});
|
---|
260 | const mod = super.get(modulePath);
|
---|
261 | return mod.imports || Object.assign(mod, {
|
---|
262 | imports: /* @__PURE__ */ new Set(),
|
---|
263 | importers: /* @__PURE__ */ new Set()
|
---|
264 | }), mod;
|
---|
265 | }
|
---|
266 | get(fsPath) {
|
---|
267 | return this.getByModuleId(this.normalize(fsPath));
|
---|
268 | }
|
---|
269 | deleteByModuleId(modulePath) {
|
---|
270 | return super.delete(modulePath);
|
---|
271 | }
|
---|
272 | delete(fsPath) {
|
---|
273 | return this.deleteByModuleId(this.normalize(fsPath));
|
---|
274 | }
|
---|
275 | invalidate(id) {
|
---|
276 | const module = this.get(id);
|
---|
277 | module.evaluated = !1, module.meta = void 0, module.map = void 0, module.promise = void 0, module.exports = void 0, module.imports?.clear();
|
---|
278 | }
|
---|
279 | isImported({
|
---|
280 | importedId,
|
---|
281 | importedBy
|
---|
282 | }, seen = /* @__PURE__ */ new Set()) {
|
---|
283 | if (importedId = this.normalize(importedId), importedBy = this.normalize(importedBy), importedBy === importedId) return !0;
|
---|
284 | if (seen.has(importedId)) return !1;
|
---|
285 | seen.add(importedId);
|
---|
286 | const importers = this.getByModuleId(importedId)?.importers;
|
---|
287 | if (!importers) return !1;
|
---|
288 | if (importers.has(importedBy)) return !0;
|
---|
289 | for (const importer of importers)
|
---|
290 | if (this.isImported({
|
---|
291 | importedBy,
|
---|
292 | importedId: importer
|
---|
293 | }))
|
---|
294 | return !0;
|
---|
295 | return !1;
|
---|
296 | }
|
---|
297 | /**
|
---|
298 | * Invalidate modules that dependent on the given modules, up to the main entry
|
---|
299 | */
|
---|
300 | invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
|
---|
301 | for (const _id of ids) {
|
---|
302 | const id = this.normalize(_id);
|
---|
303 | if (invalidated.has(id)) continue;
|
---|
304 | invalidated.add(id);
|
---|
305 | const mod = super.get(id);
|
---|
306 | mod?.importers && this.invalidateDepTree(mod.importers, invalidated), super.delete(id);
|
---|
307 | }
|
---|
308 | return invalidated;
|
---|
309 | }
|
---|
310 | /**
|
---|
311 | * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
|
---|
312 | */
|
---|
313 | invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
|
---|
314 | for (const _id of ids) {
|
---|
315 | const id = this.normalize(_id);
|
---|
316 | if (invalidated.has(id)) continue;
|
---|
317 | invalidated.add(id);
|
---|
318 | const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
|
---|
319 | subIds.length && this.invalidateSubDepTree(subIds, invalidated), super.delete(id);
|
---|
320 | }
|
---|
321 | return invalidated;
|
---|
322 | }
|
---|
323 | getSourceMap(moduleId) {
|
---|
324 | const mod = this.get(moduleId);
|
---|
325 | if (mod.map) return mod.map;
|
---|
326 | if (!mod.meta || !("code" in mod.meta)) return null;
|
---|
327 | const mapString = VITE_RUNTIME_SOURCEMAPPING_REGEXP.exec(mod.meta.code)?.[1];
|
---|
328 | if (!mapString) return null;
|
---|
329 | const baseFile = mod.meta.file || moduleId.split("?")[0];
|
---|
330 | return mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), baseFile), mod.map;
|
---|
331 | }
|
---|
332 | }
|
---|
333 | const prefixedBuiltins = /* @__PURE__ */ new Set(["node:test"]);
|
---|
334 | function normalizeModuleId(file, root) {
|
---|
335 | if (prefixedBuiltins.has(file)) return file;
|
---|
336 | let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
|
---|
337 | return unixFile.startsWith(root) && (unixFile = unixFile.slice(root.length - 1)), unixFile.replace(/^file:\//, "/");
|
---|
338 | }
|
---|
339 | class HMRContext {
|
---|
340 | constructor(hmrClient, ownerPath) {
|
---|
341 | this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
|
---|
342 | const mod = hmrClient.hotModulesMap.get(ownerPath);
|
---|
343 | mod && (mod.callbacks = []);
|
---|
344 | const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
|
---|
345 | if (staleListeners)
|
---|
346 | for (const [event, staleFns] of staleListeners) {
|
---|
347 | const listeners = hmrClient.customListenersMap.get(event);
|
---|
348 | listeners && hmrClient.customListenersMap.set(
|
---|
349 | event,
|
---|
350 | listeners.filter((l) => !staleFns.includes(l))
|
---|
351 | );
|
---|
352 | }
|
---|
353 | this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
|
---|
354 | }
|
---|
355 | newListeners;
|
---|
356 | get data() {
|
---|
357 | return this.hmrClient.dataMap.get(this.ownerPath);
|
---|
358 | }
|
---|
359 | accept(deps, callback) {
|
---|
360 | if (typeof deps == "function" || !deps)
|
---|
361 | this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
|
---|
362 | else if (typeof deps == "string")
|
---|
363 | this.acceptDeps([deps], ([mod]) => callback?.(mod));
|
---|
364 | else if (Array.isArray(deps))
|
---|
365 | this.acceptDeps(deps, callback);
|
---|
366 | else
|
---|
367 | throw new Error("invalid hot.accept() usage.");
|
---|
368 | }
|
---|
369 | // export names (first arg) are irrelevant on the client side, they're
|
---|
370 | // extracted in the server for propagation
|
---|
371 | acceptExports(_, callback) {
|
---|
372 | this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
|
---|
373 | }
|
---|
374 | dispose(cb) {
|
---|
375 | this.hmrClient.disposeMap.set(this.ownerPath, cb);
|
---|
376 | }
|
---|
377 | prune(cb) {
|
---|
378 | this.hmrClient.pruneMap.set(this.ownerPath, cb);
|
---|
379 | }
|
---|
380 | // Kept for backward compatibility (#11036)
|
---|
381 | // eslint-disable-next-line @typescript-eslint/no-empty-function
|
---|
382 | decline() {
|
---|
383 | }
|
---|
384 | invalidate(message) {
|
---|
385 | this.hmrClient.notifyListeners("vite:invalidate", {
|
---|
386 | path: this.ownerPath,
|
---|
387 | message
|
---|
388 | }), this.send("vite:invalidate", { path: this.ownerPath, message }), this.hmrClient.logger.debug(
|
---|
389 | `[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
|
---|
390 | );
|
---|
391 | }
|
---|
392 | on(event, cb) {
|
---|
393 | const addToMap = (map) => {
|
---|
394 | const existing = map.get(event) || [];
|
---|
395 | existing.push(cb), map.set(event, existing);
|
---|
396 | };
|
---|
397 | addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
|
---|
398 | }
|
---|
399 | off(event, cb) {
|
---|
400 | const removeFromMap = (map) => {
|
---|
401 | const existing = map.get(event);
|
---|
402 | if (existing === void 0)
|
---|
403 | return;
|
---|
404 | const pruned = existing.filter((l) => l !== cb);
|
---|
405 | if (pruned.length === 0) {
|
---|
406 | map.delete(event);
|
---|
407 | return;
|
---|
408 | }
|
---|
409 | map.set(event, pruned);
|
---|
410 | };
|
---|
411 | removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
|
---|
412 | }
|
---|
413 | send(event, data) {
|
---|
414 | this.hmrClient.messenger.send(
|
---|
415 | JSON.stringify({ type: "custom", event, data })
|
---|
416 | );
|
---|
417 | }
|
---|
418 | acceptDeps(deps, callback = () => {
|
---|
419 | }) {
|
---|
420 | const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
|
---|
421 | id: this.ownerPath,
|
---|
422 | callbacks: []
|
---|
423 | };
|
---|
424 | mod.callbacks.push({
|
---|
425 | deps,
|
---|
426 | fn: callback
|
---|
427 | }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
|
---|
428 | }
|
---|
429 | }
|
---|
430 | class HMRMessenger {
|
---|
431 | constructor(connection) {
|
---|
432 | this.connection = connection;
|
---|
433 | }
|
---|
434 | queue = [];
|
---|
435 | send(message) {
|
---|
436 | this.queue.push(message), this.flush();
|
---|
437 | }
|
---|
438 | flush() {
|
---|
439 | this.connection.isReady() && (this.queue.forEach((msg) => this.connection.send(msg)), this.queue = []);
|
---|
440 | }
|
---|
441 | }
|
---|
442 | class HMRClient {
|
---|
443 | constructor(logger, connection, importUpdatedModule) {
|
---|
444 | this.logger = logger, this.importUpdatedModule = importUpdatedModule, this.messenger = new HMRMessenger(connection);
|
---|
445 | }
|
---|
446 | hotModulesMap = /* @__PURE__ */ new Map();
|
---|
447 | disposeMap = /* @__PURE__ */ new Map();
|
---|
448 | pruneMap = /* @__PURE__ */ new Map();
|
---|
449 | dataMap = /* @__PURE__ */ new Map();
|
---|
450 | customListenersMap = /* @__PURE__ */ new Map();
|
---|
451 | ctxToListenersMap = /* @__PURE__ */ new Map();
|
---|
452 | messenger;
|
---|
453 | async notifyListeners(event, data) {
|
---|
454 | const cbs = this.customListenersMap.get(event);
|
---|
455 | cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
|
---|
456 | }
|
---|
457 | clear() {
|
---|
458 | this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
|
---|
459 | }
|
---|
460 | // After an HMR update, some modules are no longer imported on the page
|
---|
461 | // but they may have left behind side effects that need to be cleaned up
|
---|
462 | // (.e.g style injections)
|
---|
463 | async prunePaths(paths) {
|
---|
464 | await Promise.all(
|
---|
465 | paths.map((path) => {
|
---|
466 | const disposer = this.disposeMap.get(path);
|
---|
467 | if (disposer) return disposer(this.dataMap.get(path));
|
---|
468 | })
|
---|
469 | ), paths.forEach((path) => {
|
---|
470 | const fn = this.pruneMap.get(path);
|
---|
471 | fn && fn(this.dataMap.get(path));
|
---|
472 | });
|
---|
473 | }
|
---|
474 | warnFailedUpdate(err, path) {
|
---|
475 | err.message.includes("fetch") || this.logger.error(err), this.logger.error(
|
---|
476 | `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
|
---|
477 | );
|
---|
478 | }
|
---|
479 | updateQueue = [];
|
---|
480 | pendingUpdateQueue = !1;
|
---|
481 | /**
|
---|
482 | * buffer multiple hot updates triggered by the same src change
|
---|
483 | * so that they are invoked in the same order they were sent.
|
---|
484 | * (otherwise the order may be inconsistent because of the http request round trip)
|
---|
485 | */
|
---|
486 | async queueUpdate(payload) {
|
---|
487 | if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
|
---|
488 | this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
|
---|
489 | const loading = [...this.updateQueue];
|
---|
490 | this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
|
---|
491 | }
|
---|
492 | }
|
---|
493 | async fetchUpdate(update) {
|
---|
494 | const { path, acceptedPath } = update, mod = this.hotModulesMap.get(path);
|
---|
495 | if (!mod)
|
---|
496 | return;
|
---|
497 | let fetchedModule;
|
---|
498 | const isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(
|
---|
499 | ({ deps }) => deps.includes(acceptedPath)
|
---|
500 | );
|
---|
501 | if (isSelfUpdate || qualifiedCallbacks.length > 0) {
|
---|
502 | const disposer = this.disposeMap.get(acceptedPath);
|
---|
503 | disposer && await disposer(this.dataMap.get(acceptedPath));
|
---|
504 | try {
|
---|
505 | fetchedModule = await this.importUpdatedModule(update);
|
---|
506 | } catch (e) {
|
---|
507 | this.warnFailedUpdate(e, acceptedPath);
|
---|
508 | }
|
---|
509 | }
|
---|
510 | return () => {
|
---|
511 | for (const { deps, fn } of qualifiedCallbacks)
|
---|
512 | fn(
|
---|
513 | deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
|
---|
514 | );
|
---|
515 | const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
|
---|
516 | this.logger.debug(`[vite] hot updated: ${loggedPath}`);
|
---|
517 | };
|
---|
518 | }
|
---|
519 | }
|
---|
520 | function analyzeImportedModDifference(mod, rawId, moduleType, metadata) {
|
---|
521 | if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
|
---|
522 | const missingBindings = metadata.importedNames.filter((s) => !(s in mod));
|
---|
523 | if (missingBindings.length) {
|
---|
524 | const lastBinding = missingBindings[missingBindings.length - 1];
|
---|
525 | throw moduleType === "module" ? new SyntaxError(
|
---|
526 | `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`
|
---|
527 | ) : new SyntaxError(`[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 |
|
---|
530 | import pkg from '${rawId}';
|
---|
531 | const {${missingBindings.join(", ")}} = pkg;
|
---|
532 | `);
|
---|
533 | }
|
---|
534 | }
|
---|
535 | }
|
---|
536 | const ssrModuleExportsKey = "__vite_ssr_exports__", ssrImportKey = "__vite_ssr_import__", ssrDynamicImportKey = "__vite_ssr_dynamic_import__", ssrExportAllKey = "__vite_ssr_exportAll__", ssrImportMetaKey = "__vite_ssr_import_meta__", noop = () => {
|
---|
537 | }, silentConsole = {
|
---|
538 | debug: noop,
|
---|
539 | error: noop
|
---|
540 | };
|
---|
541 | function createHMRHandler(runtime) {
|
---|
542 | const queue = new Queue();
|
---|
543 | return (payload) => queue.enqueue(() => handleHMRPayload(runtime, payload));
|
---|
544 | }
|
---|
545 | async function handleHMRPayload(runtime, payload) {
|
---|
546 | const hmrClient = runtime.hmrClient;
|
---|
547 | if (!(!hmrClient || runtime.isDestroyed()))
|
---|
548 | switch (payload.type) {
|
---|
549 | case "connected":
|
---|
550 | hmrClient.logger.debug("[vite] connected."), hmrClient.messenger.flush();
|
---|
551 | break;
|
---|
552 | case "update":
|
---|
553 | await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(
|
---|
554 | payload.updates.map(async (update) => {
|
---|
555 | if (update.type === "js-update")
|
---|
556 | return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
|
---|
557 | hmrClient.logger.error(
|
---|
558 | "[vite] css hmr is not supported in runtime mode."
|
---|
559 | );
|
---|
560 | })
|
---|
561 | ), await hmrClient.notifyListeners("vite:afterUpdate", payload);
|
---|
562 | break;
|
---|
563 | case "custom": {
|
---|
564 | await hmrClient.notifyListeners(payload.event, payload.data);
|
---|
565 | break;
|
---|
566 | }
|
---|
567 | case "full-reload": {
|
---|
568 | const { triggeredBy } = payload, clearEntrypoints = triggeredBy ? [...runtime.entrypoints].filter(
|
---|
569 | (entrypoint) => runtime.moduleCache.isImported({
|
---|
570 | importedId: triggeredBy,
|
---|
571 | importedBy: entrypoint
|
---|
572 | })
|
---|
573 | ) : [...runtime.entrypoints];
|
---|
574 | if (!clearEntrypoints.length) break;
|
---|
575 | hmrClient.logger.debug("[vite] program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runtime.moduleCache.clear();
|
---|
576 | for (const id of clearEntrypoints)
|
---|
577 | await runtime.executeUrl(id);
|
---|
578 | break;
|
---|
579 | }
|
---|
580 | case "prune":
|
---|
581 | await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
|
---|
582 | break;
|
---|
583 | case "error": {
|
---|
584 | await hmrClient.notifyListeners("vite:error", payload);
|
---|
585 | const err = payload.err;
|
---|
586 | hmrClient.logger.error(
|
---|
587 | `[vite] Internal Server Error
|
---|
588 | ${err.message}
|
---|
589 | ${err.stack}`
|
---|
590 | );
|
---|
591 | break;
|
---|
592 | }
|
---|
593 | default:
|
---|
594 | return payload;
|
---|
595 | }
|
---|
596 | }
|
---|
597 | class Queue {
|
---|
598 | queue = [];
|
---|
599 | pending = !1;
|
---|
600 | enqueue(promise) {
|
---|
601 | return new Promise((resolve2, reject) => {
|
---|
602 | this.queue.push({
|
---|
603 | promise,
|
---|
604 | resolve: resolve2,
|
---|
605 | reject
|
---|
606 | }), this.dequeue();
|
---|
607 | });
|
---|
608 | }
|
---|
609 | dequeue() {
|
---|
610 | if (this.pending)
|
---|
611 | return !1;
|
---|
612 | const item = this.queue.shift();
|
---|
613 | return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
|
---|
614 | this.pending = !1, this.dequeue();
|
---|
615 | }), !0) : !1;
|
---|
616 | }
|
---|
617 | }
|
---|
618 | const sourceMapCache = {}, fileContentsCache = {}, moduleGraphs = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => (...args) => {
|
---|
619 | for (const handler of handlers) {
|
---|
620 | const result = handler(...args);
|
---|
621 | if (result) return result;
|
---|
622 | }
|
---|
623 | return null;
|
---|
624 | }, retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(
|
---|
625 | retrieveSourceMapHandlers
|
---|
626 | );
|
---|
627 | let overridden = !1;
|
---|
628 | const originalPrepare = Error.prepareStackTrace;
|
---|
629 | function resetInterceptor(runtime, options) {
|
---|
630 | moduleGraphs.delete(runtime.moduleCache), options.retrieveFile && retrieveFileHandlers.delete(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.delete(options.retrieveSourceMap), moduleGraphs.size === 0 && (Error.prepareStackTrace = originalPrepare, overridden = !1);
|
---|
631 | }
|
---|
632 | function interceptStackTrace(runtime, options = {}) {
|
---|
633 | return overridden || (Error.prepareStackTrace = prepareStackTrace, overridden = !0), moduleGraphs.add(runtime.moduleCache), options.retrieveFile && retrieveFileHandlers.add(options.retrieveFile), options.retrieveSourceMap && retrieveSourceMapHandlers.add(options.retrieveSourceMap), () => resetInterceptor(runtime, options);
|
---|
634 | }
|
---|
635 | function supportRelativeURL(file, url) {
|
---|
636 | if (!file) return url;
|
---|
637 | const dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir);
|
---|
638 | let protocol = match ? match[0] : "";
|
---|
639 | const startPath = dir.slice(protocol.length);
|
---|
640 | return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
|
---|
641 | }
|
---|
642 | function getRuntimeSourceMap(position) {
|
---|
643 | for (const moduleCache of moduleGraphs) {
|
---|
644 | const sourceMap = moduleCache.getSourceMap(position.source);
|
---|
645 | if (sourceMap)
|
---|
646 | return {
|
---|
647 | url: position.source,
|
---|
648 | map: sourceMap,
|
---|
649 | vite: !0
|
---|
650 | };
|
---|
651 | }
|
---|
652 | return null;
|
---|
653 | }
|
---|
654 | function retrieveFile(path) {
|
---|
655 | if (path in fileContentsCache) return fileContentsCache[path];
|
---|
656 | const content = retrieveFileFromHandlers(path);
|
---|
657 | return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
|
---|
658 | }
|
---|
659 | function retrieveSourceMapURL(source) {
|
---|
660 | const fileData = retrieveFile(source);
|
---|
661 | if (!fileData) return null;
|
---|
662 | const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
|
---|
663 | let lastMatch, match;
|
---|
664 | for (; match = re.exec(fileData); ) lastMatch = match;
|
---|
665 | return lastMatch ? lastMatch[1] : null;
|
---|
666 | }
|
---|
667 | const reSourceMap = /^data:application\/json[^,]+base64,/;
|
---|
668 | function retrieveSourceMap(source) {
|
---|
669 | const urlAndMap = retrieveSourceMapFromHandlers(source);
|
---|
670 | if (urlAndMap) return urlAndMap;
|
---|
671 | let sourceMappingURL = retrieveSourceMapURL(source);
|
---|
672 | if (!sourceMappingURL) return null;
|
---|
673 | let sourceMapData;
|
---|
674 | if (reSourceMap.test(sourceMappingURL)) {
|
---|
675 | const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
|
---|
676 | sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
|
---|
677 | } else
|
---|
678 | sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
|
---|
679 | return sourceMapData ? {
|
---|
680 | url: sourceMappingURL,
|
---|
681 | map: sourceMapData
|
---|
682 | } : null;
|
---|
683 | }
|
---|
684 | function mapSourcePosition(position) {
|
---|
685 | if (!position.source) return position;
|
---|
686 | let sourceMap = getRuntimeSourceMap(position);
|
---|
687 | if (sourceMap || (sourceMap = sourceMapCache[position.source]), !sourceMap) {
|
---|
688 | const urlAndMap = retrieveSourceMap(position.source);
|
---|
689 | if (urlAndMap && urlAndMap.map) {
|
---|
690 | const url = urlAndMap.url;
|
---|
691 | sourceMap = sourceMapCache[position.source] = {
|
---|
692 | url,
|
---|
693 | map: new DecodedMap(
|
---|
694 | typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map,
|
---|
695 | url
|
---|
696 | )
|
---|
697 | };
|
---|
698 | const contents = sourceMap.map?.map.sourcesContent;
|
---|
699 | sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
|
---|
700 | const content = contents[i];
|
---|
701 | if (content && source && url) {
|
---|
702 | const contentUrl = supportRelativeURL(url, source);
|
---|
703 | fileContentsCache[contentUrl] = content;
|
---|
704 | }
|
---|
705 | });
|
---|
706 | } else
|
---|
707 | sourceMap = sourceMapCache[position.source] = {
|
---|
708 | url: null,
|
---|
709 | map: null
|
---|
710 | };
|
---|
711 | }
|
---|
712 | if (sourceMap && sourceMap.map && sourceMap.url) {
|
---|
713 | const originalPosition = getOriginalPosition(sourceMap.map, position);
|
---|
714 | if (originalPosition && originalPosition.source != null)
|
---|
715 | return originalPosition.source = supportRelativeURL(
|
---|
716 | sourceMap.url,
|
---|
717 | originalPosition.source
|
---|
718 | ), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
|
---|
719 | }
|
---|
720 | return position;
|
---|
721 | }
|
---|
722 | function mapEvalOrigin(origin) {
|
---|
723 | let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
|
---|
724 | if (match) {
|
---|
725 | const position = mapSourcePosition({
|
---|
726 | name: null,
|
---|
727 | source: match[2],
|
---|
728 | line: +match[3],
|
---|
729 | column: +match[4] - 1
|
---|
730 | });
|
---|
731 | return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
|
---|
732 | }
|
---|
733 | return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
|
---|
734 | }
|
---|
735 | function CallSiteToString() {
|
---|
736 | let fileName, fileLocation = "";
|
---|
737 | if (this.isNative())
|
---|
738 | fileLocation = "native";
|
---|
739 | else {
|
---|
740 | fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
|
---|
741 | const lineNumber = this.getLineNumber();
|
---|
742 | if (lineNumber != null) {
|
---|
743 | fileLocation += `:${lineNumber}`;
|
---|
744 | const columnNumber = this.getColumnNumber();
|
---|
745 | columnNumber && (fileLocation += `:${columnNumber}`);
|
---|
746 | }
|
---|
747 | }
|
---|
748 | let line = "";
|
---|
749 | const functionName = this.getFunctionName();
|
---|
750 | let addSuffix = !0;
|
---|
751 | const isConstructor = this.isConstructor();
|
---|
752 | if (this.isToplevel() || isConstructor)
|
---|
753 | isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
|
---|
754 | else {
|
---|
755 | let typeName = this.getTypeName();
|
---|
756 | typeName === "[object Object]" && (typeName = "null");
|
---|
757 | const methodName = this.getMethodName();
|
---|
758 | 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>"}`;
|
---|
759 | }
|
---|
760 | return addSuffix && (line += ` (${fileLocation})`), line;
|
---|
761 | }
|
---|
762 | function cloneCallSite(frame) {
|
---|
763 | const object = {};
|
---|
764 | return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
|
---|
765 | const key = name;
|
---|
766 | object[key] = /^(?:is|get)/.test(name) ? function() {
|
---|
767 | return frame[key].call(frame);
|
---|
768 | } : frame[key];
|
---|
769 | }), object.toString = CallSiteToString, object;
|
---|
770 | }
|
---|
771 | function wrapCallSite(frame, state) {
|
---|
772 | if (state === void 0 && (state = { nextPosition: null, curPosition: null }), frame.isNative())
|
---|
773 | return state.curPosition = null, frame;
|
---|
774 | const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
|
---|
775 | if (source) {
|
---|
776 | const line = frame.getLineNumber();
|
---|
777 | let column = frame.getColumnNumber() - 1;
|
---|
778 | const headerLength = 62;
|
---|
779 | line === 1 && column > headerLength && !frame.isEval() && (column -= headerLength);
|
---|
780 | const position = mapSourcePosition({
|
---|
781 | name: null,
|
---|
782 | source,
|
---|
783 | line,
|
---|
784 | column
|
---|
785 | });
|
---|
786 | state.curPosition = position, frame = cloneCallSite(frame);
|
---|
787 | const originalFunctionName = frame.getFunctionName;
|
---|
788 | return frame.getFunctionName = function() {
|
---|
789 | const name = state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName();
|
---|
790 | return name === "eval" && "_vite" in position ? null : name;
|
---|
791 | }, frame.getFileName = function() {
|
---|
792 | return position.source ?? void 0;
|
---|
793 | }, frame.getLineNumber = function() {
|
---|
794 | return position.line;
|
---|
795 | }, frame.getColumnNumber = function() {
|
---|
796 | return position.column + 1;
|
---|
797 | }, frame.getScriptNameOrSourceURL = function() {
|
---|
798 | return position.source;
|
---|
799 | }, frame;
|
---|
800 | }
|
---|
801 | let origin = frame.isEval() && frame.getEvalOrigin();
|
---|
802 | return origin && (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
|
---|
803 | return origin || void 0;
|
---|
804 | }), frame;
|
---|
805 | }
|
---|
806 | function prepareStackTrace(error, stack) {
|
---|
807 | const name = error.name || "Error", message = error.message || "", errorString = `${name}: ${message}`, state = { nextPosition: null, curPosition: null }, processedStack = [];
|
---|
808 | for (let i = stack.length - 1; i >= 0; i--)
|
---|
809 | processedStack.push(`
|
---|
810 | at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
|
---|
811 | return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
|
---|
812 | }
|
---|
813 | function enableSourceMapSupport(runtime) {
|
---|
814 | if (runtime.options.sourcemapInterceptor === "node") {
|
---|
815 | if (typeof process > "u")
|
---|
816 | throw new TypeError(
|
---|
817 | `Cannot use "sourcemapInterceptor: 'node'" because global "process" variable is not available.`
|
---|
818 | );
|
---|
819 | if (typeof process.setSourceMapsEnabled != "function")
|
---|
820 | throw new TypeError(
|
---|
821 | `Cannot use "sourcemapInterceptor: 'node'" because "process.setSourceMapsEnabled" function is not available. Please use Node >= 16.6.0.`
|
---|
822 | );
|
---|
823 | const isEnabledAlready = process.sourceMapsEnabled ?? !1;
|
---|
824 | return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
|
---|
825 | }
|
---|
826 | return interceptStackTrace(
|
---|
827 | runtime,
|
---|
828 | typeof runtime.options.sourcemapInterceptor == "object" ? runtime.options.sourcemapInterceptor : void 0
|
---|
829 | );
|
---|
830 | }
|
---|
831 | class ViteRuntime {
|
---|
832 | constructor(options, runner, debug) {
|
---|
833 | this.options = options, this.runner = runner, this.debug = debug, this.moduleCache = options.moduleCache ?? new ModuleCacheMap(options.root), typeof options.hmr == "object" && (this.hmrClient = new HMRClient(
|
---|
834 | options.hmr.logger === !1 ? silentConsole : options.hmr.logger || console,
|
---|
835 | options.hmr.connection,
|
---|
836 | ({ acceptedPath, ssrInvalidates }) => (this.moduleCache.invalidate(acceptedPath), ssrInvalidates && this.invalidateFiles(ssrInvalidates), this.executeUrl(acceptedPath))
|
---|
837 | ), options.hmr.connection.onUpdate(createHMRHandler(this))), options.sourcemapInterceptor !== !1 && (this._resetSourceMapSupport = enableSourceMapSupport(this));
|
---|
838 | }
|
---|
839 | /**
|
---|
840 | * Holds the cache of modules
|
---|
841 | * Keys of the map are ids
|
---|
842 | */
|
---|
843 | moduleCache;
|
---|
844 | hmrClient;
|
---|
845 | entrypoints = /* @__PURE__ */ new Set();
|
---|
846 | idToUrlMap = /* @__PURE__ */ new Map();
|
---|
847 | fileToIdMap = /* @__PURE__ */ new Map();
|
---|
848 | envProxy = new Proxy({}, {
|
---|
849 | get(_, p) {
|
---|
850 | throw new Error(
|
---|
851 | `[vite-runtime] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`
|
---|
852 | );
|
---|
853 | }
|
---|
854 | });
|
---|
855 | _destroyed = !1;
|
---|
856 | _resetSourceMapSupport;
|
---|
857 | /**
|
---|
858 | * URL to execute. Accepts file path, server path or id relative to the root.
|
---|
859 | */
|
---|
860 | async executeUrl(url) {
|
---|
861 | url = this.normalizeEntryUrl(url);
|
---|
862 | const fetchedModule = await this.cachedModule(url);
|
---|
863 | return await this.cachedRequest(url, fetchedModule);
|
---|
864 | }
|
---|
865 | /**
|
---|
866 | * Entrypoint URL to execute. Accepts file path, server path or id relative to the root.
|
---|
867 | * In the case of a full reload triggered by HMR, this is the module that will be reloaded.
|
---|
868 | * If this method is called multiple times, all entrypoints will be reloaded one at a time.
|
---|
869 | */
|
---|
870 | async executeEntrypoint(url) {
|
---|
871 | url = this.normalizeEntryUrl(url);
|
---|
872 | const fetchedModule = await this.cachedModule(url);
|
---|
873 | return await this.cachedRequest(url, fetchedModule, [], {
|
---|
874 | entrypoint: !0
|
---|
875 | });
|
---|
876 | }
|
---|
877 | /**
|
---|
878 | * Clear all caches including HMR listeners.
|
---|
879 | */
|
---|
880 | clearCache() {
|
---|
881 | this.moduleCache.clear(), this.idToUrlMap.clear(), this.entrypoints.clear(), this.hmrClient?.clear();
|
---|
882 | }
|
---|
883 | /**
|
---|
884 | * Clears all caches, removes all HMR listeners, and resets source map support.
|
---|
885 | * This method doesn't stop the HMR connection.
|
---|
886 | */
|
---|
887 | async destroy() {
|
---|
888 | this._resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this._destroyed = !0;
|
---|
889 | }
|
---|
890 | /**
|
---|
891 | * Returns `true` if the runtime has been destroyed by calling `destroy()` method.
|
---|
892 | */
|
---|
893 | isDestroyed() {
|
---|
894 | return this._destroyed;
|
---|
895 | }
|
---|
896 | invalidateFiles(files) {
|
---|
897 | files.forEach((file) => {
|
---|
898 | const ids = this.fileToIdMap.get(file);
|
---|
899 | ids && ids.forEach((id) => this.moduleCache.invalidate(id));
|
---|
900 | });
|
---|
901 | }
|
---|
902 | // we don't use moduleCache.normalize because this URL doesn't have to follow the same rules
|
---|
903 | // this URL is something that user passes down manually, and is later resolved by fetchModule
|
---|
904 | // moduleCache.normalize is used on resolved "file" property
|
---|
905 | normalizeEntryUrl(url) {
|
---|
906 | if (url[0] === ".")
|
---|
907 | return url;
|
---|
908 | url.startsWith("file://") && (url = url.slice(isWindows ? 8 : 7)), url = slash(url);
|
---|
909 | const _root = this.options.root, root = _root[_root.length - 1] === "/" ? _root : `${_root}/`;
|
---|
910 | return url.startsWith(root) ? url.slice(root.length - 1) : url[0] === "/" ? url : wrapId(url);
|
---|
911 | }
|
---|
912 | processImport(exports, fetchResult, metadata) {
|
---|
913 | if (!("externalize" in fetchResult))
|
---|
914 | return exports;
|
---|
915 | const { id, type } = fetchResult;
|
---|
916 | return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, id, type, metadata), exports;
|
---|
917 | }
|
---|
918 | async cachedRequest(id, fetchedModule, callstack = [], metadata) {
|
---|
919 | const moduleId = fetchedModule.id;
|
---|
920 | metadata?.entrypoint && this.entrypoints.add(moduleId);
|
---|
921 | const mod = this.moduleCache.getByModuleId(moduleId), { imports, importers } = mod, importee = callstack[callstack.length - 1];
|
---|
922 | if (importee && importers.add(importee), (callstack.includes(moduleId) || Array.from(imports.values()).some((i) => importers.has(i))) && mod.exports)
|
---|
923 | return this.processImport(mod.exports, fetchedModule, metadata);
|
---|
924 | let debugTimer;
|
---|
925 | this.debug && (debugTimer = setTimeout(() => {
|
---|
926 | const getStack = () => `stack:
|
---|
927 | ${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join(`
|
---|
928 | `)}`;
|
---|
929 | this.debug(
|
---|
930 | `[vite-runtime] module ${moduleId} takes over 2s to load.
|
---|
931 | ${getStack()}`
|
---|
932 | );
|
---|
933 | }, 2e3));
|
---|
934 | try {
|
---|
935 | if (mod.promise)
|
---|
936 | return this.processImport(await mod.promise, fetchedModule, metadata);
|
---|
937 | const promise = this.directRequest(id, fetchedModule, callstack);
|
---|
938 | return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, fetchedModule, metadata);
|
---|
939 | } finally {
|
---|
940 | mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
|
---|
941 | }
|
---|
942 | }
|
---|
943 | async cachedModule(id, importer) {
|
---|
944 | if (this._destroyed)
|
---|
945 | throw new Error("[vite] Vite runtime has been destroyed.");
|
---|
946 | const normalized = this.idToUrlMap.get(id);
|
---|
947 | if (normalized) {
|
---|
948 | const mod2 = this.moduleCache.getByModuleId(normalized);
|
---|
949 | if (mod2.meta)
|
---|
950 | return mod2.meta;
|
---|
951 | }
|
---|
952 | this.debug?.("[vite-runtime] fetching", id);
|
---|
953 | const fetchedModule = id.startsWith("data:") ? { externalize: id, type: "builtin" } : await this.options.fetchModule(id, importer), idQuery = id.split("?")[1], query = idQuery ? `?${idQuery}` : "", file = "file" in fetchedModule ? fetchedModule.file : void 0, fullFile = file ? `${file}${query}` : id, moduleId = this.moduleCache.normalize(fullFile), mod = this.moduleCache.getByModuleId(moduleId);
|
---|
954 | if (fetchedModule.id = moduleId, mod.meta = fetchedModule, file) {
|
---|
955 | const fileModules = this.fileToIdMap.get(file) || [];
|
---|
956 | fileModules.push(moduleId), this.fileToIdMap.set(file, fileModules);
|
---|
957 | }
|
---|
958 | return this.idToUrlMap.set(id, moduleId), this.idToUrlMap.set(unwrapId(id), moduleId), fetchedModule;
|
---|
959 | }
|
---|
960 | // override is allowed, consider this a public API
|
---|
961 | async directRequest(id, fetchResult, _callstack) {
|
---|
962 | const moduleId = fetchResult.id, callstack = [..._callstack, moduleId], mod = this.moduleCache.getByModuleId(moduleId), request = async (dep, metadata) => {
|
---|
963 | const fetchedModule = await this.cachedModule(dep, moduleId);
|
---|
964 | return this.moduleCache.getByModuleId(fetchedModule.id).importers.add(moduleId), mod.imports.add(fetchedModule.id), this.cachedRequest(dep, fetchedModule, callstack, metadata);
|
---|
965 | }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(id), dep)), request(dep, { isDynamicImport: !0 }));
|
---|
966 | if ("externalize" in fetchResult) {
|
---|
967 | const { externalize } = fetchResult;
|
---|
968 | this.debug?.("[vite-runtime] externalizing", externalize);
|
---|
969 | const exports2 = await this.runner.runExternalModule(externalize);
|
---|
970 | return mod.exports = exports2, exports2;
|
---|
971 | }
|
---|
972 | const { code, file } = fetchResult;
|
---|
973 | if (code == null) {
|
---|
974 | const importer = callstack[callstack.length - 2];
|
---|
975 | throw new Error(
|
---|
976 | `[vite-runtime] Failed to load "${id}"${importer ? ` imported from ${importer}` : ""}`
|
---|
977 | );
|
---|
978 | }
|
---|
979 | const modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), filename = modulePath, dirname2 = posixDirname(modulePath), meta = {
|
---|
980 | filename: isWindows ? toWindowsPath(filename) : filename,
|
---|
981 | dirname: isWindows ? toWindowsPath(dirname2) : dirname2,
|
---|
982 | url: href,
|
---|
983 | env: this.envProxy,
|
---|
984 | resolve(id2, parent) {
|
---|
985 | throw new Error(
|
---|
986 | '[vite-runtime] "import.meta.resolve" is not supported.'
|
---|
987 | );
|
---|
988 | },
|
---|
989 | // should be replaced during transformation
|
---|
990 | glob() {
|
---|
991 | throw new Error('[vite-runtime] "import.meta.glob" is not supported.');
|
---|
992 | }
|
---|
993 | }, exports = /* @__PURE__ */ Object.create(null);
|
---|
994 | Object.defineProperty(exports, Symbol.toStringTag, {
|
---|
995 | value: "Module",
|
---|
996 | enumerable: !1,
|
---|
997 | configurable: !1
|
---|
998 | }), mod.exports = exports;
|
---|
999 | let hotContext;
|
---|
1000 | this.hmrClient && Object.defineProperty(meta, "hot", {
|
---|
1001 | enumerable: !0,
|
---|
1002 | get: () => {
|
---|
1003 | if (!this.hmrClient)
|
---|
1004 | throw new Error("[vite-runtime] HMR client was destroyed.");
|
---|
1005 | return this.debug?.("[vite-runtime] creating hmr context for", moduleId), hotContext ||= new HMRContext(this.hmrClient, moduleId), hotContext;
|
---|
1006 | },
|
---|
1007 | set: (value) => {
|
---|
1008 | hotContext = value;
|
---|
1009 | }
|
---|
1010 | });
|
---|
1011 | const context = {
|
---|
1012 | [ssrImportKey]: request,
|
---|
1013 | [ssrDynamicImportKey]: dynamicRequest,
|
---|
1014 | [ssrModuleExportsKey]: exports,
|
---|
1015 | [ssrExportAllKey]: (obj) => exportAll(exports, obj),
|
---|
1016 | [ssrImportMetaKey]: meta
|
---|
1017 | };
|
---|
1018 | return this.debug?.("[vite-runtime] executing", href), await this.runner.runViteModule(context, code, id), exports;
|
---|
1019 | }
|
---|
1020 | }
|
---|
1021 | function exportAll(exports, sourceModule) {
|
---|
1022 | if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
|
---|
1023 | for (const key in sourceModule)
|
---|
1024 | if (key !== "default" && key !== "__esModule")
|
---|
1025 | try {
|
---|
1026 | Object.defineProperty(exports, key, {
|
---|
1027 | enumerable: !0,
|
---|
1028 | configurable: !0,
|
---|
1029 | get: () => sourceModule[key]
|
---|
1030 | });
|
---|
1031 | } catch {
|
---|
1032 | }
|
---|
1033 | }
|
---|
1034 | }
|
---|
1035 | class ESModulesRunner {
|
---|
1036 | async runViteModule(context, code) {
|
---|
1037 | await new AsyncFunction(
|
---|
1038 | ssrModuleExportsKey,
|
---|
1039 | ssrImportMetaKey,
|
---|
1040 | ssrImportKey,
|
---|
1041 | ssrDynamicImportKey,
|
---|
1042 | ssrExportAllKey,
|
---|
1043 | // source map should already be inlined by Vite
|
---|
1044 | '"use strict";' + code
|
---|
1045 | )(
|
---|
1046 | context[ssrModuleExportsKey],
|
---|
1047 | context[ssrImportMetaKey],
|
---|
1048 | context[ssrImportKey],
|
---|
1049 | context[ssrDynamicImportKey],
|
---|
1050 | context[ssrExportAllKey]
|
---|
1051 | ), Object.seal(context[ssrModuleExportsKey]);
|
---|
1052 | }
|
---|
1053 | runExternalModule(filepath) {
|
---|
1054 | return import(filepath);
|
---|
1055 | }
|
---|
1056 | }
|
---|
1057 | export {
|
---|
1058 | ESModulesRunner,
|
---|
1059 | ModuleCacheMap,
|
---|
1060 | ViteRuntime,
|
---|
1061 | ssrDynamicImportKey,
|
---|
1062 | ssrExportAllKey,
|
---|
1063 | ssrImportKey,
|
---|
1064 | ssrImportMetaKey,
|
---|
1065 | ssrModuleExportsKey
|
---|
1066 | };
|
---|