es-module-shims 2.4.0 → 2.5.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,477 +1,482 @@
1
- /** ES Module Shims @version 2.4.0 */
1
+ /** ES Module Shims @version 2.5.0 */
2
2
  (function (exports) {
3
3
 
4
- let invalidate;
5
- const hotReload$1 = url => invalidate(new URL(url, baseUrl).href);
6
- const initHotReload = () => {
7
- let _importHook = importHook,
8
- _resolveHook = resolveHook,
9
- _metaHook = metaHook;
4
+ let invalidate;
5
+ const hotReload$1 = url => invalidate(new URL(url, baseUrl).href);
6
+ const initHotReload = () => {
7
+ let _importHook = importHook,
8
+ _resolveHook = resolveHook,
9
+ _metaHook = metaHook;
10
+
11
+ let defaultResolve;
12
+ let hotResolveHook = (id, parent, _defaultResolve) => {
13
+ if (!defaultResolve) defaultResolve = _defaultResolve;
14
+ const originalParent = stripVersion(parent);
15
+ const url = stripVersion(defaultResolve(id, originalParent));
16
+ const hotState = getHotState(url);
17
+ const parents = hotState.p;
18
+ if (!parents.includes(originalParent)) parents.push(originalParent);
19
+ return toVersioned(url, hotState);
20
+ };
21
+ const hotImportHook = (url, _, __, source, sourceType) => {
22
+ const hotState = getHotState(url);
23
+ hotState.e = typeof source === 'string' ? source : true;
24
+ hotState.t = sourceType;
25
+ };
26
+ const hotMetaHook = (metaObj, url) => {
27
+ metaObj.hot = new Hot(url);
28
+ };
29
+
30
+ const Hot = class Hot {
31
+ constructor(url) {
32
+ this.data = getHotState((this.url = stripVersion(url))).d;
33
+ }
34
+ accept(deps, cb) {
35
+ if (typeof deps === 'function') {
36
+ cb = deps;
37
+ deps = null;
38
+ }
39
+ const hotState = getHotState(this.url);
40
+ if (!hotState.A) return;
41
+ (hotState.a = hotState.a || []).push([
42
+ typeof deps === 'string' ? defaultResolve(deps, this.url)
43
+ : deps ? deps.map(d => defaultResolve(d, this.url))
44
+ : null,
45
+ cb
46
+ ]);
47
+ }
48
+ dispose(cb) {
49
+ getHotState(this.url).u = cb;
50
+ }
51
+ invalidate() {
52
+ const hotState = getHotState(this.url);
53
+ hotState.a = null;
54
+ hotState.A = true;
55
+ const seen = [this.url];
56
+ for (const p of hotState.p) invalidate(p, this.url, seen);
57
+ }
58
+ };
59
+
60
+ const versionedRegEx = /\?v=\d+$/;
61
+ const stripVersion = url => {
62
+ const versionMatch = url.match(versionedRegEx);
63
+ return versionMatch ? url.slice(0, -versionMatch[0].length) : url;
64
+ };
65
+
66
+ const toVersioned = (url, hotState) => {
67
+ const { v } = hotState;
68
+ return url + (v ? '?v=' + v : '');
69
+ };
70
+
71
+ let hotRegistry = {},
72
+ curInvalidationRoots = new Set(),
73
+ curInvalidationInterval;
74
+ const getHotState = url =>
75
+ hotRegistry[url] ||
76
+ (hotRegistry[url] = {
77
+ // version
78
+ v: 0,
79
+ // accept list ([deps, cb] pairs)
80
+ a: null,
81
+ // accepting acceptors
82
+ A: true,
83
+ // unload callback
84
+ u: null,
85
+ // entry point or inline script source
86
+ e: false,
87
+ // hot data
88
+ d: {},
89
+ // parents
90
+ p: [],
91
+ // source type
92
+ t: undefined
93
+ });
94
+
95
+ invalidate = (url, fromUrl, seen = []) => {
96
+ if (!seen.includes(url)) {
97
+ seen.push(url);
98
+ console.info(`es-module-shims: hot reload ${url}`);
99
+ const hotState = hotRegistry[url];
100
+ if (hotState) {
101
+ hotState.A = false;
102
+ if (
103
+ fromUrl &&
104
+ hotState.a &&
105
+ hotState.a.some(([d]) => d && (typeof d === 'string' ? d === fromUrl : d.includes(fromUrl)))
106
+ ) {
107
+ curInvalidationRoots.add(fromUrl);
108
+ } else {
109
+ if (hotState.e || hotState.a) curInvalidationRoots.add(url);
110
+ hotState.v++;
111
+ if (!hotState.a) for (const parent of hotState.p) invalidate(parent, url, seen);
112
+ }
113
+ }
114
+ if (!curInvalidationInterval) curInvalidationInterval = setTimeout(handleInvalidations, hotReloadInterval);
115
+ }
116
+ };
117
+
118
+ const handleInvalidations = () => {
119
+ curInvalidationInterval = null;
120
+ const earlyRoots = new Set();
121
+ for (const root of curInvalidationRoots) {
122
+ const hotState = hotRegistry[root];
123
+ topLevelLoad(
124
+ toVersioned(root, hotState),
125
+ baseUrl,
126
+ defaultFetchOpts,
127
+ typeof hotState.e === 'string' ? hotState.e : undefined,
128
+ false,
129
+ undefined,
130
+ hotState.t
131
+ ).then(m => {
132
+ if (hotState.a) {
133
+ hotState.a.every(([d, c]) => d === null && !earlyRoots.has(c) && c(m));
134
+ // unload should be the latest unload handler from the just loaded module
135
+ if (hotState.u) {
136
+ hotState.u(hotState.d);
137
+ hotState.u = null;
138
+ }
139
+ }
140
+ for (const parent of hotState.p) {
141
+ const hotState = hotRegistry[parent];
142
+ if (hotState && hotState.a)
143
+ hotState.a.every(async ([d, c]) => {
144
+ return (
145
+ d &&
146
+ !earlyRoots.has(c) &&
147
+ (typeof d === 'string' ?
148
+ d === root && c(m)
149
+ : c(await Promise.all(d.map(d => (earlyRoots.push(c), importShim(toVersioned(d, getHotState(d))))))))
150
+ );
151
+ });
152
+ }
153
+ }, throwError);
154
+ }
155
+ curInvalidationRoots = new Set();
156
+ };
157
+
158
+ return [
159
+ _importHook ? chain(_importHook, hotImportHook) : hotImportHook,
160
+ _resolveHook ?
161
+ (id, parent, defaultResolve) =>
162
+ hotResolveHook(id, parent, (id, parent) => _resolveHook(id, parent, defaultResolve))
163
+ : hotResolveHook,
164
+ _metaHook ? chain(_metaHook, hotMetaHook) : hotMetaHook
165
+ ];
166
+ };
10
167
 
11
- let defaultResolve;
12
- let hotResolveHook = (id, parent, _defaultResolve) => {
13
- if (!defaultResolve) defaultResolve = _defaultResolve;
14
- const originalParent = stripVersion(parent);
15
- const url = stripVersion(defaultResolve(id, originalParent));
16
- const parents = getHotState(url).p;
17
- if (!parents.includes(originalParent)) parents.push(originalParent);
18
- return toVersioned(url);
19
- };
20
- const hotImportHook = (url, _, __, source, sourceType) => {
21
- const hotState = getHotState(url);
22
- hotState.e = typeof source === 'string' ? source : true;
23
- hotState.t = sourceType;
24
- };
25
- const hotMetaHook = (metaObj, url) => {
26
- metaObj.hot = new Hot(url);
168
+ const hasDocument = typeof document !== 'undefined';
169
+
170
+ const noop = () => {};
171
+
172
+ const chain = (a, b) =>
173
+ function () {
174
+ a.apply(this, arguments);
175
+ b.apply(this, arguments);
27
176
  };
28
177
 
29
- const Hot = class Hot {
30
- constructor(url) {
31
- this.data = getHotState((this.url = stripVersion(url))).d;
178
+ const dynamicImport = (u, errUrl) => import(u);
179
+
180
+ const defineValue = (obj, prop, value) =>
181
+ Object.defineProperty(obj, prop, { writable: false, configurable: false, value });
182
+
183
+ const optionsScript = hasDocument ? document.querySelector('script[type=esms-options]') : undefined;
184
+
185
+ const esmsInitOptions = optionsScript ? JSON.parse(optionsScript.innerHTML) : {};
186
+ Object.assign(esmsInitOptions, self.esmsInitOptions || {});
187
+
188
+ const version = "2.5.0";
189
+
190
+ const r$1 = esmsInitOptions.version;
191
+ if (self.importShim || (r$1 && r$1 !== version)) {
192
+ console.info(
193
+ `es-module-shims: skipping initialization as ${r$1 ? `configured for ${r$1}` : 'another instance has already registered'}`
194
+ );
195
+ return;
196
+ }
197
+
198
+ // shim mode is determined on initialization, no late shim mode
199
+ const shimMode =
200
+ esmsInitOptions.shimMode ||
201
+ (hasDocument &&
202
+ document.querySelectorAll('script[type=module-shim],script[type=importmap-shim],link[rel=modulepreload-shim]')
203
+ .length > 0);
204
+
205
+ let importHook,
206
+ resolveHook,
207
+ fetchHook = fetch,
208
+ metaHook,
209
+ tsTransform =
210
+ esmsInitOptions.tsTransform ||
211
+ (hasDocument && document.currentScript && document.currentScript.src.replace(/(\.\w+)?\.js$/, '-typescript.js')) ||
212
+ './es-module-shims-typescript.js';
213
+
214
+ const defaultFetchOpts = { credentials: 'same-origin' };
215
+
216
+ const {
217
+ revokeBlobURLs,
218
+ noLoadEventRetriggers,
219
+ enforceIntegrity,
220
+ hotReload,
221
+ hotReloadInterval = 100,
222
+ nativePassthrough = !hotReload
223
+ } = esmsInitOptions;
224
+
225
+ const globalHook = name => (typeof name === 'string' ? self[name] : name);
226
+
227
+ if (esmsInitOptions.onimport) importHook = globalHook(esmsInitOptions.onimport);
228
+ if (esmsInitOptions.resolve) resolveHook = globalHook(esmsInitOptions.resolve);
229
+ if (esmsInitOptions.fetch) fetchHook = globalHook(esmsInitOptions.fetch);
230
+ if (esmsInitOptions.meta) metaHook = globalHook(esmsInitOptions.meta);
231
+
232
+ if (hotReload) [importHook, resolveHook, metaHook] = initHotReload();
233
+
234
+ const mapOverrides = esmsInitOptions.mapOverrides;
235
+
236
+ let nonce = esmsInitOptions.nonce;
237
+ if (!nonce && hasDocument) {
238
+ const nonceElement = document.querySelector('script[nonce]');
239
+ if (nonceElement) nonce = nonceElement.nonce || nonceElement.getAttribute('nonce');
240
+ }
241
+
242
+ const onerror = globalHook(esmsInitOptions.onerror || console.error.bind(console));
243
+
244
+ const enable = Array.isArray(esmsInitOptions.polyfillEnable) ? esmsInitOptions.polyfillEnable : [];
245
+ const enableAll = esmsInitOptions.polyfillEnable === 'all' || enable.includes('all');
246
+ const wasmInstancePhaseEnabled =
247
+ enable.includes('wasm-modules') || enable.includes('wasm-module-instances') || enableAll;
248
+ const wasmSourcePhaseEnabled =
249
+ enable.includes('wasm-modules') || enable.includes('wasm-module-sources') || enableAll;
250
+ const deferPhaseEnabled = enable.includes('import-defer') || enableAll;
251
+
252
+ const onpolyfill =
253
+ esmsInitOptions.onpolyfill ?
254
+ globalHook(esmsInitOptions.onpolyfill)
255
+ : () => {
256
+ console.log(`%c^^ Module error above is polyfilled and can be ignored ^^`, 'font-weight:900;color:#391');
257
+ };
258
+
259
+ const baseUrl =
260
+ hasDocument ?
261
+ document.baseURI
262
+ : `${location.protocol}//${location.host}${
263
+ location.pathname.includes('/') ?
264
+ location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1)
265
+ : location.pathname
266
+ }`;
267
+
268
+ const createBlob = (source, type = 'text/javascript') => URL.createObjectURL(new Blob([source], { type }));
269
+ let { skip } = esmsInitOptions;
270
+ if (Array.isArray(skip)) {
271
+ const l = skip.map(s => new URL(s, baseUrl).href);
272
+ skip = s => l.some(i => (i[i.length - 1] === '/' && s.startsWith(i)) || s === i);
273
+ } else if (typeof skip === 'string') {
274
+ const r = new RegExp(skip);
275
+ skip = s => r.test(s);
276
+ } else if (skip instanceof RegExp) {
277
+ skip = s => skip.test(s);
278
+ }
279
+
280
+ const dispatchError = error => self.dispatchEvent(Object.assign(new Event('error'), { error }));
281
+
282
+ const throwError = err => {
283
+ (self.reportError || dispatchError)(err), void onerror(err);
284
+ };
285
+
286
+ const fromParent = parent => (parent ? ` imported from ${parent}` : '');
287
+
288
+ const backslashRegEx = /\\/g;
289
+
290
+ const asURL = url => {
291
+ try {
292
+ if (url.indexOf(':') !== -1) return new URL(url).href;
293
+ } catch (_) {}
294
+ };
295
+
296
+ const resolveUrl = (relUrl, parentUrl) =>
297
+ resolveIfNotPlainOrUrl(relUrl, parentUrl) || asURL(relUrl) || resolveIfNotPlainOrUrl('./' + relUrl, parentUrl);
298
+
299
+ const resolveIfNotPlainOrUrl = (relUrl, parentUrl) => {
300
+ const hIdx = parentUrl.indexOf('#'),
301
+ qIdx = parentUrl.indexOf('?');
302
+ if (hIdx + qIdx > -2)
303
+ parentUrl = parentUrl.slice(
304
+ 0,
305
+ hIdx === -1 ? qIdx
306
+ : qIdx === -1 || qIdx > hIdx ? hIdx
307
+ : qIdx
308
+ );
309
+ if (relUrl.indexOf('\\') !== -1) relUrl = relUrl.replace(backslashRegEx, '/');
310
+ // protocol-relative
311
+ if (relUrl[0] === '/' && relUrl[1] === '/') {
312
+ return parentUrl.slice(0, parentUrl.indexOf(':') + 1) + relUrl;
313
+ }
314
+ // relative-url
315
+ else if (
316
+ (relUrl[0] === '.' &&
317
+ (relUrl[1] === '/' ||
318
+ (relUrl[1] === '.' && (relUrl[2] === '/' || (relUrl.length === 2 && (relUrl += '/')))) ||
319
+ (relUrl.length === 1 && (relUrl += '/')))) ||
320
+ relUrl[0] === '/'
321
+ ) {
322
+ const parentProtocol = parentUrl.slice(0, parentUrl.indexOf(':') + 1);
323
+ if (parentProtocol === 'blob:') {
324
+ throw new TypeError(
325
+ `Failed to resolve module specifier "${relUrl}". Invalid relative url or base scheme isn't hierarchical.`
326
+ );
32
327
  }
33
- accept(deps, cb) {
34
- if (typeof deps === 'function') {
35
- cb = deps;
36
- deps = null;
328
+ // Disabled, but these cases will give inconsistent results for deep backtracking
329
+ //if (parentUrl[parentProtocol.length] !== '/')
330
+ // throw new Error('Cannot resolve');
331
+ // read pathname from parent URL
332
+ // pathname taken to be part after leading "/"
333
+ let pathname;
334
+ if (parentUrl[parentProtocol.length + 1] === '/') {
335
+ // resolving to a :// so we need to read out the auth and host
336
+ if (parentProtocol !== 'file:') {
337
+ pathname = parentUrl.slice(parentProtocol.length + 2);
338
+ pathname = pathname.slice(pathname.indexOf('/') + 1);
339
+ } else {
340
+ pathname = parentUrl.slice(8);
37
341
  }
38
- const hotState = getHotState(this.url);
39
- if (!hotState.A) return;
40
- (hotState.a = hotState.a || []).push([
41
- typeof deps === 'string' ? defaultResolve(deps, this.url)
42
- : deps ? deps.map(d => defaultResolve(d, this.url))
43
- : null,
44
- cb
45
- ]);
46
- }
47
- dispose(cb) {
48
- getHotState(this.url).u = cb;
49
- }
50
- invalidate() {
51
- const hotState = getHotState(this.url);
52
- hotState.a = null;
53
- hotState.A = true;
54
- const seen = [this.url];
55
- for (const p of hotState.p) invalidate(p, this.url, seen);
342
+ } else {
343
+ // resolving to :/ so pathname is the /... part
344
+ pathname = parentUrl.slice(parentProtocol.length + (parentUrl[parentProtocol.length] === '/'));
56
345
  }
57
- };
58
346
 
59
- const versionedRegEx = /\?v=\d+$/;
60
- const stripVersion = url => {
61
- const versionMatch = url.match(versionedRegEx);
62
- return versionMatch ? url.slice(0, -versionMatch[0].length) : url;
63
- };
347
+ if (relUrl[0] === '/') return parentUrl.slice(0, parentUrl.length - pathname.length - 1) + relUrl;
64
348
 
65
- const toVersioned = url => {
66
- const v = getHotState(url).v;
67
- return url + (v ? '?v=' + v : '');
68
- };
349
+ // join together and split for removal of .. and . segments
350
+ // looping the string instead of anything fancy for perf reasons
351
+ // '../../../../../z' resolved to 'x/y' is just 'z'
352
+ const segmented = pathname.slice(0, pathname.lastIndexOf('/') + 1) + relUrl;
69
353
 
70
- let hotRegistry = {},
71
- curInvalidationRoots = new Set(),
72
- curInvalidationInterval;
73
- const getHotState = url =>
74
- hotRegistry[url] ||
75
- (hotRegistry[url] = {
76
- // version
77
- v: 0,
78
- // accept list ([deps, cb] pairs)
79
- a: null,
80
- // accepting acceptors
81
- A: true,
82
- // unload callback
83
- u: null,
84
- // entry point or inline script source
85
- e: false,
86
- // hot data
87
- d: {},
88
- // parents
89
- p: [],
90
- // source type
91
- t: undefined
92
- });
93
-
94
- invalidate = (url, fromUrl, seen = []) => {
95
- if (!seen.includes(url)) {
96
- seen.push(url);
97
- console.info(`es-module-shims: hot reload ${url}`);
98
- const hotState = hotRegistry[url];
99
- if (hotState) {
100
- hotState.A = false;
101
- if (
102
- hotState.a &&
103
- hotState.a.some(([d]) => d && (typeof d === 'string' ? d === fromUrl : d.includes(fromUrl)))
104
- ) {
105
- curInvalidationRoots.add(fromUrl);
106
- } else {
107
- if (hotState.e || hotState.a) curInvalidationRoots.add(url);
108
- hotState.v++;
109
- if (!hotState.a) for (const parent of hotState.p) invalidate(parent, url, seen);
354
+ const output = [];
355
+ let segmentIndex = -1;
356
+ for (let i = 0; i < segmented.length; i++) {
357
+ // busy reading a segment - only terminate on '/'
358
+ if (segmentIndex !== -1) {
359
+ if (segmented[i] === '/') {
360
+ output.push(segmented.slice(segmentIndex, i + 1));
361
+ segmentIndex = -1;
110
362
  }
363
+ continue;
111
364
  }
112
- }
113
- if (!curInvalidationInterval)
114
- curInvalidationInterval = setTimeout(() => {
115
- curInvalidationInterval = null;
116
- const earlyRoots = new Set();
117
- for (const root of curInvalidationRoots) {
118
- const hotState = hotRegistry[root];
119
- topLevelLoad(
120
- toVersioned(root),
121
- baseUrl,
122
- defaultFetchOpts,
123
- typeof hotState.e === 'string' ? hotState.e : undefined,
124
- false,
125
- undefined,
126
- hotState.t
127
- ).then(m => {
128
- if (hotState.a) {
129
- hotState.a.every(([d, c]) => d === null && !earlyRoots.has(c) && c(m));
130
- // unload should be the latest unload handler from the just loaded module
131
- if (hotState.u) {
132
- hotState.u(hotState.d);
133
- hotState.u = null;
134
- }
135
- }
136
- for (const parent of hotState.p) {
137
- const hotState = hotRegistry[parent];
138
- if (hotState && hotState.a)
139
- hotState.a.every(async ([d, c]) => {
140
- return (
141
- d &&
142
- !earlyRoots.has(c) &&
143
- (typeof d === 'string' ?
144
- d === root && c(m)
145
- : c(await Promise.all(d.map(d => (earlyRoots.push(c), importShim(toVersioned(d)))))))
146
- );
147
- });
148
- }
149
- }, throwError);
365
+ // new segment - check if it is relative
366
+ else if (segmented[i] === '.') {
367
+ // ../ segment
368
+ if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {
369
+ output.pop();
370
+ i += 2;
371
+ continue;
150
372
  }
151
- curInvalidationRoots = new Set();
152
- }, hotReloadInterval);
373
+ // ./ segment
374
+ else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {
375
+ i += 1;
376
+ continue;
377
+ }
378
+ }
379
+ // it is the start of a new segment
380
+ while (segmented[i] === '/') i++;
381
+ segmentIndex = i;
382
+ }
383
+ // finish reading out the last segment
384
+ if (segmentIndex !== -1) output.push(segmented.slice(segmentIndex));
385
+ return parentUrl.slice(0, parentUrl.length - pathname.length) + output.join('');
386
+ }
387
+ };
388
+
389
+ const resolveAndComposeImportMap = (json, baseUrl, parentMap) => {
390
+ const outMap = {
391
+ imports: { ...parentMap.imports },
392
+ scopes: { ...parentMap.scopes },
393
+ integrity: { ...parentMap.integrity }
153
394
  };
154
395
 
155
- return [
156
- _importHook ? chain(_importHook, hotImportHook) : hotImportHook,
157
- _resolveHook ?
158
- (id, parent, defaultResolve) =>
159
- hotResolveHook(id, parent, (id, parent) => _resolveHook(id, parent, defaultResolve))
160
- : hotResolveHook,
161
- _metaHook ? chain(_metaHook, hotMetaHook) : hotMetaHook
162
- ];
396
+ if (json.imports) resolveAndComposePackages(json.imports, outMap.imports, baseUrl, parentMap);
397
+
398
+ if (json.scopes)
399
+ for (let s in json.scopes) {
400
+ const resolvedScope = resolveUrl(s, baseUrl);
401
+ resolveAndComposePackages(
402
+ json.scopes[s],
403
+ outMap.scopes[resolvedScope] || (outMap.scopes[resolvedScope] = {}),
404
+ baseUrl,
405
+ parentMap
406
+ );
407
+ }
408
+
409
+ if (json.integrity) resolveAndComposeIntegrity(json.integrity, outMap.integrity, baseUrl);
410
+
411
+ return outMap;
163
412
  };
164
413
 
165
- const hasDocument = typeof document !== 'undefined';
166
-
167
- const noop = () => {};
168
-
169
- const chain = (a, b) =>
170
- function () {
171
- a.apply(this, arguments);
172
- b.apply(this, arguments);
173
- };
174
-
175
- const dynamicImport = (u, errUrl) => import(u);
176
-
177
- const defineValue = (obj, prop, value) =>
178
- Object.defineProperty(obj, prop, { writable: false, configurable: false, value });
179
-
180
- const optionsScript = hasDocument ? document.querySelector('script[type=esms-options]') : undefined;
181
-
182
- const esmsInitOptions = optionsScript ? JSON.parse(optionsScript.innerHTML) : {};
183
- Object.assign(esmsInitOptions, self.esmsInitOptions || {});
184
-
185
- const r$1 = esmsInitOptions.version;
186
- if (self.importShim || (r$1 && r$1 !== "2.4.0")) {
187
- console.info(
188
- `es-module-shims: skipping initialization as ${r$1 ? `configured for ${r$1}` : 'another instance has already registered'}`
189
- );
190
- return;
191
- }
192
-
193
- // shim mode is determined on initialization, no late shim mode
194
- const shimMode =
195
- esmsInitOptions.shimMode ||
196
- (hasDocument &&
197
- document.querySelectorAll('script[type=module-shim],script[type=importmap-shim],link[rel=modulepreload-shim]')
198
- .length > 0);
199
-
200
- let importHook,
201
- resolveHook,
202
- fetchHook = fetch,
203
- metaHook,
204
- tsTransform =
205
- esmsInitOptions.tsTransform ||
206
- (hasDocument && document.currentScript && document.currentScript.src.replace(/(\.\w+)?\.js$/, '-typescript.js')) ||
207
- './es-module-shims-typescript.js';
208
-
209
- const defaultFetchOpts = { credentials: 'same-origin' };
210
-
211
- const {
212
- revokeBlobURLs,
213
- noLoadEventRetriggers,
214
- enforceIntegrity,
215
- hotReload,
216
- hotReloadInterval = 100,
217
- nativePassthrough = !hotReload
218
- } = esmsInitOptions;
219
-
220
- const globalHook = name => (typeof name === 'string' ? self[name] : name);
221
-
222
- if (esmsInitOptions.onimport) importHook = globalHook(esmsInitOptions.onimport);
223
- if (esmsInitOptions.resolve) resolveHook = globalHook(esmsInitOptions.resolve);
224
- if (esmsInitOptions.fetch) fetchHook = globalHook(esmsInitOptions.fetch);
225
- if (esmsInitOptions.meta) metaHook = globalHook(esmsInitOptions.meta);
226
-
227
- if (hotReload) [importHook, resolveHook, metaHook] = initHotReload();
228
-
229
- const mapOverrides = esmsInitOptions.mapOverrides;
230
-
231
- let nonce = esmsInitOptions.nonce;
232
- if (!nonce && hasDocument) {
233
- const nonceElement = document.querySelector('script[nonce]');
234
- if (nonceElement) nonce = nonceElement.nonce || nonceElement.getAttribute('nonce');
235
- }
236
-
237
- const onerror = globalHook(esmsInitOptions.onerror || console.error.bind(console));
238
-
239
- const enable = Array.isArray(esmsInitOptions.polyfillEnable) ? esmsInitOptions.polyfillEnable : [];
240
- const enableAll = esmsInitOptions.polyfillEnable === 'all' || enable.includes('all');
241
- const wasmInstancePhaseEnabled =
242
- enable.includes('wasm-modules') || enable.includes('wasm-module-instances') || enableAll;
243
- const wasmSourcePhaseEnabled =
244
- enable.includes('wasm-modules') || enable.includes('wasm-module-sources') || enableAll;
245
- const deferPhaseEnabled = enable.includes('import-defer') || enableAll;
246
-
247
- const onpolyfill =
248
- esmsInitOptions.onpolyfill ?
249
- globalHook(esmsInitOptions.onpolyfill)
250
- : () => {
251
- console.log(`%c^^ Module error above is polyfilled and can be ignored ^^`, 'font-weight:900;color:#391');
252
- };
253
-
254
- const baseUrl =
255
- hasDocument ?
256
- document.baseURI
257
- : `${location.protocol}//${location.host}${
258
- location.pathname.includes('/') ?
259
- location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1)
260
- : location.pathname
261
- }`;
262
-
263
- const createBlob = (source, type = 'text/javascript') => URL.createObjectURL(new Blob([source], { type }));
264
- let { skip } = esmsInitOptions;
265
- if (Array.isArray(skip)) {
266
- const l = skip.map(s => new URL(s, baseUrl).href);
267
- skip = s => l.some(i => (i[i.length - 1] === '/' && s.startsWith(i)) || s === i);
268
- } else if (typeof skip === 'string') {
269
- const r = new RegExp(skip);
270
- skip = s => r.test(s);
271
- } else if (skip instanceof RegExp) {
272
- skip = s => skip.test(s);
273
- }
274
-
275
- const dispatchError = error => self.dispatchEvent(Object.assign(new Event('error'), { error }));
276
-
277
- const throwError = err => {
278
- (self.reportError || dispatchError)(err), void onerror(err);
279
- };
280
-
281
- const fromParent = parent => (parent ? ` imported from ${parent}` : '');
414
+ const getMatch = (path, matchObj) => {
415
+ if (matchObj[path]) return path;
416
+ let sepIndex = path.length;
417
+ do {
418
+ const segment = path.slice(0, sepIndex + 1);
419
+ if (segment in matchObj) return segment;
420
+ } while ((sepIndex = path.lastIndexOf('/', sepIndex - 1)) !== -1);
421
+ };
282
422
 
283
- const backslashRegEx = /\\/g;
284
-
285
- const asURL = url => {
286
- try {
287
- if (url.indexOf(':') !== -1) return new URL(url).href;
288
- } catch (_) {}
289
- };
290
-
291
- const resolveUrl = (relUrl, parentUrl) =>
292
- resolveIfNotPlainOrUrl(relUrl, parentUrl) || asURL(relUrl) || resolveIfNotPlainOrUrl('./' + relUrl, parentUrl);
293
-
294
- const resolveIfNotPlainOrUrl = (relUrl, parentUrl) => {
295
- const hIdx = parentUrl.indexOf('#'),
296
- qIdx = parentUrl.indexOf('?');
297
- if (hIdx + qIdx > -2)
298
- parentUrl = parentUrl.slice(
299
- 0,
300
- hIdx === -1 ? qIdx
301
- : qIdx === -1 || qIdx > hIdx ? hIdx
302
- : qIdx
303
- );
304
- if (relUrl.indexOf('\\') !== -1) relUrl = relUrl.replace(backslashRegEx, '/');
305
- // protocol-relative
306
- if (relUrl[0] === '/' && relUrl[1] === '/') {
307
- return parentUrl.slice(0, parentUrl.indexOf(':') + 1) + relUrl;
308
- }
309
- // relative-url
310
- else if (
311
- (relUrl[0] === '.' &&
312
- (relUrl[1] === '/' ||
313
- (relUrl[1] === '.' && (relUrl[2] === '/' || (relUrl.length === 2 && (relUrl += '/')))) ||
314
- (relUrl.length === 1 && (relUrl += '/')))) ||
315
- relUrl[0] === '/'
316
- ) {
317
- const parentProtocol = parentUrl.slice(0, parentUrl.indexOf(':') + 1);
318
- if (parentProtocol === 'blob:') {
319
- throw new TypeError(
320
- `Failed to resolve module specifier "${relUrl}". Invalid relative url or base scheme isn't hierarchical.`
321
- );
322
- }
323
- // Disabled, but these cases will give inconsistent results for deep backtracking
324
- //if (parentUrl[parentProtocol.length] !== '/')
325
- // throw new Error('Cannot resolve');
326
- // read pathname from parent URL
327
- // pathname taken to be part after leading "/"
328
- let pathname;
329
- if (parentUrl[parentProtocol.length + 1] === '/') {
330
- // resolving to a :// so we need to read out the auth and host
331
- if (parentProtocol !== 'file:') {
332
- pathname = parentUrl.slice(parentProtocol.length + 2);
333
- pathname = pathname.slice(pathname.indexOf('/') + 1);
334
- } else {
335
- pathname = parentUrl.slice(8);
336
- }
337
- } else {
338
- // resolving to :/ so pathname is the /... part
339
- pathname = parentUrl.slice(parentProtocol.length + (parentUrl[parentProtocol.length] === '/'));
340
- }
341
-
342
- if (relUrl[0] === '/') return parentUrl.slice(0, parentUrl.length - pathname.length - 1) + relUrl;
343
-
344
- // join together and split for removal of .. and . segments
345
- // looping the string instead of anything fancy for perf reasons
346
- // '../../../../../z' resolved to 'x/y' is just 'z'
347
- const segmented = pathname.slice(0, pathname.lastIndexOf('/') + 1) + relUrl;
348
-
349
- const output = [];
350
- let segmentIndex = -1;
351
- for (let i = 0; i < segmented.length; i++) {
352
- // busy reading a segment - only terminate on '/'
353
- if (segmentIndex !== -1) {
354
- if (segmented[i] === '/') {
355
- output.push(segmented.slice(segmentIndex, i + 1));
356
- segmentIndex = -1;
357
- }
358
- continue;
359
- }
360
- // new segment - check if it is relative
361
- else if (segmented[i] === '.') {
362
- // ../ segment
363
- if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) {
364
- output.pop();
365
- i += 2;
366
- continue;
367
- }
368
- // ./ segment
369
- else if (segmented[i + 1] === '/' || i + 1 === segmented.length) {
370
- i += 1;
371
- continue;
372
- }
373
- }
374
- // it is the start of a new segment
375
- while (segmented[i] === '/') i++;
376
- segmentIndex = i;
377
- }
378
- // finish reading out the last segment
379
- if (segmentIndex !== -1) output.push(segmented.slice(segmentIndex));
380
- return parentUrl.slice(0, parentUrl.length - pathname.length) + output.join('');
381
- }
382
- };
383
-
384
- const resolveAndComposeImportMap = (json, baseUrl, parentMap) => {
385
- const outMap = {
386
- imports: { ...parentMap.imports },
387
- scopes: { ...parentMap.scopes },
388
- integrity: { ...parentMap.integrity }
389
- };
390
-
391
- if (json.imports) resolveAndComposePackages(json.imports, outMap.imports, baseUrl, parentMap);
392
-
393
- if (json.scopes)
394
- for (let s in json.scopes) {
395
- const resolvedScope = resolveUrl(s, baseUrl);
396
- resolveAndComposePackages(
397
- json.scopes[s],
398
- outMap.scopes[resolvedScope] || (outMap.scopes[resolvedScope] = {}),
399
- baseUrl,
400
- parentMap
401
- );
402
- }
403
-
404
- if (json.integrity) resolveAndComposeIntegrity(json.integrity, outMap.integrity, baseUrl);
405
-
406
- return outMap;
407
- };
408
-
409
- const getMatch = (path, matchObj) => {
410
- if (matchObj[path]) return path;
411
- let sepIndex = path.length;
412
- do {
413
- const segment = path.slice(0, sepIndex + 1);
414
- if (segment in matchObj) return segment;
415
- } while ((sepIndex = path.lastIndexOf('/', sepIndex - 1)) !== -1);
416
- };
417
-
418
- const applyPackages = (id, packages) => {
419
- const pkgName = getMatch(id, packages);
420
- if (pkgName) {
421
- const pkg = packages[pkgName];
422
- if (pkg === null) return;
423
- return pkg + id.slice(pkgName.length);
424
- }
425
- };
426
-
427
- const resolveImportMap = (importMap, resolvedOrPlain, parentUrl) => {
428
- let scopeUrl = parentUrl && getMatch(parentUrl, importMap.scopes);
429
- while (scopeUrl) {
430
- const packageResolution = applyPackages(resolvedOrPlain, importMap.scopes[scopeUrl]);
431
- if (packageResolution) return packageResolution;
432
- scopeUrl = getMatch(scopeUrl.slice(0, scopeUrl.lastIndexOf('/')), importMap.scopes);
433
- }
434
- return applyPackages(resolvedOrPlain, importMap.imports) || (resolvedOrPlain.indexOf(':') !== -1 && resolvedOrPlain);
435
- };
436
-
437
- const resolveAndComposePackages = (packages, outPackages, baseUrl, parentMap) => {
438
- for (let p in packages) {
439
- const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
440
- if (
441
- (!shimMode || !mapOverrides) &&
442
- outPackages[resolvedLhs] &&
443
- outPackages[resolvedLhs] !== packages[resolvedLhs]
444
- ) {
445
- console.warn(
446
- `es-module-shims: Rejected map override "${resolvedLhs}" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`
447
- );
448
- continue;
449
- }
450
- let target = packages[p];
451
- if (typeof target !== 'string') continue;
452
- const mapped = resolveImportMap(parentMap, resolveIfNotPlainOrUrl(target, baseUrl) || target, baseUrl);
453
- if (mapped) {
454
- outPackages[resolvedLhs] = mapped;
455
- continue;
456
- }
457
- console.warn(`es-module-shims: Mapping "${p}" -> "${packages[p]}" does not resolve`);
458
- }
459
- };
460
-
461
- const resolveAndComposeIntegrity = (integrity, outIntegrity, baseUrl) => {
462
- for (let p in integrity) {
463
- const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
464
- if (
465
- (!shimMode || !mapOverrides) &&
466
- outIntegrity[resolvedLhs] &&
467
- outIntegrity[resolvedLhs] !== integrity[resolvedLhs]
468
- ) {
469
- console.warn(
470
- `es-module-shims: Rejected map integrity override "${resolvedLhs}" from ${outIntegrity[resolvedLhs]} to ${integrity[resolvedLhs]}.`
471
- );
472
- }
473
- outIntegrity[resolvedLhs] = integrity[p];
474
- }
423
+ const applyPackages = (id, packages) => {
424
+ const pkgName = getMatch(id, packages);
425
+ if (pkgName) {
426
+ const pkg = packages[pkgName];
427
+ if (pkg === null) return;
428
+ return pkg + id.slice(pkgName.length);
429
+ }
430
+ };
431
+
432
+ const resolveImportMap = (importMap, resolvedOrPlain, parentUrl) => {
433
+ let scopeUrl = parentUrl && getMatch(parentUrl, importMap.scopes);
434
+ while (scopeUrl) {
435
+ const packageResolution = applyPackages(resolvedOrPlain, importMap.scopes[scopeUrl]);
436
+ if (packageResolution) return packageResolution;
437
+ scopeUrl = getMatch(scopeUrl.slice(0, scopeUrl.lastIndexOf('/')), importMap.scopes);
438
+ }
439
+ return applyPackages(resolvedOrPlain, importMap.imports) || (resolvedOrPlain.indexOf(':') !== -1 && resolvedOrPlain);
440
+ };
441
+
442
+ const resolveAndComposePackages = (packages, outPackages, baseUrl, parentMap) => {
443
+ for (let p in packages) {
444
+ const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
445
+ if (
446
+ (!shimMode || !mapOverrides) &&
447
+ outPackages[resolvedLhs] &&
448
+ outPackages[resolvedLhs] !== packages[resolvedLhs]
449
+ ) {
450
+ console.warn(
451
+ `es-module-shims: Rejected map override "${resolvedLhs}" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`
452
+ );
453
+ continue;
454
+ }
455
+ let target = packages[p];
456
+ if (typeof target !== 'string') continue;
457
+ const mapped = resolveImportMap(parentMap, resolveIfNotPlainOrUrl(target, baseUrl) || target, baseUrl);
458
+ if (mapped) {
459
+ outPackages[resolvedLhs] = mapped;
460
+ continue;
461
+ }
462
+ console.warn(`es-module-shims: Mapping "${p}" -> "${packages[p]}" does not resolve`);
463
+ }
464
+ };
465
+
466
+ const resolveAndComposeIntegrity = (integrity, outIntegrity, baseUrl) => {
467
+ for (let p in integrity) {
468
+ const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p;
469
+ if (
470
+ (!shimMode || !mapOverrides) &&
471
+ outIntegrity[resolvedLhs] &&
472
+ outIntegrity[resolvedLhs] !== integrity[resolvedLhs]
473
+ ) {
474
+ console.warn(
475
+ `es-module-shims: Rejected map integrity override "${resolvedLhs}" from ${outIntegrity[resolvedLhs]} to ${integrity[resolvedLhs]}.`
476
+ );
477
+ }
478
+ outIntegrity[resolvedLhs] = integrity[p];
479
+ }
475
480
  };
476
481
 
477
482
  // support browsers without dynamic import support (eg Firefox 6x)
@@ -512,12 +517,13 @@
512
517
  )
513
518
  ]);
514
519
 
520
+ const msgTag = `s${version}`;
515
521
  return new Promise(resolve => {
516
522
  const iframe = document.createElement('iframe');
517
523
  iframe.style.display = 'none';
518
524
  iframe.setAttribute('nonce', nonce);
519
525
  function cb({ data }) {
520
- const isFeatureDetectionMessage = Array.isArray(data) && data[0] === 'esms';
526
+ const isFeatureDetectionMessage = Array.isArray(data) && data[0] === msgTag;
521
527
  if (!isFeatureDetectionMessage) return;
522
528
  [
523
529
  ,
@@ -547,7 +553,7 @@
547
553
  supportsImportMaps && wasmInstancePhaseEnabled ?
548
554
  `${wasmSourcePhaseEnabled ? 'sp.then(s=>s?' : ''}c(b(\`import"\${b(new Uint8Array(${JSON.stringify(wasmBytes)}),'application/wasm')\}"\`))${wasmSourcePhaseEnabled ? ':false)' : ''}`
549
555
  : 'false'
550
- }]).then(a=>parent.postMessage(['esms'].concat(a),'*'))<${''}/script>`;
556
+ }]).then(a=>parent.postMessage(['${msgTag}'].concat(a),'*'))<${''}/script>`;
551
557
 
552
558
  // Safari will call onload eagerly on head injection, but we don't want the Wechat
553
559
  // path to trigger before setting srcdoc, therefore we track the timing
@@ -698,6 +704,7 @@
698
704
  if (!shimMode) throw new Error('Unsupported in polyfill mode.');
699
705
  composedImportMap = resolveAndComposeImportMap(importMapIn, baseUrl, composedImportMap);
700
706
  };
707
+ importShim$1.version = version;
701
708
 
702
709
  const registry = (importShim$1._r = {});
703
710
  // Wasm caches
@@ -709,7 +716,6 @@
709
716
  const shimModeOptions = { ...esmsInitOptions, shimMode: true };
710
717
  if (optionsScript) optionsScript.innerHTML = JSON.stringify(shimModeOptions);
711
718
  self.esmsInitOptions = shimModeOptions;
712
- defineValue(self, '_d', undefined);
713
719
 
714
720
  const loadAll = async (load, seen) => {
715
721
  seen[load.u] = 1;
@@ -828,7 +834,8 @@
828
834
  // we mock import('./x.css', { with: { type: 'css' }}) support via an inline static reexport
829
835
  // because we can't syntactically pass through to dynamic import with a second argument
830
836
  if (sourceType === 'css' || sourceType === 'json') {
831
- source = `export{default}from'${url}'with{type:"${sourceType}"}`;
837
+ // Direct reexport for hot reloading skipped due to Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1965620
838
+ source = `import m from'${url}'with{type:"${sourceType}"};export default m;`;
832
839
  url += '?entry';
833
840
  }
834
841
 
@@ -1135,7 +1142,11 @@
1135
1142
  s += `if(h)h.accept(m=>({${obj}}=m))`;
1136
1143
  return { r, s, t: 'wasm' };
1137
1144
  } else if (jsonContentType.test(contentType))
1138
- return { r, s: `${hotPrefix}j=${await res.text()};export{j as default};if(h)h.accept(m=>j=m.default)`, t: 'json' };
1145
+ return {
1146
+ r,
1147
+ s: `${hotPrefix}j=${await res.text()};export{j as default};if(h)h.accept(m=>j=m.default)`,
1148
+ t: 'json'
1149
+ };
1139
1150
  else if (cssContentType.test(contentType)) {
1140
1151
  return {
1141
1152
  r,
@@ -1150,6 +1161,7 @@
1150
1161
  } else if (tsContentType.test(contentType) || url.endsWith('.ts') || url.endsWith('.mts')) {
1151
1162
  const source = await res.text();
1152
1163
  if (!esmsTsTransform) await initTs();
1164
+ console.info(`es-module-shims: Compiling TypeScript file ${url}`);
1153
1165
  const transformed = esmsTsTransform(source, url);
1154
1166
  // even if the TypeScript is valid JavaScript, unless it was a top-level inline source, it wasn't served with
1155
1167
  // a valid JS MIME here, so we must still polyfill it
@@ -1415,6 +1427,7 @@
1415
1427
  if (ts && !script.src) {
1416
1428
  loadPromise = Promise.resolve(esmsTsTransform || initTs())
1417
1429
  .then(() => {
1430
+ console.info(`es-module-shims: Compiling TypeScript module script`, script);
1418
1431
  const transformed = esmsTsTransform(script.innerHTML, baseUrl);
1419
1432
  if (transformed !== undefined) {
1420
1433
  onpolyfill();