@atlaspack/runtime-browser-hmr 2.12.1-canary.3354

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.
@@ -0,0 +1,636 @@
1
+ // @flow
2
+ /* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, HMR_USE_SSE, chrome, browser, __atlaspack__import__, __atlaspack__importScripts__, ServiceWorkerGlobalScope */
3
+
4
+ /*::
5
+ import type {
6
+ HMRAsset,
7
+ HMRMessage,
8
+ } from '@atlaspack/reporter-dev-server/src/HMRServer.js';
9
+ interface AtlaspackRequire {
10
+ (string): mixed;
11
+ cache: {|[string]: AtlaspackModule|};
12
+ hotData: {|[string]: mixed|};
13
+ Module: any;
14
+ parent: ?AtlaspackRequire;
15
+ isAtlaspackRequire: true;
16
+ modules: {|[string]: [Function, {|[string]: string|}]|};
17
+ HMR_BUNDLE_ID: string;
18
+ root: AtlaspackRequire;
19
+ }
20
+ interface AtlaspackModule {
21
+ hot: {|
22
+ data: mixed,
23
+ accept(cb: (Function) => void): void,
24
+ dispose(cb: (mixed) => void): void,
25
+ // accept(deps: Array<string> | string, cb: (Function) => void): void,
26
+ // decline(): void,
27
+ _acceptCallbacks: Array<(Function) => void>,
28
+ _disposeCallbacks: Array<(mixed) => void>,
29
+ |};
30
+ }
31
+ interface ExtensionContext {
32
+ runtime: {|
33
+ reload(): void,
34
+ getURL(url: string): string;
35
+ getManifest(): {manifest_version: number, ...};
36
+ |};
37
+ }
38
+ declare var module: {bundle: AtlaspackRequire, ...};
39
+ declare var HMR_HOST: string;
40
+ declare var HMR_PORT: string;
41
+ declare var HMR_ENV_HASH: string;
42
+ declare var HMR_SECURE: boolean;
43
+ declare var HMR_USE_SSE: boolean;
44
+ declare var chrome: ExtensionContext;
45
+ declare var browser: ExtensionContext;
46
+ declare var __atlaspack__import__: (string) => Promise<void>;
47
+ declare var __atlaspack__importScripts__: (string) => Promise<void>;
48
+ declare var globalThis: typeof self;
49
+ declare var ServiceWorkerGlobalScope: Object;
50
+ */
51
+
52
+ var OVERLAY_ID = '__atlaspack__error__overlay__';
53
+
54
+ var OldModule = module.bundle.Module;
55
+
56
+ function Module(moduleName) {
57
+ OldModule.call(this, moduleName);
58
+ this.hot = {
59
+ data: module.bundle.hotData[moduleName],
60
+ _acceptCallbacks: [],
61
+ _disposeCallbacks: [],
62
+ accept: function (fn) {
63
+ this._acceptCallbacks.push(fn || function () {});
64
+ },
65
+ dispose: function (fn) {
66
+ this._disposeCallbacks.push(fn);
67
+ },
68
+ };
69
+ module.bundle.hotData[moduleName] = undefined;
70
+ }
71
+ module.bundle.Module = Module;
72
+ module.bundle.hotData = {};
73
+
74
+ var checkedAssets /*: {|[string]: boolean|} */,
75
+ assetsToDispose /*: Array<[AtlaspackRequire, string]> */,
76
+ assetsToAccept /*: Array<[AtlaspackRequire, string]> */;
77
+
78
+ function getHostname() {
79
+ return (
80
+ HMR_HOST ||
81
+ (location.protocol.indexOf('http') === 0 ? location.hostname : 'localhost')
82
+ );
83
+ }
84
+
85
+ function getPort() {
86
+ return HMR_PORT || location.port;
87
+ }
88
+
89
+ // eslint-disable-next-line no-redeclare
90
+ var parent = module.bundle.parent;
91
+ if (
92
+ (!parent || !parent.isAtlaspackRequire) &&
93
+ typeof WebSocket !== 'undefined'
94
+ ) {
95
+ var hostname = getHostname();
96
+ var port = getPort();
97
+ var protocol =
98
+ HMR_SECURE ||
99
+ (location.protocol == 'https:' &&
100
+ !['localhost', '127.0.0.1', '0.0.0.0'].includes(hostname))
101
+ ? 'wss'
102
+ : 'ws';
103
+
104
+ var ws;
105
+ if (HMR_USE_SSE) {
106
+ ws = new EventSource('/__atlaspack_hmr');
107
+ } else {
108
+ try {
109
+ ws = new WebSocket(
110
+ protocol + '://' + hostname + (port ? ':' + port : '') + '/',
111
+ );
112
+ } catch (err) {
113
+ if (err.message) {
114
+ console.error(err.message);
115
+ }
116
+ ws = {};
117
+ }
118
+ }
119
+
120
+ // Web extension context
121
+ var extCtx =
122
+ typeof browser === 'undefined'
123
+ ? typeof chrome === 'undefined'
124
+ ? null
125
+ : chrome
126
+ : browser;
127
+
128
+ // Safari doesn't support sourceURL in error stacks.
129
+ // eval may also be disabled via CSP, so do a quick check.
130
+ var supportsSourceURL = false;
131
+ try {
132
+ (0, eval)('throw new Error("test"); //# sourceURL=test.js');
133
+ } catch (err) {
134
+ supportsSourceURL = err.stack.includes('test.js');
135
+ }
136
+
137
+ // $FlowFixMe
138
+ ws.onmessage = async function (event /*: {data: string, ...} */) {
139
+ checkedAssets = ({} /*: {|[string]: boolean|} */);
140
+ assetsToAccept = [];
141
+ assetsToDispose = [];
142
+
143
+ var data /*: HMRMessage */ = JSON.parse(event.data);
144
+
145
+ if (data.type === 'reload') {
146
+ fullReload();
147
+ } else if (data.type === 'update') {
148
+ // Remove error overlay if there is one
149
+ if (typeof document !== 'undefined') {
150
+ removeErrorOverlay();
151
+ }
152
+
153
+ let assets = data.assets.filter(asset => asset.envHash === HMR_ENV_HASH);
154
+
155
+ // Handle HMR Update
156
+ let handled = assets.every(asset => {
157
+ return (
158
+ asset.type === 'css' ||
159
+ (asset.type === 'js' &&
160
+ hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle))
161
+ );
162
+ });
163
+
164
+ if (handled) {
165
+ console.clear();
166
+
167
+ // Dispatch custom event so other runtimes (e.g React Refresh) are aware.
168
+ if (
169
+ typeof window !== 'undefined' &&
170
+ typeof CustomEvent !== 'undefined'
171
+ ) {
172
+ window.dispatchEvent(new CustomEvent('atlaspackhmraccept'));
173
+ }
174
+
175
+ await hmrApplyUpdates(assets);
176
+
177
+ // Dispose all old assets.
178
+ let processedAssets = ({} /*: {|[string]: boolean|} */);
179
+ for (let i = 0; i < assetsToDispose.length; i++) {
180
+ let id = assetsToDispose[i][1];
181
+
182
+ if (!processedAssets[id]) {
183
+ hmrDispose(assetsToDispose[i][0], id);
184
+ processedAssets[id] = true;
185
+ }
186
+ }
187
+
188
+ // Run accept callbacks. This will also re-execute other disposed assets in topological order.
189
+ processedAssets = {};
190
+ for (let i = 0; i < assetsToAccept.length; i++) {
191
+ let id = assetsToAccept[i][1];
192
+
193
+ if (!processedAssets[id]) {
194
+ hmrAccept(assetsToAccept[i][0], id);
195
+ processedAssets[id] = true;
196
+ }
197
+ }
198
+ } else fullReload();
199
+ }
200
+
201
+ if (data.type === 'error') {
202
+ // Log atlaspack errors to console
203
+ for (let ansiDiagnostic of data.diagnostics.ansi) {
204
+ let stack = ansiDiagnostic.codeframe
205
+ ? ansiDiagnostic.codeframe
206
+ : ansiDiagnostic.stack;
207
+
208
+ console.error(
209
+ '🚨 [atlaspack]: ' +
210
+ ansiDiagnostic.message +
211
+ '\n' +
212
+ stack +
213
+ '\n\n' +
214
+ ansiDiagnostic.hints.join('\n'),
215
+ );
216
+ }
217
+
218
+ if (typeof document !== 'undefined') {
219
+ // Render the fancy html overlay
220
+ removeErrorOverlay();
221
+ var overlay = createErrorOverlay(data.diagnostics.html);
222
+ // $FlowFixMe
223
+ document.body.appendChild(overlay);
224
+ }
225
+ }
226
+ };
227
+ if (ws instanceof WebSocket) {
228
+ ws.onerror = function (e) {
229
+ if (e.message) {
230
+ console.error(e.message);
231
+ }
232
+ };
233
+ ws.onclose = function (e) {
234
+ if (process.env.ATLASPACK_BUILD_ENV !== 'test') {
235
+ console.warn('[atlaspack] 🚨 Connection to the HMR server was lost');
236
+ }
237
+ };
238
+ }
239
+ }
240
+
241
+ function removeErrorOverlay() {
242
+ var overlay = document.getElementById(OVERLAY_ID);
243
+ if (overlay) {
244
+ overlay.remove();
245
+ console.log('[atlaspack] ✨ Error resolved');
246
+ }
247
+ }
248
+
249
+ function createErrorOverlay(diagnostics) {
250
+ var overlay = document.createElement('div');
251
+ overlay.id = OVERLAY_ID;
252
+
253
+ let errorHTML =
254
+ '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
255
+
256
+ for (let diagnostic of diagnostics) {
257
+ let stack = diagnostic.frames.length
258
+ ? diagnostic.frames.reduce((p, frame) => {
259
+ return `${p}
260
+ <a href="/__atlaspack_launch_editor?file=${encodeURIComponent(
261
+ frame.location,
262
+ )}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${
263
+ frame.location
264
+ }</a>
265
+ ${frame.code}`;
266
+ }, '')
267
+ : diagnostic.stack;
268
+
269
+ errorHTML += `
270
+ <div>
271
+ <div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
272
+ 🚨 ${diagnostic.message}
273
+ </div>
274
+ <pre>${stack}</pre>
275
+ <div>
276
+ ${diagnostic.hints.map(hint => '<div>💡 ' + hint + '</div>').join('')}
277
+ </div>
278
+ ${
279
+ diagnostic.documentation
280
+ ? `<div>📝 <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>`
281
+ : ''
282
+ }
283
+ </div>
284
+ `;
285
+ }
286
+
287
+ errorHTML += '</div>';
288
+
289
+ overlay.innerHTML = errorHTML;
290
+
291
+ return overlay;
292
+ }
293
+
294
+ function fullReload() {
295
+ if ('reload' in location) {
296
+ location.reload();
297
+ } else if (extCtx && extCtx.runtime && extCtx.runtime.reload) {
298
+ extCtx.runtime.reload();
299
+ }
300
+ }
301
+
302
+ function getParents(bundle, id) /*: Array<[AtlaspackRequire, string]> */ {
303
+ var modules = bundle.modules;
304
+ if (!modules) {
305
+ return [];
306
+ }
307
+
308
+ var parents = [];
309
+ var k, d, dep;
310
+
311
+ for (k in modules) {
312
+ for (d in modules[k][1]) {
313
+ dep = modules[k][1][d];
314
+
315
+ if (dep === id || (Array.isArray(dep) && dep[dep.length - 1] === id)) {
316
+ parents.push([bundle, k]);
317
+ }
318
+ }
319
+ }
320
+
321
+ if (bundle.parent) {
322
+ parents = parents.concat(getParents(bundle.parent, id));
323
+ }
324
+
325
+ return parents;
326
+ }
327
+
328
+ function updateLink(link) {
329
+ var href = link.getAttribute('href');
330
+
331
+ if (!href) {
332
+ return;
333
+ }
334
+ var newLink = link.cloneNode();
335
+ newLink.onload = function () {
336
+ if (link.parentNode !== null) {
337
+ // $FlowFixMe
338
+ link.parentNode.removeChild(link);
339
+ }
340
+ };
341
+ newLink.setAttribute(
342
+ 'href',
343
+ // $FlowFixMe
344
+ href.split('?')[0] + '?' + Date.now(),
345
+ );
346
+ // $FlowFixMe
347
+ link.parentNode.insertBefore(newLink, link.nextSibling);
348
+ }
349
+
350
+ var cssTimeout = null;
351
+ function reloadCSS() {
352
+ if (cssTimeout) {
353
+ return;
354
+ }
355
+
356
+ cssTimeout = setTimeout(function () {
357
+ var links = document.querySelectorAll('link[rel="stylesheet"]');
358
+ for (var i = 0; i < links.length; i++) {
359
+ // $FlowFixMe[incompatible-type]
360
+ var href /*: string */ = links[i].getAttribute('href');
361
+ var hostname = getHostname();
362
+ var servedFromHMRServer =
363
+ hostname === 'localhost'
364
+ ? new RegExp(
365
+ '^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):' + getPort(),
366
+ ).test(href)
367
+ : href.indexOf(hostname + ':' + getPort());
368
+ var absolute =
369
+ /^https?:\/\//i.test(href) &&
370
+ href.indexOf(location.origin) !== 0 &&
371
+ !servedFromHMRServer;
372
+ if (!absolute) {
373
+ updateLink(links[i]);
374
+ }
375
+ }
376
+
377
+ cssTimeout = null;
378
+ }, 50);
379
+ }
380
+
381
+ function hmrDownload(asset) {
382
+ if (asset.type === 'js') {
383
+ if (typeof document !== 'undefined') {
384
+ let script = document.createElement('script');
385
+ script.src = asset.url + '?t=' + Date.now();
386
+ if (asset.outputFormat === 'esmodule') {
387
+ script.type = 'module';
388
+ }
389
+ return new Promise((resolve, reject) => {
390
+ script.onload = () => resolve(script);
391
+ script.onerror = reject;
392
+ document.head?.appendChild(script);
393
+ });
394
+ } else if (typeof importScripts === 'function') {
395
+ // Worker scripts
396
+ if (asset.outputFormat === 'esmodule') {
397
+ return __atlaspack__import__(asset.url + '?t=' + Date.now());
398
+ } else {
399
+ return new Promise((resolve, reject) => {
400
+ try {
401
+ __atlaspack__importScripts__(asset.url + '?t=' + Date.now());
402
+ resolve();
403
+ } catch (err) {
404
+ reject(err);
405
+ }
406
+ });
407
+ }
408
+ }
409
+ }
410
+ }
411
+
412
+ async function hmrApplyUpdates(assets) {
413
+ global.atlaspackHotUpdate = Object.create(null);
414
+
415
+ let scriptsToRemove;
416
+ try {
417
+ // If sourceURL comments aren't supported in eval, we need to load
418
+ // the update from the dev server over HTTP so that stack traces
419
+ // are correct in errors/logs. This is much slower than eval, so
420
+ // we only do it if needed (currently just Safari).
421
+ // https://bugs.webkit.org/show_bug.cgi?id=137297
422
+ // This path is also taken if a CSP disallows eval.
423
+ if (!supportsSourceURL) {
424
+ let promises = assets.map(asset =>
425
+ hmrDownload(asset)?.catch(err => {
426
+ // Web extension fix
427
+ if (
428
+ extCtx &&
429
+ extCtx.runtime &&
430
+ extCtx.runtime.getManifest().manifest_version == 3 &&
431
+ typeof ServiceWorkerGlobalScope != 'undefined' &&
432
+ global instanceof ServiceWorkerGlobalScope
433
+ ) {
434
+ extCtx.runtime.reload();
435
+ return;
436
+ }
437
+ throw err;
438
+ }),
439
+ );
440
+
441
+ scriptsToRemove = await Promise.all(promises);
442
+ }
443
+
444
+ assets.forEach(function (asset) {
445
+ hmrApply(module.bundle.root, asset);
446
+ });
447
+ } finally {
448
+ delete global.atlaspackHotUpdate;
449
+
450
+ if (scriptsToRemove) {
451
+ scriptsToRemove.forEach(script => {
452
+ if (script) {
453
+ document.head?.removeChild(script);
454
+ }
455
+ });
456
+ }
457
+ }
458
+ }
459
+
460
+ function hmrApply(bundle /*: AtlaspackRequire */, asset /*: HMRAsset */) {
461
+ var modules = bundle.modules;
462
+ if (!modules) {
463
+ return;
464
+ }
465
+
466
+ if (asset.type === 'css') {
467
+ reloadCSS();
468
+ } else if (asset.type === 'js') {
469
+ let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
470
+ if (deps) {
471
+ if (modules[asset.id]) {
472
+ // Remove dependencies that are removed and will become orphaned.
473
+ // This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
474
+ let oldDeps = modules[asset.id][1];
475
+ for (let dep in oldDeps) {
476
+ if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
477
+ let id = oldDeps[dep];
478
+ let parents = getParents(module.bundle.root, id);
479
+ if (parents.length === 1) {
480
+ hmrDelete(module.bundle.root, id);
481
+ }
482
+ }
483
+ }
484
+ }
485
+
486
+ if (supportsSourceURL) {
487
+ // Global eval. We would use `new Function` here but browser
488
+ // support for source maps is better with eval.
489
+ (0, eval)(asset.output);
490
+ }
491
+
492
+ // $FlowFixMe
493
+ let fn = global.atlaspackHotUpdate[asset.id];
494
+ modules[asset.id] = [fn, deps];
495
+ } else if (bundle.parent) {
496
+ hmrApply(bundle.parent, asset);
497
+ }
498
+ }
499
+ }
500
+
501
+ function hmrDelete(bundle, id) {
502
+ let modules = bundle.modules;
503
+ if (!modules) {
504
+ return;
505
+ }
506
+
507
+ if (modules[id]) {
508
+ // Collect dependencies that will become orphaned when this module is deleted.
509
+ let deps = modules[id][1];
510
+ let orphans = [];
511
+ for (let dep in deps) {
512
+ let parents = getParents(module.bundle.root, deps[dep]);
513
+ if (parents.length === 1) {
514
+ orphans.push(deps[dep]);
515
+ }
516
+ }
517
+
518
+ // Delete the module. This must be done before deleting dependencies in case of circular dependencies.
519
+ delete modules[id];
520
+ delete bundle.cache[id];
521
+
522
+ // Now delete the orphans.
523
+ orphans.forEach(id => {
524
+ hmrDelete(module.bundle.root, id);
525
+ });
526
+ } else if (bundle.parent) {
527
+ hmrDelete(bundle.parent, id);
528
+ }
529
+ }
530
+
531
+ function hmrAcceptCheck(
532
+ bundle /*: AtlaspackRequire */,
533
+ id /*: string */,
534
+ depsByBundle /*: ?{ [string]: { [string]: string } }*/,
535
+ ) {
536
+ if (hmrAcceptCheckOne(bundle, id, depsByBundle)) {
537
+ return true;
538
+ }
539
+
540
+ // Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
541
+ let parents = getParents(module.bundle.root, id);
542
+ let accepted = false;
543
+ while (parents.length > 0) {
544
+ let v = parents.shift();
545
+ let a = hmrAcceptCheckOne(v[0], v[1], null);
546
+ if (a) {
547
+ // If this parent accepts, stop traversing upward, but still consider siblings.
548
+ accepted = true;
549
+ } else {
550
+ // Otherwise, queue the parents in the next level upward.
551
+ let p = getParents(module.bundle.root, v[1]);
552
+ if (p.length === 0) {
553
+ // If there are no parents, then we've reached an entry without accepting. Reload.
554
+ accepted = false;
555
+ break;
556
+ }
557
+ parents.push(...p);
558
+ }
559
+ }
560
+
561
+ return accepted;
562
+ }
563
+
564
+ function hmrAcceptCheckOne(
565
+ bundle /*: AtlaspackRequire */,
566
+ id /*: string */,
567
+ depsByBundle /*: ?{ [string]: { [string]: string } }*/,
568
+ ) {
569
+ var modules = bundle.modules;
570
+ if (!modules) {
571
+ return;
572
+ }
573
+
574
+ if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
575
+ // If we reached the root bundle without finding where the asset should go,
576
+ // there's nothing to do. Mark as "accepted" so we don't reload the page.
577
+ if (!bundle.parent) {
578
+ return true;
579
+ }
580
+
581
+ return hmrAcceptCheck(bundle.parent, id, depsByBundle);
582
+ }
583
+
584
+ if (checkedAssets[id]) {
585
+ return true;
586
+ }
587
+
588
+ checkedAssets[id] = true;
589
+
590
+ var cached = bundle.cache[id];
591
+ assetsToDispose.push([bundle, id]);
592
+
593
+ if (!cached || (cached.hot && cached.hot._acceptCallbacks.length)) {
594
+ assetsToAccept.push([bundle, id]);
595
+ return true;
596
+ }
597
+ }
598
+
599
+ function hmrDispose(bundle /*: AtlaspackRequire */, id /*: string */) {
600
+ var cached = bundle.cache[id];
601
+ bundle.hotData[id] = {};
602
+ if (cached && cached.hot) {
603
+ cached.hot.data = bundle.hotData[id];
604
+ }
605
+
606
+ if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
607
+ cached.hot._disposeCallbacks.forEach(function (cb) {
608
+ cb(bundle.hotData[id]);
609
+ });
610
+ }
611
+
612
+ delete bundle.cache[id];
613
+ }
614
+
615
+ function hmrAccept(bundle /*: AtlaspackRequire */, id /*: string */) {
616
+ // Execute the module.
617
+ bundle(id);
618
+
619
+ // Run the accept callbacks in the new version of the module.
620
+ var cached = bundle.cache[id];
621
+ if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
622
+ cached.hot._acceptCallbacks.forEach(function (cb) {
623
+ var assetsToAlsoAccept = cb(function () {
624
+ return getParents(module.bundle.root, id);
625
+ });
626
+ if (assetsToAlsoAccept && assetsToAccept.length) {
627
+ assetsToAlsoAccept.forEach(function (a) {
628
+ hmrDispose(a[0], a[1]);
629
+ });
630
+
631
+ // $FlowFixMe[method-unbinding]
632
+ assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
633
+ }
634
+ });
635
+ }
636
+ }