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