-
-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathindex.js
More file actions
577 lines (516 loc) · 17.2 KB
/
Copy pathindex.js
File metadata and controls
577 lines (516 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
/* global __resourceQuery, __webpack_public_path__ */
import * as indicator from "./indicator.js";
import configureOverlay from "./overlay.js";
import applyUpdate from "./process-update.js";
import { log, setLogLevel } from "./utils/log.js";
import stripAnsi from "./utils/strip-ansi.js";
/** @typedef {import("./utils/log.js").LogLevel} LogLevel */
/**
* Superset of webpack-dev-server's `client.overlay` object; `styles`,
* `ansiColors`, `openEditorEndpoint` and `paginate` are webpack-dev-middleware
* extensions.
* @typedef {object} OverlayOptions
* @property {(boolean | ((error: string) => boolean))=} errors show build errors in the overlay
* @property {(boolean | ((warning: string) => boolean))=} warnings show build warnings in the overlay
* @property {(boolean | ((error: Error) => boolean))=} runtimeErrors show uncaught runtime errors and unhandled rejections in the overlay
* @property {string=} trustedTypesPolicyName Trusted Types policy name used for the overlay's HTML
* @property {Record<string, string | number>=} styles overrides for the overlay card CSS
* @property {Record<string, string | string[]>=} ansiColors overrides for ANSI → HTML color mapping
* @property {string=} openEditorEndpoint endpoint the overlay calls (GET `?fileName=file:line:column`) when a file reference is clicked; empty disables it
* @property {boolean=} paginate show one problem at a time with prev/next navigation
*/
/**
* @typedef {object} ClientOptions
* @property {string} path SSE endpoint path
* @property {number} timeout reconnection timeout in milliseconds
* @property {boolean | OverlayOptions} overlay enable the in-page error overlay (same value shape as webpack-dev-server's `client.overlay`)
* @property {boolean} reload reload the page when HMR cannot apply the update
* @property {LogLevel} logging logger level
* @property {string} name limit updates to this compilation name
* @property {boolean} autoConnect connect immediately when the entry runs
* @property {boolean} progress show a small badge while a rebuild is in progress
*/
/** @type {ClientOptions} */
const options = {
path: "/__webpack_hmr",
timeout: 20 * 1000,
overlay: true,
reload: true,
logging: "info",
name: "",
autoConnect: true,
progress: true,
};
/**
* Turn the string values that `errors`/`warnings`/`runtimeErrors` may carry
* in the resource query into filter functions (same behavior as
* webpack-dev-server).
* @param {boolean | OverlayOptions} overlayOptions overlay options
*/
function decodeOverlayOptions(overlayOptions) {
if (typeof overlayOptions === "object") {
for (const property of ["errors", "warnings", "runtimeErrors"]) {
const value =
overlayOptions[/** @type {keyof OverlayOptions} */ (property)];
if (typeof value === "string") {
const filterFunctionString = decodeURIComponent(value);
/** @type {EXPECTED_ANY} */ (overlayOptions)[property] =
// eslint-disable-next-line no-new-func
new Function(
"message",
`var callback = ${filterFunctionString}
return callback(message)`,
);
}
}
}
}
setLogLevel(options.logging);
/**
* @param {Record<string, string>} overrides parsed query-string overrides
*/
function setOverrides(overrides) {
if (overrides.autoConnect) {
options.autoConnect = overrides.autoConnect === "true";
}
if (overrides.path) options.path = overrides.path;
if (overrides.timeout) options.timeout = Number(overrides.timeout);
if (overrides.overlay) {
// Same value shape as webpack-dev-server's `client.overlay`: a boolean or
// a JSON object with `errors`, `warnings`, `runtimeErrors` (booleans or
// encoded filter functions) and `trustedTypesPolicyName`.
try {
options.overlay = JSON.parse(overrides.overlay);
} catch {
options.overlay = overrides.overlay !== "false";
}
// Fill in default "true" params for partially-specified objects.
if (typeof options.overlay === "object") {
options.overlay = {
errors: true,
warnings: true,
runtimeErrors: true,
...options.overlay,
};
decodeOverlayOptions(options.overlay);
}
}
if (overrides.reload) options.reload = overrides.reload !== "false";
if (overrides.logging) {
options.logging = /** @type {LogLevel} */ (overrides.logging);
}
if (overrides.name) {
options.name = overrides.name;
}
if (overrides.progress) {
options.progress = overrides.progress !== "false";
}
if (overrides.dynamicPublicPath) {
// `path` is appended like a filename (no leading slash); the public path
// itself is not normalized.
options.path = __webpack_public_path__ + options.path.replace(/^\//, "");
}
setLogLevel(options.logging);
}
/**
* @typedef {(event: { data: string }) => void} MessageListener
*/
/**
* @returns {{ addMessageListener: (fn: MessageListener) => void, close: () => void }} event source wrapper
*/
function createEventSourceWrapper() {
/** @type {EventSource} */
let source;
let lastActivity = Date.now();
/** @type {MessageListener[]} */
const listeners = [];
/** @type {ReturnType<typeof setInterval>} */
let timer;
/** @type {ReturnType<typeof setTimeout>} */
let reconnectTimer;
let closed = false;
const handleOnline = () => {
log.info("connected");
lastActivity = Date.now();
};
/**
* @param {{ data: string }} event event
*/
const handleMessage = (event) => {
lastActivity = Date.now();
for (const listener of listeners) {
listener(event);
}
};
/**
* Tear the current connection down without deciding whether it is final.
*/
const stop = () => {
clearInterval(timer);
clearTimeout(reconnectTimer);
source.close();
};
/**
* Close for good: no reconnection is scheduled, a pending one is cancelled,
* and error events already queued behind the close (the EventSource fires
* one when its connection dies) can no longer resurrect the wrapper.
*/
const close = () => {
closed = true;
stop();
};
const handleDisconnect = () => {
if (closed) {
return;
}
stop();
reconnectTimer = setTimeout(init, /** @type {number} */ (options.timeout));
};
/**
* Open the EventSource connection and (re)start the inactivity watchdog —
* `handleDisconnect` stops the watchdog, so a reconnected source has to
* bring its own.
*/
function init() {
source = new window.EventSource(/** @type {string} */ (options.path));
source.addEventListener("open", handleOnline);
source.addEventListener("error", handleDisconnect);
source.addEventListener("message", handleMessage);
lastActivity = Date.now();
clearInterval(timer);
timer = setInterval(
() => {
if (
Date.now() - lastActivity >
/** @type {number} */ (options.timeout)
) {
handleDisconnect();
}
},
/** @type {number} */ (options.timeout) / 2,
);
}
init();
return {
addMessageListener(fn) {
listeners.push(fn);
},
close,
};
}
const WRAPPER_KEY = "__wdmEventSourceWrapper";
/**
* @returns {ReturnType<typeof createEventSourceWrapper>} cached event source wrapper for this path
*/
function getEventSourceWrapper() {
const path = /** @type {string} */ (options.path);
if (!window[WRAPPER_KEY]) {
window[WRAPPER_KEY] = {};
}
if (!window[WRAPPER_KEY][path]) {
// Cache the wrapper so multiple entries on the same page sharing the same
// `options.path` reuse a single SSE connection.
window[WRAPPER_KEY][path] = createEventSourceWrapper();
}
return window[WRAPPER_KEY][path];
}
/**
* Subscribe the message handler to the shared event source wrapper.
*/
function connect() {
getEventSourceWrapper().addMessageListener((event) => {
if (event.data === "💓") {
return;
}
try {
processMessage(JSON.parse(event.data));
} catch (err) {
log.warn(`Invalid HMR message: ${event.data}\n${err}`);
}
});
}
/**
* @param {Record<string, string>} overrides overrides
*/
export function setOptionsAndConnect(overrides) {
setOverrides(overrides);
connect();
}
/**
* Close the SSE connection for the current path and stop reconnecting. A
* later `setOptionsAndConnect` call opens a fresh connection.
*/
export function disconnect() {
const path = /** @type {string} */ (options.path);
const wrappers = window[WRAPPER_KEY];
if (wrappers && wrappers[path]) {
wrappers[path].close();
delete wrappers[path];
}
}
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
/** @typedef {{ name?: string, errors: string[], warnings: string[], hash: string, time?: number, action?: string, file?: string, percent?: number, message?: string }} HMRPayload */
/**
* @returns {{
* cleanProblemsCache: (name: string) => void,
* problems: (type: "errors" | "warnings", obj: HMRPayload) => boolean,
* success: (obj?: HMRPayload) => void,
* useCustomOverlay: (customOverlay: EXPECTED_ANY) => void,
* }} reporter
*/
function createReporter() {
/** @type {EXPECTED_ANY} */
let overlay;
if (typeof document !== "undefined" && options.overlay) {
// Same mapping as webpack-dev-server's createOverlay call, extended with
// the webpack-dev-middleware-specific keys.
overlay = configureOverlay(
typeof options.overlay === "object"
? {
catchRuntimeError: options.overlay.runtimeErrors,
trustedTypesPolicyName: options.overlay.trustedTypesPolicyName,
ansiColors: options.overlay.ansiColors,
overlayStyles: options.overlay.styles,
openEditorEndpoint: options.overlay.openEditorEndpoint,
paginate: options.overlay.paginate,
}
: {
catchRuntimeError: options.overlay,
},
);
}
// Console de-duplication cache, keyed per bundle name and type so interleaved
// multi-compiler payloads do not defeat it.
/** @type {Map<string, string>} */
const previousProblems = new Map();
// Live problems per compilation name. A multi-compiler publishes one event
// per bundle; a success from one bundle must not wipe another bundle's
// still-valid errors from the overlay.
/** @type {Map<string, { errors: string[], warnings: string[] }>} */
const problemsByName = new Map();
/**
* Resolve the show/hide/filter setting for a problem type. Same resolution
* as webpack-dev-server: a boolean overlay applies to both types; an object
* carries a boolean or a filter function per type.
* @param {"errors" | "warnings"} type problem type
* @param {string[]} problems problems of one bundle
* @returns {string[]} the problems the overlay should show
*/
const filterForOverlay = (type, problems) => {
const setting =
typeof options.overlay === "boolean"
? options.overlay
: options.overlay && options.overlay[type];
if (!setting) {
return [];
}
return typeof setting === "function"
? problems.filter((message) => setting(message))
: problems;
};
/**
* Render the union of every bundle's live problems, or clear the overlay
* when nothing is left.
* @returns {boolean} true when nothing is shown
*/
const renderOverlay = () => {
if (!overlay) {
return true;
}
/** @type {string[]} */
const errors = [];
/** @type {string[]} */
const warnings = [];
for (const entry of problemsByName.values()) {
errors.push(...filterForOverlay("errors", entry.errors));
warnings.push(...filterForOverlay("warnings", entry.warnings));
}
if (errors.length > 0) {
overlay.showProblems("errors", errors);
return false;
}
if (warnings.length > 0) {
overlay.showProblems("warnings", warnings);
return false;
}
// Clear only this client's problems and the runtime errors — other
// clients sharing the overlay keep theirs.
overlay.clear("");
overlay.clear("runtime");
return true;
};
/**
* @param {"errors" | "warnings"} type problem type
* @param {HMRPayload} obj payload
*/
const logProblems = (type, obj) => {
const cacheKey = `${obj.name || ""}|${type}`;
const newProblems = obj[type].map(stripAnsi).join("\n");
if (previousProblems.get(cacheKey) === newProblems) {
return;
}
previousProblems.set(cacheKey, newProblems);
const name = obj.name ? `'${obj.name}' ` : "";
const title = `bundle ${name}has ${obj[type].length} ${type}`;
if (type === "errors") {
log.error(title);
log.error(newProblems);
} else {
log.warn(title);
log.warn(newProblems);
}
};
return {
cleanProblemsCache(name) {
// Scoped to one bundle so a sibling's unchanged problems do not re-log.
previousProblems.delete(`${name}|errors`);
previousProblems.delete(`${name}|warnings`);
},
problems(type, obj) {
logProblems(type, obj);
problemsByName.set(obj.name || "", {
errors: obj.errors || [],
warnings: obj.warnings || [],
});
return renderOverlay();
},
success(obj) {
problemsByName.delete((obj && obj.name) || "");
renderOverlay();
},
useCustomOverlay(customOverlay) {
overlay = customOverlay;
},
};
}
// The reporter is a singleton on the page so that, when multiple bundles
// include the client, errors are reported once but all clients receive them.
const REPORTER_KEY = "__webpack_dev_middleware_hot_reporter__";
/** @type {ReturnType<typeof createReporter> | undefined} */
let reporter;
/** @type {((obj: HMRPayload) => void) | undefined} */
let customHandler;
/** @type {((obj: HMRPayload) => void) | undefined} */
let subscribeAllHandler;
// Name of the build that most recently reported `building` — progress
// payloads carry no name, so they are attributed to it.
let lastBuildingName = "";
/**
* @param {HMRPayload} obj payload
*/
function processMessage(obj) {
switch (obj.action) {
case "building": {
log.info(
`bundle ${obj.name ? `'${obj.name}' ` : ""}rebuilding${
obj.file ? ` (${obj.file} changed)` : ""
}`,
);
if (options.progress && typeof document !== "undefined") {
lastBuildingName = obj.name || "";
indicator.show(
obj.file ? `Rebuilding… (${obj.file})` : undefined,
undefined,
lastBuildingName,
);
}
break;
}
case "progress": {
// Progress payloads carry no name — attribute them to the build that
// most recently reported `building`.
if (options.progress && typeof document !== "undefined") {
indicator.show(
`Rebuilding… ${obj.percent}%${obj.message ? ` (${obj.message})` : ""}`,
obj.percent,
lastBuildingName,
);
}
break;
}
case "built":
case "sync": {
if (options.progress && typeof document !== "undefined") {
indicator.hide(obj.name || "");
}
if (obj.action === "built") {
log.info(
`bundle ${obj.name ? `'${obj.name}' ` : ""}rebuilt in ${obj.time}ms`,
);
}
if (obj.name && options.name && obj.name !== options.name) {
return;
}
let shouldApply = true;
if (obj.errors.length > 0) {
if (reporter) reporter.problems("errors", obj);
shouldApply = false;
} else if (obj.warnings.length > 0) {
// Warnings are reported (and possibly shown in the overlay) but do
// not block the update, matching webpack-dev-server.
if (reporter) {
reporter.problems("warnings", obj);
}
} else if (reporter) {
reporter.cleanProblemsCache(obj.name || "");
reporter.success(obj);
}
if (shouldApply) {
applyUpdate(obj.hash, options, obj.name);
}
break;
}
default: {
if (customHandler) {
customHandler(obj);
}
}
}
if (subscribeAllHandler) {
subscribeAllHandler(obj);
}
}
// Bootstrap: parse query string overrides, then connect (if enabled).
if (typeof __resourceQuery === "string" && __resourceQuery.length > 0) {
const params = [...new URLSearchParams(__resourceQuery.slice(1))];
/** @type {Record<string, string>} */
const overrides = {};
for (const [key, value] of params) {
overrides[key] = value;
}
setOverrides(overrides);
}
if (typeof window !== "undefined") {
if (!window[REPORTER_KEY]) {
window[REPORTER_KEY] = createReporter();
}
reporter = window[REPORTER_KEY];
if (typeof window.EventSource === "undefined") {
log.warn(
"webpack-dev-middleware's hot client requires EventSource to work. " +
"Include a polyfill if you want to support this browser: " +
"https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events#Tools",
);
} else if (options.autoConnect) {
connect();
}
}
/**
* @param {(obj: HMRPayload) => void} handler called for every incoming HMR message
*/
export function subscribeAll(handler) {
subscribeAllHandler = handler;
}
/**
* @param {(obj: HMRPayload) => void} handler called for messages whose `action` is not recognized
*/
export function subscribe(handler) {
customHandler = handler;
}
/**
* @param {EXPECTED_ANY} customOverlay replacement for the default error overlay
*/
export function useCustomOverlay(customOverlay) {
if (reporter) reporter.useCustomOverlay(customOverlay);
}