@module-federation/sdk 0.3.0 → 0.3.2

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 (40) hide show
  1. package/README.md +99 -0
  2. package/dist/LICENSE +21 -0
  3. package/dist/index.cjs.js +749 -0
  4. package/dist/index.esm.js +701 -0
  5. package/dist/normalize-webpack-path.cjs.js +48 -0
  6. package/dist/normalize-webpack-path.esm.js +39 -0
  7. package/dist/package.json +44 -0
  8. package/{src → dist/src}/constant.d.ts +9 -0
  9. package/dist/src/dom.d.ts +30 -0
  10. package/{src → dist/src}/generateSnapshotFromManifest.d.ts +1 -0
  11. package/dist/src/index.d.ts +9 -0
  12. package/dist/src/node.d.ts +5 -0
  13. package/{src → dist/src}/normalize-webpack-path.d.ts +3 -1
  14. package/dist/src/normalizeOptions.d.ts +1 -0
  15. package/{src → dist/src}/types/index.d.ts +1 -0
  16. package/dist/src/types/plugins/ContainerPlugin.d.ts +159 -0
  17. package/dist/src/types/plugins/ContainerReferencePlugin.d.ts +52 -0
  18. package/dist/src/types/plugins/ModuleFederationPlugin.d.ts +334 -0
  19. package/dist/src/types/plugins/SharePlugin.d.ts +71 -0
  20. package/dist/src/types/plugins/index.d.ts +4 -0
  21. package/{src → dist/src}/types/snapshot.d.ts +7 -0
  22. package/{src → dist/src}/types/stats.d.ts +15 -5
  23. package/{src → dist/src}/utils.d.ts +1 -1
  24. package/package.json +14 -11
  25. package/index.cjs.default.js +0 -1
  26. package/index.cjs.js +0 -793
  27. package/index.cjs.mjs +0 -2
  28. package/index.esm.js +0 -761
  29. package/normalize-webpack-path.cjs.default.js +0 -1
  30. package/normalize-webpack-path.cjs.js +0 -42
  31. package/normalize-webpack-path.cjs.mjs +0 -2
  32. package/normalize-webpack-path.esm.js +0 -33
  33. package/src/dom.d.ts +0 -10
  34. package/src/index.d.ts +0 -7
  35. /package/{index.cjs.d.ts → dist/index.cjs.d.ts} +0 -0
  36. /package/{normalize-webpack-path.cjs.d.ts → dist/normalize-webpack-path.cjs.d.ts} +0 -0
  37. /package/{src → dist/src}/env.d.ts +0 -0
  38. /package/{src → dist/src}/logger.d.ts +0 -0
  39. /package/{src → dist/src}/types/common.d.ts +0 -0
  40. /package/{src → dist/src}/types/manifest.d.ts +0 -0
@@ -0,0 +1,701 @@
1
+ const FederationModuleManifest = 'federation-manifest.json';
2
+ const MANIFEST_EXT = '.json';
3
+ const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';
4
+ const BROWSER_LOG_VALUE = '1';
5
+ const NameTransformSymbol = {
6
+ AT: '@',
7
+ HYPHEN: '-',
8
+ SLASH: '/'
9
+ };
10
+ const NameTransformMap = {
11
+ [NameTransformSymbol.AT]: 'scope_',
12
+ [NameTransformSymbol.HYPHEN]: '_',
13
+ [NameTransformSymbol.SLASH]: '__'
14
+ };
15
+ const EncodedNameTransformMap = {
16
+ [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
17
+ [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
18
+ [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
19
+ };
20
+ const SEPARATOR = ':';
21
+ const ManifestFileName = 'mf-manifest.json';
22
+ const StatsFileName = 'mf-stats.json';
23
+ const MFModuleType = {
24
+ NPM: 'npm',
25
+ APP: 'app'
26
+ };
27
+ const MODULE_DEVTOOL_IDENTIFIER = '__MF_DEVTOOLS_MODULE_INFO__';
28
+ const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';
29
+ const TEMP_DIR = '.federation';
30
+
31
+ var ContainerPlugin = /*#__PURE__*/Object.freeze({
32
+ __proto__: null
33
+ });
34
+
35
+ var ContainerReferencePlugin = /*#__PURE__*/Object.freeze({
36
+ __proto__: null
37
+ });
38
+
39
+ var ModuleFederationPlugin = /*#__PURE__*/Object.freeze({
40
+ __proto__: null
41
+ });
42
+
43
+ var SharePlugin = /*#__PURE__*/Object.freeze({
44
+ __proto__: null
45
+ });
46
+
47
+ function isBrowserEnv() {
48
+ return typeof window !== 'undefined';
49
+ }
50
+ function isDebugMode() {
51
+ if (typeof process !== 'undefined' && process.env && process.env['FEDERATION_DEBUG']) {
52
+ return Boolean(process.env['FEDERATION_DEBUG']);
53
+ }
54
+ return typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG);
55
+ }
56
+ const getProcessEnv = function() {
57
+ return typeof process !== 'undefined' && process.env ? process.env : {};
58
+ };
59
+
60
+ function safeToString(info) {
61
+ try {
62
+ return JSON.stringify(info, null, 2);
63
+ } catch (e) {
64
+ return '';
65
+ }
66
+ }
67
+ const DEBUG_LOG = '[ FEDERATION DEBUG ]';
68
+ function safeGetLocalStorageItem() {
69
+ try {
70
+ if (typeof window !== 'undefined' && window.localStorage) {
71
+ return localStorage.getItem(BROWSER_LOG_KEY) === BROWSER_LOG_VALUE;
72
+ }
73
+ } catch (error) {
74
+ return typeof document !== 'undefined';
75
+ }
76
+ return false;
77
+ }
78
+ let Logger = class Logger {
79
+ info(msg, info) {
80
+ if (this.enable) {
81
+ const argsToString = safeToString(info) || '';
82
+ if (isBrowserEnv()) {
83
+ console.info(`%c ${this.identifier}: ${msg} ${argsToString}`, 'color:#3300CC');
84
+ } else {
85
+ console.info('\x1b[34m%s', `${this.identifier}: ${msg} ${argsToString ? `\n${argsToString}` : ''}`);
86
+ }
87
+ }
88
+ }
89
+ logOriginalInfo(...args) {
90
+ if (this.enable) {
91
+ if (isBrowserEnv()) {
92
+ console.info(`%c ${this.identifier}: OriginalInfo`, 'color:#3300CC');
93
+ console.log(...args);
94
+ } else {
95
+ console.info(`%c ${this.identifier}: OriginalInfo`, 'color:#3300CC');
96
+ console.log(...args);
97
+ }
98
+ }
99
+ }
100
+ constructor(identifier){
101
+ this.enable = false;
102
+ this.identifier = identifier || DEBUG_LOG;
103
+ if (isBrowserEnv() && safeGetLocalStorageItem()) {
104
+ this.enable = true;
105
+ } else if (isDebugMode()) {
106
+ this.enable = true;
107
+ }
108
+ }
109
+ };
110
+
111
+ const LOG_CATEGORY = '[ Federation Runtime ]';
112
+ // entry: name:version version : 1.0.0 | ^1.2.3
113
+ // entry: name:entry entry: https://localhost:9000/federation-manifest.json
114
+ const parseEntry = (str, devVerOrUrl, separator = SEPARATOR)=>{
115
+ const strSplit = str.split(separator);
116
+ const devVersionOrUrl = getProcessEnv()['NODE_ENV'] === 'development' && devVerOrUrl;
117
+ const defaultVersion = '*';
118
+ const isEntry = (s)=>s.startsWith('http') || s.includes(MANIFEST_EXT);
119
+ // Check if the string starts with a type
120
+ if (strSplit.length >= 2) {
121
+ let [name, ...versionOrEntryArr] = strSplit;
122
+ if (str.startsWith(separator)) {
123
+ versionOrEntryArr = [
124
+ devVersionOrUrl || strSplit.slice(-1)[0]
125
+ ];
126
+ name = strSplit.slice(0, -1).join(separator);
127
+ }
128
+ let versionOrEntry = devVersionOrUrl || versionOrEntryArr.join(separator);
129
+ if (isEntry(versionOrEntry)) {
130
+ return {
131
+ name,
132
+ entry: versionOrEntry
133
+ };
134
+ } else {
135
+ // Apply version rule
136
+ // devVersionOrUrl => inputVersion => defaultVersion
137
+ return {
138
+ name,
139
+ version: versionOrEntry || defaultVersion
140
+ };
141
+ }
142
+ } else if (strSplit.length === 1) {
143
+ const [name] = strSplit;
144
+ if (devVersionOrUrl && isEntry(devVersionOrUrl)) {
145
+ return {
146
+ name,
147
+ entry: devVersionOrUrl
148
+ };
149
+ }
150
+ return {
151
+ name,
152
+ version: devVersionOrUrl || defaultVersion
153
+ };
154
+ } else {
155
+ throw `Invalid entry value: ${str}`;
156
+ }
157
+ };
158
+ const logger = new Logger();
159
+ const composeKeyWithSeparator = function(...args) {
160
+ if (!args.length) {
161
+ return '';
162
+ }
163
+ return args.reduce((sum, cur)=>{
164
+ if (!cur) {
165
+ return sum;
166
+ }
167
+ if (!sum) {
168
+ return cur;
169
+ }
170
+ return `${sum}${SEPARATOR}${cur}`;
171
+ }, '');
172
+ };
173
+ const encodeName = function(name, prefix = '', withExt = false) {
174
+ try {
175
+ const ext = withExt ? '.js' : '';
176
+ 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}`;
177
+ } catch (err) {
178
+ throw err;
179
+ }
180
+ };
181
+ const decodeName = function(name, prefix, withExt) {
182
+ try {
183
+ let decodedName = name;
184
+ if (prefix) {
185
+ if (!decodedName.startsWith(prefix)) {
186
+ return decodedName;
187
+ }
188
+ decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');
189
+ }
190
+ 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
+ if (withExt) {
192
+ decodedName = decodedName.replace('.js', '');
193
+ }
194
+ return decodedName;
195
+ } catch (err) {
196
+ throw err;
197
+ }
198
+ };
199
+ const generateExposeFilename = (exposeName, withExt)=>{
200
+ if (!exposeName) {
201
+ return '';
202
+ }
203
+ let expose = exposeName;
204
+ if (expose === '.') {
205
+ expose = 'default_export';
206
+ }
207
+ if (expose.startsWith('./')) {
208
+ expose = expose.replace('./', '');
209
+ }
210
+ return encodeName(expose, '__federation_expose_', withExt);
211
+ };
212
+ const generateShareFilename = (pkgName, withExt)=>{
213
+ if (!pkgName) {
214
+ return '';
215
+ }
216
+ return encodeName(pkgName, '__federation_shared_', withExt);
217
+ };
218
+ const getResourceUrl = (module, sourceUrl)=>{
219
+ if ('getPublicPath' in module) {
220
+ let publicPath;
221
+ if (!module.getPublicPath.startsWith('function')) {
222
+ publicPath = new Function(module.getPublicPath)();
223
+ } else {
224
+ publicPath = new Function('return ' + module.getPublicPath)()();
225
+ }
226
+ return `${publicPath}${sourceUrl}`;
227
+ } else if ('publicPath' in module) {
228
+ return `${module.publicPath}${sourceUrl}`;
229
+ } else {
230
+ console.warn('Cannot get resource URL. If in debug mode, please ignore.', module, sourceUrl);
231
+ return '';
232
+ }
233
+ };
234
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
235
+ const assert = (condition, msg)=>{
236
+ if (!condition) {
237
+ error(msg);
238
+ }
239
+ };
240
+ const error = (msg)=>{
241
+ throw new Error(`${LOG_CATEGORY}: ${msg}`);
242
+ };
243
+ const warn = (msg)=>{
244
+ console.warn(`${LOG_CATEGORY}: ${msg}`);
245
+ };
246
+
247
+ function _extends() {
248
+ _extends = Object.assign || function assign(target) {
249
+ for(var i = 1; i < arguments.length; i++){
250
+ var source = arguments[i];
251
+ for(var key in source)if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
252
+ }
253
+ return target;
254
+ };
255
+ return _extends.apply(this, arguments);
256
+ }
257
+
258
+ const simpleJoinRemoteEntry = (rPath, rName)=>{
259
+ if (!rPath) {
260
+ return rName;
261
+ }
262
+ const transformPath = (str)=>{
263
+ if (str === '.') {
264
+ return '';
265
+ }
266
+ if (str.startsWith('./')) {
267
+ return str.replace('./', '');
268
+ }
269
+ if (str.startsWith('/')) {
270
+ const strWithoutSlash = str.slice(1);
271
+ if (strWithoutSlash.endsWith('/')) {
272
+ return strWithoutSlash.slice(0, -1);
273
+ }
274
+ return strWithoutSlash;
275
+ }
276
+ return str;
277
+ };
278
+ const transformedPath = transformPath(rPath);
279
+ if (!transformedPath) {
280
+ return rName;
281
+ }
282
+ if (transformedPath.endsWith('/')) {
283
+ return `${transformedPath}${rName}`;
284
+ }
285
+ return `${transformedPath}/${rName}`;
286
+ };
287
+ function inferAutoPublicPath(url) {
288
+ return url.replace(/#.*$/, '').replace(/\?.*$/, '').replace(/\/[^\/]+$/, '/');
289
+ }
290
+ // Priority: overrides > remotes
291
+ // eslint-disable-next-line max-lines-per-function
292
+ function generateSnapshotFromManifest(manifest, options = {}) {
293
+ var _manifest_metaData, _manifest_metaData1;
294
+ const { remotes = {}, overrides = {}, version } = options;
295
+ let remoteSnapshot;
296
+ const getPublicPath = ()=>{
297
+ if ('publicPath' in manifest.metaData) {
298
+ if (manifest.metaData.publicPath === 'auto' && version) {
299
+ // use same implementation as publicPath auto runtime module implements
300
+ return inferAutoPublicPath(version);
301
+ }
302
+ return manifest.metaData.publicPath;
303
+ } else {
304
+ return manifest.metaData.getPublicPath;
305
+ }
306
+ };
307
+ const overridesKeys = Object.keys(overrides);
308
+ let remotesInfo = {};
309
+ // If remotes are not provided, only the remotes in the manifest will be read
310
+ if (!Object.keys(remotes).length) {
311
+ var _manifest_remotes;
312
+ remotesInfo = ((_manifest_remotes = manifest.remotes) == null ? void 0 : _manifest_remotes.reduce((res, next)=>{
313
+ let matchedVersion;
314
+ const name = next.federationContainerName;
315
+ // overrides have higher priority
316
+ if (overridesKeys.includes(name)) {
317
+ matchedVersion = overrides[name];
318
+ } else {
319
+ if ('version' in next) {
320
+ matchedVersion = next.version;
321
+ } else {
322
+ matchedVersion = next.entry;
323
+ }
324
+ }
325
+ res[name] = {
326
+ matchedVersion
327
+ };
328
+ return res;
329
+ }, {})) || {};
330
+ }
331
+ // If remotes (deploy scenario) are specified, they need to be traversed again
332
+ Object.keys(remotes).forEach((key)=>remotesInfo[key] = {
333
+ // overrides will override dependencies
334
+ matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
335
+ });
336
+ const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes, 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 == null ? void 0 : manifest.shared.map((item)=>({
349
+ assets: item.assets,
350
+ sharedName: item.name,
351
+ version: item.version
352
+ })),
353
+ modules: exposes == null ? void 0 : exposes.map((expose)=>({
354
+ moduleName: expose.name,
355
+ modulePath: expose.path,
356
+ assets: expose.assets
357
+ }))
358
+ };
359
+ if ((_manifest_metaData = manifest.metaData) == null ? void 0 : _manifest_metaData.prefetchInterface) {
360
+ const prefetchInterface = manifest.metaData.prefetchInterface;
361
+ basicRemoteSnapshot = _extends({}, basicRemoteSnapshot, {
362
+ prefetchInterface
363
+ });
364
+ }
365
+ if ((_manifest_metaData1 = manifest.metaData) == null ? void 0 : _manifest_metaData1.prefetchEntry) {
366
+ const { path, name, type } = manifest.metaData.prefetchEntry;
367
+ basicRemoteSnapshot = _extends({}, basicRemoteSnapshot, {
368
+ prefetchEntry: simpleJoinRemoteEntry(path, name),
369
+ prefetchEntryType: type
370
+ });
371
+ }
372
+ if ('publicPath' in manifest.metaData) {
373
+ remoteSnapshot = _extends({}, basicRemoteSnapshot, {
374
+ publicPath: getPublicPath()
375
+ });
376
+ } else {
377
+ remoteSnapshot = _extends({}, basicRemoteSnapshot, {
378
+ getPublicPath: getPublicPath()
379
+ });
380
+ }
381
+ if (ssrRemoteEntry) {
382
+ const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
383
+ remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
384
+ remoteSnapshot.ssrRemoteEntryType = 'commonjs-module';
385
+ }
386
+ return remoteSnapshot;
387
+ }
388
+ function isManifestProvider(moduleInfo) {
389
+ if ('remoteEntry' in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
390
+ return true;
391
+ } else {
392
+ return false;
393
+ }
394
+ }
395
+
396
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
397
+ async function safeWrapper(callback, disableWarn) {
398
+ try {
399
+ const res = await callback();
400
+ return res;
401
+ } catch (e) {
402
+ !disableWarn && warn(e);
403
+ return;
404
+ }
405
+ }
406
+ function isStaticResourcesEqual(url1, url2) {
407
+ const REG_EXP = /^(https?:)?\/\//i;
408
+ // Transform url1 and url2 into relative paths
409
+ const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
410
+ const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
411
+ // Check if the relative paths are identical
412
+ return relativeUrl1 === relativeUrl2;
413
+ }
414
+ function createScript(info) {
415
+ // Retrieve the existing script element by its src attribute
416
+ let script = null;
417
+ let needAttach = true;
418
+ let timeout = 20000;
419
+ let timeoutId;
420
+ const scripts = document.getElementsByTagName('script');
421
+ for(let i = 0; i < scripts.length; i++){
422
+ const s = scripts[i];
423
+ const scriptSrc = s.getAttribute('src');
424
+ if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
425
+ script = s;
426
+ needAttach = false;
427
+ break;
428
+ }
429
+ }
430
+ if (!script) {
431
+ script = document.createElement('script');
432
+ script.type = 'text/javascript';
433
+ script.src = info.url;
434
+ if (info.createScriptHook) {
435
+ const createScriptRes = info.createScriptHook(info.url, info.attrs);
436
+ if (createScriptRes instanceof HTMLScriptElement) {
437
+ script = createScriptRes;
438
+ } else if (typeof createScriptRes === 'object') {
439
+ if (createScriptRes.script) script = createScriptRes.script;
440
+ if (createScriptRes.timeout) timeout = createScriptRes.timeout;
441
+ }
442
+ }
443
+ const attrs = info.attrs;
444
+ if (attrs) {
445
+ Object.keys(attrs).forEach((name)=>{
446
+ if (script) {
447
+ if (name === 'async' || name === 'defer') {
448
+ script[name] = attrs[name];
449
+ // Attributes that do not exist are considered overridden
450
+ } else if (!script.getAttribute(name)) {
451
+ script.setAttribute(name, attrs[name]);
452
+ }
453
+ }
454
+ });
455
+ }
456
+ }
457
+ const onScriptComplete = (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
458
+ event)=>{
459
+ var _info_cb;
460
+ clearTimeout(timeoutId);
461
+ // Prevent memory leaks in IE.
462
+ if (script) {
463
+ script.onerror = null;
464
+ script.onload = null;
465
+ safeWrapper(()=>{
466
+ const { needDeleteScript = true } = info;
467
+ if (needDeleteScript) {
468
+ (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
469
+ }
470
+ });
471
+ if (prev) {
472
+ var _info_cb1;
473
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
474
+ const res = prev(event);
475
+ info == null ? void 0 : (_info_cb1 = info.cb) == null ? void 0 : _info_cb1.call(info);
476
+ return res;
477
+ }
478
+ }
479
+ info == null ? void 0 : (_info_cb = info.cb) == null ? void 0 : _info_cb.call(info);
480
+ };
481
+ script.onerror = onScriptComplete.bind(null, script.onerror);
482
+ script.onload = onScriptComplete.bind(null, script.onload);
483
+ timeoutId = setTimeout(()=>{
484
+ onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
485
+ }, timeout);
486
+ return {
487
+ script,
488
+ needAttach
489
+ };
490
+ }
491
+ function createLink(info) {
492
+ // <link rel="preload" href="script.js" as="script">
493
+ // Retrieve the existing script element by its src attribute
494
+ let link = null;
495
+ let needAttach = true;
496
+ const links = document.getElementsByTagName('link');
497
+ for(let i = 0; i < links.length; i++){
498
+ const l = links[i];
499
+ const linkHref = l.getAttribute('href');
500
+ const linkRef = l.getAttribute('ref');
501
+ if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRef === info.attrs['ref']) {
502
+ link = l;
503
+ needAttach = false;
504
+ break;
505
+ }
506
+ }
507
+ if (!link) {
508
+ link = document.createElement('link');
509
+ link.setAttribute('href', info.url);
510
+ if (info.createLinkHook) {
511
+ const createLinkRes = info.createLinkHook(info.url);
512
+ if (createLinkRes instanceof HTMLLinkElement) {
513
+ link = createLinkRes;
514
+ }
515
+ }
516
+ const attrs = info.attrs;
517
+ if (attrs) {
518
+ Object.keys(attrs).forEach((name)=>{
519
+ if (link && !link.getAttribute(name)) {
520
+ link.setAttribute(name, attrs[name]);
521
+ }
522
+ });
523
+ }
524
+ }
525
+ const onLinkComplete = (prev, // eslint-disable-next-line @typescript-eslint/no-explicit-any
526
+ event)=>{
527
+ // Prevent memory leaks in IE.
528
+ if (link) {
529
+ link.onerror = null;
530
+ link.onload = null;
531
+ safeWrapper(()=>{
532
+ const { needDeleteLink = true } = info;
533
+ if (needDeleteLink) {
534
+ (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);
535
+ }
536
+ });
537
+ if (prev) {
538
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
539
+ const res = prev(event);
540
+ info.cb();
541
+ return res;
542
+ }
543
+ }
544
+ info.cb();
545
+ };
546
+ link.onerror = onLinkComplete.bind(null, link.onerror);
547
+ link.onload = onLinkComplete.bind(null, link.onload);
548
+ return {
549
+ link,
550
+ needAttach
551
+ };
552
+ }
553
+ function loadScript(url, info) {
554
+ const { attrs = {}, createScriptHook } = info;
555
+ return new Promise((resolve, _reject)=>{
556
+ const { script, needAttach } = createScript({
557
+ url,
558
+ cb: resolve,
559
+ attrs: _extends({
560
+ fetchpriority: 'high'
561
+ }, attrs),
562
+ createScriptHook,
563
+ needDeleteScript: true
564
+ });
565
+ needAttach && document.head.appendChild(script);
566
+ });
567
+ }
568
+
569
+ function importNodeModule(name) {
570
+ if (!name) {
571
+ throw new Error('import specifier is required');
572
+ }
573
+ const importModule = new Function('name', `return import(name)`);
574
+ return importModule(name).then((res)=>res).catch((error)=>{
575
+ console.error(`Error importing module ${name}:`, error);
576
+ throw error;
577
+ });
578
+ }
579
+ const loadNodeFetch = async ()=>{
580
+ const fetchModule = await importNodeModule('node-fetch');
581
+ return fetchModule.default || fetchModule;
582
+ };
583
+ const lazyLoaderHookFetch = async (input, init)=>{
584
+ // @ts-ignore
585
+ const loaderHooks = __webpack_require__.federation.instance.loaderHook;
586
+ const hook = (url, init)=>{
587
+ return loaderHooks.lifecycle.fetch.emit(url, init);
588
+ };
589
+ const res = await hook(input, init || {});
590
+ if (!res || !(res instanceof Response)) {
591
+ const fetchFunction = typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;
592
+ return fetchFunction(input, init || {});
593
+ }
594
+ return res;
595
+ };
596
+ function createScriptNode(url, cb, attrs, createScriptHook) {
597
+ if (createScriptHook) {
598
+ const hookResult = createScriptHook(url);
599
+ if (hookResult && typeof hookResult === 'object' && 'url' in hookResult) {
600
+ url = hookResult.url;
601
+ }
602
+ }
603
+ let urlObj;
604
+ try {
605
+ urlObj = new URL(url);
606
+ } catch (e) {
607
+ console.error('Error constructing URL:', e);
608
+ cb(new Error(`Invalid URL: ${e}`));
609
+ return;
610
+ }
611
+ const getFetch = async ()=>{
612
+ //@ts-ignore
613
+ if (typeof __webpack_require__ !== 'undefined') {
614
+ try {
615
+ //@ts-ignore
616
+ const loaderHooks = __webpack_require__.federation.instance.loaderHook;
617
+ if (loaderHooks.lifecycle.fetch) {
618
+ return lazyLoaderHookFetch;
619
+ }
620
+ } catch (e) {
621
+ console.warn('federation.instance.loaderHook.lifecycle.fetch failed:', e);
622
+ }
623
+ }
624
+ return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
625
+ };
626
+ const handleScriptFetch = async (f, urlObj)=>{
627
+ try {
628
+ var _vm_constants;
629
+ const res = await f(urlObj.href);
630
+ const data = await res.text();
631
+ const [path, vm] = await Promise.all([
632
+ importNodeModule('path'),
633
+ importNodeModule('vm')
634
+ ]);
635
+ const scriptContext = {
636
+ exports: {},
637
+ module: {
638
+ exports: {}
639
+ }
640
+ };
641
+ const urlDirname = urlObj.pathname.split('/').slice(0, -1).join('/');
642
+ const filename = path.basename(urlObj.pathname);
643
+ var _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER;
644
+ const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
645
+ filename,
646
+ 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
647
+ });
648
+ script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
649
+ const exportedInterface = scriptContext.module.exports || scriptContext.exports;
650
+ if (attrs && exportedInterface && attrs['globalName']) {
651
+ const container = exportedInterface[attrs['globalName']] || exportedInterface;
652
+ cb(undefined, container);
653
+ return;
654
+ }
655
+ cb(undefined, exportedInterface);
656
+ } catch (e) {
657
+ cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
658
+ }
659
+ };
660
+ getFetch().then((f)=>handleScriptFetch(f, urlObj)).catch((err)=>{
661
+ cb(err);
662
+ });
663
+ }
664
+ function loadScriptNode(url, info) {
665
+ return new Promise((resolve, reject)=>{
666
+ createScriptNode(url, (error, scriptContext)=>{
667
+ if (error) {
668
+ reject(error);
669
+ } else {
670
+ var _info_attrs, _info_attrs1;
671
+ 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__`;
672
+ const entryExports = globalThis[remoteEntryKey] = scriptContext;
673
+ resolve(entryExports);
674
+ }
675
+ }, info.attrs, info.createScriptHook);
676
+ });
677
+ }
678
+
679
+ function normalizeOptions(enableDefault, defaultOptions, key) {
680
+ return function(options) {
681
+ if (options === false) {
682
+ return false;
683
+ }
684
+ if (typeof options === 'undefined') {
685
+ if (enableDefault) {
686
+ return defaultOptions;
687
+ } else {
688
+ return false;
689
+ }
690
+ }
691
+ if (options === true) {
692
+ return defaultOptions;
693
+ }
694
+ if (options && typeof options === 'object') {
695
+ return _extends({}, defaultOptions, options);
696
+ }
697
+ throw new Error(`Unexpected type for \`${key}\`, expect boolean/undefined/object, got: ${typeof options}`);
698
+ };
699
+ }
700
+
701
+ export { BROWSER_LOG_KEY, BROWSER_LOG_VALUE, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, Logger, MANIFEST_EXT, MFModuleType, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, assert, composeKeyWithSeparator, ContainerPlugin as containerPlugin, ContainerReferencePlugin as containerReferencePlugin, createLink, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getProcessEnv, getResourceUrl, inferAutoPublicPath, isBrowserEnv, isDebugMode, isManifestProvider, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin as moduleFederationPlugin, normalizeOptions, parseEntry, safeWrapper, SharePlugin as sharePlugin, simpleJoinRemoteEntry, warn };