vite 6.3.5 → 7.1.5

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 (39) hide show
  1. package/LICENSE.md +81 -314
  2. package/bin/openChrome.js +68 -0
  3. package/bin/vite.js +7 -7
  4. package/dist/client/client.mjs +886 -922
  5. package/dist/client/env.mjs +14 -19
  6. package/dist/node/chunks/dep-BuoK8Wda.js +377 -0
  7. package/dist/node/chunks/dep-BvyJBvVx.js +4 -0
  8. package/dist/node/chunks/dep-Cs9lwdKu.js +4 -0
  9. package/dist/node/chunks/dep-DCVhRpiz.js +5595 -0
  10. package/dist/node/chunks/dep-DDbTn5rw.js +482 -0
  11. package/dist/node/chunks/dep-D_YDhiNx.js +4 -0
  12. package/dist/node/chunks/dep-M_KD0XSK.js +36707 -0
  13. package/dist/node/chunks/dep-SmwnYDP9.js +320 -0
  14. package/dist/node/chunks/dep-cWFO4sv4.js +4 -0
  15. package/dist/node/chunks/dep-lCKrEJQm.js +31 -0
  16. package/dist/node/chunks/dep-sDKrrA4S.js +6814 -0
  17. package/dist/node/chunks/dep-yxQqhtZq.js +4 -0
  18. package/dist/node/cli.js +624 -865
  19. package/dist/node/index.d.ts +2723 -3277
  20. package/dist/node/index.js +24 -188
  21. package/dist/node/module-runner.d.ts +256 -234
  22. package/dist/node/module-runner.js +1000 -1178
  23. package/dist/node/moduleRunnerTransport-BWUZBVLX.d.ts +88 -0
  24. package/package.json +52 -55
  25. package/types/importGlob.d.ts +14 -0
  26. package/types/internal/cssPreprocessorOptions.d.ts +3 -22
  27. package/types/internal/terserOptions.d.ts +11 -0
  28. package/types/metadata.d.ts +0 -2
  29. package/bin/openChrome.applescript +0 -95
  30. package/dist/node/chunks/dep-3RmXg9uo.js +0 -553
  31. package/dist/node/chunks/dep-AiMcmC_f.js +0 -822
  32. package/dist/node/chunks/dep-CvfTChi5.js +0 -8218
  33. package/dist/node/chunks/dep-DBxKXgDP.js +0 -49496
  34. package/dist/node/chunks/dep-SgSik2vo.js +0 -7113
  35. package/dist/node/constants.js +0 -149
  36. package/dist/node/moduleRunnerTransport.d-DJ_mE5sf.d.ts +0 -87
  37. package/dist/node-cjs/publicUtils.cjs +0 -3986
  38. package/index.cjs +0 -96
  39. package/index.d.cts +0 -6
@@ -1,1311 +1,1133 @@
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, promise = new Promise((_resolve, _reject) => {
29
+ resolve$1 = _resolve, reject = _reject;
30
+ });
31
+ return {
32
+ promise,
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);
103
- for (let i = 0; i < chars.length; i++) {
104
- const c = chars.charCodeAt(i);
105
- intToChar[i] = c, charToInt[c] = i;
96
+ const intToChar = new Uint8Array(64), charToInt = new Uint8Array(128);
97
+ for (let i = 0; i < 64; i++) {
98
+ let c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".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
+ let c = reader.next();
105
+ integer = charToInt[c], value |= (integer & 31) << shift, shift += 5;
106
+ } while (integer & 32);
107
+ let shouldNegate = value & 1;
108
+ return value >>>= 1, shouldNegate && (value = -2147483648 | -value), relative + value;
115
109
  }
116
110
  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
- }
111
+ return reader.pos >= max ? !1 : reader.peek() !== 44;
133
112
  }
113
+ var StringReader = class {
114
+ constructor(buffer) {
115
+ this.pos = 0, this.buffer = buffer;
116
+ }
117
+ next() {
118
+ return this.buffer.charCodeAt(this.pos++);
119
+ }
120
+ peek() {
121
+ return this.buffer.charCodeAt(this.pos);
122
+ }
123
+ indexOf(char) {
124
+ let { buffer, pos } = this, idx = buffer.indexOf(char, pos);
125
+ return idx === -1 ? buffer.length : idx;
126
+ }
127
+ };
134
128
  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;
129
+ let { length } = mappings, reader = new StringReader(mappings), decoded = [], genColumn = 0, sourcesIndex = 0, sourceLine = 0, sourceColumn = 0, namesIndex = 0;
130
+ do {
131
+ let semi = reader.indexOf(";"), line = [], sorted = !0, lastCol = 0;
132
+ for (genColumn = 0; reader.pos < semi;) {
133
+ let seg;
134
+ 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 = [
135
+ genColumn,
136
+ sourcesIndex,
137
+ sourceLine,
138
+ sourceColumn,
139
+ namesIndex
140
+ ]) : seg = [
141
+ genColumn,
142
+ sourcesIndex,
143
+ sourceLine,
144
+ sourceColumn
145
+ ]) : seg = [genColumn], line.push(seg), reader.pos++;
146
+ }
147
+ sorted || sort(line), decoded.push(line), reader.pos = semi + 1;
148
+ } while (reader.pos <= length);
149
+ return decoded;
147
150
  }
148
151
  function sort(line) {
149
- line.sort(sortComparator);
152
+ line.sort(sortComparator);
150
153
  }
151
154
  function sortComparator(a, b) {
152
- return a[0] - b[0];
155
+ return a[0] - b[0];
153
156
  }
154
- const COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4;
155
- let found = !1;
157
+ var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_INDEX = 4, found = !1;
156
158
  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;
159
+ for (; low <= high;) {
160
+ let mid = low + (high - low >> 1), cmp = haystack[mid][COLUMN] - needle;
161
+ if (cmp === 0) return found = !0, mid;
162
+ cmp < 0 ? low = mid + 1 : high = mid - 1;
163
+ }
164
+ return found = !1, low - 1;
164
165
  }
165
166
  function upperBound(haystack, needle, index) {
166
- for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++)
167
- ;
168
- return index;
167
+ for (let i = index + 1; i < haystack.length && haystack[i][COLUMN] === needle; index = i++);
168
+ return index;
169
169
  }
170
170
  function lowerBound(haystack, needle, index) {
171
- for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--)
172
- ;
173
- return index;
171
+ for (let i = index - 1; i >= 0 && haystack[i][COLUMN] === needle; index = i--);
172
+ return index;
174
173
  }
175
174
  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);
175
+ let { lastKey, lastNeedle, lastIndex } = state, low = 0, high = haystack.length - 1;
176
+ if (key === lastKey) {
177
+ if (needle === lastNeedle) return found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle, lastIndex;
178
+ needle >= lastNeedle ? low = lastIndex === -1 ? 0 : lastIndex : high = lastIndex;
179
+ }
180
+ return state.lastKey = key, state.lastNeedle = needle, state.lastIndex = binarySearch(haystack, needle, low, high);
184
181
  }
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;
182
+ 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
183
  function cast(map) {
187
- return map;
184
+ return map;
188
185
  }
189
186
  function decodedMappings(map) {
190
- var _a;
191
- return (_a = map)._decoded || (_a._decoded = decode(map._encoded));
187
+ var _a;
188
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
192
189
  }
193
190
  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);
191
+ let { line, column, bias } = needle;
192
+ if (line--, line < 0) throw Error(LINE_GTR_ZERO);
193
+ if (column < 0) throw Error(COL_GTR_EQ_ZERO);
194
+ let decoded = decodedMappings(map);
195
+ if (line >= decoded.length) return OMapping(null, null, null, null);
196
+ let segments = decoded[line], index = traceSegmentInternal(segments, cast(map)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
197
+ if (index === -1) return OMapping(null, null, null, null);
198
+ let segment = segments[index];
199
+ if (segment.length === 1) return OMapping(null, null, null, null);
200
+ let { names, resolvedSources } = map;
201
+ return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
210
202
  }
211
203
  function OMapping(source, line, column, name) {
212
- return { source, line, column, name };
204
+ return {
205
+ source,
206
+ line,
207
+ column,
208
+ name
209
+ };
213
210
  }
214
211
  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;
212
+ let index = memoizedBinarySearch(segments, column, memo, line);
213
+ 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
214
  }
215
+ var DecodedMap = class {
216
+ _encoded;
217
+ _decoded;
218
+ _decodedMemo;
219
+ url;
220
+ version;
221
+ names = [];
222
+ resolvedSources;
223
+ constructor(map, from) {
224
+ this.map = map;
225
+ let { mappings, names, sources } = map;
226
+ this.version = map.version, this.names = names || [], this._encoded = mappings || "", this._decodedMemo = memoizedState(), this.url = from, this.resolvedSources = (sources || []).map((s) => posixResolve(s || "", from));
227
+ }
228
+ };
234
229
  function memoizedState() {
235
- return {
236
- lastKey: -1,
237
- lastNeedle: -1,
238
- lastIndex: -1
239
- };
230
+ return {
231
+ lastKey: -1,
232
+ lastNeedle: -1,
233
+ lastIndex: -1
234
+ };
240
235
  }
241
236
  function getOriginalPosition(map, needle) {
242
- const result = originalPositionFor(map, needle);
243
- return result.column == null ? null : result;
237
+ let result = originalPositionFor(map, needle);
238
+ return result.column == null ? null : result;
244
239
  }
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"
240
+ const MODULE_RUNNER_SOURCEMAPPING_REGEXP = /* @__PURE__ */ RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json;base64,(.+)`);
241
+ var EvaluatedModuleNode = class {
242
+ importers = /* @__PURE__ */ new Set();
243
+ imports = /* @__PURE__ */ new Set();
244
+ evaluated = !1;
245
+ meta;
246
+ promise;
247
+ exports;
248
+ file;
249
+ map;
250
+ constructor(id, url) {
251
+ this.id = id, this.url = url, this.file = cleanUrl(id);
252
+ }
253
+ }, EvaluatedModules = class {
254
+ idToModuleMap = /* @__PURE__ */ new Map();
255
+ fileToModulesMap = /* @__PURE__ */ new Map();
256
+ urlToIdModuleMap = /* @__PURE__ */ new Map();
257
+ getModuleById(id) {
258
+ return this.idToModuleMap.get(id);
259
+ }
260
+ getModulesByFile(file) {
261
+ return this.fileToModulesMap.get(file);
262
+ }
263
+ getModuleByUrl(url) {
264
+ return this.urlToIdModuleMap.get(unwrapId(url));
265
+ }
266
+ ensureModule(id, url) {
267
+ if (id = normalizeModuleId(id), this.idToModuleMap.has(id)) {
268
+ let moduleNode$1 = this.idToModuleMap.get(id);
269
+ return this.urlToIdModuleMap.set(url, moduleNode$1), moduleNode$1;
270
+ }
271
+ let moduleNode = new EvaluatedModuleNode(id, url);
272
+ this.idToModuleMap.set(id, moduleNode), this.urlToIdModuleMap.set(url, moduleNode);
273
+ let fileModules = this.fileToModulesMap.get(moduleNode.file) || /* @__PURE__ */ new Set();
274
+ return fileModules.add(moduleNode), this.fileToModulesMap.set(moduleNode.file, fileModules), moduleNode;
275
+ }
276
+ invalidateModule(node) {
277
+ node.evaluated = !1, node.meta = void 0, node.map = void 0, node.promise = void 0, node.exports = void 0, node.imports.clear();
278
+ }
279
+ getModuleSourceMapById(id) {
280
+ let mod = this.getModuleById(id);
281
+ if (!mod) return null;
282
+ if (mod.map) return mod.map;
283
+ if (!mod.meta || !("code" in mod.meta)) return null;
284
+ let pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`, lastIndex = mod.meta.code.lastIndexOf(pattern);
285
+ if (lastIndex === -1) return null;
286
+ let mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(mod.meta.code.slice(lastIndex))?.[1];
287
+ return mapString ? (mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file), mod.map) : null;
288
+ }
289
+ clear() {
290
+ this.idToModuleMap.clear(), this.fileToModulesMap.clear(), this.urlToIdModuleMap.clear();
291
+ }
292
+ };
293
+ const prefixedBuiltins = new Set([
294
+ "node:sea",
295
+ "node:sqlite",
296
+ "node:test",
297
+ "node:test/reporters"
336
298
  ]);
337
299
  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
- }
300
+ if (prefixedBuiltins.has(file)) return file;
301
+ let unixFile = slash(file).replace(/^\/@fs\//, isWindows ? "" : "/").replace(/^node:/, "").replace(/^\/+/, "/");
302
+ return unixFile.replace(/^file:\/+/, isWindows ? "" : "/");
524
303
  }
304
+ var HMRContext = class {
305
+ newListeners;
306
+ constructor(hmrClient, ownerPath) {
307
+ this.hmrClient = hmrClient, this.ownerPath = ownerPath, hmrClient.dataMap.has(ownerPath) || hmrClient.dataMap.set(ownerPath, {});
308
+ let mod = hmrClient.hotModulesMap.get(ownerPath);
309
+ mod && (mod.callbacks = []);
310
+ let staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
311
+ if (staleListeners) for (let [event, staleFns] of staleListeners) {
312
+ let listeners = hmrClient.customListenersMap.get(event);
313
+ listeners && hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
314
+ }
315
+ this.newListeners = /* @__PURE__ */ new Map(), hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
316
+ }
317
+ get data() {
318
+ return this.hmrClient.dataMap.get(this.ownerPath);
319
+ }
320
+ accept(deps, callback) {
321
+ if (typeof deps == "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
322
+ else if (typeof deps == "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
323
+ else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
324
+ else throw Error("invalid hot.accept() usage.");
325
+ }
326
+ acceptExports(_, callback) {
327
+ this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
328
+ }
329
+ dispose(cb) {
330
+ this.hmrClient.disposeMap.set(this.ownerPath, cb);
331
+ }
332
+ prune(cb) {
333
+ this.hmrClient.pruneMap.set(this.ownerPath, cb);
334
+ }
335
+ decline() {}
336
+ invalidate(message) {
337
+ let firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
338
+ this.hmrClient.notifyListeners("vite:invalidate", {
339
+ path: this.ownerPath,
340
+ message,
341
+ firstInvalidatedBy
342
+ }), this.send("vite:invalidate", {
343
+ path: this.ownerPath,
344
+ message,
345
+ firstInvalidatedBy
346
+ }), this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
347
+ }
348
+ on(event, cb) {
349
+ let addToMap = (map) => {
350
+ let existing = map.get(event) || [];
351
+ existing.push(cb), map.set(event, existing);
352
+ };
353
+ addToMap(this.hmrClient.customListenersMap), addToMap(this.newListeners);
354
+ }
355
+ off(event, cb) {
356
+ let removeFromMap = (map) => {
357
+ let existing = map.get(event);
358
+ if (existing === void 0) return;
359
+ let pruned = existing.filter((l) => l !== cb);
360
+ if (pruned.length === 0) {
361
+ map.delete(event);
362
+ return;
363
+ }
364
+ map.set(event, pruned);
365
+ };
366
+ removeFromMap(this.hmrClient.customListenersMap), removeFromMap(this.newListeners);
367
+ }
368
+ send(event, data) {
369
+ this.hmrClient.send({
370
+ type: "custom",
371
+ event,
372
+ data
373
+ });
374
+ }
375
+ acceptDeps(deps, callback = () => {}) {
376
+ let mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
377
+ id: this.ownerPath,
378
+ callbacks: []
379
+ };
380
+ mod.callbacks.push({
381
+ deps,
382
+ fn: callback
383
+ }), this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
384
+ }
385
+ }, HMRClient = class {
386
+ hotModulesMap = /* @__PURE__ */ new Map();
387
+ disposeMap = /* @__PURE__ */ new Map();
388
+ pruneMap = /* @__PURE__ */ new Map();
389
+ dataMap = /* @__PURE__ */ new Map();
390
+ customListenersMap = /* @__PURE__ */ new Map();
391
+ ctxToListenersMap = /* @__PURE__ */ new Map();
392
+ currentFirstInvalidatedBy;
393
+ constructor(logger, transport, importUpdatedModule) {
394
+ this.logger = logger, this.transport = transport, this.importUpdatedModule = importUpdatedModule;
395
+ }
396
+ async notifyListeners(event, data) {
397
+ let cbs = this.customListenersMap.get(event);
398
+ cbs && await Promise.allSettled(cbs.map((cb) => cb(data)));
399
+ }
400
+ send(payload) {
401
+ this.transport.send(payload).catch((err) => {
402
+ this.logger.error(err);
403
+ });
404
+ }
405
+ clear() {
406
+ this.hotModulesMap.clear(), this.disposeMap.clear(), this.pruneMap.clear(), this.dataMap.clear(), this.customListenersMap.clear(), this.ctxToListenersMap.clear();
407
+ }
408
+ async prunePaths(paths) {
409
+ await Promise.all(paths.map((path) => {
410
+ let disposer = this.disposeMap.get(path);
411
+ if (disposer) return disposer(this.dataMap.get(path));
412
+ })), paths.forEach((path) => {
413
+ let fn = this.pruneMap.get(path);
414
+ fn && fn(this.dataMap.get(path));
415
+ });
416
+ }
417
+ warnFailedUpdate(err, path) {
418
+ (!(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)`);
419
+ }
420
+ updateQueue = [];
421
+ pendingUpdateQueue = !1;
422
+ async queueUpdate(payload) {
423
+ if (this.updateQueue.push(this.fetchUpdate(payload)), !this.pendingUpdateQueue) {
424
+ this.pendingUpdateQueue = !0, await Promise.resolve(), this.pendingUpdateQueue = !1;
425
+ let loading = [...this.updateQueue];
426
+ this.updateQueue = [], (await Promise.all(loading)).forEach((fn) => fn && fn());
427
+ }
428
+ }
429
+ async fetchUpdate(update) {
430
+ let { path, acceptedPath, firstInvalidatedBy } = update, mod = this.hotModulesMap.get(path);
431
+ if (!mod) return;
432
+ let fetchedModule, isSelfUpdate = path === acceptedPath, qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
433
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
434
+ let disposer = this.disposeMap.get(acceptedPath);
435
+ disposer && await disposer(this.dataMap.get(acceptedPath));
436
+ try {
437
+ fetchedModule = await this.importUpdatedModule(update);
438
+ } catch (e) {
439
+ this.warnFailedUpdate(e, acceptedPath);
440
+ }
441
+ }
442
+ return () => {
443
+ try {
444
+ this.currentFirstInvalidatedBy = firstInvalidatedBy;
445
+ for (let { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
446
+ let loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
447
+ this.logger.debug(`hot updated: ${loggedPath}`);
448
+ } finally {
449
+ this.currentFirstInvalidatedBy = void 0;
450
+ }
451
+ };
452
+ }
453
+ };
525
454
  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.
455
+ if (!metadata?.isDynamicImport && metadata?.importedNames?.length) {
456
+ let missingBindings = metadata.importedNames.filter((s) => !(s in mod));
457
+ if (missingBindings.length) {
458
+ let lastBinding = missingBindings[missingBindings.length - 1];
459
+ throw moduleType === "module" ? SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'`) : SyntaxError(`\
460
+ [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
461
  CommonJS modules can always be imported via the default export, for example using:
534
462
 
535
463
  import pkg from '${rawId}';
536
464
  const {${missingBindings.join(", ")}} = pkg;
537
465
  `);
538
- }
539
- }
466
+ }
467
+ }
540
468
  }
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;
469
+ let nanoid = (size = 21) => {
470
+ let id = "", i = size | 0;
471
+ for (; i--;) id += "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[Math.random() * 64 | 0];
472
+ return id;
546
473
  };
547
474
  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;
475
+ let error = Error(e.message || "Unknown invoke error");
476
+ return Object.assign(error, e, { runnerError: /* @__PURE__ */ Error("RunnerError") }), error;
554
477
  }
555
478
  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
- };
479
+ if (transport.invoke) return {
480
+ ...transport,
481
+ async invoke(name, data) {
482
+ let result = await transport.invoke({
483
+ type: "custom",
484
+ event: "vite:invoke",
485
+ data: {
486
+ id: "send",
487
+ name,
488
+ data
489
+ }
490
+ });
491
+ if ("error" in result) throw reviveInvokeError(result.error);
492
+ return result.result;
493
+ }
494
+ };
495
+ if (!transport.send || !transport.connect) throw Error("transport must implement send and connect when invoke is not implemented");
496
+ let rpcPromises = /* @__PURE__ */ new Map();
497
+ return {
498
+ ...transport,
499
+ connect({ onMessage, onDisconnection }) {
500
+ return transport.connect({
501
+ onMessage(payload) {
502
+ if (payload.type === "custom" && payload.event === "vite:invoke") {
503
+ let data = payload.data;
504
+ if (data.id.startsWith("response:")) {
505
+ let invokeId = data.id.slice(9), promise = rpcPromises.get(invokeId);
506
+ if (!promise) return;
507
+ promise.timeoutId && clearTimeout(promise.timeoutId), rpcPromises.delete(invokeId);
508
+ let { error, result } = data.data;
509
+ error ? promise.reject(error) : promise.resolve(result);
510
+ return;
511
+ }
512
+ }
513
+ onMessage(payload);
514
+ },
515
+ onDisconnection
516
+ });
517
+ },
518
+ disconnect() {
519
+ return rpcPromises.forEach((promise) => {
520
+ promise.reject(/* @__PURE__ */ Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
521
+ }), rpcPromises.clear(), transport.disconnect?.();
522
+ },
523
+ send(data) {
524
+ return transport.send(data);
525
+ },
526
+ async invoke(name, data) {
527
+ let promiseId = nanoid(), wrappedData = {
528
+ type: "custom",
529
+ event: "vite:invoke",
530
+ data: {
531
+ name,
532
+ id: `send:${promiseId}`,
533
+ data
534
+ }
535
+ }, sendPromise = transport.send(wrappedData), { promise, resolve: resolve$1, reject } = promiseWithResolvers(), timeout = transport.timeout ?? 6e4, timeoutId;
536
+ timeout > 0 && (timeoutId = setTimeout(() => {
537
+ rpcPromises.delete(promiseId), reject(/* @__PURE__ */ Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
538
+ }, timeout), timeoutId?.unref?.()), rpcPromises.set(promiseId, {
539
+ resolve: resolve$1,
540
+ reject,
541
+ name,
542
+ timeoutId
543
+ }), sendPromise && sendPromise.catch((err) => {
544
+ clearTimeout(timeoutId), rpcPromises.delete(promiseId), reject(err);
545
+ });
546
+ try {
547
+ return await promise;
548
+ } catch (err) {
549
+ throw reviveInvokeError(err);
550
+ }
551
+ }
552
+ };
639
553
  }, 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
- };
554
+ let invokeableTransport = createInvokeableTransport(transport), isConnected = !invokeableTransport.connect, connectingPromise;
555
+ return {
556
+ ...transport,
557
+ ...invokeableTransport.connect ? { async connect(onMessage) {
558
+ if (isConnected) return;
559
+ if (connectingPromise) {
560
+ await connectingPromise;
561
+ return;
562
+ }
563
+ let maybePromise = invokeableTransport.connect({
564
+ onMessage: onMessage ?? (() => {}),
565
+ onDisconnection() {
566
+ isConnected = !1;
567
+ }
568
+ });
569
+ maybePromise && (connectingPromise = maybePromise, await connectingPromise, connectingPromise = void 0), isConnected = !0;
570
+ } } : {},
571
+ ...invokeableTransport.disconnect ? { async disconnect() {
572
+ isConnected && (connectingPromise && await connectingPromise, isConnected = !1, await invokeableTransport.disconnect());
573
+ } } : {},
574
+ async send(data) {
575
+ if (invokeableTransport.send) {
576
+ if (!isConnected) if (connectingPromise) await connectingPromise;
577
+ else throw Error("send was called before connect");
578
+ await invokeableTransport.send(data);
579
+ }
580
+ },
581
+ async invoke(name, data) {
582
+ if (!isConnected) if (connectingPromise) await connectingPromise;
583
+ else throw Error("invoke was called before connect");
584
+ return invokeableTransport.invoke(name, data);
585
+ }
586
+ };
685
587
  }, 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
588
+ let pingInterval = options.pingInterval ?? 3e4, ws, pingIntervalId;
589
+ return {
590
+ async connect({ onMessage, onDisconnection }) {
591
+ let socket = options.createConnection();
592
+ socket.addEventListener("message", async ({ data }) => {
593
+ onMessage(JSON.parse(data));
594
+ });
595
+ let isOpened = socket.readyState === socket.OPEN;
596
+ isOpened || await new Promise((resolve$1, reject) => {
597
+ socket.addEventListener("open", () => {
598
+ isOpened = !0, resolve$1();
599
+ }, { once: !0 }), socket.addEventListener("close", async () => {
600
+ if (!isOpened) {
601
+ reject(/* @__PURE__ */ Error("WebSocket closed without opened."));
602
+ return;
603
+ }
604
+ onMessage({
605
+ type: "custom",
606
+ event: "vite:ws:disconnect",
607
+ data: { webSocket: socket }
608
+ }), onDisconnection();
609
+ });
610
+ }), onMessage({
611
+ type: "custom",
612
+ event: "vite:ws:connect",
613
+ data: { webSocket: socket }
614
+ }), ws = socket, pingIntervalId = setInterval(() => {
615
+ socket.readyState === socket.OPEN && socket.send(JSON.stringify({ type: "ping" }));
616
+ }, pingInterval);
617
+ },
618
+ disconnect() {
619
+ clearInterval(pingIntervalId), ws?.close();
620
+ },
621
+ send(data) {
622
+ ws.send(JSON.stringify(data));
623
+ }
624
+ };
625
+ }, 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 = {
626
+ debug: noop,
627
+ error: noop
732
628
  }, hmrLogger = {
733
- debug: (...msg) => console.log("[vite]", ...msg),
734
- error: (error) => console.log("[vite]", error)
629
+ debug: (...msg) => console.log("[vite]", ...msg),
630
+ error: (error) => console.log("[vite]", error)
735
631
  };
736
632
  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
- }
633
+ let queue = new Queue();
634
+ return (payload) => queue.enqueue(() => handler(payload));
760
635
  }
636
+ var Queue = class {
637
+ queue = [];
638
+ pending = !1;
639
+ enqueue(promise) {
640
+ return new Promise((resolve$1, reject) => {
641
+ this.queue.push({
642
+ promise,
643
+ resolve: resolve$1,
644
+ reject
645
+ }), this.dequeue();
646
+ });
647
+ }
648
+ dequeue() {
649
+ if (this.pending) return !1;
650
+ let item = this.queue.shift();
651
+ return item ? (this.pending = !0, item.promise().then(item.resolve).catch(item.reject).finally(() => {
652
+ this.pending = !1, this.dequeue();
653
+ }), !0) : !1;
654
+ }
655
+ };
761
656
  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
- });
657
+ return createHMRHandler(async (payload) => {
658
+ let hmrClient = runner.hmrClient;
659
+ if (!(!hmrClient || runner.isClosed())) switch (payload.type) {
660
+ case "connected":
661
+ hmrClient.logger.debug("connected.");
662
+ break;
663
+ case "update":
664
+ await hmrClient.notifyListeners("vite:beforeUpdate", payload), await Promise.all(payload.updates.map(async (update) => {
665
+ if (update.type === "js-update") return update.acceptedPath = unwrapId(update.acceptedPath), update.path = unwrapId(update.path), hmrClient.queueUpdate(update);
666
+ hmrClient.logger.error("css hmr is not supported in runner mode.");
667
+ })), await hmrClient.notifyListeners("vite:afterUpdate", payload);
668
+ break;
669
+ case "custom":
670
+ await hmrClient.notifyListeners(payload.event, payload.data);
671
+ break;
672
+ case "full-reload": {
673
+ let { triggeredBy } = payload, clearEntrypointUrls = triggeredBy ? getModulesEntrypoints(runner, getModulesByFile(runner, slash(triggeredBy))) : findAllEntrypoints(runner);
674
+ if (!clearEntrypointUrls.size) break;
675
+ hmrClient.logger.debug("program reload"), await hmrClient.notifyListeners("vite:beforeFullReload", payload), runner.evaluatedModules.clear();
676
+ for (let url of clearEntrypointUrls) try {
677
+ await runner.import(url);
678
+ } catch (err) {
679
+ err.code !== "ERR_OUTDATED_OPTIMIZED_DEP" && hmrClient.logger.error(`An error happened during full reload\n${err.message}\n${err.stack}`);
680
+ }
681
+ break;
682
+ }
683
+ case "prune":
684
+ await hmrClient.notifyListeners("vite:beforePrune", payload), await hmrClient.prunePaths(payload.paths);
685
+ break;
686
+ case "error": {
687
+ await hmrClient.notifyListeners("vite:error", payload);
688
+ let err = payload.err;
689
+ hmrClient.logger.error(`Internal Server Error\n${err.message}\n${err.stack}`);
690
+ break;
691
+ }
692
+ case "ping": break;
693
+ default: {
694
+ let check = payload;
695
+ return check;
696
+ }
697
+ }
698
+ });
820
699
  }
821
700
  function getModulesByFile(runner, file) {
822
- const nodes = runner.evaluatedModules.getModulesByFile(file);
823
- return nodes ? [...nodes].map((node) => node.id) : [];
701
+ let nodes = runner.evaluatedModules.getModulesByFile(file);
702
+ return nodes ? [...nodes].map((node) => node.id) : [];
824
703
  }
825
704
  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;
705
+ for (let moduleId of modules) {
706
+ if (visited.has(moduleId)) continue;
707
+ visited.add(moduleId);
708
+ let module = runner.evaluatedModules.getModuleById(moduleId);
709
+ if (!module) continue;
710
+ if (!module.importers.size) {
711
+ entrypoints.add(module.url);
712
+ continue;
713
+ }
714
+ for (let importer of module.importers) getModulesEntrypoints(runner, [importer], visited, entrypoints);
715
+ }
716
+ return entrypoints;
840
717
  }
841
718
  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;
719
+ for (let mod of runner.evaluatedModules.idToModuleMap.values()) mod.importers.size || entrypoints.add(mod.url);
720
+ return entrypoints;
845
721
  }
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
- );
722
+ const sourceMapCache = {}, fileContentsCache = {}, evaluatedModulesCache = /* @__PURE__ */ new Set(), retrieveFileHandlers = /* @__PURE__ */ new Set(), retrieveSourceMapHandlers = /* @__PURE__ */ new Set(), createExecHandlers = (handlers) => ((...args) => {
723
+ for (let handler of handlers) {
724
+ let result = handler(...args);
725
+ if (result) return result;
726
+ }
727
+ return null;
728
+ }), retrieveFileFromHandlers = createExecHandlers(retrieveFileHandlers), retrieveSourceMapFromHandlers = createExecHandlers(retrieveSourceMapHandlers);
855
729
  let overridden = !1;
856
730
  const originalPrepare = Error.prepareStackTrace;
857
731
  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);
732
+ 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
733
  }
860
734
  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);
735
+ 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);
862
736
  }
863
737
  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);
738
+ if (!file) return url;
739
+ let dir = posixDirname(slash(file)), match = /^\w+:\/\/[^/]*/.exec(dir), protocol = match ? match[0] : "", startPath = dir.slice(protocol.length);
740
+ return protocol && /^\/\w:/.test(startPath) ? (protocol += "/", protocol + slash(posixResolve(startPath, url))) : protocol + posixResolve(startPath, url);
869
741
  }
870
742
  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;
743
+ for (let moduleGraph of evaluatedModulesCache) {
744
+ let sourceMap = moduleGraph.getModuleSourceMapById(position.source);
745
+ if (sourceMap) return {
746
+ url: position.source,
747
+ map: sourceMap,
748
+ vite: !0
749
+ };
750
+ }
751
+ return null;
881
752
  }
882
753
  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;
754
+ if (path in fileContentsCache) return fileContentsCache[path];
755
+ let content = retrieveFileFromHandlers(path);
756
+ return typeof content == "string" ? (fileContentsCache[path] = content, content) : null;
886
757
  }
887
758
  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;
759
+ let fileData = retrieveFile(source);
760
+ if (!fileData) return null;
761
+ let re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm, lastMatch, match;
762
+ for (; match = re.exec(fileData);) lastMatch = match;
763
+ return lastMatch ? lastMatch[1] : null;
894
764
  }
895
765
  const reSourceMap = /^data:application\/json[^,]+base64,/;
896
766
  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;
767
+ let urlAndMap = retrieveSourceMapFromHandlers(source);
768
+ if (urlAndMap) return urlAndMap;
769
+ let sourceMappingURL = retrieveSourceMapURL(source);
770
+ if (!sourceMappingURL) return null;
771
+ let sourceMapData;
772
+ if (reSourceMap.test(sourceMappingURL)) {
773
+ let rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
774
+ sourceMapData = Buffer.from(rawData, "base64").toString(), sourceMappingURL = source;
775
+ } else sourceMappingURL = supportRelativeURL(source, sourceMappingURL), sourceMapData = retrieveFile(sourceMappingURL);
776
+ return sourceMapData ? {
777
+ url: sourceMappingURL,
778
+ map: sourceMapData
779
+ } : null;
911
780
  }
912
781
  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;
782
+ if (!position.source) return position;
783
+ let sourceMap = getRunnerSourceMap(position);
784
+ if (sourceMap ||= sourceMapCache[position.source], !sourceMap) {
785
+ let urlAndMap = retrieveSourceMap(position.source);
786
+ if (urlAndMap && urlAndMap.map) {
787
+ let url = urlAndMap.url;
788
+ sourceMap = sourceMapCache[position.source] = {
789
+ url,
790
+ map: new DecodedMap(typeof urlAndMap.map == "string" ? JSON.parse(urlAndMap.map) : urlAndMap.map, url)
791
+ };
792
+ let contents = sourceMap.map?.map.sourcesContent;
793
+ sourceMap.map && contents && sourceMap.map.resolvedSources.forEach((source, i) => {
794
+ let content = contents[i];
795
+ if (content && source && url) {
796
+ let contentUrl = supportRelativeURL(url, source);
797
+ fileContentsCache[contentUrl] = content;
798
+ }
799
+ });
800
+ } else sourceMap = sourceMapCache[position.source] = {
801
+ url: null,
802
+ map: null
803
+ };
804
+ }
805
+ if (sourceMap.map && sourceMap.url) {
806
+ let originalPosition = getOriginalPosition(sourceMap.map, position);
807
+ if (originalPosition && originalPosition.source != null) return originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source), sourceMap.vite && (originalPosition._vite = !0), originalPosition;
808
+ }
809
+ return position;
949
810
  }
950
811
  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;
812
+ let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
813
+ if (match) {
814
+ let position = mapSourcePosition({
815
+ name: null,
816
+ source: match[2],
817
+ line: +match[3],
818
+ column: match[4] - 1
819
+ });
820
+ return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
821
+ }
822
+ return match = /^eval at ([^(]+) \((.+)\)$/.exec(origin), match ? `eval at ${match[1]} (${mapEvalOrigin(match[2])})` : origin;
962
823
  }
963
824
  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;
825
+ let fileName, fileLocation = "";
826
+ if (this.isNative()) fileLocation = "native";
827
+ else {
828
+ fileName = this.getScriptNameOrSourceURL(), !fileName && this.isEval() && (fileLocation = this.getEvalOrigin(), fileLocation += ", "), fileName ? fileLocation += fileName : fileLocation += "<anonymous>";
829
+ let lineNumber = this.getLineNumber();
830
+ if (lineNumber != null) {
831
+ fileLocation += `:${lineNumber}`;
832
+ let columnNumber = this.getColumnNumber();
833
+ columnNumber && (fileLocation += `:${columnNumber}`);
834
+ }
835
+ }
836
+ let line = "", functionName = this.getFunctionName(), addSuffix = !0, isConstructor = this.isConstructor(), isMethodCall = !(this.isToplevel() || isConstructor);
837
+ if (isMethodCall) {
838
+ let typeName = this.getTypeName();
839
+ typeName === "[object Object]" && (typeName = "null");
840
+ let methodName = this.getMethodName();
841
+ 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>"}`;
842
+ } else isConstructor ? line += `new ${functionName || "<anonymous>"}` : functionName ? line += functionName : (line += fileLocation, addSuffix = !1);
843
+ return addSuffix && (line += ` (${fileLocation})`), line;
989
844
  }
990
845
  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;
846
+ let object = {};
847
+ return Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
848
+ let key = name;
849
+ object[key] = /^(?:is|get)/.test(name) ? function() {
850
+ return frame[key].call(frame);
851
+ } : frame[key];
852
+ }), object.toString = CallSiteToString, object;
998
853
  }
999
854
  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;
855
+ if (state === void 0 && (state = {
856
+ nextPosition: null,
857
+ curPosition: null
858
+ }), frame.isNative()) return state.curPosition = null, frame;
859
+ let source = frame.getFileName() || frame.getScriptNameOrSourceURL();
860
+ if (source) {
861
+ let line = frame.getLineNumber(), column = frame.getColumnNumber() - 1;
862
+ line === 1 && column > 62 && !frame.isEval() && (column -= 62);
863
+ let position = mapSourcePosition({
864
+ name: null,
865
+ source,
866
+ line,
867
+ column
868
+ });
869
+ state.curPosition = position, frame = cloneCallSite(frame);
870
+ let originalFunctionName = frame.getFunctionName;
871
+ return frame.getFunctionName = function() {
872
+ let name = (() => state.nextPosition == null ? originalFunctionName() : state.nextPosition.name || originalFunctionName())();
873
+ return name === "eval" && "_vite" in position ? null : name;
874
+ }, frame.getFileName = function() {
875
+ return position.source ?? null;
876
+ }, frame.getLineNumber = function() {
877
+ return position.line;
878
+ }, frame.getColumnNumber = function() {
879
+ return position.column + 1;
880
+ }, frame.getScriptNameOrSourceURL = function() {
881
+ return position.source;
882
+ }, frame;
883
+ }
884
+ let origin = frame.isEval() && frame.getEvalOrigin();
885
+ return origin ? (origin = mapEvalOrigin(origin), frame = cloneCallSite(frame), frame.getEvalOrigin = function() {
886
+ return origin || void 0;
887
+ }, frame) : frame;
1033
888
  }
1034
889
  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("");
890
+ let name = error.name || "Error", message = error.message || "", errorString = `${name}: ${message}`, state = {
891
+ nextPosition: null,
892
+ curPosition: null
893
+ }, processedStack = [];
894
+ for (let i = stack.length - 1; i >= 0; i--) processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`), state.nextPosition = state.curPosition;
895
+ return state.curPosition = state.nextPosition = null, errorString + processedStack.reverse().join("");
1040
896
  }
1041
897
  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
- );
898
+ if (runner.options.sourcemapInterceptor === "node") {
899
+ if (typeof process > "u") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because global \"process\" variable is not available.");
900
+ if (typeof process.setSourceMapsEnabled != "function") throw TypeError("Cannot use \"sourcemapInterceptor: 'node'\" because \"process.setSourceMapsEnabled\" function is not available. Please use Node >= 16.6.0.");
901
+ let isEnabledAlready = process.sourceMapsEnabled ?? !1;
902
+ return process.setSourceMapsEnabled(!0), () => !isEnabledAlready && process.setSourceMapsEnabled(!1);
903
+ }
904
+ return interceptStackTrace(runner, typeof runner.options.sourcemapInterceptor == "object" ? runner.options.sourcemapInterceptor : void 0);
1058
905
  }
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);
906
+ var ESModulesEvaluator = class {
907
+ startOffset = getAsyncFunctionDeclarationPaddingLineCount();
908
+ async runInlinedModule(context, code) {
909
+ let initModule = new AsyncFunction(ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, "\"use strict\";" + code);
910
+ await initModule(context[ssrModuleExportsKey], context[ssrImportMetaKey], context[ssrImportKey], context[ssrDynamicImportKey], context[ssrExportAllKey], context[ssrExportNameKey]), Object.seal(context[ssrModuleExportsKey]);
911
+ }
912
+ runExternalModule(filepath) {
913
+ return import(filepath);
914
+ }
915
+ };
916
+ const customizationHookNamespace = "vite-module-runner:import-meta-resolve/v1/", customizationHooksModule = `
917
+
918
+ export async function resolve(specifier, context, nextResolve) {
919
+ if (specifier.startsWith(${JSON.stringify(customizationHookNamespace)})) {
920
+ const data = specifier.slice(${JSON.stringify(customizationHookNamespace)}.length)
921
+ const [parsedSpecifier, parsedImporter] = JSON.parse(data)
922
+ specifier = parsedSpecifier
923
+ context.parentURL = parsedImporter
1080
924
  }
925
+
926
+ return nextResolve(specifier, context)
1081
927
  }
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
- }
928
+
929
+ `;
930
+ async function createImportMetaResolver() {
931
+ let module;
932
+ try {
933
+ module = (await import("node:module")).Module;
934
+ } catch {
935
+ return;
936
+ }
937
+ if (module?.register) {
938
+ try {
939
+ let hookModuleContent = `data:text/javascript,${encodeURI(customizationHooksModule)}`;
940
+ module.register(hookModuleContent);
941
+ } catch (e) {
942
+ if ("code" in e && e.code === "ERR_NETWORK_IMPORT_DISALLOWED") return;
943
+ throw e;
944
+ }
945
+ return (specifier, importer) => import.meta.resolve(`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`);
946
+ }
1286
947
  }
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
- }
948
+ const envProxy = new Proxy({}, { get(_, p) {
949
+ throw Error(`[module runner] Dynamic access of "import.meta.env" is not supported. Please, use "import.meta.env.${String(p)}" instead.`);
950
+ } });
951
+ function createDefaultImportMeta(modulePath) {
952
+ let href = posixPathToFileHref(modulePath), filename = modulePath, dirname$1 = posixDirname(modulePath);
953
+ return {
954
+ filename: isWindows ? toWindowsPath(filename) : filename,
955
+ dirname: isWindows ? toWindowsPath(dirname$1) : dirname$1,
956
+ url: href,
957
+ env: envProxy,
958
+ resolve(_id, _parent) {
959
+ throw Error("[module runner] \"import.meta.resolve\" is not supported.");
960
+ },
961
+ glob() {
962
+ throw Error("[module runner] \"import.meta.glob\" is statically replaced during file transformation. Make sure to reference it by the full name.");
963
+ }
964
+ };
965
+ }
966
+ let importMetaResolverCache;
967
+ async function createNodeImportMeta(modulePath) {
968
+ let defaultMeta = createDefaultImportMeta(modulePath), href = defaultMeta.url;
969
+ importMetaResolverCache ??= createImportMetaResolver();
970
+ let importMetaResolver = await importMetaResolverCache;
971
+ return {
972
+ ...defaultMeta,
973
+ main: !1,
974
+ resolve(id, parent) {
975
+ let resolver = importMetaResolver ?? defaultMeta.resolve;
976
+ return resolver(id, parent ?? href);
977
+ }
978
+ };
1300
979
  }
1301
- export {
1302
- ESModulesEvaluator,
1303
- EvaluatedModules,
1304
- ModuleRunner,
1305
- createWebSocketModuleRunnerTransport,
1306
- ssrDynamicImportKey,
1307
- ssrExportAllKey,
1308
- ssrImportKey,
1309
- ssrImportMetaKey,
1310
- ssrModuleExportsKey
980
+ var ModuleRunner = class {
981
+ evaluatedModules;
982
+ hmrClient;
983
+ transport;
984
+ resetSourceMapSupport;
985
+ concurrentModuleNodePromises = /* @__PURE__ */ new Map();
986
+ closed = !1;
987
+ constructor(options, evaluator = new ESModulesEvaluator(), debug) {
988
+ if (this.options = options, this.evaluator = evaluator, this.debug = debug, this.evaluatedModules = options.evaluatedModules ?? new EvaluatedModules(), this.transport = normalizeModuleRunnerTransport(options.transport), options.hmr !== !1) {
989
+ let optionsHmr = options.hmr ?? !0, resolvedHmrLogger = optionsHmr === !0 || optionsHmr.logger === void 0 ? hmrLogger : optionsHmr.logger === !1 ? silentConsole : optionsHmr.logger;
990
+ if (this.hmrClient = new HMRClient(resolvedHmrLogger, this.transport, ({ acceptedPath }) => this.import(acceptedPath)), !this.transport.connect) throw Error("HMR is not supported by this runner transport, but `hmr` option was set to true");
991
+ this.transport.connect(createHMRHandlerForRunner(this));
992
+ } else this.transport.connect?.();
993
+ options.sourcemapInterceptor !== !1 && (this.resetSourceMapSupport = enableSourceMapSupport(this));
994
+ }
995
+ async import(url) {
996
+ let fetchedModule = await this.cachedModule(url);
997
+ return await this.cachedRequest(url, fetchedModule);
998
+ }
999
+ clearCache() {
1000
+ this.evaluatedModules.clear(), this.hmrClient?.clear();
1001
+ }
1002
+ async close() {
1003
+ this.resetSourceMapSupport?.(), this.clearCache(), this.hmrClient = void 0, this.closed = !0, await this.transport.disconnect?.();
1004
+ }
1005
+ isClosed() {
1006
+ return this.closed;
1007
+ }
1008
+ processImport(exports, fetchResult, metadata) {
1009
+ if (!("externalize" in fetchResult)) return exports;
1010
+ let { url, type } = fetchResult;
1011
+ return type !== "module" && type !== "commonjs" || analyzeImportedModDifference(exports, url, type, metadata), exports;
1012
+ }
1013
+ isCircularModule(mod) {
1014
+ for (let importedFile of mod.imports) if (mod.importers.has(importedFile)) return !0;
1015
+ return !1;
1016
+ }
1017
+ isCircularImport(importers, moduleUrl, visited = /* @__PURE__ */ new Set()) {
1018
+ for (let importer of importers) {
1019
+ if (visited.has(importer)) continue;
1020
+ if (visited.add(importer), importer === moduleUrl) return !0;
1021
+ let mod = this.evaluatedModules.getModuleById(importer);
1022
+ if (mod && mod.importers.size && this.isCircularImport(mod.importers, moduleUrl, visited)) return !0;
1023
+ }
1024
+ return !1;
1025
+ }
1026
+ async cachedRequest(url, mod, callstack = [], metadata) {
1027
+ let meta = mod.meta, moduleId = meta.id, { importers } = mod, importee = callstack[callstack.length - 1];
1028
+ if (importee && importers.add(importee), (callstack.includes(moduleId) || this.isCircularModule(mod) || this.isCircularImport(importers, moduleId)) && mod.exports) return this.processImport(mod.exports, meta, metadata);
1029
+ let debugTimer;
1030
+ this.debug && (debugTimer = setTimeout(() => {
1031
+ let getStack = () => `stack:\n${[...callstack, moduleId].reverse().map((p) => ` - ${p}`).join("\n")}`;
1032
+ this.debug(`[module runner] module ${moduleId} takes over 2s to load.\n${getStack()}`);
1033
+ }, 2e3));
1034
+ try {
1035
+ if (mod.promise) return this.processImport(await mod.promise, meta, metadata);
1036
+ let promise = this.directRequest(url, mod, callstack);
1037
+ return mod.promise = promise, mod.evaluated = !1, this.processImport(await promise, meta, metadata);
1038
+ } finally {
1039
+ mod.evaluated = !0, debugTimer && clearTimeout(debugTimer);
1040
+ }
1041
+ }
1042
+ async cachedModule(url, importer) {
1043
+ let cached = this.concurrentModuleNodePromises.get(url);
1044
+ if (cached) this.debug?.("[module runner] using cached module info for", url);
1045
+ else {
1046
+ let cachedModule = this.evaluatedModules.getModuleByUrl(url);
1047
+ cached = this.getModuleInformation(url, importer, cachedModule).finally(() => {
1048
+ this.concurrentModuleNodePromises.delete(url);
1049
+ }), this.concurrentModuleNodePromises.set(url, cached);
1050
+ }
1051
+ return cached;
1052
+ }
1053
+ async getModuleInformation(url, importer, cachedModule) {
1054
+ if (this.closed) throw Error("Vite module runner has been closed.");
1055
+ this.debug?.("[module runner] fetching", url);
1056
+ let isCached = !!(typeof cachedModule == "object" && cachedModule.meta), fetchedModule = url.startsWith("data:") ? {
1057
+ externalize: url,
1058
+ type: "builtin"
1059
+ } : await this.transport.invoke("fetchModule", [
1060
+ url,
1061
+ importer,
1062
+ {
1063
+ cached: isCached,
1064
+ startOffset: this.evaluator.startOffset
1065
+ }
1066
+ ]);
1067
+ if ("cache" in fetchedModule) {
1068
+ if (!cachedModule || !cachedModule.meta) throw Error(`Module "${url}" was mistakenly invalidated during fetch phase.`);
1069
+ return cachedModule;
1070
+ }
1071
+ let moduleId = "externalize" in fetchedModule ? fetchedModule.externalize : fetchedModule.id, moduleUrl = "url" in fetchedModule ? fetchedModule.url : url, module = this.evaluatedModules.ensureModule(moduleId, moduleUrl);
1072
+ return "invalidate" in fetchedModule && fetchedModule.invalidate && this.evaluatedModules.invalidateModule(module), fetchedModule.url = moduleUrl, fetchedModule.id = moduleId, module.meta = fetchedModule, module;
1073
+ }
1074
+ async directRequest(url, mod, _callstack) {
1075
+ let fetchResult = mod.meta, moduleId = fetchResult.id, callstack = [..._callstack, moduleId], request = async (dep, metadata) => {
1076
+ let importer = "file" in fetchResult && fetchResult.file || moduleId, depMod = await this.cachedModule(dep, importer);
1077
+ return depMod.importers.add(moduleId), mod.imports.add(depMod.id), this.cachedRequest(dep, depMod, callstack, metadata);
1078
+ }, dynamicRequest = async (dep) => (dep = String(dep), dep[0] === "." && (dep = posixResolve(posixDirname(url), dep)), request(dep, { isDynamicImport: !0 }));
1079
+ if ("externalize" in fetchResult) {
1080
+ let { externalize } = fetchResult;
1081
+ this.debug?.("[module runner] externalizing", externalize);
1082
+ let exports$1 = await this.evaluator.runExternalModule(externalize);
1083
+ return mod.exports = exports$1, exports$1;
1084
+ }
1085
+ let { code, file } = fetchResult;
1086
+ if (code == null) {
1087
+ let importer = callstack[callstack.length - 2];
1088
+ throw Error(`[module runner] Failed to load "${url}"${importer ? ` imported from ${importer}` : ""}`);
1089
+ }
1090
+ let createImportMeta = this.options.createImportMeta ?? createDefaultImportMeta, modulePath = cleanUrl(file || moduleId), href = posixPathToFileHref(modulePath), meta = await createImportMeta(modulePath), exports = Object.create(null);
1091
+ Object.defineProperty(exports, Symbol.toStringTag, {
1092
+ value: "Module",
1093
+ enumerable: !1,
1094
+ configurable: !1
1095
+ }), mod.exports = exports;
1096
+ let hotContext;
1097
+ this.hmrClient && Object.defineProperty(meta, "hot", {
1098
+ enumerable: !0,
1099
+ get: () => {
1100
+ if (!this.hmrClient) throw Error("[module runner] HMR client was closed.");
1101
+ return this.debug?.("[module runner] creating hmr context for", mod.url), hotContext ||= new HMRContext(this.hmrClient, mod.url), hotContext;
1102
+ },
1103
+ set: (value) => {
1104
+ hotContext = value;
1105
+ }
1106
+ });
1107
+ let context = {
1108
+ [ssrImportKey]: request,
1109
+ [ssrDynamicImportKey]: dynamicRequest,
1110
+ [ssrModuleExportsKey]: exports,
1111
+ [ssrExportAllKey]: (obj) => exportAll(exports, obj),
1112
+ [ssrExportNameKey]: (name, getter) => Object.defineProperty(exports, name, {
1113
+ enumerable: !0,
1114
+ configurable: !0,
1115
+ get: getter
1116
+ }),
1117
+ [ssrImportMetaKey]: meta
1118
+ };
1119
+ return this.debug?.("[module runner] executing", href), await this.evaluator.runInlinedModule(context, code, mod), exports;
1120
+ }
1311
1121
  };
1122
+ function exportAll(exports, sourceModule) {
1123
+ if (exports !== sourceModule && !(isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise)) {
1124
+ for (let key in sourceModule) if (key !== "default" && key !== "__esModule" && !(key in exports)) try {
1125
+ Object.defineProperty(exports, key, {
1126
+ enumerable: !0,
1127
+ configurable: !0,
1128
+ get: () => sourceModule[key]
1129
+ });
1130
+ } catch {}
1131
+ }
1132
+ }
1133
+ export { ESModulesEvaluator, EvaluatedModules, ModuleRunner, createDefaultImportMeta, createNodeImportMeta, createWebSocketModuleRunnerTransport, normalizeModuleId, ssrDynamicImportKey, ssrExportAllKey, ssrExportNameKey, ssrImportKey, ssrImportMetaKey, ssrModuleExportsKey };