@module-federation/sdk 0.19.0 → 0.20.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,31 +1,29 @@
1
1
  'use strict';
2
2
 
3
- var polyfills = require('./polyfills.cjs.cjs');
4
-
5
3
  const FederationModuleManifest = 'federation-manifest.json';
6
4
  const MANIFEST_EXT = '.json';
7
5
  const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';
8
6
  const NameTransformSymbol = {
9
7
  AT: '@',
10
8
  HYPHEN: '-',
11
- SLASH: '/'
9
+ SLASH: '/',
12
10
  };
13
11
  const NameTransformMap = {
14
12
  [NameTransformSymbol.AT]: 'scope_',
15
13
  [NameTransformSymbol.HYPHEN]: '_',
16
- [NameTransformSymbol.SLASH]: '__'
14
+ [NameTransformSymbol.SLASH]: '__',
17
15
  };
18
16
  const EncodedNameTransformMap = {
19
17
  [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
20
18
  [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
21
- [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
19
+ [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH,
22
20
  };
23
21
  const SEPARATOR = ':';
24
22
  const ManifestFileName = 'mf-manifest.json';
25
23
  const StatsFileName = 'mf-stats.json';
26
24
  const MFModuleType = {
27
25
  NPM: 'npm',
28
- APP: 'app'
26
+ APP: 'app',
29
27
  };
30
28
  const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';
31
29
  const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';
@@ -35,13 +33,25 @@ const MFPrefetchCommon = {
35
33
  globalKey: '__PREFETCH__',
36
34
  library: 'mf-data-prefetch',
37
35
  exportsKey: '__PREFETCH_EXPORTS__',
38
- fileName: 'bootstrap.js'
36
+ fileName: 'bootstrap.js',
39
37
  };
40
38
 
39
+ /*
40
+ * This file was automatically generated.
41
+ * DO NOT MODIFY BY HAND.
42
+ * Run `yarn special-lint-fix` to update
43
+ */
44
+
41
45
  var ContainerPlugin = /*#__PURE__*/Object.freeze({
42
46
  __proto__: null
43
47
  });
44
48
 
49
+ /*
50
+ * This file was automatically generated.
51
+ * DO NOT MODIFY BY HAND.
52
+ * Run `yarn special-lint-fix` to update
53
+ */
54
+
45
55
  var ContainerReferencePlugin = /*#__PURE__*/Object.freeze({
46
56
  __proto__: null
47
57
  });
@@ -50,29 +60,37 @@ var ModuleFederationPlugin = /*#__PURE__*/Object.freeze({
50
60
  __proto__: null
51
61
  });
52
62
 
63
+ /*
64
+ * This file was automatically generated.
65
+ * DO NOT MODIFY BY HAND.
66
+ * Run `yarn special-lint-fix` to update
67
+ */
68
+
53
69
  var SharePlugin = /*#__PURE__*/Object.freeze({
54
70
  __proto__: null
55
71
  });
56
72
 
57
73
  function isBrowserEnv() {
58
- return typeof window !== 'undefined' && typeof window.document !== 'undefined';
74
+ return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
59
75
  }
60
76
  function isReactNativeEnv() {
61
- var _navigator;
62
- return typeof navigator !== 'undefined' && ((_navigator = navigator) == null ? void 0 : _navigator.product) === 'ReactNative';
77
+ return (typeof navigator !== 'undefined' && navigator?.product === 'ReactNative');
63
78
  }
64
79
  function isBrowserDebug() {
65
80
  try {
66
81
  if (isBrowserEnv() && window.localStorage) {
67
82
  return Boolean(localStorage.getItem(BROWSER_LOG_KEY));
68
83
  }
69
- } catch (error) {
84
+ }
85
+ catch (error) {
70
86
  return false;
71
87
  }
72
88
  return false;
73
89
  }
74
90
  function isDebugMode() {
75
- if (typeof process !== 'undefined' && process.env && process.env['FEDERATION_DEBUG']) {
91
+ if (typeof process !== 'undefined' &&
92
+ process.env &&
93
+ process.env['FEDERATION_DEBUG']) {
76
94
  return Boolean(process.env['FEDERATION_DEBUG']);
77
95
  }
78
96
  if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {
@@ -80,18 +98,18 @@ function isDebugMode() {
80
98
  }
81
99
  return isBrowserDebug();
82
100
  }
83
- const getProcessEnv = function() {
101
+ const getProcessEnv = function () {
84
102
  return typeof process !== 'undefined' && process.env ? process.env : {};
85
103
  };
86
104
 
87
105
  const LOG_CATEGORY = '[ Federation Runtime ]';
88
106
  // entry: name:version version : 1.0.0 | ^1.2.3
89
107
  // entry: name:entry entry: https://localhost:9000/federation-manifest.json
90
- const parseEntry = (str, devVerOrUrl, separator = SEPARATOR)=>{
108
+ const parseEntry = (str, devVerOrUrl, separator = SEPARATOR) => {
91
109
  const strSplit = str.split(separator);
92
110
  const devVersionOrUrl = getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;
93
111
  const defaultVersion = '*';
94
- const isEntry = (s)=>s.startsWith('http') || s.includes(MANIFEST_EXT);
112
+ const isEntry = (s) => s.startsWith('http') || s.includes(MANIFEST_EXT);
95
113
  // Check if the string starts with a type
96
114
  if (strSplit.length >= 2) {
97
115
  let [name, ...versionOrEntryArr] = strSplit;
@@ -99,44 +117,47 @@ const parseEntry = (str, devVerOrUrl, separator = SEPARATOR)=>{
99
117
  if (str.startsWith(separator)) {
100
118
  name = strSplit.slice(0, 2).join(separator);
101
119
  versionOrEntryArr = [
102
- devVersionOrUrl || strSplit.slice(2).join(separator)
120
+ devVersionOrUrl || strSplit.slice(2).join(separator),
103
121
  ];
104
122
  }
105
123
  let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
106
124
  if (isEntry(versionOrEntry)) {
107
125
  return {
108
126
  name,
109
- entry: versionOrEntry
127
+ entry: versionOrEntry,
110
128
  };
111
- } else {
129
+ }
130
+ else {
112
131
  // Apply version rule
113
132
  // devVersionOrUrl => inputVersion => defaultVersion
114
133
  return {
115
134
  name,
116
- version: versionOrEntry || defaultVersion
135
+ version: versionOrEntry || defaultVersion,
117
136
  };
118
137
  }
119
- } else if (strSplit.length === 1) {
138
+ }
139
+ else if (strSplit.length === 1) {
120
140
  const [name] = strSplit;
121
141
  if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
122
142
  return {
123
143
  name,
124
- entry: devVersionOrUrl
144
+ entry: devVersionOrUrl,
125
145
  };
126
146
  }
127
147
  return {
128
148
  name,
129
- version: devVersionOrUrl || defaultVersion
149
+ version: devVersionOrUrl || defaultVersion,
130
150
  };
131
- } else {
151
+ }
152
+ else {
132
153
  throw `Invalid entry value: ${str}`;
133
154
  }
134
155
  };
135
- const composeKeyWithSeparator = function(...args) {
156
+ const composeKeyWithSeparator = function (...args) {
136
157
  if (!args.length) {
137
158
  return '';
138
159
  }
139
- return args.reduce((sum, cur)=>{
160
+ return args.reduce((sum, cur) => {
140
161
  if (!cur) {
141
162
  return sum;
142
163
  }
@@ -146,15 +167,19 @@ const composeKeyWithSeparator = function(...args) {
146
167
  return `${sum}${SEPARATOR}${cur}`;
147
168
  }, '');
148
169
  };
149
- const encodeName = function(name, prefix = '', withExt = false) {
170
+ const encodeName = function (name, prefix = '', withExt = false) {
150
171
  try {
151
172
  const ext = withExt ? '.js' : '';
152
- return `${prefix}${name.replace(new RegExp(`${NameTransformSymbol.AT}`, 'g'), NameTransformMap[NameTransformSymbol.AT]).replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'), NameTransformMap[NameTransformSymbol.HYPHEN]).replace(new RegExp(`${NameTransformSymbol.SLASH}`, 'g'), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
153
- } catch (err) {
173
+ return `${prefix}${name
174
+ .replace(new RegExp(`${NameTransformSymbol.AT}`, 'g'), NameTransformMap[NameTransformSymbol.AT])
175
+ .replace(new RegExp(`${NameTransformSymbol.HYPHEN}`, 'g'), NameTransformMap[NameTransformSymbol.HYPHEN])
176
+ .replace(new RegExp(`${NameTransformSymbol.SLASH}`, 'g'), NameTransformMap[NameTransformSymbol.SLASH])}${ext}`;
177
+ }
178
+ catch (err) {
154
179
  throw err;
155
180
  }
156
181
  };
157
- const decodeName = function(name, prefix, withExt) {
182
+ const decodeName = function (name, prefix, withExt) {
158
183
  try {
159
184
  let decodedName = name;
160
185
  if (prefix) {
@@ -163,16 +188,20 @@ const decodeName = function(name, prefix, withExt) {
163
188
  }
164
189
  decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');
165
190
  }
166
- decodedName = decodedName.replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]]).replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
191
+ decodedName = decodedName
192
+ .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.AT]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.AT]])
193
+ .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.SLASH]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.SLASH]])
194
+ .replace(new RegExp(`${NameTransformMap[NameTransformSymbol.HYPHEN]}`, 'g'), EncodedNameTransformMap[NameTransformMap[NameTransformSymbol.HYPHEN]]);
167
195
  if (withExt) {
168
196
  decodedName = decodedName.replace('.js', '');
169
197
  }
170
198
  return decodedName;
171
- } catch (err) {
199
+ }
200
+ catch (err) {
172
201
  throw err;
173
202
  }
174
203
  };
175
- const generateExposeFilename = (exposeName, withExt)=>{
204
+ const generateExposeFilename = (exposeName, withExt) => {
176
205
  if (!exposeName) {
177
206
  return '';
178
207
  }
@@ -185,47 +214,51 @@ const generateExposeFilename = (exposeName, withExt)=>{
185
214
  }
186
215
  return encodeName(expose, '__federation_expose_', withExt);
187
216
  };
188
- const generateShareFilename = (pkgName, withExt)=>{
217
+ const generateShareFilename = (pkgName, withExt) => {
189
218
  if (!pkgName) {
190
219
  return '';
191
220
  }
192
221
  return encodeName(pkgName, '__federation_shared_', withExt);
193
222
  };
194
- const getResourceUrl = (module, sourceUrl)=>{
223
+ const getResourceUrl = (module, sourceUrl) => {
195
224
  if ('getPublicPath' in module) {
196
225
  let publicPath;
197
226
  if (!module.getPublicPath.startsWith('function')) {
198
227
  publicPath = new Function(module.getPublicPath)();
199
- } else {
228
+ }
229
+ else {
200
230
  publicPath = new Function('return ' + module.getPublicPath)()();
201
231
  }
202
232
  return `${publicPath}${sourceUrl}`;
203
- } else if ('publicPath' in module) {
233
+ }
234
+ else if ('publicPath' in module) {
204
235
  if (!isBrowserEnv() && !isReactNativeEnv() && 'ssrPublicPath' in module) {
205
236
  return `${module.ssrPublicPath}${sourceUrl}`;
206
237
  }
207
238
  return `${module.publicPath}${sourceUrl}`;
208
- } else {
239
+ }
240
+ else {
209
241
  console.warn('Cannot get resource URL. If in debug mode, please ignore.', module, sourceUrl);
210
242
  return '';
211
243
  }
212
244
  };
213
245
  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
214
- const assert = (condition, msg)=>{
246
+ const assert = (condition, msg) => {
215
247
  if (!condition) {
216
248
  error(msg);
217
249
  }
218
250
  };
219
- const error = (msg)=>{
251
+ const error = (msg) => {
220
252
  throw new Error(`${LOG_CATEGORY}: ${msg}`);
221
253
  };
222
- const warn = (msg)=>{
254
+ const warn = (msg) => {
223
255
  console.warn(`${LOG_CATEGORY}: ${msg}`);
224
256
  };
225
257
  function safeToString(info) {
226
258
  try {
227
259
  return JSON.stringify(info, null, 2);
228
- } catch (e) {
260
+ }
261
+ catch (e) {
229
262
  return '';
230
263
  }
231
264
  }
@@ -235,11 +268,11 @@ function isRequiredVersion(str) {
235
268
  return VERSION_PATTERN_REGEXP.test(str);
236
269
  }
237
270
 
238
- const simpleJoinRemoteEntry = (rPath, rName)=>{
271
+ const simpleJoinRemoteEntry = (rPath, rName) => {
239
272
  if (!rPath) {
240
273
  return rName;
241
274
  }
242
- const transformPath = (str)=>{
275
+ const transformPath = (str) => {
243
276
  if (str === '.') {
244
277
  return '';
245
278
  }
@@ -265,22 +298,25 @@ const simpleJoinRemoteEntry = (rPath, rName)=>{
265
298
  return `${transformedPath}/${rName}`;
266
299
  };
267
300
  function inferAutoPublicPath(url) {
268
- return url.replace(/#.*$/, '').replace(/\?.*$/, '').replace(/\/[^\/]+$/, '/');
301
+ return url
302
+ .replace(/#.*$/, '')
303
+ .replace(/\?.*$/, '')
304
+ .replace(/\/[^\/]+$/, '/');
269
305
  }
270
306
  // Priority: overrides > remotes
271
307
  // eslint-disable-next-line max-lines-per-function
272
308
  function generateSnapshotFromManifest(manifest, options = {}) {
273
- var _manifest_metaData, _manifest_metaData1;
274
309
  const { remotes = {}, overrides = {}, version } = options;
275
310
  let remoteSnapshot;
276
- const getPublicPath = ()=>{
311
+ const getPublicPath = () => {
277
312
  if ('publicPath' in manifest.metaData) {
278
313
  if (manifest.metaData.publicPath === 'auto' && version) {
279
314
  // use same implementation as publicPath auto runtime module implements
280
315
  return inferAutoPublicPath(version);
281
316
  }
282
317
  return manifest.metaData.publicPath;
283
- } else {
318
+ }
319
+ else {
284
320
  return manifest.metaData.getPublicPath;
285
321
  }
286
322
  };
@@ -288,32 +324,36 @@ function generateSnapshotFromManifest(manifest, options = {}) {
288
324
  let remotesInfo = {};
289
325
  // If remotes are not provided, only the remotes in the manifest will be read
290
326
  if (!Object.keys(remotes).length) {
291
- var _manifest_remotes;
292
- remotesInfo = ((_manifest_remotes = manifest.remotes) == null ? void 0 : _manifest_remotes.reduce((res, next)=>{
293
- let matchedVersion;
294
- const name = next.federationContainerName;
295
- // overrides have higher priority
296
- if (overridesKeys.includes(name)) {
297
- matchedVersion = overrides[name];
298
- } else {
299
- if ('version' in next) {
300
- matchedVersion = next.version;
301
- } else {
302
- matchedVersion = next.entry;
327
+ remotesInfo =
328
+ manifest.remotes?.reduce((res, next) => {
329
+ let matchedVersion;
330
+ const name = next.federationContainerName;
331
+ // overrides have higher priority
332
+ if (overridesKeys.includes(name)) {
333
+ matchedVersion = overrides[name];
303
334
  }
304
- }
305
- res[name] = {
306
- matchedVersion
307
- };
308
- return res;
309
- }, {})) || {};
335
+ else {
336
+ if ('version' in next) {
337
+ matchedVersion = next.version;
338
+ }
339
+ else {
340
+ matchedVersion = next.entry;
341
+ }
342
+ }
343
+ res[name] = {
344
+ matchedVersion,
345
+ };
346
+ return res;
347
+ }, {}) || {};
310
348
  }
311
349
  // If remotes (deploy scenario) are specified, they need to be traversed again
312
- Object.keys(remotes).forEach((key)=>remotesInfo[key] = {
313
- // overrides will override dependencies
314
- matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
315
- });
316
- const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
350
+ Object.keys(remotes).forEach((key) => (remotesInfo[key] = {
351
+ // overrides will override dependencies
352
+ matchedVersion: overridesKeys.includes(key)
353
+ ? overrides[key]
354
+ : remotes[key],
355
+ }));
356
+ const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType, }, types: remoteTypes, buildInfo: { buildVersion }, globalName, ssrRemoteEntry, } = manifest.metaData;
317
357
  const { exposes } = manifest;
318
358
  let basicRemoteSnapshot = {
319
359
  version: version ? version : '',
@@ -325,98 +365,178 @@ function generateSnapshotFromManifest(manifest, options = {}) {
325
365
  remoteTypesZip: remoteTypes.zip || '',
326
366
  remoteTypesAPI: remoteTypes.api || '',
327
367
  remotesInfo,
328
- shared: manifest == null ? void 0 : manifest.shared.map((item)=>({
329
- assets: item.assets,
330
- sharedName: item.name,
331
- version: item.version
332
- })),
333
- modules: exposes == null ? void 0 : exposes.map((expose)=>({
334
- moduleName: expose.name,
335
- modulePath: expose.path,
336
- assets: expose.assets
337
- }))
368
+ shared: manifest?.shared.map((item) => ({
369
+ assets: item.assets,
370
+ sharedName: item.name,
371
+ version: item.version,
372
+ })),
373
+ modules: exposes?.map((expose) => ({
374
+ moduleName: expose.name,
375
+ modulePath: expose.path,
376
+ assets: expose.assets,
377
+ })),
338
378
  };
339
- if ((_manifest_metaData = manifest.metaData) == null ? void 0 : _manifest_metaData.prefetchInterface) {
379
+ if (manifest.metaData?.prefetchInterface) {
340
380
  const prefetchInterface = manifest.metaData.prefetchInterface;
341
- basicRemoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
342
- prefetchInterface
343
- });
381
+ basicRemoteSnapshot = {
382
+ ...basicRemoteSnapshot,
383
+ prefetchInterface,
384
+ };
344
385
  }
345
- if ((_manifest_metaData1 = manifest.metaData) == null ? void 0 : _manifest_metaData1.prefetchEntry) {
386
+ if (manifest.metaData?.prefetchEntry) {
346
387
  const { path, name, type } = manifest.metaData.prefetchEntry;
347
- basicRemoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
388
+ basicRemoteSnapshot = {
389
+ ...basicRemoteSnapshot,
348
390
  prefetchEntry: simpleJoinRemoteEntry(path, name),
349
- prefetchEntryType: type
350
- });
391
+ prefetchEntryType: type,
392
+ };
351
393
  }
352
394
  if ('publicPath' in manifest.metaData) {
353
- remoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
395
+ remoteSnapshot = {
396
+ ...basicRemoteSnapshot,
354
397
  publicPath: getPublicPath(),
355
- ssrPublicPath: manifest.metaData.ssrPublicPath
356
- });
357
- } else {
358
- remoteSnapshot = polyfills._({}, basicRemoteSnapshot, {
359
- getPublicPath: getPublicPath()
360
- });
398
+ ssrPublicPath: manifest.metaData.ssrPublicPath,
399
+ };
400
+ }
401
+ else {
402
+ remoteSnapshot = {
403
+ ...basicRemoteSnapshot,
404
+ getPublicPath: getPublicPath(),
405
+ };
361
406
  }
362
407
  if (ssrRemoteEntry) {
363
408
  const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
364
409
  remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
365
- remoteSnapshot.ssrRemoteEntryType = ssrRemoteEntry.type || 'commonjs-module';
410
+ remoteSnapshot.ssrRemoteEntryType =
411
+ ssrRemoteEntry.type || 'commonjs-module';
366
412
  }
367
413
  return remoteSnapshot;
368
414
  }
369
415
  function isManifestProvider(moduleInfo) {
370
- if ('remoteEntry' in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
416
+ if ('remoteEntry' in moduleInfo &&
417
+ moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
371
418
  return true;
372
- } else {
419
+ }
420
+ else {
373
421
  return false;
374
422
  }
375
423
  }
376
424
 
377
425
  const PREFIX = '[ Module Federation ]';
378
- let Logger = class Logger {
426
+ const DEFAULT_DELEGATE = console;
427
+ class Logger {
428
+ constructor(prefix, delegate = DEFAULT_DELEGATE) {
429
+ this.prefix = prefix;
430
+ this.delegate = delegate ?? DEFAULT_DELEGATE;
431
+ }
379
432
  setPrefix(prefix) {
380
433
  this.prefix = prefix;
381
434
  }
435
+ setDelegate(delegate) {
436
+ this.delegate = delegate ?? DEFAULT_DELEGATE;
437
+ }
438
+ emit(method, args) {
439
+ const delegate = this.delegate;
440
+ const order = (() => {
441
+ switch (method) {
442
+ case 'log':
443
+ return ['log', 'info'];
444
+ case 'info':
445
+ return ['info', 'log'];
446
+ case 'warn':
447
+ return ['warn', 'info', 'log'];
448
+ case 'error':
449
+ return ['error', 'warn', 'log'];
450
+ case 'debug':
451
+ default:
452
+ return ['debug', 'log'];
453
+ }
454
+ })();
455
+ for (const candidate of order) {
456
+ const handler = delegate[candidate];
457
+ if (typeof handler === 'function') {
458
+ handler.call(delegate, this.prefix, ...args);
459
+ return;
460
+ }
461
+ }
462
+ for (const candidate of order) {
463
+ const handler = DEFAULT_DELEGATE[candidate];
464
+ if (typeof handler === 'function') {
465
+ handler.call(DEFAULT_DELEGATE, this.prefix, ...args);
466
+ return;
467
+ }
468
+ }
469
+ }
382
470
  log(...args) {
383
- console.log(this.prefix, ...args);
471
+ this.emit('log', args);
384
472
  }
385
473
  warn(...args) {
386
- console.log(this.prefix, ...args);
474
+ this.emit('warn', args);
387
475
  }
388
476
  error(...args) {
389
- console.log(this.prefix, ...args);
477
+ this.emit('error', args);
390
478
  }
391
479
  success(...args) {
392
- console.log(this.prefix, ...args);
480
+ this.emit('info', args);
393
481
  }
394
482
  info(...args) {
395
- console.log(this.prefix, ...args);
483
+ this.emit('info', args);
396
484
  }
397
485
  ready(...args) {
398
- console.log(this.prefix, ...args);
486
+ this.emit('info', args);
399
487
  }
400
488
  debug(...args) {
401
489
  if (isDebugMode()) {
402
- console.log(this.prefix, ...args);
490
+ this.emit('debug', args);
403
491
  }
404
492
  }
405
- constructor(prefix){
406
- this.prefix = prefix;
407
- }
408
- };
493
+ }
409
494
  function createLogger(prefix) {
410
495
  return new Logger(prefix);
411
496
  }
497
+ function createInfrastructureLogger(prefix) {
498
+ const infrastructureLogger = new Logger(prefix);
499
+ Object.defineProperty(infrastructureLogger, '__mf_infrastructure_logger__', {
500
+ value: true,
501
+ enumerable: false,
502
+ configurable: false,
503
+ });
504
+ return infrastructureLogger;
505
+ }
506
+ function bindLoggerToCompiler(loggerInstance, compiler, name) {
507
+ if (!loggerInstance
508
+ .__mf_infrastructure_logger__) {
509
+ return;
510
+ }
511
+ if (!compiler?.getInfrastructureLogger) {
512
+ return;
513
+ }
514
+ try {
515
+ const infrastructureLogger = compiler.getInfrastructureLogger(name);
516
+ if (infrastructureLogger &&
517
+ typeof infrastructureLogger === 'object' &&
518
+ (typeof infrastructureLogger.log === 'function' ||
519
+ typeof infrastructureLogger.info === 'function' ||
520
+ typeof infrastructureLogger.warn === 'function' ||
521
+ typeof infrastructureLogger.error === 'function')) {
522
+ loggerInstance.setDelegate(infrastructureLogger);
523
+ }
524
+ }
525
+ catch {
526
+ // If the bundler throws (older versions), fall back to default console logger.
527
+ loggerInstance.setDelegate(undefined);
528
+ }
529
+ }
412
530
  const logger = createLogger(PREFIX);
531
+ const infrastructureLogger = createInfrastructureLogger(PREFIX);
413
532
 
414
533
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
415
534
  async function safeWrapper(callback, disableWarn) {
416
535
  try {
417
536
  const res = await callback();
418
537
  return res;
419
- } catch (e) {
538
+ }
539
+ catch (e) {
420
540
  !disableWarn && warn(e);
421
541
  return;
422
542
  }
@@ -436,7 +556,7 @@ function createScript(info) {
436
556
  let timeout = 20000;
437
557
  let timeoutId;
438
558
  const scripts = document.getElementsByTagName('script');
439
- for(let i = 0; i < scripts.length; i++){
559
+ for (let i = 0; i < scripts.length; i++) {
440
560
  const s = scripts[i];
441
561
  const scriptSrc = s.getAttribute('src');
442
562
  if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
@@ -448,13 +568,14 @@ function createScript(info) {
448
568
  if (!script) {
449
569
  const attrs = info.attrs;
450
570
  script = document.createElement('script');
451
- script.type = (attrs == null ? void 0 : attrs['type']) === 'module' ? 'module' : 'text/javascript';
571
+ script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';
452
572
  let createScriptRes = undefined;
453
573
  if (info.createScriptHook) {
454
574
  createScriptRes = info.createScriptHook(info.url, info.attrs);
455
575
  if (createScriptRes instanceof HTMLScriptElement) {
456
576
  script = createScriptRes;
457
- } else if (typeof createScriptRes === 'object') {
577
+ }
578
+ else if (typeof createScriptRes === 'object') {
458
579
  if ('script' in createScriptRes && createScriptRes.script) {
459
580
  script = createScriptRes.script;
460
581
  }
@@ -467,36 +588,39 @@ function createScript(info) {
467
588
  script.src = info.url;
468
589
  }
469
590
  if (attrs && !createScriptRes) {
470
- Object.keys(attrs).forEach((name)=>{
591
+ Object.keys(attrs).forEach((name) => {
471
592
  if (script) {
472
593
  if (name === 'async' || name === 'defer') {
473
594
  script[name] = attrs[name];
474
- // Attributes that do not exist are considered overridden
475
- } else if (!script.getAttribute(name)) {
595
+ // Attributes that do not exist are considered overridden
596
+ }
597
+ else if (!script.getAttribute(name)) {
476
598
  script.setAttribute(name, attrs[name]);
477
599
  }
478
600
  }
479
601
  });
480
602
  }
481
603
  }
482
- const onScriptComplete = async (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
483
- event)=>{
604
+ const onScriptComplete = async (prev,
605
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
606
+ event) => {
484
607
  clearTimeout(timeoutId);
485
- const onScriptCompleteCallback = ()=>{
486
- if ((event == null ? void 0 : event.type) === 'error') {
487
- (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
488
- } else {
489
- (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
608
+ const onScriptCompleteCallback = () => {
609
+ if (event?.type === 'error') {
610
+ info?.onErrorCallback && info?.onErrorCallback(event);
611
+ }
612
+ else {
613
+ info?.cb && info?.cb();
490
614
  }
491
615
  };
492
616
  // Prevent memory leaks in IE.
493
617
  if (script) {
494
618
  script.onerror = null;
495
619
  script.onload = null;
496
- safeWrapper(()=>{
620
+ safeWrapper(() => {
497
621
  const { needDeleteScript = true } = info;
498
622
  if (needDeleteScript) {
499
- (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
623
+ script?.parentNode && script.parentNode.removeChild(script);
500
624
  }
501
625
  });
502
626
  if (prev && typeof prev === 'function') {
@@ -514,13 +638,10 @@ function createScript(info) {
514
638
  };
515
639
  script.onerror = onScriptComplete.bind(null, script.onerror);
516
640
  script.onload = onScriptComplete.bind(null, script.onload);
517
- timeoutId = setTimeout(()=>{
641
+ timeoutId = setTimeout(() => {
518
642
  onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
519
643
  }, timeout);
520
- return {
521
- script,
522
- needAttach
523
- };
644
+ return { script, needAttach };
524
645
  }
525
646
  function createLink(info) {
526
647
  // <link rel="preload" href="script.js" as="script">
@@ -528,11 +649,13 @@ function createLink(info) {
528
649
  let link = null;
529
650
  let needAttach = true;
530
651
  const links = document.getElementsByTagName('link');
531
- for(let i = 0; i < links.length; i++){
652
+ for (let i = 0; i < links.length; i++) {
532
653
  const l = links[i];
533
654
  const linkHref = l.getAttribute('href');
534
655
  const linkRel = l.getAttribute('rel');
535
- if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs['rel']) {
656
+ if (linkHref &&
657
+ isStaticResourcesEqual(linkHref, info.url) &&
658
+ linkRel === info.attrs['rel']) {
536
659
  link = l;
537
660
  needAttach = false;
538
661
  break;
@@ -550,30 +673,32 @@ function createLink(info) {
550
673
  }
551
674
  }
552
675
  if (attrs && !createLinkRes) {
553
- Object.keys(attrs).forEach((name)=>{
676
+ Object.keys(attrs).forEach((name) => {
554
677
  if (link && !link.getAttribute(name)) {
555
678
  link.setAttribute(name, attrs[name]);
556
679
  }
557
680
  });
558
681
  }
559
682
  }
560
- const onLinkComplete = (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
561
- event)=>{
562
- const onLinkCompleteCallback = ()=>{
563
- if ((event == null ? void 0 : event.type) === 'error') {
564
- (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
565
- } else {
566
- (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
683
+ const onLinkComplete = (prev,
684
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
685
+ event) => {
686
+ const onLinkCompleteCallback = () => {
687
+ if (event?.type === 'error') {
688
+ info?.onErrorCallback && info?.onErrorCallback(event);
689
+ }
690
+ else {
691
+ info?.cb && info?.cb();
567
692
  }
568
693
  };
569
694
  // Prevent memory leaks in IE.
570
695
  if (link) {
571
696
  link.onerror = null;
572
697
  link.onload = null;
573
- safeWrapper(()=>{
698
+ safeWrapper(() => {
574
699
  const { needDeleteLink = true } = info;
575
700
  if (needDeleteLink) {
576
- (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);
701
+ link?.parentNode && link.parentNode.removeChild(link);
577
702
  }
578
703
  });
579
704
  if (prev) {
@@ -587,23 +712,21 @@ function createLink(info) {
587
712
  };
588
713
  link.onerror = onLinkComplete.bind(null, link.onerror);
589
714
  link.onload = onLinkComplete.bind(null, link.onload);
590
- return {
591
- link,
592
- needAttach
593
- };
715
+ return { link, needAttach };
594
716
  }
595
717
  function loadScript(url, info) {
596
718
  const { attrs = {}, createScriptHook } = info;
597
- return new Promise((resolve, reject)=>{
719
+ return new Promise((resolve, reject) => {
598
720
  const { script, needAttach } = createScript({
599
721
  url,
600
722
  cb: resolve,
601
723
  onErrorCallback: reject,
602
- attrs: polyfills._({
603
- fetchpriority: 'high'
604
- }, attrs),
724
+ attrs: {
725
+ fetchpriority: 'high',
726
+ ...attrs,
727
+ },
605
728
  createScriptHook,
606
- needDeleteScript: true
729
+ needDeleteScript: true,
607
730
  });
608
731
  needAttach && document.head.appendChild(script);
609
732
  });
@@ -619,7 +742,9 @@ function importNodeModule(name) {
619
742
  return sdkImportCache.get(name);
620
743
  }
621
744
  const importModule = new Function('name', `return import(name)`);
622
- const promise = importModule(name).then((res)=>res).catch((error)=>{
745
+ const promise = importModule(name)
746
+ .then((res) => res)
747
+ .catch((error) => {
623
748
  console.error(`Error importing module ${name}:`, error);
624
749
  // Remove from cache on error so it can be retried
625
750
  sdkImportCache.delete(name);
@@ -629,12 +754,12 @@ function importNodeModule(name) {
629
754
  sdkImportCache.set(name, promise);
630
755
  return promise;
631
756
  }
632
- const loadNodeFetch = async ()=>{
757
+ const loadNodeFetch = async () => {
633
758
  const fetchModule = await importNodeModule('node-fetch');
634
- return fetchModule.default || fetchModule;
759
+ return (fetchModule.default || fetchModule);
635
760
  };
636
- const lazyLoaderHookFetch = async (input, init, loaderHook)=>{
637
- const hook = (url, init)=>{
761
+ const lazyLoaderHookFetch = async (input, init, loaderHook) => {
762
+ const hook = (url, init) => {
638
763
  return loaderHook.lifecycle.fetch.emit(url, init);
639
764
  };
640
765
  const res = await hook(input, init || {});
@@ -644,116 +769,132 @@ const lazyLoaderHookFetch = async (input, init, loaderHook)=>{
644
769
  }
645
770
  return res;
646
771
  };
647
- const createScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web' ? (url, cb, attrs, loaderHook)=>{
648
- if (loaderHook == null ? void 0 : loaderHook.createScriptHook) {
649
- const hookResult = loaderHook.createScriptHook(url);
650
- if (hookResult && typeof hookResult === 'object' && 'url' in hookResult) {
651
- url = hookResult.url;
652
- }
653
- }
654
- let urlObj;
655
- try {
656
- urlObj = new URL(url);
657
- } catch (e) {
658
- console.error('Error constructing URL:', e);
659
- cb(new Error(`Invalid URL: ${e}`));
660
- return;
661
- }
662
- const getFetch = async ()=>{
663
- if (loaderHook == null ? void 0 : loaderHook.fetch) {
664
- return (input, init)=>lazyLoaderHookFetch(input, init, loaderHook);
772
+ const createScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'
773
+ ? (url, cb, attrs, loaderHook) => {
774
+ if (loaderHook?.createScriptHook) {
775
+ const hookResult = loaderHook.createScriptHook(url);
776
+ if (hookResult &&
777
+ typeof hookResult === 'object' &&
778
+ 'url' in hookResult) {
779
+ url = hookResult.url;
780
+ }
665
781
  }
666
- return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
667
- };
668
- const handleScriptFetch = async (f, urlObj)=>{
782
+ let urlObj;
669
783
  try {
670
- var //@ts-ignore
671
- _vm_constants;
672
- const res = await f(urlObj.href);
673
- const data = await res.text();
674
- const [path, vm] = await Promise.all([
675
- importNodeModule('path'),
676
- importNodeModule('vm')
677
- ]);
678
- const scriptContext = {
679
- exports: {},
680
- module: {
681
- exports: {}
682
- }
683
- };
684
- const urlDirname = urlObj.pathname.split('/').slice(0, -1).join('/');
685
- const filename = path.basename(urlObj.pathname);
686
- var _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER;
687
- const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
688
- filename,
689
- importModuleDynamically: (_vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER = (_vm_constants = vm.constants) == null ? void 0 : _vm_constants.USE_MAIN_CONTEXT_DEFAULT_LOADER) != null ? _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER : importNodeModule
690
- });
691
- script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
692
- const exportedInterface = scriptContext.module.exports || scriptContext.exports;
693
- if (attrs && exportedInterface && attrs['globalName']) {
694
- const container = exportedInterface[attrs['globalName']] || exportedInterface;
695
- cb(undefined, container);
696
- return;
697
- }
698
- cb(undefined, exportedInterface);
699
- } catch (e) {
700
- cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
784
+ urlObj = new URL(url);
701
785
  }
702
- };
703
- getFetch().then(async (f)=>{
704
- if ((attrs == null ? void 0 : attrs['type']) === 'esm' || (attrs == null ? void 0 : attrs['type']) === 'module') {
705
- return loadModule(urlObj.href, {
706
- fetch: f,
707
- vm: await importNodeModule('vm')
708
- }).then(async (module)=>{
709
- await module.evaluate();
710
- cb(undefined, module.namespace);
711
- }).catch((e)=>{
712
- cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
713
- });
786
+ catch (e) {
787
+ console.error('Error constructing URL:', e);
788
+ cb(new Error(`Invalid URL: ${e}`));
789
+ return;
714
790
  }
715
- handleScriptFetch(f, urlObj);
716
- }).catch((err)=>{
717
- cb(err);
718
- });
719
- } : (url, cb, attrs, loaderHook)=>{
720
- cb(new Error('createScriptNode is disabled in non-Node.js environment'));
721
- };
722
- const loadScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web' ? (url, info)=>{
723
- return new Promise((resolve, reject)=>{
724
- createScriptNode(url, (error, scriptContext)=>{
725
- if (error) {
726
- reject(error);
727
- } else {
728
- var _info_attrs, _info_attrs1;
729
- const remoteEntryKey = (info == null ? void 0 : (_info_attrs = info.attrs) == null ? void 0 : _info_attrs['globalName']) || `__FEDERATION_${info == null ? void 0 : (_info_attrs1 = info.attrs) == null ? void 0 : _info_attrs1['name']}:custom__`;
730
- const entryExports = globalThis[remoteEntryKey] = scriptContext;
731
- resolve(entryExports);
791
+ const getFetch = async () => {
792
+ if (loaderHook?.fetch) {
793
+ return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
732
794
  }
733
- }, info.attrs, info.loaderHook);
734
- });
735
- } : (url, info)=>{
736
- throw new Error('loadScriptNode is disabled in non-Node.js environment');
737
- };
795
+ return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
796
+ };
797
+ const handleScriptFetch = async (f, urlObj) => {
798
+ try {
799
+ const res = await f(urlObj.href);
800
+ const data = await res.text();
801
+ const [path, vm] = await Promise.all([
802
+ importNodeModule('path'),
803
+ importNodeModule('vm'),
804
+ ]);
805
+ const scriptContext = { exports: {}, module: { exports: {} } };
806
+ const urlDirname = urlObj.pathname
807
+ .split('/')
808
+ .slice(0, -1)
809
+ .join('/');
810
+ const filename = path.basename(urlObj.pathname);
811
+ const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
812
+ filename,
813
+ importModuleDynamically:
814
+ //@ts-ignore
815
+ vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??
816
+ importNodeModule,
817
+ });
818
+ script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
819
+ const exportedInterface = scriptContext.module.exports || scriptContext.exports;
820
+ if (attrs && exportedInterface && attrs['globalName']) {
821
+ const container = exportedInterface[attrs['globalName']] || exportedInterface;
822
+ cb(undefined, container);
823
+ return;
824
+ }
825
+ cb(undefined, exportedInterface);
826
+ }
827
+ catch (e) {
828
+ cb(e instanceof Error
829
+ ? e
830
+ : new Error(`Script execution error: ${e}`));
831
+ }
832
+ };
833
+ getFetch()
834
+ .then(async (f) => {
835
+ if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {
836
+ return loadModule(urlObj.href, {
837
+ fetch: f,
838
+ vm: await importNodeModule('vm'),
839
+ })
840
+ .then(async (module) => {
841
+ await module.evaluate();
842
+ cb(undefined, module.namespace);
843
+ })
844
+ .catch((e) => {
845
+ cb(e instanceof Error
846
+ ? e
847
+ : new Error(`Script execution error: ${e}`));
848
+ });
849
+ }
850
+ handleScriptFetch(f, urlObj);
851
+ })
852
+ .catch((err) => {
853
+ cb(err);
854
+ });
855
+ }
856
+ : (url, cb, attrs, loaderHook) => {
857
+ cb(new Error('createScriptNode is disabled in non-Node.js environment'));
858
+ };
859
+ const loadScriptNode = typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'
860
+ ? (url, info) => {
861
+ return new Promise((resolve, reject) => {
862
+ createScriptNode(url, (error, scriptContext) => {
863
+ if (error) {
864
+ reject(error);
865
+ }
866
+ else {
867
+ const remoteEntryKey = info?.attrs?.['globalName'] ||
868
+ `__FEDERATION_${info?.attrs?.['name']}:custom__`;
869
+ const entryExports = (globalThis[remoteEntryKey] =
870
+ scriptContext);
871
+ resolve(entryExports);
872
+ }
873
+ }, info.attrs, info.loaderHook);
874
+ });
875
+ }
876
+ : (url, info) => {
877
+ throw new Error('loadScriptNode is disabled in non-Node.js environment');
878
+ };
738
879
  const esmModuleCache = new Map();
739
880
  async function loadModule(url, options) {
740
881
  // Check cache to prevent infinite recursion in ESM loading
741
882
  if (esmModuleCache.has(url)) {
742
883
  return esmModuleCache.get(url);
743
884
  }
744
- const { fetch: fetch1, vm } = options;
745
- const response = await fetch1(url);
885
+ const { fetch, vm } = options;
886
+ const response = await fetch(url);
746
887
  const code = await response.text();
747
888
  const module = new vm.SourceTextModule(code, {
748
889
  // @ts-ignore
749
- importModuleDynamically: async (specifier, script)=>{
890
+ importModuleDynamically: async (specifier, script) => {
750
891
  const resolvedUrl = new URL(specifier, url).href;
751
892
  return loadModule(resolvedUrl, options);
752
- }
893
+ },
753
894
  });
754
895
  // Cache the module before linking to prevent cycles
755
896
  esmModuleCache.set(url, module);
756
- await module.link(async (specifier)=>{
897
+ await module.link(async (specifier) => {
757
898
  const resolvedUrl = new URL(specifier, url).href;
758
899
  const module = await loadModule(resolvedUrl, options);
759
900
  return module;
@@ -762,14 +903,15 @@ async function loadModule(url, options) {
762
903
  }
763
904
 
764
905
  function normalizeOptions(enableDefault, defaultOptions, key) {
765
- return function(options) {
906
+ return function (options) {
766
907
  if (options === false) {
767
908
  return false;
768
909
  }
769
910
  if (typeof options === 'undefined') {
770
911
  if (enableDefault) {
771
912
  return defaultOptions;
772
- } else {
913
+ }
914
+ else {
773
915
  return false;
774
916
  }
775
917
  }
@@ -777,13 +919,16 @@ function normalizeOptions(enableDefault, defaultOptions, key) {
777
919
  return defaultOptions;
778
920
  }
779
921
  if (options && typeof options === 'object') {
780
- return polyfills._({}, defaultOptions, options);
922
+ return {
923
+ ...defaultOptions,
924
+ ...options,
925
+ };
781
926
  }
782
927
  throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
783
928
  };
784
929
  }
785
930
 
786
- const createModuleFederationConfig = (options)=>{
931
+ const createModuleFederationConfig = (options) => {
787
932
  return options;
788
933
  };
789
934
 
@@ -802,9 +947,11 @@ exports.SEPARATOR = SEPARATOR;
802
947
  exports.StatsFileName = StatsFileName;
803
948
  exports.TEMP_DIR = TEMP_DIR;
804
949
  exports.assert = assert;
950
+ exports.bindLoggerToCompiler = bindLoggerToCompiler;
805
951
  exports.composeKeyWithSeparator = composeKeyWithSeparator;
806
952
  exports.containerPlugin = ContainerPlugin;
807
953
  exports.containerReferencePlugin = ContainerReferencePlugin;
954
+ exports.createInfrastructureLogger = createInfrastructureLogger;
808
955
  exports.createLink = createLink;
809
956
  exports.createLogger = createLogger;
810
957
  exports.createModuleFederationConfig = createModuleFederationConfig;
@@ -819,6 +966,7 @@ exports.generateSnapshotFromManifest = generateSnapshotFromManifest;
819
966
  exports.getProcessEnv = getProcessEnv;
820
967
  exports.getResourceUrl = getResourceUrl;
821
968
  exports.inferAutoPublicPath = inferAutoPublicPath;
969
+ exports.infrastructureLogger = infrastructureLogger;
822
970
  exports.isBrowserEnv = isBrowserEnv;
823
971
  exports.isDebugMode = isDebugMode;
824
972
  exports.isManifestProvider = isManifestProvider;