vite 6.4.1 → 7.1.12

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