vite 6.0.0-alpha.8 → 6.0.0-beta.0

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.
@@ -1,248 +1,246 @@
1
1
  import '@vite/env';
2
2
 
3
3
  class HMRContext {
4
- constructor(hmrClient, ownerPath) {
5
- this.hmrClient = hmrClient;
6
- this.ownerPath = ownerPath;
7
- if (!hmrClient.dataMap.has(ownerPath)) {
8
- hmrClient.dataMap.set(ownerPath, {});
4
+ constructor(hmrClient, ownerPath) {
5
+ this.hmrClient = hmrClient;
6
+ this.ownerPath = ownerPath;
7
+ if (!hmrClient.dataMap.has(ownerPath)) {
8
+ hmrClient.dataMap.set(ownerPath, {});
9
+ }
10
+ const mod = hmrClient.hotModulesMap.get(ownerPath);
11
+ if (mod) {
12
+ mod.callbacks = [];
13
+ }
14
+ const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
15
+ if (staleListeners) {
16
+ for (const [event, staleFns] of staleListeners) {
17
+ const listeners = hmrClient.customListenersMap.get(event);
18
+ if (listeners) {
19
+ hmrClient.customListenersMap.set(
20
+ event,
21
+ listeners.filter((l) => !staleFns.includes(l))
22
+ );
9
23
  }
10
- // when a file is hot updated, a new context is created
11
- // clear its stale callbacks
12
- const mod = hmrClient.hotModulesMap.get(ownerPath);
13
- if (mod) {
14
- mod.callbacks = [];
15
- }
16
- // clear stale custom event listeners
17
- const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
18
- if (staleListeners) {
19
- for (const [event, staleFns] of staleListeners) {
20
- const listeners = hmrClient.customListenersMap.get(event);
21
- if (listeners) {
22
- hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
23
- }
24
- }
25
- }
26
- this.newListeners = new Map();
27
- hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
28
- }
29
- get data() {
30
- return this.hmrClient.dataMap.get(this.ownerPath);
31
- }
32
- accept(deps, callback) {
33
- if (typeof deps === 'function' || !deps) {
34
- // self-accept: hot.accept(() => {})
35
- this.acceptDeps([this.ownerPath], ([mod]) => deps === null || deps === void 0 ? void 0 : deps(mod));
36
- }
37
- else if (typeof deps === 'string') {
38
- // explicit deps
39
- this.acceptDeps([deps], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
40
- }
41
- else if (Array.isArray(deps)) {
42
- this.acceptDeps(deps, callback);
43
- }
44
- else {
45
- throw new Error(`invalid hot.accept() usage.`);
46
- }
47
- }
48
- // export names (first arg) are irrelevant on the client side, they're
49
- // extracted in the server for propagation
50
- acceptExports(_, callback) {
51
- this.acceptDeps([this.ownerPath], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
52
- }
53
- dispose(cb) {
54
- this.hmrClient.disposeMap.set(this.ownerPath, cb);
55
- }
56
- prune(cb) {
57
- this.hmrClient.pruneMap.set(this.ownerPath, cb);
58
- }
59
- // Kept for backward compatibility (#11036)
60
- // eslint-disable-next-line @typescript-eslint/no-empty-function
61
- decline() { }
62
- invalidate(message) {
63
- this.hmrClient.notifyListeners('vite:invalidate', {
64
- path: this.ownerPath,
65
- message,
66
- });
67
- this.send('vite:invalidate', {
68
- path: this.ownerPath,
69
- message,
70
- });
71
- this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`);
72
- }
73
- on(event, cb) {
74
- const addToMap = (map) => {
75
- const existing = map.get(event) || [];
76
- existing.push(cb);
77
- map.set(event, existing);
78
- };
79
- addToMap(this.hmrClient.customListenersMap);
80
- addToMap(this.newListeners);
81
- }
82
- off(event, cb) {
83
- const removeFromMap = (map) => {
84
- const existing = map.get(event);
85
- if (existing === undefined) {
86
- return;
87
- }
88
- const pruned = existing.filter((l) => l !== cb);
89
- if (pruned.length === 0) {
90
- map.delete(event);
91
- return;
92
- }
93
- map.set(event, pruned);
94
- };
95
- removeFromMap(this.hmrClient.customListenersMap);
96
- removeFromMap(this.newListeners);
97
- }
98
- send(event, data) {
99
- this.hmrClient.messenger.send(JSON.stringify({ type: 'custom', event, data }));
100
- }
101
- acceptDeps(deps, callback = () => { }) {
102
- const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
103
- id: this.ownerPath,
104
- callbacks: [],
105
- };
106
- mod.callbacks.push({
107
- deps,
108
- fn: callback,
109
- });
110
- this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
111
- }
24
+ }
25
+ }
26
+ this.newListeners = /* @__PURE__ */ new Map();
27
+ hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
28
+ }
29
+ get data() {
30
+ return this.hmrClient.dataMap.get(this.ownerPath);
31
+ }
32
+ accept(deps, callback) {
33
+ if (typeof deps === "function" || !deps) {
34
+ this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
35
+ } else if (typeof deps === "string") {
36
+ this.acceptDeps([deps], ([mod]) => callback?.(mod));
37
+ } else if (Array.isArray(deps)) {
38
+ this.acceptDeps(deps, callback);
39
+ } else {
40
+ throw new Error(`invalid hot.accept() usage.`);
41
+ }
42
+ }
43
+ // export names (first arg) are irrelevant on the client side, they're
44
+ // extracted in the server for propagation
45
+ acceptExports(_, callback) {
46
+ this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
47
+ }
48
+ dispose(cb) {
49
+ this.hmrClient.disposeMap.set(this.ownerPath, cb);
50
+ }
51
+ prune(cb) {
52
+ this.hmrClient.pruneMap.set(this.ownerPath, cb);
53
+ }
54
+ // Kept for backward compatibility (#11036)
55
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
56
+ decline() {
57
+ }
58
+ invalidate(message) {
59
+ this.hmrClient.notifyListeners("vite:invalidate", {
60
+ path: this.ownerPath,
61
+ message
62
+ });
63
+ this.send("vite:invalidate", {
64
+ path: this.ownerPath,
65
+ message
66
+ });
67
+ this.hmrClient.logger.debug(
68
+ `invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
69
+ );
70
+ }
71
+ on(event, cb) {
72
+ const addToMap = (map) => {
73
+ const existing = map.get(event) || [];
74
+ existing.push(cb);
75
+ map.set(event, existing);
76
+ };
77
+ addToMap(this.hmrClient.customListenersMap);
78
+ addToMap(this.newListeners);
79
+ }
80
+ off(event, cb) {
81
+ const removeFromMap = (map) => {
82
+ const existing = map.get(event);
83
+ if (existing === void 0) {
84
+ return;
85
+ }
86
+ const pruned = existing.filter((l) => l !== cb);
87
+ if (pruned.length === 0) {
88
+ map.delete(event);
89
+ return;
90
+ }
91
+ map.set(event, pruned);
92
+ };
93
+ removeFromMap(this.hmrClient.customListenersMap);
94
+ removeFromMap(this.newListeners);
95
+ }
96
+ send(event, data) {
97
+ this.hmrClient.messenger.send(
98
+ JSON.stringify({ type: "custom", event, data })
99
+ );
100
+ }
101
+ acceptDeps(deps, callback = () => {
102
+ }) {
103
+ const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
104
+ id: this.ownerPath,
105
+ callbacks: []
106
+ };
107
+ mod.callbacks.push({
108
+ deps,
109
+ fn: callback
110
+ });
111
+ this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
112
+ }
112
113
  }
113
114
  class HMRMessenger {
114
- constructor(connection) {
115
- this.connection = connection;
116
- this.queue = [];
117
- }
118
- send(message) {
119
- this.queue.push(message);
120
- this.flush();
121
- }
122
- flush() {
123
- if (this.connection.isReady()) {
124
- this.queue.forEach((msg) => this.connection.send(msg));
125
- this.queue = [];
126
- }
127
- }
115
+ constructor(connection) {
116
+ this.connection = connection;
117
+ this.queue = [];
118
+ }
119
+ send(message) {
120
+ this.queue.push(message);
121
+ this.flush();
122
+ }
123
+ flush() {
124
+ if (this.connection.isReady()) {
125
+ this.queue.forEach((msg) => this.connection.send(msg));
126
+ this.queue = [];
127
+ }
128
+ }
128
129
  }
129
130
  class HMRClient {
130
- constructor(logger, connection,
131
- // This allows implementing reloading via different methods depending on the environment
132
- importUpdatedModule) {
133
- this.logger = logger;
134
- this.importUpdatedModule = importUpdatedModule;
135
- this.hotModulesMap = new Map();
136
- this.disposeMap = new Map();
137
- this.pruneMap = new Map();
138
- this.dataMap = new Map();
139
- this.customListenersMap = new Map();
140
- this.ctxToListenersMap = new Map();
141
- this.updateQueue = [];
142
- this.pendingUpdateQueue = false;
143
- this.messenger = new HMRMessenger(connection);
144
- }
145
- async notifyListeners(event, data) {
146
- const cbs = this.customListenersMap.get(event);
147
- if (cbs) {
148
- await Promise.allSettled(cbs.map((cb) => cb(data)));
149
- }
150
- }
151
- clear() {
152
- this.hotModulesMap.clear();
153
- this.disposeMap.clear();
154
- this.pruneMap.clear();
155
- this.dataMap.clear();
156
- this.customListenersMap.clear();
157
- this.ctxToListenersMap.clear();
158
- }
159
- // After an HMR update, some modules are no longer imported on the page
160
- // but they may have left behind side effects that need to be cleaned up
161
- // (.e.g style injections)
162
- async prunePaths(paths) {
163
- await Promise.all(paths.map((path) => {
164
- const disposer = this.disposeMap.get(path);
165
- if (disposer)
166
- return disposer(this.dataMap.get(path));
167
- }));
168
- paths.forEach((path) => {
169
- const fn = this.pruneMap.get(path);
170
- if (fn) {
171
- fn(this.dataMap.get(path));
172
- }
173
- });
174
- }
175
- warnFailedUpdate(err, path) {
176
- if (!err.message.includes('fetch')) {
177
- this.logger.error(err);
178
- }
179
- this.logger.error(`Failed to reload ${path}. ` +
180
- `This could be due to syntax errors or importing non-existent ` +
181
- `modules. (see errors above)`);
182
- }
183
- /**
184
- * buffer multiple hot updates triggered by the same src change
185
- * so that they are invoked in the same order they were sent.
186
- * (otherwise the order may be inconsistent because of the http request round trip)
187
- */
188
- async queueUpdate(payload) {
189
- this.updateQueue.push(this.fetchUpdate(payload));
190
- if (!this.pendingUpdateQueue) {
191
- this.pendingUpdateQueue = true;
192
- await Promise.resolve();
193
- this.pendingUpdateQueue = false;
194
- const loading = [...this.updateQueue];
195
- this.updateQueue = [];
196
- (await Promise.all(loading)).forEach((fn) => fn && fn());
197
- }
198
- }
199
- async fetchUpdate(update) {
200
- const { path, acceptedPath } = update;
201
- const mod = this.hotModulesMap.get(path);
202
- if (!mod) {
203
- // In a code-splitting project,
204
- // it is common that the hot-updating module is not loaded yet.
205
- // https://github.com/vitejs/vite/issues/721
206
- return;
207
- }
208
- let fetchedModule;
209
- const isSelfUpdate = path === acceptedPath;
210
- // determine the qualified callbacks before we re-import the modules
211
- const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
212
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
213
- const disposer = this.disposeMap.get(acceptedPath);
214
- if (disposer)
215
- await disposer(this.dataMap.get(acceptedPath));
216
- try {
217
- fetchedModule = await this.importUpdatedModule(update);
218
- }
219
- catch (e) {
220
- this.warnFailedUpdate(e, acceptedPath);
221
- }
222
- }
223
- return () => {
224
- for (const { deps, fn } of qualifiedCallbacks) {
225
- fn(deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined)));
226
- }
227
- const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
228
- this.logger.debug(`hot updated: ${loggedPath}`);
229
- };
131
+ constructor(logger, connection, importUpdatedModule) {
132
+ this.logger = logger;
133
+ this.importUpdatedModule = importUpdatedModule;
134
+ this.hotModulesMap = /* @__PURE__ */ new Map();
135
+ this.disposeMap = /* @__PURE__ */ new Map();
136
+ this.pruneMap = /* @__PURE__ */ new Map();
137
+ this.dataMap = /* @__PURE__ */ new Map();
138
+ this.customListenersMap = /* @__PURE__ */ new Map();
139
+ this.ctxToListenersMap = /* @__PURE__ */ new Map();
140
+ this.updateQueue = [];
141
+ this.pendingUpdateQueue = false;
142
+ this.messenger = new HMRMessenger(connection);
143
+ }
144
+ async notifyListeners(event, data) {
145
+ const cbs = this.customListenersMap.get(event);
146
+ if (cbs) {
147
+ await Promise.allSettled(cbs.map((cb) => cb(data)));
148
+ }
149
+ }
150
+ clear() {
151
+ this.hotModulesMap.clear();
152
+ this.disposeMap.clear();
153
+ this.pruneMap.clear();
154
+ this.dataMap.clear();
155
+ this.customListenersMap.clear();
156
+ this.ctxToListenersMap.clear();
157
+ }
158
+ // After an HMR update, some modules are no longer imported on the page
159
+ // but they may have left behind side effects that need to be cleaned up
160
+ // (.e.g style injections)
161
+ async prunePaths(paths) {
162
+ await Promise.all(
163
+ paths.map((path) => {
164
+ const disposer = this.disposeMap.get(path);
165
+ if (disposer) return disposer(this.dataMap.get(path));
166
+ })
167
+ );
168
+ paths.forEach((path) => {
169
+ const fn = this.pruneMap.get(path);
170
+ if (fn) {
171
+ fn(this.dataMap.get(path));
172
+ }
173
+ });
174
+ }
175
+ warnFailedUpdate(err, path) {
176
+ if (!err.message.includes("fetch")) {
177
+ this.logger.error(err);
178
+ }
179
+ this.logger.error(
180
+ `Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
181
+ );
182
+ }
183
+ /**
184
+ * buffer multiple hot updates triggered by the same src change
185
+ * so that they are invoked in the same order they were sent.
186
+ * (otherwise the order may be inconsistent because of the http request round trip)
187
+ */
188
+ async queueUpdate(payload) {
189
+ this.updateQueue.push(this.fetchUpdate(payload));
190
+ if (!this.pendingUpdateQueue) {
191
+ this.pendingUpdateQueue = true;
192
+ await Promise.resolve();
193
+ this.pendingUpdateQueue = false;
194
+ const loading = [...this.updateQueue];
195
+ this.updateQueue = [];
196
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
197
+ }
198
+ }
199
+ async fetchUpdate(update) {
200
+ const { path, acceptedPath } = update;
201
+ const mod = this.hotModulesMap.get(path);
202
+ if (!mod) {
203
+ return;
204
+ }
205
+ let fetchedModule;
206
+ const isSelfUpdate = path === acceptedPath;
207
+ const qualifiedCallbacks = mod.callbacks.filter(
208
+ ({ deps }) => deps.includes(acceptedPath)
209
+ );
210
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
211
+ const disposer = this.disposeMap.get(acceptedPath);
212
+ if (disposer) await disposer(this.dataMap.get(acceptedPath));
213
+ try {
214
+ fetchedModule = await this.importUpdatedModule(update);
215
+ } catch (e) {
216
+ this.warnFailedUpdate(e, acceptedPath);
217
+ }
230
218
  }
219
+ return () => {
220
+ for (const { deps, fn } of qualifiedCallbacks) {
221
+ fn(
222
+ deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
223
+ );
224
+ }
225
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
226
+ this.logger.debug(`hot updated: ${loggedPath}`);
227
+ };
228
+ }
231
229
  }
232
230
 
233
231
  const hmrConfigName = __HMR_CONFIG_NAME__;
234
- const base$1 = __BASE__ || '/';
235
- // Create an element with provided attributes and optional children
232
+ const base$1 = __BASE__ || "/";
236
233
  function h(e, attrs = {}, ...children) {
237
- const elem = document.createElement(e);
238
- for (const [k, v] of Object.entries(attrs)) {
239
- elem.setAttribute(k, v);
240
- }
241
- elem.append(...children);
242
- return elem;
243
- }
244
- // set :host styles to make playwright detect the element as visible
245
- const templateStyle = /*css*/ `
234
+ const elem = document.createElement(e);
235
+ for (const [k, v] of Object.entries(attrs)) {
236
+ elem.setAttribute(k, v);
237
+ }
238
+ elem.append(...children);
239
+ return elem;
240
+ }
241
+ const templateStyle = (
242
+ /*css*/
243
+ `
246
244
  :host {
247
245
  position: fixed;
248
246
  top: 0;
@@ -382,448 +380,452 @@ kbd {
382
380
  border-color: rgb(54, 57, 64);
383
381
  border-image: initial;
384
382
  }
385
- `;
386
- // Error Template
387
- const createTemplate = () => h('div', { class: 'backdrop', part: 'backdrop' }, h('div', { class: 'window', part: 'window' }, h('pre', { class: 'message', part: 'message' }, h('span', { class: 'plugin', part: 'plugin' }), h('span', { class: 'message-body', part: 'message-body' })), h('pre', { class: 'file', part: 'file' }), h('pre', { class: 'frame', part: 'frame' }), h('pre', { class: 'stack', part: 'stack' }), h('div', { class: 'tip', part: 'tip' }, 'Click outside, press ', h('kbd', {}, 'Esc'), ' key, or fix the code to dismiss.', h('br'), 'You can also disable this overlay by setting ', h('code', { part: 'config-option-name' }, 'server.hmr.overlay'), ' to ', h('code', { part: 'config-option-value' }, 'false'), ' in ', h('code', { part: 'config-file-name' }, hmrConfigName), '.')), h('style', {}, templateStyle));
383
+ `
384
+ );
385
+ const createTemplate = () => h(
386
+ "div",
387
+ { class: "backdrop", part: "backdrop" },
388
+ h(
389
+ "div",
390
+ { class: "window", part: "window" },
391
+ h(
392
+ "pre",
393
+ { class: "message", part: "message" },
394
+ h("span", { class: "plugin", part: "plugin" }),
395
+ h("span", { class: "message-body", part: "message-body" })
396
+ ),
397
+ h("pre", { class: "file", part: "file" }),
398
+ h("pre", { class: "frame", part: "frame" }),
399
+ h("pre", { class: "stack", part: "stack" }),
400
+ h(
401
+ "div",
402
+ { class: "tip", part: "tip" },
403
+ "Click outside, press ",
404
+ h("kbd", {}, "Esc"),
405
+ " key, or fix the code to dismiss.",
406
+ h("br"),
407
+ "You can also disable this overlay by setting ",
408
+ h("code", { part: "config-option-name" }, "server.hmr.overlay"),
409
+ " to ",
410
+ h("code", { part: "config-option-value" }, "false"),
411
+ " in ",
412
+ h("code", { part: "config-file-name" }, hmrConfigName),
413
+ "."
414
+ )
415
+ ),
416
+ h("style", {}, templateStyle)
417
+ );
388
418
  const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
389
419
  const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
390
- // Allow `ErrorOverlay` to extend `HTMLElement` even in environments where
391
- // `HTMLElement` was not originally defined.
392
420
  const { HTMLElement = class {
393
421
  } } = globalThis;
394
422
  class ErrorOverlay extends HTMLElement {
395
- constructor(err, links = true) {
396
- var _a;
397
- super();
398
- this.root = this.attachShadow({ mode: 'open' });
399
- this.root.appendChild(createTemplate());
400
- codeframeRE.lastIndex = 0;
401
- const hasFrame = err.frame && codeframeRE.test(err.frame);
402
- const message = hasFrame
403
- ? err.message.replace(codeframeRE, '')
404
- : err.message;
405
- if (err.plugin) {
406
- this.text('.plugin', `[plugin:${err.plugin}] `);
407
- }
408
- this.text('.message-body', message.trim());
409
- const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`);
410
- if (err.loc) {
411
- this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links);
412
- }
413
- else if (err.id) {
414
- this.text('.file', file);
415
- }
416
- if (hasFrame) {
417
- this.text('.frame', err.frame.trim());
418
- }
419
- this.text('.stack', err.stack, links);
420
- this.root.querySelector('.window').addEventListener('click', (e) => {
421
- e.stopPropagation();
422
- });
423
- this.addEventListener('click', () => {
424
- this.close();
425
- });
426
- this.closeOnEsc = (e) => {
427
- if (e.key === 'Escape' || e.code === 'Escape') {
428
- this.close();
429
- }
430
- };
431
- document.addEventListener('keydown', this.closeOnEsc);
432
- }
433
- text(selector, text, linkFiles = false) {
434
- const el = this.root.querySelector(selector);
435
- if (!linkFiles) {
436
- el.textContent = text;
437
- }
438
- else {
439
- let curIndex = 0;
440
- let match;
441
- fileRE.lastIndex = 0;
442
- while ((match = fileRE.exec(text))) {
443
- const { 0: file, index } = match;
444
- if (index != null) {
445
- const frag = text.slice(curIndex, index);
446
- el.appendChild(document.createTextNode(frag));
447
- const link = document.createElement('a');
448
- link.textContent = file;
449
- link.className = 'file-link';
450
- link.onclick = () => {
451
- fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
452
- };
453
- el.appendChild(link);
454
- curIndex += frag.length + file.length;
455
- }
456
- }
423
+ constructor(err, links = true) {
424
+ super();
425
+ this.root = this.attachShadow({ mode: "open" });
426
+ this.root.appendChild(createTemplate());
427
+ codeframeRE.lastIndex = 0;
428
+ const hasFrame = err.frame && codeframeRE.test(err.frame);
429
+ const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
430
+ if (err.plugin) {
431
+ this.text(".plugin", `[plugin:${err.plugin}] `);
432
+ }
433
+ this.text(".message-body", message.trim());
434
+ const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
435
+ if (err.loc) {
436
+ this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
437
+ } else if (err.id) {
438
+ this.text(".file", file);
439
+ }
440
+ if (hasFrame) {
441
+ this.text(".frame", err.frame.trim());
442
+ }
443
+ this.text(".stack", err.stack, links);
444
+ this.root.querySelector(".window").addEventListener("click", (e) => {
445
+ e.stopPropagation();
446
+ });
447
+ this.addEventListener("click", () => {
448
+ this.close();
449
+ });
450
+ this.closeOnEsc = (e) => {
451
+ if (e.key === "Escape" || e.code === "Escape") {
452
+ this.close();
453
+ }
454
+ };
455
+ document.addEventListener("keydown", this.closeOnEsc);
456
+ }
457
+ text(selector, text, linkFiles = false) {
458
+ const el = this.root.querySelector(selector);
459
+ if (!linkFiles) {
460
+ el.textContent = text;
461
+ } else {
462
+ let curIndex = 0;
463
+ let match;
464
+ fileRE.lastIndex = 0;
465
+ while (match = fileRE.exec(text)) {
466
+ const { 0: file, index } = match;
467
+ if (index != null) {
468
+ const frag = text.slice(curIndex, index);
469
+ el.appendChild(document.createTextNode(frag));
470
+ const link = document.createElement("a");
471
+ link.textContent = file;
472
+ link.className = "file-link";
473
+ link.onclick = () => {
474
+ fetch(
475
+ new URL(
476
+ `${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
477
+ import.meta.url
478
+ )
479
+ );
480
+ };
481
+ el.appendChild(link);
482
+ curIndex += frag.length + file.length;
457
483
  }
484
+ }
458
485
  }
459
- close() {
460
- var _a;
461
- (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this);
462
- document.removeEventListener('keydown', this.closeOnEsc);
463
- }
486
+ }
487
+ close() {
488
+ this.parentNode?.removeChild(this);
489
+ document.removeEventListener("keydown", this.closeOnEsc);
490
+ }
464
491
  }
465
- const overlayId = 'vite-error-overlay';
466
- const { customElements } = globalThis; // Ensure `customElements` is defined before the next line.
492
+ const overlayId = "vite-error-overlay";
493
+ const { customElements } = globalThis;
467
494
  if (customElements && !customElements.get(overlayId)) {
468
- customElements.define(overlayId, ErrorOverlay);
495
+ customElements.define(overlayId, ErrorOverlay);
469
496
  }
470
497
 
471
- var _a;
472
- console.debug('[vite] connecting...');
498
+ console.debug("[vite] connecting...");
473
499
  const importMetaUrl = new URL(import.meta.url);
474
- // use server configuration, then fallback to inference
475
500
  const serverHost = __SERVER_HOST__;
476
- const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws');
501
+ const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
477
502
  const hmrPort = __HMR_PORT__;
478
503
  const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
479
504
  const directSocketHost = __HMR_DIRECT_TARGET__;
480
- const base = __BASE__ || '/';
505
+ const base = __BASE__ || "/";
481
506
  let socket;
482
507
  try {
483
- let fallback;
484
- // only use fallback when port is inferred to prevent confusion
485
- if (!hmrPort) {
486
- fallback = () => {
487
- // fallback to connecting directly to the hmr server
488
- // for servers which does not support proxying websocket
489
- socket = setupWebSocket(socketProtocol, directSocketHost, () => {
490
- const currentScriptHostURL = new URL(import.meta.url);
491
- const currentScriptHost = currentScriptHostURL.host +
492
- currentScriptHostURL.pathname.replace(/@vite\/client$/, '');
493
- console.error('[vite] failed to connect to websocket.\n' +
494
- 'your current setup:\n' +
495
- ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` +
496
- ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` +
497
- 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .');
498
- });
499
- socket.addEventListener('open', () => {
500
- console.info('[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.');
501
- }, { once: true });
502
- };
503
- }
504
- socket = setupWebSocket(socketProtocol, socketHost, fallback);
505
- }
506
- catch (error) {
507
- console.error(`[vite] failed to connect to websocket (${error}). `);
508
+ let fallback;
509
+ if (!hmrPort) {
510
+ fallback = () => {
511
+ socket = setupWebSocket(socketProtocol, directSocketHost, () => {
512
+ const currentScriptHostURL = new URL(import.meta.url);
513
+ const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
514
+ console.error(
515
+ `[vite] failed to connect to websocket.
516
+ your current setup:
517
+ (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)
518
+ (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)
519
+ Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .`
520
+ );
521
+ });
522
+ socket.addEventListener(
523
+ "open",
524
+ () => {
525
+ console.info(
526
+ "[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error."
527
+ );
528
+ },
529
+ { once: true }
530
+ );
531
+ };
532
+ }
533
+ socket = setupWebSocket(socketProtocol, socketHost, fallback);
534
+ } catch (error) {
535
+ console.error(`[vite] failed to connect to websocket (${error}). `);
508
536
  }
509
537
  function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) {
510
- const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr');
511
- let isOpened = false;
512
- socket.addEventListener('open', () => {
513
- isOpened = true;
514
- notifyListeners('vite:ws:connect', { webSocket: socket });
515
- }, { once: true });
516
- // Listen for messages
517
- socket.addEventListener('message', async ({ data }) => {
518
- handleMessage(JSON.parse(data));
519
- });
520
- // ping server
521
- socket.addEventListener('close', async ({ wasClean }) => {
522
- if (wasClean)
523
- return;
524
- if (!isOpened && onCloseWithoutOpen) {
525
- onCloseWithoutOpen();
526
- return;
527
- }
528
- notifyListeners('vite:ws:disconnect', { webSocket: socket });
529
- if (hasDocument) {
530
- console.log(`[vite] server connection lost. polling for restart...`);
531
- await waitForSuccessfulPing(protocol, hostAndPath);
532
- location.reload();
533
- }
534
- });
535
- return socket;
538
+ const socket2 = new WebSocket(`${protocol}://${hostAndPath}`, "vite-hmr");
539
+ let isOpened = false;
540
+ socket2.addEventListener(
541
+ "open",
542
+ () => {
543
+ isOpened = true;
544
+ notifyListeners("vite:ws:connect", { webSocket: socket2 });
545
+ },
546
+ { once: true }
547
+ );
548
+ socket2.addEventListener("message", async ({ data }) => {
549
+ handleMessage(JSON.parse(data));
550
+ });
551
+ socket2.addEventListener("close", async ({ wasClean }) => {
552
+ if (wasClean) return;
553
+ if (!isOpened && onCloseWithoutOpen) {
554
+ onCloseWithoutOpen();
555
+ return;
556
+ }
557
+ notifyListeners("vite:ws:disconnect", { webSocket: socket2 });
558
+ if (hasDocument) {
559
+ console.log(`[vite] server connection lost. Polling for restart...`);
560
+ await waitForSuccessfulPing(protocol, hostAndPath);
561
+ location.reload();
562
+ }
563
+ });
564
+ return socket2;
536
565
  }
537
566
  function cleanUrl(pathname) {
538
- const url = new URL(pathname, 'http://vitejs.dev');
539
- url.searchParams.delete('direct');
540
- return url.pathname + url.search;
567
+ const url = new URL(pathname, "http://vitejs.dev");
568
+ url.searchParams.delete("direct");
569
+ return url.pathname + url.search;
541
570
  }
542
571
  let isFirstUpdate = true;
543
- const outdatedLinkTags = new WeakSet();
572
+ const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
544
573
  const debounceReload = (time) => {
545
- let timer;
546
- return () => {
547
- if (timer) {
548
- clearTimeout(timer);
549
- timer = null;
550
- }
551
- timer = setTimeout(() => {
552
- location.reload();
553
- }, time);
554
- };
574
+ let timer;
575
+ return () => {
576
+ if (timer) {
577
+ clearTimeout(timer);
578
+ timer = null;
579
+ }
580
+ timer = setTimeout(() => {
581
+ location.reload();
582
+ }, time);
583
+ };
555
584
  };
556
585
  const pageReload = debounceReload(50);
557
- const hmrClient = new HMRClient({
558
- error: (err) => console.error('[vite]', err),
559
- debug: (...msg) => console.debug('[vite]', ...msg),
560
- }, {
586
+ const hmrClient = new HMRClient(
587
+ {
588
+ error: (err) => console.error("[vite]", err),
589
+ debug: (...msg) => console.debug("[vite]", ...msg)
590
+ },
591
+ {
561
592
  isReady: () => socket && socket.readyState === 1,
562
- send: (message) => socket.send(message),
563
- }, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport, }) {
593
+ send: (message) => socket.send(message)
594
+ },
595
+ async function importUpdatedModule({
596
+ acceptedPath,
597
+ timestamp,
598
+ explicitImportRequired,
599
+ isWithinCircularImport
600
+ }) {
564
601
  const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
565
602
  const importPromise = import(
566
- /* @vite-ignore */
567
- base +
568
- acceptedPathWithoutQuery.slice(1) +
569
- `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`);
603
+ /* @vite-ignore */
604
+ base + acceptedPathWithoutQuery.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
605
+ );
570
606
  if (isWithinCircularImport) {
571
- importPromise.catch(() => {
572
- console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` +
573
- `To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`);
574
- pageReload();
575
- });
607
+ importPromise.catch(() => {
608
+ console.info(
609
+ `[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`
610
+ );
611
+ pageReload();
612
+ });
576
613
  }
577
614
  return await importPromise;
578
- });
615
+ }
616
+ );
579
617
  async function handleMessage(payload) {
580
- switch (payload.type) {
581
- case 'connected':
582
- console.debug(`connected.`);
583
- hmrClient.messenger.flush();
584
- // proxy(nginx, docker) hmr ws maybe caused timeout,
585
- // so send ping package let ws keep alive.
586
- setInterval(() => {
587
- if (socket.readyState === socket.OPEN) {
588
- socket.send('{"type":"ping"}');
589
- }
590
- }, __HMR_TIMEOUT__);
591
- break;
592
- case 'update':
593
- notifyListeners('vite:beforeUpdate', payload);
594
- if (hasDocument) {
595
- // if this is the first update and there's already an error overlay, it
596
- // means the page opened with existing server compile error and the whole
597
- // module script failed to load (since one of the nested imports is 500).
598
- // in this case a normal update won't work and a full reload is needed.
599
- if (isFirstUpdate && hasErrorOverlay()) {
600
- window.location.reload();
601
- return;
602
- }
603
- else {
604
- if (enableOverlay) {
605
- clearErrorOverlay();
606
- }
607
- isFirstUpdate = false;
608
- }
609
- }
610
- await Promise.all(payload.updates.map(async (update) => {
611
- if (update.type === 'js-update') {
612
- return hmrClient.queueUpdate(update);
613
- }
614
- // css-update
615
- // this is only sent when a css file referenced with <link> is updated
616
- const { path, timestamp } = update;
617
- const searchUrl = cleanUrl(path);
618
- // can't use querySelector with `[href*=]` here since the link may be
619
- // using relative paths so we need to use link.href to grab the full
620
- // URL for the include check.
621
- const el = Array.from(document.querySelectorAll('link')).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
622
- if (!el) {
623
- return;
624
- }
625
- const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`;
626
- // rather than swapping the href on the existing tag, we will
627
- // create a new link tag. Once the new stylesheet has loaded we
628
- // will remove the existing link tag. This removes a Flash Of
629
- // Unstyled Content that can occur when swapping out the tag href
630
- // directly, as the new stylesheet has not yet been loaded.
631
- return new Promise((resolve) => {
632
- const newLinkTag = el.cloneNode();
633
- newLinkTag.href = new URL(newPath, el.href).href;
634
- const removeOldEl = () => {
635
- el.remove();
636
- console.debug(`[vite] css hot updated: ${searchUrl}`);
637
- resolve();
638
- };
639
- newLinkTag.addEventListener('load', removeOldEl);
640
- newLinkTag.addEventListener('error', removeOldEl);
641
- outdatedLinkTags.add(el);
642
- el.after(newLinkTag);
643
- });
644
- }));
645
- notifyListeners('vite:afterUpdate', payload);
646
- break;
647
- case 'custom': {
648
- notifyListeners(payload.event, payload.data);
649
- break;
618
+ switch (payload.type) {
619
+ case "connected":
620
+ console.debug(`[vite] connected.`);
621
+ hmrClient.messenger.flush();
622
+ setInterval(() => {
623
+ if (socket.readyState === socket.OPEN) {
624
+ socket.send('{"type":"ping"}');
625
+ }
626
+ }, __HMR_TIMEOUT__);
627
+ break;
628
+ case "update":
629
+ notifyListeners("vite:beforeUpdate", payload);
630
+ if (hasDocument) {
631
+ if (isFirstUpdate && hasErrorOverlay()) {
632
+ location.reload();
633
+ return;
634
+ } else {
635
+ if (enableOverlay) {
636
+ clearErrorOverlay();
637
+ }
638
+ isFirstUpdate = false;
650
639
  }
651
- case 'full-reload':
652
- notifyListeners('vite:beforeFullReload', payload);
653
- if (hasDocument) {
654
- if (payload.path && payload.path.endsWith('.html')) {
655
- // if html file is edited, only reload the page if the browser is
656
- // currently on that page.
657
- const pagePath = decodeURI(location.pathname);
658
- const payloadPath = base + payload.path.slice(1);
659
- if (pagePath === payloadPath ||
660
- payload.path === '/index.html' ||
661
- (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) {
662
- pageReload();
663
- }
664
- return;
665
- }
666
- else {
667
- pageReload();
668
- }
669
- }
670
- break;
671
- case 'prune':
672
- notifyListeners('vite:beforePrune', payload);
673
- await hmrClient.prunePaths(payload.paths);
674
- break;
675
- case 'error': {
676
- notifyListeners('vite:error', payload);
677
- if (hasDocument) {
678
- const err = payload.err;
679
- if (enableOverlay) {
680
- createErrorOverlay(err);
681
- }
682
- else {
683
- console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
684
- }
685
- }
686
- break;
640
+ }
641
+ await Promise.all(
642
+ payload.updates.map(async (update) => {
643
+ if (update.type === "js-update") {
644
+ return hmrClient.queueUpdate(update);
645
+ }
646
+ const { path, timestamp } = update;
647
+ const searchUrl = cleanUrl(path);
648
+ const el = Array.from(
649
+ document.querySelectorAll("link")
650
+ ).find(
651
+ (e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)
652
+ );
653
+ if (!el) {
654
+ return;
655
+ }
656
+ const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
657
+ return new Promise((resolve) => {
658
+ const newLinkTag = el.cloneNode();
659
+ newLinkTag.href = new URL(newPath, el.href).href;
660
+ const removeOldEl = () => {
661
+ el.remove();
662
+ console.debug(`[vite] css hot updated: ${searchUrl}`);
663
+ resolve();
664
+ };
665
+ newLinkTag.addEventListener("load", removeOldEl);
666
+ newLinkTag.addEventListener("error", removeOldEl);
667
+ outdatedLinkTags.add(el);
668
+ el.after(newLinkTag);
669
+ });
670
+ })
671
+ );
672
+ notifyListeners("vite:afterUpdate", payload);
673
+ break;
674
+ case "custom": {
675
+ notifyListeners(payload.event, payload.data);
676
+ break;
677
+ }
678
+ case "full-reload":
679
+ notifyListeners("vite:beforeFullReload", payload);
680
+ if (hasDocument) {
681
+ if (payload.path && payload.path.endsWith(".html")) {
682
+ const pagePath = decodeURI(location.pathname);
683
+ const payloadPath = base + payload.path.slice(1);
684
+ if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) {
685
+ pageReload();
686
+ }
687
+ return;
688
+ } else {
689
+ pageReload();
687
690
  }
688
- default: {
689
- const check = payload;
690
- return check;
691
+ }
692
+ break;
693
+ case "prune":
694
+ notifyListeners("vite:beforePrune", payload);
695
+ await hmrClient.prunePaths(payload.paths);
696
+ break;
697
+ case "error": {
698
+ notifyListeners("vite:error", payload);
699
+ if (hasDocument) {
700
+ const err = payload.err;
701
+ if (enableOverlay) {
702
+ createErrorOverlay(err);
703
+ } else {
704
+ console.error(
705
+ `[vite] Internal Server Error
706
+ ${err.message}
707
+ ${err.stack}`
708
+ );
691
709
  }
710
+ }
711
+ break;
712
+ }
713
+ default: {
714
+ const check = payload;
715
+ return check;
692
716
  }
717
+ }
693
718
  }
694
719
  function notifyListeners(event, data) {
695
- hmrClient.notifyListeners(event, data);
720
+ hmrClient.notifyListeners(event, data);
696
721
  }
697
722
  const enableOverlay = __HMR_ENABLE_OVERLAY__;
698
- const hasDocument = 'document' in globalThis;
723
+ const hasDocument = "document" in globalThis;
699
724
  function createErrorOverlay(err) {
700
- clearErrorOverlay();
701
- document.body.appendChild(new ErrorOverlay(err));
725
+ clearErrorOverlay();
726
+ document.body.appendChild(new ErrorOverlay(err));
702
727
  }
703
728
  function clearErrorOverlay() {
704
- document.querySelectorAll(overlayId).forEach((n) => n.close());
729
+ document.querySelectorAll(overlayId).forEach((n) => n.close());
705
730
  }
706
731
  function hasErrorOverlay() {
707
- return document.querySelectorAll(overlayId).length;
708
- }
709
- async function waitForSuccessfulPing(socketProtocol, hostAndPath, ms = 1000) {
710
- const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http';
711
- const ping = async () => {
712
- // A fetch on a websocket URL will return a successful promise with status 400,
713
- // but will reject a networking error.
714
- // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
715
- try {
716
- await fetch(`${pingHostProtocol}://${hostAndPath}`, {
717
- mode: 'no-cors',
718
- headers: {
719
- // Custom headers won't be included in a request with no-cors so (ab)use one of the
720
- // safelisted headers to identify the ping request
721
- Accept: 'text/x-vite-ping',
722
- },
723
- });
724
- return true;
725
- }
726
- catch { }
727
- return false;
728
- };
729
- if (await ping()) {
730
- return;
731
- }
732
- await wait(ms);
733
- // eslint-disable-next-line no-constant-condition
734
- while (true) {
735
- if (document.visibilityState === 'visible') {
736
- if (await ping()) {
737
- break;
738
- }
739
- await wait(ms);
740
- }
741
- else {
742
- await waitForWindowShow();
732
+ return document.querySelectorAll(overlayId).length;
733
+ }
734
+ async function waitForSuccessfulPing(socketProtocol2, hostAndPath, ms = 1e3) {
735
+ const pingHostProtocol = socketProtocol2 === "wss" ? "https" : "http";
736
+ const ping = async () => {
737
+ try {
738
+ await fetch(`${pingHostProtocol}://${hostAndPath}`, {
739
+ mode: "no-cors",
740
+ headers: {
741
+ // Custom headers won't be included in a request with no-cors so (ab)use one of the
742
+ // safelisted headers to identify the ping request
743
+ Accept: "text/x-vite-ping"
743
744
  }
744
- }
745
+ });
746
+ return true;
747
+ } catch {
748
+ }
749
+ return false;
750
+ };
751
+ if (await ping()) {
752
+ return;
753
+ }
754
+ await wait(ms);
755
+ while (true) {
756
+ if (document.visibilityState === "visible") {
757
+ if (await ping()) {
758
+ break;
759
+ }
760
+ await wait(ms);
761
+ } else {
762
+ await waitForWindowShow();
763
+ }
764
+ }
745
765
  }
746
766
  function wait(ms) {
747
- return new Promise((resolve) => setTimeout(resolve, ms));
767
+ return new Promise((resolve) => setTimeout(resolve, ms));
748
768
  }
749
769
  function waitForWindowShow() {
750
- return new Promise((resolve) => {
751
- const onChange = async () => {
752
- if (document.visibilityState === 'visible') {
753
- resolve();
754
- document.removeEventListener('visibilitychange', onChange);
755
- }
756
- };
757
- document.addEventListener('visibilitychange', onChange);
758
- });
770
+ return new Promise((resolve) => {
771
+ const onChange = async () => {
772
+ if (document.visibilityState === "visible") {
773
+ resolve();
774
+ document.removeEventListener("visibilitychange", onChange);
775
+ }
776
+ };
777
+ document.addEventListener("visibilitychange", onChange);
778
+ });
759
779
  }
760
- const sheetsMap = new Map();
761
- // collect existing style elements that may have been inserted during SSR
762
- // to avoid FOUC or duplicate styles
763
- if ('document' in globalThis) {
764
- document
765
- .querySelectorAll('style[data-vite-dev-id]')
766
- .forEach((el) => {
767
- sheetsMap.set(el.getAttribute('data-vite-dev-id'), el);
768
- });
780
+ const sheetsMap = /* @__PURE__ */ new Map();
781
+ if ("document" in globalThis) {
782
+ document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
783
+ sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
784
+ });
769
785
  }
770
- const cspNonce = 'document' in globalThis
771
- ? (_a = document.querySelector('meta[property=csp-nonce]')) === null || _a === void 0 ? void 0 : _a.nonce
772
- : undefined;
773
- // all css imports should be inserted at the same position
774
- // because after build it will be a single css file
786
+ const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
775
787
  let lastInsertedStyle;
776
788
  function updateStyle(id, content) {
777
- let style = sheetsMap.get(id);
778
- if (!style) {
779
- style = document.createElement('style');
780
- style.setAttribute('type', 'text/css');
781
- style.setAttribute('data-vite-dev-id', id);
782
- style.textContent = content;
783
- if (cspNonce) {
784
- style.setAttribute('nonce', cspNonce);
785
- }
786
- if (!lastInsertedStyle) {
787
- document.head.appendChild(style);
788
- // reset lastInsertedStyle after async
789
- // because dynamically imported css will be splitted into a different file
790
- setTimeout(() => {
791
- lastInsertedStyle = undefined;
792
- }, 0);
793
- }
794
- else {
795
- lastInsertedStyle.insertAdjacentElement('afterend', style);
796
- }
797
- lastInsertedStyle = style;
798
- }
799
- else {
800
- style.textContent = content;
801
- }
802
- sheetsMap.set(id, style);
789
+ let style = sheetsMap.get(id);
790
+ if (!style) {
791
+ style = document.createElement("style");
792
+ style.setAttribute("type", "text/css");
793
+ style.setAttribute("data-vite-dev-id", id);
794
+ style.textContent = content;
795
+ if (cspNonce) {
796
+ style.setAttribute("nonce", cspNonce);
797
+ }
798
+ if (!lastInsertedStyle) {
799
+ document.head.appendChild(style);
800
+ setTimeout(() => {
801
+ lastInsertedStyle = void 0;
802
+ }, 0);
803
+ } else {
804
+ lastInsertedStyle.insertAdjacentElement("afterend", style);
805
+ }
806
+ lastInsertedStyle = style;
807
+ } else {
808
+ style.textContent = content;
809
+ }
810
+ sheetsMap.set(id, style);
803
811
  }
804
812
  function removeStyle(id) {
805
- const style = sheetsMap.get(id);
806
- if (style) {
807
- document.head.removeChild(style);
808
- sheetsMap.delete(id);
809
- }
813
+ const style = sheetsMap.get(id);
814
+ if (style) {
815
+ document.head.removeChild(style);
816
+ sheetsMap.delete(id);
817
+ }
810
818
  }
811
819
  function createHotContext(ownerPath) {
812
- return new HMRContext(hmrClient, ownerPath);
820
+ return new HMRContext(hmrClient, ownerPath);
813
821
  }
814
- /**
815
- * urls here are dynamic import() urls that couldn't be statically analyzed
816
- */
817
822
  function injectQuery(url, queryToInject) {
818
- // skip urls that won't be handled by vite
819
- if (url[0] !== '.' && url[0] !== '/') {
820
- return url;
821
- }
822
- // can't use pathname from URL since it may be relative like ../
823
- const pathname = url.replace(/[?#].*$/, '');
824
- const { search, hash } = new URL(url, 'http://vitejs.dev');
825
- return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
823
+ if (url[0] !== "." && url[0] !== "/") {
824
+ return url;
825
+ }
826
+ const pathname = url.replace(/[?#].*$/, "");
827
+ const { search, hash } = new URL(url, "http://vitejs.dev");
828
+ return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
826
829
  }
827
830
 
828
831
  export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };
829
- //# sourceMappingURL=client.mjs.map