@module-federation/webpack-bundler-runtime 0.0.0-next-20240830062908 → 0.0.0-next-20240830100524

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,3511 +0,0 @@
1
- import { _ } from '@swc/helpers/_/_extends';
2
- import { _ as _$1 } from '@swc/helpers/_/_object_without_properties_loose';
3
-
4
- const MANIFEST_EXT = '.json';
5
- const BROWSER_LOG_KEY = 'FEDERATION_DEBUG';
6
- const BROWSER_LOG_VALUE = '1';
7
- const NameTransformSymbol = {
8
- AT: '@',
9
- HYPHEN: '-',
10
- SLASH: '/'
11
- };
12
- const NameTransformMap = {
13
- [NameTransformSymbol.AT]: 'scope_',
14
- [NameTransformSymbol.HYPHEN]: '_',
15
- [NameTransformSymbol.SLASH]: '__'
16
- };
17
- const EncodedNameTransformMap = {
18
- [NameTransformMap[NameTransformSymbol.AT]]: NameTransformSymbol.AT,
19
- [NameTransformMap[NameTransformSymbol.HYPHEN]]: NameTransformSymbol.HYPHEN,
20
- [NameTransformMap[NameTransformSymbol.SLASH]]: NameTransformSymbol.SLASH
21
- };
22
- const SEPARATOR = ':';
23
- const ENCODE_NAME_PREFIX = 'ENCODE_NAME_PREFIX';
24
- function isBrowserEnv() {
25
- return typeof window !== 'undefined';
26
- }
27
- function isDebugMode() {
28
- if (typeof process !== 'undefined' && process.env && process.env['FEDERATION_DEBUG']) {
29
- return Boolean(process.env['FEDERATION_DEBUG']);
30
- }
31
- return typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG);
32
- }
33
- const DEBUG_LOG = '[ FEDERATION DEBUG ]';
34
- function safeGetLocalStorageItem() {
35
- try {
36
- if (typeof window !== 'undefined' && window.localStorage) {
37
- return localStorage.getItem(BROWSER_LOG_KEY) === BROWSER_LOG_VALUE;
38
- }
39
- } catch (error1) {
40
- return typeof document !== 'undefined';
41
- }
42
- return false;
43
- }
44
- let Logger = class Logger {
45
- info(msg, info) {
46
- if (this.enable) {
47
- const argsToString = safeToString(info) || '';
48
- if (isBrowserEnv()) {
49
- console.info(`%c ${this.identifier}: ${msg} ${argsToString}`, 'color:#3300CC');
50
- } else {
51
- console.info('\x1b[34m%s', `${this.identifier}: ${msg} ${argsToString ? `\n${argsToString}` : ''}`);
52
- }
53
- }
54
- }
55
- logOriginalInfo(...args) {
56
- if (this.enable) {
57
- if (isBrowserEnv()) {
58
- console.info(`%c ${this.identifier}: OriginalInfo`, 'color:#3300CC');
59
- console.log(...args);
60
- } else {
61
- console.info(`%c ${this.identifier}: OriginalInfo`, 'color:#3300CC');
62
- console.log(...args);
63
- }
64
- }
65
- }
66
- constructor(identifier){
67
- this.enable = false;
68
- this.identifier = identifier || DEBUG_LOG;
69
- if (isBrowserEnv() && safeGetLocalStorageItem()) {
70
- this.enable = true;
71
- } else if (isDebugMode()) {
72
- this.enable = true;
73
- }
74
- }
75
- };
76
- const LOG_CATEGORY$1 = '[ Federation Runtime ]';
77
- new Logger();
78
- const composeKeyWithSeparator = function(...args) {
79
- if (!args.length) {
80
- return '';
81
- }
82
- return args.reduce((sum, cur)=>{
83
- if (!cur) {
84
- return sum;
85
- }
86
- if (!sum) {
87
- return cur;
88
- }
89
- return `${sum}${SEPARATOR}${cur}`;
90
- }, '');
91
- };
92
- const decodeName = function(name, prefix, withExt) {
93
- try {
94
- let decodedName = name;
95
- if (prefix) {
96
- if (!decodedName.startsWith(prefix)) {
97
- return decodedName;
98
- }
99
- decodedName = decodedName.replace(new RegExp(prefix, 'g'), '');
100
- }
101
- 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]]);
102
- if (withExt) ;
103
- return decodedName;
104
- } catch (err) {
105
- throw err;
106
- }
107
- };
108
- const getResourceUrl = (module, sourceUrl)=>{
109
- if ('getPublicPath' in module) {
110
- let publicPath;
111
- if (!module.getPublicPath.startsWith('function')) {
112
- publicPath = new Function(module.getPublicPath)();
113
- } else {
114
- publicPath = new Function('return ' + module.getPublicPath)()();
115
- }
116
- return `${publicPath}${sourceUrl}`;
117
- } else if ('publicPath' in module) {
118
- return `${module.publicPath}${sourceUrl}`;
119
- } else {
120
- console.warn('Cannot get resource URL. If in debug mode, please ignore.', module, sourceUrl);
121
- return '';
122
- }
123
- };
124
- const warn$1 = (msg)=>{
125
- console.warn(`${LOG_CATEGORY$1}: ${msg}`);
126
- };
127
- function safeToString(info) {
128
- try {
129
- return JSON.stringify(info, null, 2);
130
- } catch (e) {
131
- return '';
132
- }
133
- }
134
- const simpleJoinRemoteEntry = (rPath, rName)=>{
135
- if (!rPath) {
136
- return rName;
137
- }
138
- const transformPath = (str)=>{
139
- if (str === '.') {
140
- return '';
141
- }
142
- if (str.startsWith('./')) {
143
- return str.replace('./', '');
144
- }
145
- if (str.startsWith('/')) {
146
- const strWithoutSlash = str.slice(1);
147
- if (strWithoutSlash.endsWith('/')) {
148
- return strWithoutSlash.slice(0, -1);
149
- }
150
- return strWithoutSlash;
151
- }
152
- return str;
153
- };
154
- const transformedPath = transformPath(rPath);
155
- if (!transformedPath) {
156
- return rName;
157
- }
158
- if (transformedPath.endsWith('/')) {
159
- return `${transformedPath}${rName}`;
160
- }
161
- return `${transformedPath}/${rName}`;
162
- };
163
- function inferAutoPublicPath(url) {
164
- return url.replace(/#.*$/, '').replace(/\?.*$/, '').replace(/\/[^\/]+$/, '/');
165
- }
166
- function generateSnapshotFromManifest(manifest, options = {}) {
167
- var _manifest_metaData, _manifest_metaData1;
168
- const { remotes = {}, overrides = {}, version } = options;
169
- let remoteSnapshot;
170
- const getPublicPath = ()=>{
171
- if ('publicPath' in manifest.metaData) {
172
- if (manifest.metaData.publicPath === 'auto' && version) {
173
- return inferAutoPublicPath(version);
174
- }
175
- return manifest.metaData.publicPath;
176
- } else {
177
- return manifest.metaData.getPublicPath;
178
- }
179
- };
180
- const overridesKeys = Object.keys(overrides);
181
- let remotesInfo = {};
182
- if (!Object.keys(remotes).length) {
183
- var _manifest_remotes;
184
- remotesInfo = ((_manifest_remotes = manifest.remotes) == null ? void 0 : _manifest_remotes.reduce((res, next)=>{
185
- let matchedVersion;
186
- const name = next.federationContainerName;
187
- if (overridesKeys.includes(name)) {
188
- matchedVersion = overrides[name];
189
- } else {
190
- if ('version' in next) {
191
- matchedVersion = next.version;
192
- } else {
193
- matchedVersion = next.entry;
194
- }
195
- }
196
- res[name] = {
197
- matchedVersion
198
- };
199
- return res;
200
- }, {})) || {};
201
- }
202
- Object.keys(remotes).forEach((key)=>remotesInfo[key] = {
203
- matchedVersion: overridesKeys.includes(key) ? overrides[key] : remotes[key]
204
- });
205
- const { remoteEntry: { path: remoteEntryPath, name: remoteEntryName, type: remoteEntryType }, types: remoteTypes, buildInfo: { buildVersion }, globalName, ssrRemoteEntry } = manifest.metaData;
206
- const { exposes } = manifest;
207
- let basicRemoteSnapshot = {
208
- version: version ? version : '',
209
- buildVersion,
210
- globalName,
211
- remoteEntry: simpleJoinRemoteEntry(remoteEntryPath, remoteEntryName),
212
- remoteEntryType,
213
- remoteTypes: simpleJoinRemoteEntry(remoteTypes.path, remoteTypes.name),
214
- remoteTypesZip: remoteTypes.zip || '',
215
- remoteTypesAPI: remoteTypes.api || '',
216
- remotesInfo,
217
- shared: manifest == null ? void 0 : manifest.shared.map((item)=>({
218
- assets: item.assets,
219
- sharedName: item.name,
220
- version: item.version
221
- })),
222
- modules: exposes == null ? void 0 : exposes.map((expose)=>({
223
- moduleName: expose.name,
224
- modulePath: expose.path,
225
- assets: expose.assets
226
- }))
227
- };
228
- if ((_manifest_metaData = manifest.metaData) == null ? void 0 : _manifest_metaData.prefetchInterface) {
229
- const prefetchInterface = manifest.metaData.prefetchInterface;
230
- basicRemoteSnapshot = _({}, basicRemoteSnapshot, {
231
- prefetchInterface
232
- });
233
- }
234
- if ((_manifest_metaData1 = manifest.metaData) == null ? void 0 : _manifest_metaData1.prefetchEntry) {
235
- const { path, name, type } = manifest.metaData.prefetchEntry;
236
- basicRemoteSnapshot = _({}, basicRemoteSnapshot, {
237
- prefetchEntry: simpleJoinRemoteEntry(path, name),
238
- prefetchEntryType: type
239
- });
240
- }
241
- if ('publicPath' in manifest.metaData) {
242
- remoteSnapshot = _({}, basicRemoteSnapshot, {
243
- publicPath: getPublicPath()
244
- });
245
- } else {
246
- remoteSnapshot = _({}, basicRemoteSnapshot, {
247
- getPublicPath: getPublicPath()
248
- });
249
- }
250
- if (ssrRemoteEntry) {
251
- const fullSSRRemoteEntry = simpleJoinRemoteEntry(ssrRemoteEntry.path, ssrRemoteEntry.name);
252
- remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
253
- remoteSnapshot.ssrRemoteEntryType = 'commonjs-module';
254
- }
255
- return remoteSnapshot;
256
- }
257
- function isManifestProvider(moduleInfo) {
258
- if ('remoteEntry' in moduleInfo && moduleInfo.remoteEntry.includes(MANIFEST_EXT)) {
259
- return true;
260
- } else {
261
- return false;
262
- }
263
- }
264
- async function safeWrapper(callback, disableWarn) {
265
- try {
266
- const res = await callback();
267
- return res;
268
- } catch (e) {
269
- warn$1(e);
270
- return;
271
- }
272
- }
273
- function isStaticResourcesEqual(url1, url2) {
274
- const REG_EXP = /^(https?:)?\/\//i;
275
- const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\/$/, '');
276
- const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\/$/, '');
277
- return relativeUrl1 === relativeUrl2;
278
- }
279
- function createScript(info) {
280
- let script = null;
281
- let needAttach = true;
282
- let timeout = 20000;
283
- let timeoutId;
284
- const scripts = document.getElementsByTagName('script');
285
- for(let i = 0; i < scripts.length; i++){
286
- const s = scripts[i];
287
- const scriptSrc = s.getAttribute('src');
288
- if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
289
- script = s;
290
- needAttach = false;
291
- break;
292
- }
293
- }
294
- if (!script) {
295
- script = document.createElement('script');
296
- script.type = 'text/javascript';
297
- script.src = info.url;
298
- let createScriptRes = undefined;
299
- if (info.createScriptHook) {
300
- createScriptRes = info.createScriptHook(info.url, info.attrs);
301
- if (createScriptRes instanceof HTMLScriptElement) {
302
- script = createScriptRes;
303
- } else if (typeof createScriptRes === 'object') {
304
- if ('script' in createScriptRes && createScriptRes.script) {
305
- script = createScriptRes.script;
306
- }
307
- if ('timeout' in createScriptRes && createScriptRes.timeout) {
308
- timeout = createScriptRes.timeout;
309
- }
310
- }
311
- }
312
- const attrs = info.attrs;
313
- if (attrs && !createScriptRes) {
314
- Object.keys(attrs).forEach((name)=>{
315
- if (script) {
316
- if (name === 'async' || name === 'defer') {
317
- script[name] = attrs[name];
318
- } else if (!script.getAttribute(name)) {
319
- script.setAttribute(name, attrs[name]);
320
- }
321
- }
322
- });
323
- }
324
- }
325
- const onScriptComplete = (prev, event)=>{
326
- var _info_cb;
327
- clearTimeout(timeoutId);
328
- if (script) {
329
- script.onerror = null;
330
- script.onload = null;
331
- safeWrapper(()=>{
332
- const { needDeleteScript = true } = info;
333
- if (needDeleteScript) {
334
- (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
335
- }
336
- });
337
- if (prev) {
338
- var _info_cb1;
339
- const res = prev(event);
340
- info == null ? void 0 : (_info_cb1 = info.cb) == null ? void 0 : _info_cb1.call(info);
341
- return res;
342
- }
343
- }
344
- info == null ? void 0 : (_info_cb = info.cb) == null ? void 0 : _info_cb.call(info);
345
- };
346
- script.onerror = onScriptComplete.bind(null, script.onerror);
347
- script.onload = onScriptComplete.bind(null, script.onload);
348
- timeoutId = setTimeout(()=>{
349
- onScriptComplete(null, new Error(`Remote script "${info.url}" time-outed.`));
350
- }, timeout);
351
- return {
352
- script,
353
- needAttach
354
- };
355
- }
356
- function createLink(info) {
357
- let link = null;
358
- let needAttach = true;
359
- const links = document.getElementsByTagName('link');
360
- for(let i = 0; i < links.length; i++){
361
- const l = links[i];
362
- const linkHref = l.getAttribute('href');
363
- const linkRef = l.getAttribute('ref');
364
- if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRef === info.attrs['ref']) {
365
- link = l;
366
- needAttach = false;
367
- break;
368
- }
369
- }
370
- if (!link) {
371
- link = document.createElement('link');
372
- link.setAttribute('href', info.url);
373
- let createLinkRes = undefined;
374
- const attrs = info.attrs;
375
- if (info.createLinkHook) {
376
- createLinkRes = info.createLinkHook(info.url, attrs);
377
- if (createLinkRes instanceof HTMLLinkElement) {
378
- link = createLinkRes;
379
- }
380
- }
381
- if (attrs && !createLinkRes) {
382
- Object.keys(attrs).forEach((name)=>{
383
- if (link && !link.getAttribute(name)) {
384
- link.setAttribute(name, attrs[name]);
385
- }
386
- });
387
- }
388
- }
389
- const onLinkComplete = (prev, event)=>{
390
- if (link) {
391
- link.onerror = null;
392
- link.onload = null;
393
- safeWrapper(()=>{
394
- const { needDeleteLink = true } = info;
395
- if (needDeleteLink) {
396
- (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);
397
- }
398
- });
399
- if (prev) {
400
- const res = prev(event);
401
- info.cb();
402
- return res;
403
- }
404
- }
405
- info.cb();
406
- };
407
- link.onerror = onLinkComplete.bind(null, link.onerror);
408
- link.onload = onLinkComplete.bind(null, link.onload);
409
- return {
410
- link,
411
- needAttach
412
- };
413
- }
414
- function loadScript(url, info) {
415
- const { attrs = {}, createScriptHook } = info;
416
- return new Promise((resolve, _reject)=>{
417
- const { script, needAttach } = createScript({
418
- url,
419
- cb: resolve,
420
- attrs: _({
421
- fetchpriority: 'high'
422
- }, attrs),
423
- createScriptHook,
424
- needDeleteScript: true
425
- });
426
- needAttach && document.head.appendChild(script);
427
- });
428
- }
429
- function importNodeModule(name) {
430
- if (!name) {
431
- throw new Error('import specifier is required');
432
- }
433
- const importModule = new Function('name', `return import(name)`);
434
- return importModule(name).then((res)=>res).catch((error1)=>{
435
- console.error(`Error importing module ${name}:`, error1);
436
- throw error1;
437
- });
438
- }
439
- const loadNodeFetch = async ()=>{
440
- const fetchModule = await importNodeModule('node-fetch');
441
- return fetchModule.default || fetchModule;
442
- };
443
- const lazyLoaderHookFetch = async (input, init)=>{
444
- const loaderHooks = __webpack_require__.federation.instance.loaderHook;
445
- const hook = (url, init)=>{
446
- return loaderHooks.lifecycle.fetch.emit(url, init);
447
- };
448
- const res = await hook(input, init || {});
449
- if (!res || !(res instanceof Response)) {
450
- const fetchFunction = typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;
451
- return fetchFunction(input, init || {});
452
- }
453
- return res;
454
- };
455
- function createScriptNode(url, cb, attrs, createScriptHook) {
456
- if (createScriptHook) {
457
- const hookResult = createScriptHook(url);
458
- if (hookResult && typeof hookResult === 'object' && 'url' in hookResult) {
459
- url = hookResult.url;
460
- }
461
- }
462
- let urlObj;
463
- try {
464
- urlObj = new URL(url);
465
- } catch (e) {
466
- console.error('Error constructing URL:', e);
467
- cb(new Error(`Invalid URL: ${e}`));
468
- return;
469
- }
470
- const getFetch = async ()=>{
471
- if (typeof __webpack_require__ !== 'undefined') {
472
- try {
473
- const loaderHooks = __webpack_require__.federation.instance.loaderHook;
474
- if (loaderHooks.lifecycle.fetch) {
475
- return lazyLoaderHookFetch;
476
- }
477
- } catch (e) {
478
- console.warn('federation.instance.loaderHook.lifecycle.fetch failed:', e);
479
- }
480
- }
481
- return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;
482
- };
483
- const handleScriptFetch = async (f, urlObj)=>{
484
- try {
485
- var _vm_constants;
486
- const res = await f(urlObj.href);
487
- const data = await res.text();
488
- const [path, vm] = await Promise.all([
489
- importNodeModule('path'),
490
- importNodeModule('vm')
491
- ]);
492
- const scriptContext = {
493
- exports: {},
494
- module: {
495
- exports: {}
496
- }
497
- };
498
- const urlDirname = urlObj.pathname.split('/').slice(0, -1).join('/');
499
- const filename = path.basename(urlObj.pathname);
500
- var _vm_constants_USE_MAIN_CONTEXT_DEFAULT_LOADER;
501
- const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}\n})`, {
502
- filename,
503
- 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
504
- });
505
- script.runInThisContext()(scriptContext.exports, scriptContext.module, eval('require'), urlDirname, filename);
506
- const exportedInterface = scriptContext.module.exports || scriptContext.exports;
507
- if (attrs && exportedInterface && attrs['globalName']) {
508
- const container = exportedInterface[attrs['globalName']] || exportedInterface;
509
- cb(undefined, container);
510
- return;
511
- }
512
- cb(undefined, exportedInterface);
513
- } catch (e) {
514
- cb(e instanceof Error ? e : new Error(`Script execution error: ${e}`));
515
- }
516
- };
517
- getFetch().then((f)=>handleScriptFetch(f, urlObj)).catch((err)=>{
518
- cb(err);
519
- });
520
- }
521
- function loadScriptNode(url, info) {
522
- return new Promise((resolve, reject)=>{
523
- createScriptNode(url, (error1, scriptContext)=>{
524
- if (error1) {
525
- reject(error1);
526
- } else {
527
- var _info_attrs, _info_attrs1;
528
- 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__`;
529
- const entryExports = globalThis[remoteEntryKey] = scriptContext;
530
- resolve(entryExports);
531
- }
532
- }, info.attrs, info.createScriptHook);
533
- });
534
- }
535
-
536
- function getBuilderId() {
537
- return typeof FEDERATION_BUILD_IDENTIFIER !== 'undefined' ? FEDERATION_BUILD_IDENTIFIER : '';
538
- }
539
- const LOG_CATEGORY = '[ Federation Runtime ]';
540
- function assert(condition, msg) {
541
- if (!condition) {
542
- error(msg);
543
- }
544
- }
545
- function error(msg) {
546
- if (msg instanceof Error) {
547
- msg.message = `${LOG_CATEGORY}: ${msg.message}`;
548
- throw msg;
549
- }
550
- throw new Error(`${LOG_CATEGORY}: ${msg}`);
551
- }
552
- function warn(msg) {
553
- if (msg instanceof Error) {
554
- msg.message = `${LOG_CATEGORY}: ${msg.message}`;
555
- console.warn(msg);
556
- } else {
557
- console.warn(`${LOG_CATEGORY}: ${msg}`);
558
- }
559
- }
560
- function addUniqueItem(arr, item) {
561
- if (arr.findIndex((name)=>name === item) === -1) {
562
- arr.push(item);
563
- }
564
- return arr;
565
- }
566
- function getFMId(remoteInfo) {
567
- if ('version' in remoteInfo && remoteInfo.version) {
568
- return `${remoteInfo.name}:${remoteInfo.version}`;
569
- } else if ('entry' in remoteInfo && remoteInfo.entry) {
570
- return `${remoteInfo.name}:${remoteInfo.entry}`;
571
- } else {
572
- return `${remoteInfo.name}`;
573
- }
574
- }
575
- function isRemoteInfoWithEntry(remote) {
576
- return typeof remote.entry !== 'undefined';
577
- }
578
- function isPureRemoteEntry(remote) {
579
- return !remote.entry.includes('.json') && remote.entry.includes('.js');
580
- }
581
- function isObject(val) {
582
- return val && typeof val === 'object';
583
- }
584
- const objectToString = Object.prototype.toString;
585
- function isPlainObject(val) {
586
- return objectToString.call(val) === '[object Object]';
587
- }
588
- function arrayOptions(options) {
589
- return Array.isArray(options) ? options : [
590
- options
591
- ];
592
- }
593
- function getRemoteEntryInfoFromSnapshot(snapshot) {
594
- const defaultRemoteEntryInfo = {
595
- url: '',
596
- type: 'global',
597
- globalName: ''
598
- };
599
- if (isBrowserEnv()) {
600
- return 'remoteEntry' in snapshot ? {
601
- url: snapshot.remoteEntry,
602
- type: snapshot.remoteEntryType,
603
- globalName: snapshot.globalName
604
- } : defaultRemoteEntryInfo;
605
- }
606
- if ('ssrRemoteEntry' in snapshot) {
607
- return {
608
- url: snapshot.ssrRemoteEntry || defaultRemoteEntryInfo.url,
609
- type: snapshot.ssrRemoteEntryType || defaultRemoteEntryInfo.type,
610
- globalName: snapshot.globalName
611
- };
612
- }
613
- return defaultRemoteEntryInfo;
614
- }
615
- const nativeGlobal = (()=>{
616
- try {
617
- return new Function('return this')();
618
- } catch (e) {
619
- return globalThis;
620
- }
621
- })();
622
- const Global = nativeGlobal;
623
- function definePropertyGlobalVal(target, key, val) {
624
- Object.defineProperty(target, key, {
625
- value: val,
626
- configurable: false,
627
- writable: true
628
- });
629
- }
630
- function includeOwnProperty(target, key) {
631
- return Object.hasOwnProperty.call(target, key);
632
- }
633
- if (!includeOwnProperty(globalThis, '__GLOBAL_LOADING_REMOTE_ENTRY__')) {
634
- definePropertyGlobalVal(globalThis, '__GLOBAL_LOADING_REMOTE_ENTRY__', {});
635
- }
636
- const globalLoading = globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__;
637
- function setGlobalDefaultVal(target) {
638
- var _target___FEDERATION__, _target___FEDERATION__1, _target___FEDERATION__2, _target___FEDERATION__3, _target___FEDERATION__4, _target___FEDERATION__5;
639
- if (includeOwnProperty(target, '__VMOK__') && !includeOwnProperty(target, '__FEDERATION__')) {
640
- definePropertyGlobalVal(target, '__FEDERATION__', target.__VMOK__);
641
- }
642
- if (!includeOwnProperty(target, '__FEDERATION__')) {
643
- definePropertyGlobalVal(target, '__FEDERATION__', {
644
- __GLOBAL_PLUGIN__: [],
645
- __INSTANCES__: [],
646
- moduleInfo: {},
647
- __SHARE__: {},
648
- __MANIFEST_LOADING__: {},
649
- __PRELOADED_MAP__: new Map()
650
- });
651
- definePropertyGlobalVal(target, '__VMOK__', target.__FEDERATION__);
652
- }
653
- var ___GLOBAL_PLUGIN__;
654
- (___GLOBAL_PLUGIN__ = (_target___FEDERATION__ = target.__FEDERATION__).__GLOBAL_PLUGIN__) != null ? ___GLOBAL_PLUGIN__ : _target___FEDERATION__.__GLOBAL_PLUGIN__ = [];
655
- var ___INSTANCES__;
656
- (___INSTANCES__ = (_target___FEDERATION__1 = target.__FEDERATION__).__INSTANCES__) != null ? ___INSTANCES__ : _target___FEDERATION__1.__INSTANCES__ = [];
657
- var _moduleInfo;
658
- (_moduleInfo = (_target___FEDERATION__2 = target.__FEDERATION__).moduleInfo) != null ? _moduleInfo : _target___FEDERATION__2.moduleInfo = {};
659
- var ___SHARE__;
660
- (___SHARE__ = (_target___FEDERATION__3 = target.__FEDERATION__).__SHARE__) != null ? ___SHARE__ : _target___FEDERATION__3.__SHARE__ = {};
661
- var ___MANIFEST_LOADING__;
662
- (___MANIFEST_LOADING__ = (_target___FEDERATION__4 = target.__FEDERATION__).__MANIFEST_LOADING__) != null ? ___MANIFEST_LOADING__ : _target___FEDERATION__4.__MANIFEST_LOADING__ = {};
663
- var ___PRELOADED_MAP__;
664
- (___PRELOADED_MAP__ = (_target___FEDERATION__5 = target.__FEDERATION__).__PRELOADED_MAP__) != null ? ___PRELOADED_MAP__ : _target___FEDERATION__5.__PRELOADED_MAP__ = new Map();
665
- }
666
- setGlobalDefaultVal(globalThis);
667
- setGlobalDefaultVal(nativeGlobal);
668
- function getGlobalFederationInstance(name, version) {
669
- const buildId = getBuilderId();
670
- return globalThis.__FEDERATION__.__INSTANCES__.find((GMInstance)=>{
671
- if (buildId && GMInstance.options.id === getBuilderId()) {
672
- return true;
673
- }
674
- if (GMInstance.options.name === name && !GMInstance.options.version && !version) {
675
- return true;
676
- }
677
- if (GMInstance.options.name === name && version && GMInstance.options.version === version) {
678
- return true;
679
- }
680
- return false;
681
- });
682
- }
683
- function setGlobalFederationInstance(FederationInstance) {
684
- globalThis.__FEDERATION__.__INSTANCES__.push(FederationInstance);
685
- }
686
- function getGlobalFederationConstructor() {
687
- return globalThis.__FEDERATION__.__DEBUG_CONSTRUCTOR__;
688
- }
689
- function setGlobalFederationConstructor(FederationConstructor, isDebug = isDebugMode()) {
690
- if (isDebug) {
691
- globalThis.__FEDERATION__.__DEBUG_CONSTRUCTOR__ = FederationConstructor;
692
- globalThis.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__ = "0.6.0";
693
- }
694
- }
695
- function getInfoWithoutType(target, key) {
696
- if (typeof key === 'string') {
697
- const keyRes = target[key];
698
- if (keyRes) {
699
- return {
700
- value: target[key],
701
- key: key
702
- };
703
- } else {
704
- const targetKeys = Object.keys(target);
705
- for (const targetKey of targetKeys){
706
- const [targetTypeOrName, _] = targetKey.split(':');
707
- const nKey = `${targetTypeOrName}:${key}`;
708
- const typeWithKeyRes = target[nKey];
709
- if (typeWithKeyRes) {
710
- return {
711
- value: typeWithKeyRes,
712
- key: nKey
713
- };
714
- }
715
- }
716
- return {
717
- value: undefined,
718
- key: key
719
- };
720
- }
721
- } else {
722
- throw new Error('key must be string');
723
- }
724
- }
725
- const getGlobalSnapshot = ()=>nativeGlobal.__FEDERATION__.moduleInfo;
726
- const getTargetSnapshotInfoByModuleInfo = (moduleInfo, snapshot)=>{
727
- const moduleKey = getFMId(moduleInfo);
728
- const getModuleInfo = getInfoWithoutType(snapshot, moduleKey).value;
729
- if (getModuleInfo && !getModuleInfo.version && 'version' in moduleInfo && moduleInfo['version']) {
730
- getModuleInfo.version = moduleInfo['version'];
731
- }
732
- if (getModuleInfo) {
733
- return getModuleInfo;
734
- }
735
- if ('version' in moduleInfo && moduleInfo['version']) {
736
- const { version } = moduleInfo, resModuleInfo = _$1(moduleInfo, [
737
- "version"
738
- ]);
739
- const moduleKeyWithoutVersion = getFMId(resModuleInfo);
740
- const getModuleInfoWithoutVersion = getInfoWithoutType(nativeGlobal.__FEDERATION__.moduleInfo, moduleKeyWithoutVersion).value;
741
- if ((getModuleInfoWithoutVersion == null ? void 0 : getModuleInfoWithoutVersion.version) === version) {
742
- return getModuleInfoWithoutVersion;
743
- }
744
- }
745
- return;
746
- };
747
- const getGlobalSnapshotInfoByModuleInfo = (moduleInfo)=>getTargetSnapshotInfoByModuleInfo(moduleInfo, nativeGlobal.__FEDERATION__.moduleInfo);
748
- const setGlobalSnapshotInfoByModuleInfo = (remoteInfo, moduleDetailInfo)=>{
749
- const moduleKey = getFMId(remoteInfo);
750
- nativeGlobal.__FEDERATION__.moduleInfo[moduleKey] = moduleDetailInfo;
751
- return nativeGlobal.__FEDERATION__.moduleInfo;
752
- };
753
- const addGlobalSnapshot = (moduleInfos)=>{
754
- nativeGlobal.__FEDERATION__.moduleInfo = _({}, nativeGlobal.__FEDERATION__.moduleInfo, moduleInfos);
755
- return ()=>{
756
- const keys = Object.keys(moduleInfos);
757
- for (const key of keys){
758
- delete nativeGlobal.__FEDERATION__.moduleInfo[key];
759
- }
760
- };
761
- };
762
- const getRemoteEntryExports = (name, globalName)=>{
763
- const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;
764
- const entryExports = globalThis[remoteEntryKey];
765
- return {
766
- remoteEntryKey,
767
- entryExports
768
- };
769
- };
770
- const registerGlobalPlugins = (plugins)=>{
771
- const { __GLOBAL_PLUGIN__ } = nativeGlobal.__FEDERATION__;
772
- plugins.forEach((plugin)=>{
773
- if (__GLOBAL_PLUGIN__.findIndex((p)=>p.name === plugin.name) === -1) {
774
- __GLOBAL_PLUGIN__.push(plugin);
775
- } else {
776
- warn(`The plugin ${plugin.name} has been registered.`);
777
- }
778
- });
779
- };
780
- const getGlobalHostPlugins = ()=>nativeGlobal.__FEDERATION__.__GLOBAL_PLUGIN__;
781
- const getPreloaded = (id)=>globalThis.__FEDERATION__.__PRELOADED_MAP__.get(id);
782
- const setPreloaded = (id)=>globalThis.__FEDERATION__.__PRELOADED_MAP__.set(id, true);
783
- const DEFAULT_SCOPE = 'default';
784
- const DEFAULT_REMOTE_TYPE = 'global';
785
- const buildIdentifier = '[0-9A-Za-z-]+';
786
- const build = `(?:\\+(${buildIdentifier}(?:\\.${buildIdentifier})*))`;
787
- const numericIdentifier = '0|[1-9]\\d*';
788
- const numericIdentifierLoose = '[0-9]+';
789
- const nonNumericIdentifier = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
790
- const preReleaseIdentifierLoose = `(?:${numericIdentifierLoose}|${nonNumericIdentifier})`;
791
- const preReleaseLoose = `(?:-?(${preReleaseIdentifierLoose}(?:\\.${preReleaseIdentifierLoose})*))`;
792
- const preReleaseIdentifier = `(?:${numericIdentifier}|${nonNumericIdentifier})`;
793
- const preRelease = `(?:-(${preReleaseIdentifier}(?:\\.${preReleaseIdentifier})*))`;
794
- const xRangeIdentifier = `${numericIdentifier}|x|X|\\*`;
795
- const xRangePlain = `[v=\\s]*(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:${preRelease})?${build}?)?)?`;
796
- const hyphenRange = `^\\s*(${xRangePlain})\\s+-\\s+(${xRangePlain})\\s*$`;
797
- const mainVersionLoose = `(${numericIdentifierLoose})\\.(${numericIdentifierLoose})\\.(${numericIdentifierLoose})`;
798
- const loosePlain = `[v=\\s]*${mainVersionLoose}${preReleaseLoose}?${build}?`;
799
- const gtlt = '((?:<|>)?=?)';
800
- const comparatorTrim = `(\\s*)${gtlt}\\s*(${loosePlain}|${xRangePlain})`;
801
- const loneTilde = '(?:~>?)';
802
- const tildeTrim = `(\\s*)${loneTilde}\\s+`;
803
- const loneCaret = '(?:\\^)';
804
- const caretTrim = `(\\s*)${loneCaret}\\s+`;
805
- const star = '(<|>)?=?\\s*\\*';
806
- const caret = `^${loneCaret}${xRangePlain}$`;
807
- const mainVersion = `(${numericIdentifier})\\.(${numericIdentifier})\\.(${numericIdentifier})`;
808
- const fullPlain = `v?${mainVersion}${preRelease}?${build}?`;
809
- const tilde = `^${loneTilde}${xRangePlain}$`;
810
- const xRange = `^${gtlt}\\s*${xRangePlain}$`;
811
- const comparator = `^${gtlt}\\s*(${fullPlain})$|^$`;
812
- const gte0 = '^\\s*>=\\s*0.0.0\\s*$';
813
- function parseRegex(source) {
814
- return new RegExp(source);
815
- }
816
- function isXVersion(version) {
817
- return !version || version.toLowerCase() === 'x' || version === '*';
818
- }
819
- function pipe(...fns) {
820
- return (x)=>fns.reduce((v, f)=>f(v), x);
821
- }
822
- function extractComparator(comparatorString) {
823
- return comparatorString.match(parseRegex(comparator));
824
- }
825
- function combineVersion(major, minor, patch, preRelease) {
826
- const mainVersion = `${major}.${minor}.${patch}`;
827
- if (preRelease) {
828
- return `${mainVersion}-${preRelease}`;
829
- }
830
- return mainVersion;
831
- }
832
- function parseHyphen(range) {
833
- return range.replace(parseRegex(hyphenRange), (_range, from, fromMajor, fromMinor, fromPatch, _fromPreRelease, _fromBuild, to, toMajor, toMinor, toPatch, toPreRelease)=>{
834
- if (isXVersion(fromMajor)) {
835
- from = '';
836
- } else if (isXVersion(fromMinor)) {
837
- from = `>=${fromMajor}.0.0`;
838
- } else if (isXVersion(fromPatch)) {
839
- from = `>=${fromMajor}.${fromMinor}.0`;
840
- } else {
841
- from = `>=${from}`;
842
- }
843
- if (isXVersion(toMajor)) {
844
- to = '';
845
- } else if (isXVersion(toMinor)) {
846
- to = `<${Number(toMajor) + 1}.0.0-0`;
847
- } else if (isXVersion(toPatch)) {
848
- to = `<${toMajor}.${Number(toMinor) + 1}.0-0`;
849
- } else if (toPreRelease) {
850
- to = `<=${toMajor}.${toMinor}.${toPatch}-${toPreRelease}`;
851
- } else {
852
- to = `<=${to}`;
853
- }
854
- return `${from} ${to}`.trim();
855
- });
856
- }
857
- function parseComparatorTrim(range) {
858
- return range.replace(parseRegex(comparatorTrim), '$1$2$3');
859
- }
860
- function parseTildeTrim(range) {
861
- return range.replace(parseRegex(tildeTrim), '$1~');
862
- }
863
- function parseCaretTrim(range) {
864
- return range.replace(parseRegex(caretTrim), '$1^');
865
- }
866
- function parseCarets(range) {
867
- return range.trim().split(/\s+/).map((rangeVersion)=>rangeVersion.replace(parseRegex(caret), (_, major, minor, patch, preRelease)=>{
868
- if (isXVersion(major)) {
869
- return '';
870
- } else if (isXVersion(minor)) {
871
- return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
872
- } else if (isXVersion(patch)) {
873
- if (major === '0') {
874
- return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
875
- } else {
876
- return `>=${major}.${minor}.0 <${Number(major) + 1}.0.0-0`;
877
- }
878
- } else if (preRelease) {
879
- if (major === '0') {
880
- if (minor === '0') {
881
- return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${minor}.${Number(patch) + 1}-0`;
882
- } else {
883
- return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
884
- }
885
- } else {
886
- return `>=${major}.${minor}.${patch}-${preRelease} <${Number(major) + 1}.0.0-0`;
887
- }
888
- } else {
889
- if (major === '0') {
890
- if (minor === '0') {
891
- return `>=${major}.${minor}.${patch} <${major}.${minor}.${Number(patch) + 1}-0`;
892
- } else {
893
- return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
894
- }
895
- }
896
- return `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0-0`;
897
- }
898
- })).join(' ');
899
- }
900
- function parseTildes(range) {
901
- return range.trim().split(/\s+/).map((rangeVersion)=>rangeVersion.replace(parseRegex(tilde), (_, major, minor, patch, preRelease)=>{
902
- if (isXVersion(major)) {
903
- return '';
904
- } else if (isXVersion(minor)) {
905
- return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
906
- } else if (isXVersion(patch)) {
907
- return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
908
- } else if (preRelease) {
909
- return `>=${major}.${minor}.${patch}-${preRelease} <${major}.${Number(minor) + 1}.0-0`;
910
- }
911
- return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
912
- })).join(' ');
913
- }
914
- function parseXRanges(range) {
915
- return range.split(/\s+/).map((rangeVersion)=>rangeVersion.trim().replace(parseRegex(xRange), (ret, gtlt, major, minor, patch, preRelease)=>{
916
- const isXMajor = isXVersion(major);
917
- const isXMinor = isXMajor || isXVersion(minor);
918
- const isXPatch = isXMinor || isXVersion(patch);
919
- if (gtlt === '=' && isXPatch) {
920
- gtlt = '';
921
- }
922
- preRelease = '';
923
- if (isXMajor) {
924
- if (gtlt === '>' || gtlt === '<') {
925
- return '<0.0.0-0';
926
- } else {
927
- return '*';
928
- }
929
- } else if (gtlt && isXPatch) {
930
- if (isXMinor) {
931
- minor = 0;
932
- }
933
- patch = 0;
934
- if (gtlt === '>') {
935
- gtlt = '>=';
936
- if (isXMinor) {
937
- major = Number(major) + 1;
938
- minor = 0;
939
- patch = 0;
940
- } else {
941
- minor = Number(minor) + 1;
942
- patch = 0;
943
- }
944
- } else if (gtlt === '<=') {
945
- gtlt = '<';
946
- if (isXMinor) {
947
- major = Number(major) + 1;
948
- } else {
949
- minor = Number(minor) + 1;
950
- }
951
- }
952
- if (gtlt === '<') {
953
- preRelease = '-0';
954
- }
955
- return `${gtlt + major}.${minor}.${patch}${preRelease}`;
956
- } else if (isXMinor) {
957
- return `>=${major}.0.0${preRelease} <${Number(major) + 1}.0.0-0`;
958
- } else if (isXPatch) {
959
- return `>=${major}.${minor}.0${preRelease} <${major}.${Number(minor) + 1}.0-0`;
960
- }
961
- return ret;
962
- })).join(' ');
963
- }
964
- function parseStar(range) {
965
- return range.trim().replace(parseRegex(star), '');
966
- }
967
- function parseGTE0(comparatorString) {
968
- return comparatorString.trim().replace(parseRegex(gte0), '');
969
- }
970
- function compareAtom(rangeAtom, versionAtom) {
971
- rangeAtom = Number(rangeAtom) || rangeAtom;
972
- versionAtom = Number(versionAtom) || versionAtom;
973
- if (rangeAtom > versionAtom) {
974
- return 1;
975
- }
976
- if (rangeAtom === versionAtom) {
977
- return 0;
978
- }
979
- return -1;
980
- }
981
- function comparePreRelease(rangeAtom, versionAtom) {
982
- const { preRelease: rangePreRelease } = rangeAtom;
983
- const { preRelease: versionPreRelease } = versionAtom;
984
- if (rangePreRelease === undefined && Boolean(versionPreRelease)) {
985
- return 1;
986
- }
987
- if (Boolean(rangePreRelease) && versionPreRelease === undefined) {
988
- return -1;
989
- }
990
- if (rangePreRelease === undefined && versionPreRelease === undefined) {
991
- return 0;
992
- }
993
- for(let i = 0, n = rangePreRelease.length; i <= n; i++){
994
- const rangeElement = rangePreRelease[i];
995
- const versionElement = versionPreRelease[i];
996
- if (rangeElement === versionElement) {
997
- continue;
998
- }
999
- if (rangeElement === undefined && versionElement === undefined) {
1000
- return 0;
1001
- }
1002
- if (!rangeElement) {
1003
- return 1;
1004
- }
1005
- if (!versionElement) {
1006
- return -1;
1007
- }
1008
- return compareAtom(rangeElement, versionElement);
1009
- }
1010
- return 0;
1011
- }
1012
- function compareVersion(rangeAtom, versionAtom) {
1013
- return compareAtom(rangeAtom.major, versionAtom.major) || compareAtom(rangeAtom.minor, versionAtom.minor) || compareAtom(rangeAtom.patch, versionAtom.patch) || comparePreRelease(rangeAtom, versionAtom);
1014
- }
1015
- function eq(rangeAtom, versionAtom) {
1016
- return rangeAtom.version === versionAtom.version;
1017
- }
1018
- function compare(rangeAtom, versionAtom) {
1019
- switch(rangeAtom.operator){
1020
- case '':
1021
- case '=':
1022
- return eq(rangeAtom, versionAtom);
1023
- case '>':
1024
- return compareVersion(rangeAtom, versionAtom) < 0;
1025
- case '>=':
1026
- return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) < 0;
1027
- case '<':
1028
- return compareVersion(rangeAtom, versionAtom) > 0;
1029
- case '<=':
1030
- return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) > 0;
1031
- case undefined:
1032
- {
1033
- return true;
1034
- }
1035
- default:
1036
- return false;
1037
- }
1038
- }
1039
- function parseComparatorString(range) {
1040
- return pipe(parseCarets, parseTildes, parseXRanges, parseStar)(range);
1041
- }
1042
- function parseRange(range) {
1043
- return pipe(parseHyphen, parseComparatorTrim, parseTildeTrim, parseCaretTrim)(range.trim()).split(/\s+/).join(' ');
1044
- }
1045
- function satisfy(version, range) {
1046
- if (!version) {
1047
- return false;
1048
- }
1049
- const parsedRange = parseRange(range);
1050
- const parsedComparator = parsedRange.split(' ').map((rangeVersion)=>parseComparatorString(rangeVersion)).join(' ');
1051
- const comparators = parsedComparator.split(/\s+/).map((comparator)=>parseGTE0(comparator));
1052
- const extractedVersion = extractComparator(version);
1053
- if (!extractedVersion) {
1054
- return false;
1055
- }
1056
- const [, versionOperator, , versionMajor, versionMinor, versionPatch, versionPreRelease] = extractedVersion;
1057
- const versionAtom = {
1058
- operator: versionOperator,
1059
- version: combineVersion(versionMajor, versionMinor, versionPatch, versionPreRelease),
1060
- major: versionMajor,
1061
- minor: versionMinor,
1062
- patch: versionPatch,
1063
- preRelease: versionPreRelease == null ? void 0 : versionPreRelease.split('.')
1064
- };
1065
- for (const comparator of comparators){
1066
- const extractedComparator = extractComparator(comparator);
1067
- if (!extractedComparator) {
1068
- return false;
1069
- }
1070
- const [, rangeOperator, , rangeMajor, rangeMinor, rangePatch, rangePreRelease] = extractedComparator;
1071
- const rangeAtom = {
1072
- operator: rangeOperator,
1073
- version: combineVersion(rangeMajor, rangeMinor, rangePatch, rangePreRelease),
1074
- major: rangeMajor,
1075
- minor: rangeMinor,
1076
- patch: rangePatch,
1077
- preRelease: rangePreRelease == null ? void 0 : rangePreRelease.split('.')
1078
- };
1079
- if (!compare(rangeAtom, versionAtom)) {
1080
- return false;
1081
- }
1082
- }
1083
- return true;
1084
- }
1085
- function formatShare(shareArgs, from, name, shareStrategy) {
1086
- let get;
1087
- if ('get' in shareArgs) {
1088
- get = shareArgs.get;
1089
- } else if ('lib' in shareArgs) {
1090
- get = ()=>Promise.resolve(shareArgs.lib);
1091
- } else {
1092
- get = ()=>Promise.resolve(()=>{
1093
- throw new Error(`Can not get shared '${name}'!`);
1094
- });
1095
- }
1096
- if (shareArgs.strategy) {
1097
- warn(`"shared.strategy is deprecated, please set in initOptions.shareStrategy instead!"`);
1098
- }
1099
- var _shareArgs_version, _shareArgs_scope, _shareArgs_strategy;
1100
- return _({
1101
- deps: [],
1102
- useIn: [],
1103
- from,
1104
- loading: null
1105
- }, shareArgs, {
1106
- shareConfig: _({
1107
- requiredVersion: `^${shareArgs.version}`,
1108
- singleton: false,
1109
- eager: false,
1110
- strictVersion: false
1111
- }, shareArgs.shareConfig),
1112
- get,
1113
- loaded: (shareArgs == null ? void 0 : shareArgs.loaded) || 'lib' in shareArgs ? true : undefined,
1114
- version: (_shareArgs_version = shareArgs.version) != null ? _shareArgs_version : '0',
1115
- scope: Array.isArray(shareArgs.scope) ? shareArgs.scope : [
1116
- (_shareArgs_scope = shareArgs.scope) != null ? _shareArgs_scope : 'default'
1117
- ],
1118
- strategy: ((_shareArgs_strategy = shareArgs.strategy) != null ? _shareArgs_strategy : shareStrategy) || 'version-first'
1119
- });
1120
- }
1121
- function formatShareConfigs(globalOptions, userOptions) {
1122
- const shareArgs = userOptions.shared || {};
1123
- const from = userOptions.name;
1124
- const shareInfos = Object.keys(shareArgs).reduce((res, pkgName)=>{
1125
- const arrayShareArgs = arrayOptions(shareArgs[pkgName]);
1126
- res[pkgName] = res[pkgName] || [];
1127
- arrayShareArgs.forEach((shareConfig)=>{
1128
- res[pkgName].push(formatShare(shareConfig, from, pkgName, userOptions.shareStrategy));
1129
- });
1130
- return res;
1131
- }, {});
1132
- const shared = _({}, globalOptions.shared);
1133
- Object.keys(shareInfos).forEach((shareKey)=>{
1134
- if (!shared[shareKey]) {
1135
- shared[shareKey] = shareInfos[shareKey];
1136
- } else {
1137
- shareInfos[shareKey].forEach((newUserSharedOptions)=>{
1138
- const isSameVersion = shared[shareKey].find((sharedVal)=>sharedVal.version === newUserSharedOptions.version);
1139
- if (!isSameVersion) {
1140
- shared[shareKey].push(newUserSharedOptions);
1141
- }
1142
- });
1143
- }
1144
- });
1145
- return {
1146
- shared,
1147
- shareInfos
1148
- };
1149
- }
1150
- function versionLt(a, b) {
1151
- const transformInvalidVersion = (version)=>{
1152
- const isNumberVersion = !Number.isNaN(Number(version));
1153
- if (isNumberVersion) {
1154
- const splitArr = version.split('.');
1155
- let validVersion = version;
1156
- for(let i = 0; i < 3 - splitArr.length; i++){
1157
- validVersion += '.0';
1158
- }
1159
- return validVersion;
1160
- }
1161
- return version;
1162
- };
1163
- if (satisfy(transformInvalidVersion(a), `<=${transformInvalidVersion(b)}`)) {
1164
- return true;
1165
- } else {
1166
- return false;
1167
- }
1168
- }
1169
- const findVersion = (shareVersionMap, cb)=>{
1170
- const callback = cb || function(prev, cur) {
1171
- return versionLt(prev, cur);
1172
- };
1173
- return Object.keys(shareVersionMap).reduce((prev, cur)=>{
1174
- if (!prev) {
1175
- return cur;
1176
- }
1177
- if (callback(prev, cur)) {
1178
- return cur;
1179
- }
1180
- if (prev === '0') {
1181
- return cur;
1182
- }
1183
- return prev;
1184
- }, 0);
1185
- };
1186
- const isLoaded = (shared)=>{
1187
- return Boolean(shared.loaded) || typeof shared.lib === 'function';
1188
- };
1189
- function findSingletonVersionOrderByVersion(shareScopeMap, scope, pkgName) {
1190
- const versions = shareScopeMap[scope][pkgName];
1191
- const callback = function(prev, cur) {
1192
- return !isLoaded(versions[prev]) && versionLt(prev, cur);
1193
- };
1194
- return findVersion(shareScopeMap[scope][pkgName], callback);
1195
- }
1196
- function findSingletonVersionOrderByLoaded(shareScopeMap, scope, pkgName) {
1197
- const versions = shareScopeMap[scope][pkgName];
1198
- const callback = function(prev, cur) {
1199
- if (isLoaded(versions[cur])) {
1200
- if (isLoaded(versions[prev])) {
1201
- return Boolean(versionLt(prev, cur));
1202
- } else {
1203
- return true;
1204
- }
1205
- }
1206
- if (isLoaded(versions[prev])) {
1207
- return false;
1208
- }
1209
- return versionLt(prev, cur);
1210
- };
1211
- return findVersion(shareScopeMap[scope][pkgName], callback);
1212
- }
1213
- function getFindShareFunction(strategy) {
1214
- if (strategy === 'loaded-first') {
1215
- return findSingletonVersionOrderByLoaded;
1216
- }
1217
- return findSingletonVersionOrderByVersion;
1218
- }
1219
- function getRegisteredShare(localShareScopeMap, pkgName, shareInfo, resolveShare) {
1220
- if (!localShareScopeMap) {
1221
- return;
1222
- }
1223
- const { shareConfig, scope = DEFAULT_SCOPE, strategy } = shareInfo;
1224
- const scopes = Array.isArray(scope) ? scope : [
1225
- scope
1226
- ];
1227
- for (const sc of scopes){
1228
- if (shareConfig && localShareScopeMap[sc] && localShareScopeMap[sc][pkgName]) {
1229
- const { requiredVersion } = shareConfig;
1230
- const findShareFunction = getFindShareFunction(strategy);
1231
- const maxOrSingletonVersion = findShareFunction(localShareScopeMap, sc, pkgName);
1232
- const defaultResolver = ()=>{
1233
- if (shareConfig.singleton) {
1234
- if (typeof requiredVersion === 'string' && !satisfy(maxOrSingletonVersion, requiredVersion)) {
1235
- const msg = `Version ${maxOrSingletonVersion} from ${maxOrSingletonVersion && localShareScopeMap[sc][pkgName][maxOrSingletonVersion].from} of shared singleton module ${pkgName} does not satisfy the requirement of ${shareInfo.from} which needs ${requiredVersion})`;
1236
- if (shareConfig.strictVersion) {
1237
- error(msg);
1238
- } else {
1239
- warn(msg);
1240
- }
1241
- }
1242
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1243
- } else {
1244
- if (requiredVersion === false || requiredVersion === '*') {
1245
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1246
- }
1247
- if (satisfy(maxOrSingletonVersion, requiredVersion)) {
1248
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
1249
- }
1250
- for (const [versionKey, versionValue] of Object.entries(localShareScopeMap[sc][pkgName])){
1251
- if (satisfy(versionKey, requiredVersion)) {
1252
- return versionValue;
1253
- }
1254
- }
1255
- }
1256
- };
1257
- const params = {
1258
- shareScopeMap: localShareScopeMap,
1259
- scope: sc,
1260
- pkgName,
1261
- version: maxOrSingletonVersion,
1262
- GlobalFederation: Global.__FEDERATION__,
1263
- resolver: defaultResolver
1264
- };
1265
- const resolveShared = resolveShare.emit(params) || params;
1266
- return resolveShared.resolver();
1267
- }
1268
- }
1269
- }
1270
- function getGlobalShareScope() {
1271
- return Global.__FEDERATION__.__SHARE__;
1272
- }
1273
- function getTargetSharedOptions(options) {
1274
- const { pkgName, extraOptions, shareInfos } = options;
1275
- const defaultResolver = (sharedOptions)=>{
1276
- if (!sharedOptions) {
1277
- return undefined;
1278
- }
1279
- const shareVersionMap = {};
1280
- sharedOptions.forEach((shared)=>{
1281
- shareVersionMap[shared.version] = shared;
1282
- });
1283
- const callback = function(prev, cur) {
1284
- return !isLoaded(shareVersionMap[prev]) && versionLt(prev, cur);
1285
- };
1286
- const maxVersion = findVersion(shareVersionMap, callback);
1287
- return shareVersionMap[maxVersion];
1288
- };
1289
- var _extraOptions_resolver;
1290
- const resolver = (_extraOptions_resolver = extraOptions == null ? void 0 : extraOptions.resolver) != null ? _extraOptions_resolver : defaultResolver;
1291
- return Object.assign({}, resolver(shareInfos[pkgName]), extraOptions == null ? void 0 : extraOptions.customShareInfo);
1292
- }
1293
-
1294
- function matchRemoteWithNameAndExpose(remotes, id) {
1295
- for (const remote of remotes){
1296
- const isNameMatched = id.startsWith(remote.name);
1297
- let expose = id.replace(remote.name, '');
1298
- if (isNameMatched) {
1299
- if (expose.startsWith('/')) {
1300
- const pkgNameOrAlias = remote.name;
1301
- expose = `.${expose}`;
1302
- return {
1303
- pkgNameOrAlias,
1304
- expose,
1305
- remote
1306
- };
1307
- } else if (expose === '') {
1308
- return {
1309
- pkgNameOrAlias: remote.name,
1310
- expose: '.',
1311
- remote
1312
- };
1313
- }
1314
- }
1315
- const isAliasMatched = remote.alias && id.startsWith(remote.alias);
1316
- let exposeWithAlias = remote.alias && id.replace(remote.alias, '');
1317
- if (remote.alias && isAliasMatched) {
1318
- if (exposeWithAlias && exposeWithAlias.startsWith('/')) {
1319
- const pkgNameOrAlias = remote.alias;
1320
- exposeWithAlias = `.${exposeWithAlias}`;
1321
- return {
1322
- pkgNameOrAlias,
1323
- expose: exposeWithAlias,
1324
- remote
1325
- };
1326
- } else if (exposeWithAlias === '') {
1327
- return {
1328
- pkgNameOrAlias: remote.alias,
1329
- expose: '.',
1330
- remote
1331
- };
1332
- }
1333
- }
1334
- }
1335
- return;
1336
- }
1337
- function matchRemote(remotes, nameOrAlias) {
1338
- for (const remote of remotes){
1339
- const isNameMatched = nameOrAlias === remote.name;
1340
- if (isNameMatched) {
1341
- return remote;
1342
- }
1343
- const isAliasMatched = remote.alias && nameOrAlias === remote.alias;
1344
- if (isAliasMatched) {
1345
- return remote;
1346
- }
1347
- }
1348
- return;
1349
- }
1350
- function registerPlugins$1(plugins, hookInstances) {
1351
- const globalPlugins = getGlobalHostPlugins();
1352
- if (globalPlugins.length > 0) {
1353
- globalPlugins.forEach((plugin)=>{
1354
- if (plugins == null ? void 0 : plugins.find((item)=>item.name !== plugin.name)) {
1355
- plugins.push(plugin);
1356
- }
1357
- });
1358
- }
1359
- if (plugins && plugins.length > 0) {
1360
- plugins.forEach((plugin)=>{
1361
- hookInstances.forEach((hookInstance)=>{
1362
- hookInstance.applyPlugin(plugin);
1363
- });
1364
- });
1365
- }
1366
- return plugins;
1367
- }
1368
- async function loadEsmEntry({ entry, remoteEntryExports }) {
1369
- return new Promise((resolve, reject)=>{
1370
- try {
1371
- if (!remoteEntryExports) {
1372
- new Function('callbacks', `import("${entry}").then(callbacks[0]).catch(callbacks[1])`)([
1373
- resolve,
1374
- reject
1375
- ]);
1376
- } else {
1377
- resolve(remoteEntryExports);
1378
- }
1379
- } catch (e) {
1380
- reject(e);
1381
- }
1382
- });
1383
- }
1384
- async function loadSystemJsEntry({ entry, remoteEntryExports }) {
1385
- return new Promise((resolve, reject)=>{
1386
- try {
1387
- if (!remoteEntryExports) {
1388
- new Function('callbacks', `System.import("${entry}").then(callbacks[0]).catch(callbacks[1])`)([
1389
- resolve,
1390
- reject
1391
- ]);
1392
- } else {
1393
- resolve(remoteEntryExports);
1394
- }
1395
- } catch (e) {
1396
- reject(e);
1397
- }
1398
- });
1399
- }
1400
- async function loadEntryScript({ name, globalName, entry, createScriptHook }) {
1401
- const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
1402
- if (remoteEntryExports) {
1403
- return remoteEntryExports;
1404
- }
1405
- return loadScript(entry, {
1406
- attrs: {},
1407
- createScriptHook: (url, attrs)=>{
1408
- const res = createScriptHook.emit({
1409
- url,
1410
- attrs
1411
- });
1412
- if (!res) return;
1413
- if (res instanceof HTMLScriptElement) {
1414
- return res;
1415
- }
1416
- if ('script' in res || 'timeout' in res) {
1417
- return res;
1418
- }
1419
- return;
1420
- }
1421
- }).then(()=>{
1422
- const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
1423
- assert(entryExports, `
1424
- Unable to use the ${name}'s '${entry}' URL with ${remoteEntryKey}'s globalName to get remoteEntry exports.
1425
- Possible reasons could be:\n
1426
- 1. '${entry}' is not the correct URL, or the remoteEntry resource or name is incorrect.\n
1427
- 2. ${remoteEntryKey} cannot be used to get remoteEntry exports in the window object.
1428
- `);
1429
- return entryExports;
1430
- }).catch((e)=>{
1431
- throw e;
1432
- });
1433
- }
1434
- async function loadEntryDom({ remoteInfo, remoteEntryExports, createScriptHook }) {
1435
- const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
1436
- switch(type){
1437
- case 'esm':
1438
- case 'module':
1439
- return loadEsmEntry({
1440
- entry,
1441
- remoteEntryExports
1442
- });
1443
- case 'system':
1444
- return loadSystemJsEntry({
1445
- entry,
1446
- remoteEntryExports
1447
- });
1448
- default:
1449
- return loadEntryScript({
1450
- entry,
1451
- globalName,
1452
- name,
1453
- createScriptHook
1454
- });
1455
- }
1456
- }
1457
- async function loadEntryNode({ remoteInfo, createScriptHook }) {
1458
- const { entry, entryGlobalName: globalName, name } = remoteInfo;
1459
- const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
1460
- if (remoteEntryExports) {
1461
- return remoteEntryExports;
1462
- }
1463
- return loadScriptNode(entry, {
1464
- attrs: {
1465
- name,
1466
- globalName
1467
- },
1468
- createScriptHook: (url, attrs)=>{
1469
- const res = createScriptHook.emit({
1470
- url,
1471
- attrs
1472
- });
1473
- if (!res) return;
1474
- if ('url' in res) {
1475
- return res;
1476
- }
1477
- return;
1478
- }
1479
- }).then(()=>{
1480
- const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
1481
- assert(entryExports, `
1482
- Unable to use the ${name}'s '${entry}' URL with ${remoteEntryKey}'s globalName to get remoteEntry exports.
1483
- Possible reasons could be:\n
1484
- 1. '${entry}' is not the correct URL, or the remoteEntry resource or name is incorrect.\n
1485
- 2. ${remoteEntryKey} cannot be used to get remoteEntry exports in the window object.
1486
- `);
1487
- return entryExports;
1488
- }).catch((e)=>{
1489
- throw e;
1490
- });
1491
- }
1492
- function getRemoteEntryUniqueKey(remoteInfo) {
1493
- const { entry, name } = remoteInfo;
1494
- return composeKeyWithSeparator(name, entry);
1495
- }
1496
- async function getRemoteEntry({ origin, remoteEntryExports, remoteInfo }) {
1497
- const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
1498
- if (remoteEntryExports) {
1499
- return remoteEntryExports;
1500
- }
1501
- if (!globalLoading[uniqueKey]) {
1502
- const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;
1503
- if (loadEntryHook.listeners.size) {
1504
- globalLoading[uniqueKey] = loadEntryHook.emit({
1505
- createScriptHook: origin.loaderHook.lifecycle.createScript,
1506
- remoteInfo,
1507
- remoteEntryExports
1508
- }).then((res)=>res || undefined);
1509
- } else {
1510
- const createScriptHook = origin.loaderHook.lifecycle.createScript;
1511
- if (!isBrowserEnv()) {
1512
- globalLoading[uniqueKey] = loadEntryNode({
1513
- remoteInfo,
1514
- createScriptHook
1515
- });
1516
- } else {
1517
- globalLoading[uniqueKey] = loadEntryDom({
1518
- remoteInfo,
1519
- remoteEntryExports,
1520
- createScriptHook
1521
- });
1522
- }
1523
- }
1524
- }
1525
- return globalLoading[uniqueKey];
1526
- }
1527
- function getRemoteInfo(remote) {
1528
- return _({}, remote, {
1529
- entry: 'entry' in remote ? remote.entry : '',
1530
- type: remote.type || DEFAULT_REMOTE_TYPE,
1531
- entryGlobalName: remote.entryGlobalName || remote.name,
1532
- shareScope: remote.shareScope || DEFAULT_SCOPE
1533
- });
1534
- }
1535
- let Module = class Module {
1536
- async getEntry() {
1537
- if (this.remoteEntryExports) {
1538
- return this.remoteEntryExports;
1539
- }
1540
- const remoteEntryExports = await getRemoteEntry({
1541
- origin: this.host,
1542
- remoteInfo: this.remoteInfo,
1543
- remoteEntryExports: this.remoteEntryExports
1544
- });
1545
- assert(remoteEntryExports, `remoteEntryExports is undefined \n ${safeToString(this.remoteInfo)}`);
1546
- this.remoteEntryExports = remoteEntryExports;
1547
- return this.remoteEntryExports;
1548
- }
1549
- async get(id, expose, options) {
1550
- const { loadFactory = true } = options || {
1551
- loadFactory: true
1552
- };
1553
- const remoteEntryExports = await this.getEntry();
1554
- if (!this.inited) {
1555
- const localShareScopeMap = this.host.shareScopeMap;
1556
- const remoteShareScope = this.remoteInfo.shareScope || 'default';
1557
- if (!localShareScopeMap[remoteShareScope]) {
1558
- localShareScopeMap[remoteShareScope] = {};
1559
- }
1560
- const shareScope = localShareScopeMap[remoteShareScope];
1561
- const initScope = [];
1562
- const remoteEntryInitOptions = {
1563
- version: this.remoteInfo.version || ''
1564
- };
1565
- Object.defineProperty(remoteEntryInitOptions, 'shareScopeMap', {
1566
- value: localShareScopeMap,
1567
- enumerable: false
1568
- });
1569
- const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({
1570
- shareScope,
1571
- remoteEntryInitOptions,
1572
- initScope,
1573
- remoteInfo: this.remoteInfo,
1574
- origin: this.host
1575
- });
1576
- if (typeof (remoteEntryExports == null ? void 0 : remoteEntryExports.init) === 'undefined') {
1577
- console.error('The remote entry interface does not contain "init"', '\n', 'Ensure the name of this remote is not reserved or in use. Check if anything already exists on window[nameOfRemote]', '\n', 'Ensure that window[nameOfRemote] is returning a {get,init} object.');
1578
- }
1579
- await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);
1580
- await this.host.hooks.lifecycle.initContainer.emit(_({}, initContainerOptions, {
1581
- remoteEntryExports
1582
- }));
1583
- }
1584
- this.lib = remoteEntryExports;
1585
- this.inited = true;
1586
- const moduleFactory = await remoteEntryExports.get(expose);
1587
- assert(moduleFactory, `${getFMId(this.remoteInfo)} remote don't export ${expose}.`);
1588
- const wrapModuleFactory = this.wraperFactory(moduleFactory, id);
1589
- if (!loadFactory) {
1590
- return wrapModuleFactory;
1591
- }
1592
- const exposeContent = await wrapModuleFactory();
1593
- return exposeContent;
1594
- }
1595
- wraperFactory(moduleFactory, id) {
1596
- function defineModuleId(res, id) {
1597
- if (res && typeof res === 'object' && Object.isExtensible(res) && !Object.getOwnPropertyDescriptor(res, Symbol.for('mf_module_id'))) {
1598
- Object.defineProperty(res, Symbol.for('mf_module_id'), {
1599
- value: id,
1600
- enumerable: false
1601
- });
1602
- }
1603
- }
1604
- if (moduleFactory instanceof Promise) {
1605
- return async ()=>{
1606
- const res = await moduleFactory();
1607
- defineModuleId(res, id);
1608
- return res;
1609
- };
1610
- } else {
1611
- return ()=>{
1612
- const res = moduleFactory();
1613
- defineModuleId(res, id);
1614
- return res;
1615
- };
1616
- }
1617
- }
1618
- constructor({ remoteInfo, host }){
1619
- this.inited = false;
1620
- this.lib = undefined;
1621
- this.remoteInfo = remoteInfo;
1622
- this.host = host;
1623
- }
1624
- };
1625
- class SyncHook {
1626
- on(fn) {
1627
- if (typeof fn === 'function') {
1628
- this.listeners.add(fn);
1629
- }
1630
- }
1631
- once(fn) {
1632
- const self = this;
1633
- this.on(function wrapper(...args) {
1634
- self.remove(wrapper);
1635
- return fn.apply(null, args);
1636
- });
1637
- }
1638
- emit(...data) {
1639
- let result;
1640
- if (this.listeners.size > 0) {
1641
- this.listeners.forEach((fn)=>{
1642
- result = fn(...data);
1643
- });
1644
- }
1645
- return result;
1646
- }
1647
- remove(fn) {
1648
- this.listeners.delete(fn);
1649
- }
1650
- removeAll() {
1651
- this.listeners.clear();
1652
- }
1653
- constructor(type){
1654
- this.type = '';
1655
- this.listeners = new Set();
1656
- if (type) {
1657
- this.type = type;
1658
- }
1659
- }
1660
- }
1661
- class AsyncHook extends SyncHook {
1662
- emit(...data) {
1663
- let result;
1664
- const ls = Array.from(this.listeners);
1665
- if (ls.length > 0) {
1666
- let i = 0;
1667
- const call = (prev)=>{
1668
- if (prev === false) {
1669
- return false;
1670
- } else if (i < ls.length) {
1671
- return Promise.resolve(ls[i++].apply(null, data)).then(call);
1672
- } else {
1673
- return prev;
1674
- }
1675
- };
1676
- result = call();
1677
- }
1678
- return Promise.resolve(result);
1679
- }
1680
- }
1681
- function checkReturnData(originalData, returnedData) {
1682
- if (!isObject(returnedData)) {
1683
- return false;
1684
- }
1685
- if (originalData !== returnedData) {
1686
- for(const key in originalData){
1687
- if (!(key in returnedData)) {
1688
- return false;
1689
- }
1690
- }
1691
- }
1692
- return true;
1693
- }
1694
- class SyncWaterfallHook extends SyncHook {
1695
- emit(data) {
1696
- if (!isObject(data)) {
1697
- error(`The data for the "${this.type}" hook should be an object.`);
1698
- }
1699
- for (const fn of this.listeners){
1700
- try {
1701
- const tempData = fn(data);
1702
- if (checkReturnData(data, tempData)) {
1703
- data = tempData;
1704
- } else {
1705
- this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);
1706
- break;
1707
- }
1708
- } catch (e) {
1709
- warn(e);
1710
- this.onerror(e);
1711
- }
1712
- }
1713
- return data;
1714
- }
1715
- constructor(type){
1716
- super();
1717
- this.onerror = error;
1718
- this.type = type;
1719
- }
1720
- }
1721
- class AsyncWaterfallHook extends SyncHook {
1722
- emit(data) {
1723
- if (!isObject(data)) {
1724
- error(`The response data for the "${this.type}" hook must be an object.`);
1725
- }
1726
- const ls = Array.from(this.listeners);
1727
- if (ls.length > 0) {
1728
- let i = 0;
1729
- const processError = (e)=>{
1730
- warn(e);
1731
- this.onerror(e);
1732
- return data;
1733
- };
1734
- const call = (prevData)=>{
1735
- if (checkReturnData(data, prevData)) {
1736
- data = prevData;
1737
- if (i < ls.length) {
1738
- try {
1739
- return Promise.resolve(ls[i++](data)).then(call, processError);
1740
- } catch (e) {
1741
- return processError(e);
1742
- }
1743
- }
1744
- } else {
1745
- this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);
1746
- }
1747
- return data;
1748
- };
1749
- return Promise.resolve(call(data));
1750
- }
1751
- return Promise.resolve(data);
1752
- }
1753
- constructor(type){
1754
- super();
1755
- this.onerror = error;
1756
- this.type = type;
1757
- }
1758
- }
1759
- class PluginSystem {
1760
- applyPlugin(plugin) {
1761
- assert(isPlainObject(plugin), 'Plugin configuration is invalid.');
1762
- const pluginName = plugin.name;
1763
- assert(pluginName, 'A name must be provided by the plugin.');
1764
- if (!this.registerPlugins[pluginName]) {
1765
- this.registerPlugins[pluginName] = plugin;
1766
- Object.keys(this.lifecycle).forEach((key)=>{
1767
- const pluginLife = plugin[key];
1768
- if (pluginLife) {
1769
- this.lifecycle[key].on(pluginLife);
1770
- }
1771
- });
1772
- }
1773
- }
1774
- removePlugin(pluginName) {
1775
- assert(pluginName, 'A name is required.');
1776
- const plugin = this.registerPlugins[pluginName];
1777
- assert(plugin, `The plugin "${pluginName}" is not registered.`);
1778
- Object.keys(plugin).forEach((key)=>{
1779
- if (key !== 'name') {
1780
- this.lifecycle[key].remove(plugin[key]);
1781
- }
1782
- });
1783
- }
1784
- inherit({ lifecycle, registerPlugins }) {
1785
- Object.keys(lifecycle).forEach((hookName)=>{
1786
- assert(!this.lifecycle[hookName], `The hook "${hookName}" has a conflict and cannot be inherited.`);
1787
- this.lifecycle[hookName] = lifecycle[hookName];
1788
- });
1789
- Object.keys(registerPlugins).forEach((pluginName)=>{
1790
- assert(!this.registerPlugins[pluginName], `The plugin "${pluginName}" has a conflict and cannot be inherited.`);
1791
- this.applyPlugin(registerPlugins[pluginName]);
1792
- });
1793
- }
1794
- constructor(lifecycle){
1795
- this.registerPlugins = {};
1796
- this.lifecycle = lifecycle;
1797
- this.lifecycleKeys = Object.keys(lifecycle);
1798
- }
1799
- }
1800
- function defaultPreloadArgs(preloadConfig) {
1801
- return _({
1802
- resourceCategory: 'sync',
1803
- share: true,
1804
- depsRemote: true,
1805
- prefetchInterface: false
1806
- }, preloadConfig);
1807
- }
1808
- function formatPreloadArgs(remotes, preloadArgs) {
1809
- return preloadArgs.map((args)=>{
1810
- const remoteInfo = matchRemote(remotes, args.nameOrAlias);
1811
- assert(remoteInfo, `Unable to preload ${args.nameOrAlias} as it is not included in ${!remoteInfo && safeToString({
1812
- remoteInfo,
1813
- remotes
1814
- })}`);
1815
- return {
1816
- remote: remoteInfo,
1817
- preloadConfig: defaultPreloadArgs(args)
1818
- };
1819
- });
1820
- }
1821
- function normalizePreloadExposes(exposes) {
1822
- if (!exposes) {
1823
- return [];
1824
- }
1825
- return exposes.map((expose)=>{
1826
- if (expose === '.') {
1827
- return expose;
1828
- }
1829
- if (expose.startsWith('./')) {
1830
- return expose.replace('./', '');
1831
- }
1832
- return expose;
1833
- });
1834
- }
1835
- function preloadAssets(remoteInfo, host, assets, useLinkPreload = true) {
1836
- const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
1837
- if (host.options.inBrowser) {
1838
- entryAssets.forEach((asset)=>{
1839
- const { moduleInfo } = asset;
1840
- const module = host.moduleCache.get(remoteInfo.name);
1841
- if (module) {
1842
- getRemoteEntry({
1843
- origin: host,
1844
- remoteInfo: moduleInfo,
1845
- remoteEntryExports: module.remoteEntryExports
1846
- });
1847
- } else {
1848
- getRemoteEntry({
1849
- origin: host,
1850
- remoteInfo: moduleInfo,
1851
- remoteEntryExports: undefined
1852
- });
1853
- }
1854
- });
1855
- if (useLinkPreload) {
1856
- const defaultAttrs = {
1857
- rel: 'preload',
1858
- as: 'style',
1859
- crossorigin: 'anonymous'
1860
- };
1861
- cssAssets.forEach((cssUrl)=>{
1862
- const { link: cssEl, needAttach } = createLink({
1863
- url: cssUrl,
1864
- cb: ()=>{},
1865
- attrs: defaultAttrs,
1866
- createLinkHook: (url, attrs)=>{
1867
- const res = host.loaderHook.lifecycle.createLink.emit({
1868
- url,
1869
- attrs
1870
- });
1871
- if (res instanceof HTMLLinkElement) {
1872
- return res;
1873
- }
1874
- return;
1875
- }
1876
- });
1877
- needAttach && document.head.appendChild(cssEl);
1878
- });
1879
- } else {
1880
- const defaultAttrs = {
1881
- rel: 'stylesheet',
1882
- type: 'text/css'
1883
- };
1884
- cssAssets.forEach((cssUrl)=>{
1885
- const { link: cssEl, needAttach } = createLink({
1886
- url: cssUrl,
1887
- cb: ()=>{},
1888
- attrs: defaultAttrs,
1889
- createLinkHook: (url, attrs)=>{
1890
- const res = host.loaderHook.lifecycle.createLink.emit({
1891
- url,
1892
- attrs
1893
- });
1894
- if (res instanceof HTMLLinkElement) {
1895
- return res;
1896
- }
1897
- return;
1898
- },
1899
- needDeleteLink: false
1900
- });
1901
- needAttach && document.head.appendChild(cssEl);
1902
- });
1903
- }
1904
- if (useLinkPreload) {
1905
- const defaultAttrs = {
1906
- rel: 'preload',
1907
- as: 'script',
1908
- crossorigin: 'anonymous'
1909
- };
1910
- jsAssetsWithoutEntry.forEach((jsUrl)=>{
1911
- const { link: linkEl, needAttach } = createLink({
1912
- url: jsUrl,
1913
- cb: ()=>{},
1914
- attrs: defaultAttrs,
1915
- createLinkHook: (url, attrs)=>{
1916
- const res = host.loaderHook.lifecycle.createLink.emit({
1917
- url,
1918
- attrs
1919
- });
1920
- if (res instanceof HTMLLinkElement) {
1921
- return res;
1922
- }
1923
- return;
1924
- }
1925
- });
1926
- needAttach && document.head.appendChild(linkEl);
1927
- });
1928
- } else {
1929
- const defaultAttrs = {
1930
- fetchpriority: 'high',
1931
- type: (remoteInfo == null ? void 0 : remoteInfo.type) === 'module' ? 'module' : 'text/javascript'
1932
- };
1933
- jsAssetsWithoutEntry.forEach((jsUrl)=>{
1934
- const { script: scriptEl, needAttach } = createScript({
1935
- url: jsUrl,
1936
- cb: ()=>{},
1937
- attrs: defaultAttrs,
1938
- createScriptHook: (url, attrs)=>{
1939
- const res = host.loaderHook.lifecycle.createScript.emit({
1940
- url,
1941
- attrs
1942
- });
1943
- if (res instanceof HTMLScriptElement) {
1944
- return res;
1945
- }
1946
- return;
1947
- },
1948
- needDeleteScript: true
1949
- });
1950
- needAttach && document.head.appendChild(scriptEl);
1951
- });
1952
- }
1953
- }
1954
- }
1955
- function assignRemoteInfo(remoteInfo, remoteSnapshot) {
1956
- const remoteEntryInfo = getRemoteEntryInfoFromSnapshot(remoteSnapshot);
1957
- if (!remoteEntryInfo.url) {
1958
- error(`The attribute remoteEntry of ${remoteInfo.name} must not be undefined.`);
1959
- }
1960
- let entryUrl = getResourceUrl(remoteSnapshot, remoteEntryInfo.url);
1961
- if (!isBrowserEnv() && !entryUrl.startsWith('http')) {
1962
- entryUrl = `https:${entryUrl}`;
1963
- }
1964
- remoteInfo.type = remoteEntryInfo.type;
1965
- remoteInfo.entryGlobalName = remoteEntryInfo.globalName;
1966
- remoteInfo.entry = entryUrl;
1967
- remoteInfo.version = remoteSnapshot.version;
1968
- remoteInfo.buildVersion = remoteSnapshot.buildVersion;
1969
- }
1970
- function snapshotPlugin() {
1971
- return {
1972
- name: 'snapshot-plugin',
1973
- async afterResolve (args) {
1974
- const { remote, pkgNameOrAlias, expose, origin, remoteInfo } = args;
1975
- if (!isRemoteInfoWithEntry(remote) || !isPureRemoteEntry(remote)) {
1976
- const { remoteSnapshot, globalSnapshot } = await origin.snapshotHandler.loadRemoteSnapshotInfo(remote);
1977
- assignRemoteInfo(remoteInfo, remoteSnapshot);
1978
- const preloadOptions = {
1979
- remote,
1980
- preloadConfig: {
1981
- nameOrAlias: pkgNameOrAlias,
1982
- exposes: [
1983
- expose
1984
- ],
1985
- resourceCategory: 'sync',
1986
- share: false,
1987
- depsRemote: false
1988
- }
1989
- };
1990
- const assets = await origin.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({
1991
- origin,
1992
- preloadOptions,
1993
- remoteInfo,
1994
- remote,
1995
- remoteSnapshot,
1996
- globalSnapshot
1997
- });
1998
- if (assets) {
1999
- preloadAssets(remoteInfo, origin, assets, false);
2000
- }
2001
- return _({}, args, {
2002
- remoteSnapshot
2003
- });
2004
- }
2005
- return args;
2006
- }
2007
- };
2008
- }
2009
- function splitId(id) {
2010
- const splitInfo = id.split(':');
2011
- if (splitInfo.length === 1) {
2012
- return {
2013
- name: splitInfo[0],
2014
- version: undefined
2015
- };
2016
- } else if (splitInfo.length === 2) {
2017
- return {
2018
- name: splitInfo[0],
2019
- version: splitInfo[1]
2020
- };
2021
- } else {
2022
- return {
2023
- name: splitInfo[1],
2024
- version: splitInfo[2]
2025
- };
2026
- }
2027
- }
2028
- function traverseModuleInfo(globalSnapshot, remoteInfo, traverse, isRoot, memo = {}, remoteSnapshot) {
2029
- const id = getFMId(remoteInfo);
2030
- const { value: snapshotValue } = getInfoWithoutType(globalSnapshot, id);
2031
- const effectiveRemoteSnapshot = remoteSnapshot || snapshotValue;
2032
- if (effectiveRemoteSnapshot && !isManifestProvider(effectiveRemoteSnapshot)) {
2033
- traverse(effectiveRemoteSnapshot, remoteInfo, isRoot);
2034
- if (effectiveRemoteSnapshot.remotesInfo) {
2035
- const remoteKeys = Object.keys(effectiveRemoteSnapshot.remotesInfo);
2036
- for (const key of remoteKeys){
2037
- if (memo[key]) {
2038
- continue;
2039
- }
2040
- memo[key] = true;
2041
- const subRemoteInfo = splitId(key);
2042
- const remoteValue = effectiveRemoteSnapshot.remotesInfo[key];
2043
- traverseModuleInfo(globalSnapshot, {
2044
- name: subRemoteInfo.name,
2045
- version: remoteValue.matchedVersion
2046
- }, traverse, false, memo, undefined);
2047
- }
2048
- }
2049
- }
2050
- }
2051
- function generatePreloadAssets(origin, preloadOptions, remote, globalSnapshot, remoteSnapshot) {
2052
- const cssAssets = [];
2053
- const jsAssets = [];
2054
- const entryAssets = [];
2055
- const loadedSharedJsAssets = new Set();
2056
- const loadedSharedCssAssets = new Set();
2057
- const { options } = origin;
2058
- const { preloadConfig: rootPreloadConfig } = preloadOptions;
2059
- const { depsRemote } = rootPreloadConfig;
2060
- const memo = {};
2061
- traverseModuleInfo(globalSnapshot, remote, (moduleInfoSnapshot, remoteInfo, isRoot)=>{
2062
- let preloadConfig;
2063
- if (isRoot) {
2064
- preloadConfig = rootPreloadConfig;
2065
- } else {
2066
- if (Array.isArray(depsRemote)) {
2067
- const findPreloadConfig = depsRemote.find((remoteConfig)=>{
2068
- if (remoteConfig.nameOrAlias === remoteInfo.name || remoteConfig.nameOrAlias === remoteInfo.alias) {
2069
- return true;
2070
- }
2071
- return false;
2072
- });
2073
- if (!findPreloadConfig) {
2074
- return;
2075
- }
2076
- preloadConfig = defaultPreloadArgs(findPreloadConfig);
2077
- } else if (depsRemote === true) {
2078
- preloadConfig = rootPreloadConfig;
2079
- } else {
2080
- return;
2081
- }
2082
- }
2083
- const remoteEntryUrl = getResourceUrl(moduleInfoSnapshot, getRemoteEntryInfoFromSnapshot(moduleInfoSnapshot).url);
2084
- if (remoteEntryUrl) {
2085
- entryAssets.push({
2086
- name: remoteInfo.name,
2087
- moduleInfo: {
2088
- name: remoteInfo.name,
2089
- entry: remoteEntryUrl,
2090
- type: 'remoteEntryType' in moduleInfoSnapshot ? moduleInfoSnapshot.remoteEntryType : 'global',
2091
- entryGlobalName: 'globalName' in moduleInfoSnapshot ? moduleInfoSnapshot.globalName : remoteInfo.name,
2092
- shareScope: '',
2093
- version: 'version' in moduleInfoSnapshot ? moduleInfoSnapshot.version : undefined
2094
- },
2095
- url: remoteEntryUrl
2096
- });
2097
- }
2098
- let moduleAssetsInfo = 'modules' in moduleInfoSnapshot ? moduleInfoSnapshot.modules : [];
2099
- const normalizedPreloadExposes = normalizePreloadExposes(preloadConfig.exposes);
2100
- if (normalizedPreloadExposes.length && 'modules' in moduleInfoSnapshot) {
2101
- var _moduleInfoSnapshot_modules;
2102
- moduleAssetsInfo = moduleInfoSnapshot == null ? void 0 : (_moduleInfoSnapshot_modules = moduleInfoSnapshot.modules) == null ? void 0 : _moduleInfoSnapshot_modules.reduce((assets, moduleAssetInfo)=>{
2103
- if ((normalizedPreloadExposes == null ? void 0 : normalizedPreloadExposes.indexOf(moduleAssetInfo.moduleName)) !== -1) {
2104
- assets.push(moduleAssetInfo);
2105
- }
2106
- return assets;
2107
- }, []);
2108
- }
2109
- function handleAssets(assets) {
2110
- const assetsRes = assets.map((asset)=>getResourceUrl(moduleInfoSnapshot, asset));
2111
- if (preloadConfig.filter) {
2112
- return assetsRes.filter(preloadConfig.filter);
2113
- }
2114
- return assetsRes;
2115
- }
2116
- if (moduleAssetsInfo) {
2117
- const assetsLength = moduleAssetsInfo.length;
2118
- for(let index = 0; index < assetsLength; index++){
2119
- const assetsInfo = moduleAssetsInfo[index];
2120
- const exposeFullPath = `${remoteInfo.name}/${assetsInfo.moduleName}`;
2121
- origin.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({
2122
- id: assetsInfo.moduleName === '.' ? remoteInfo.name : exposeFullPath,
2123
- name: remoteInfo.name,
2124
- remoteSnapshot: moduleInfoSnapshot,
2125
- preloadConfig,
2126
- remote: remoteInfo,
2127
- origin
2128
- });
2129
- const preloaded = getPreloaded(exposeFullPath);
2130
- if (preloaded) {
2131
- continue;
2132
- }
2133
- if (preloadConfig.resourceCategory === 'all') {
2134
- cssAssets.push(...handleAssets(assetsInfo.assets.css.async));
2135
- cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
2136
- jsAssets.push(...handleAssets(assetsInfo.assets.js.async));
2137
- jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
2138
- } else if (preloadConfig.resourceCategory = 'sync') {
2139
- cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
2140
- jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
2141
- }
2142
- setPreloaded(exposeFullPath);
2143
- }
2144
- }
2145
- }, true, memo, remoteSnapshot);
2146
- if (remoteSnapshot.shared) {
2147
- const collectSharedAssets = (shareInfo, snapshotShared)=>{
2148
- const registeredShared = getRegisteredShare(origin.shareScopeMap, snapshotShared.sharedName, shareInfo, origin.sharedHandler.hooks.lifecycle.resolveShare);
2149
- if (registeredShared && typeof registeredShared.lib === 'function') {
2150
- snapshotShared.assets.js.sync.forEach((asset)=>{
2151
- loadedSharedJsAssets.add(asset);
2152
- });
2153
- snapshotShared.assets.css.sync.forEach((asset)=>{
2154
- loadedSharedCssAssets.add(asset);
2155
- });
2156
- }
2157
- };
2158
- remoteSnapshot.shared.forEach((shared)=>{
2159
- var _options_shared;
2160
- const shareInfos = (_options_shared = options.shared) == null ? void 0 : _options_shared[shared.sharedName];
2161
- if (!shareInfos) {
2162
- return;
2163
- }
2164
- const sharedOptions = shared.version ? shareInfos.find((s)=>s.version === shared.version) : shareInfos;
2165
- if (!sharedOptions) {
2166
- return;
2167
- }
2168
- const arrayShareInfo = arrayOptions(sharedOptions);
2169
- arrayShareInfo.forEach((s)=>{
2170
- collectSharedAssets(s, shared);
2171
- });
2172
- });
2173
- }
2174
- const needPreloadJsAssets = jsAssets.filter((asset)=>!loadedSharedJsAssets.has(asset));
2175
- const needPreloadCssAssets = cssAssets.filter((asset)=>!loadedSharedCssAssets.has(asset));
2176
- return {
2177
- cssAssets: needPreloadCssAssets,
2178
- jsAssetsWithoutEntry: needPreloadJsAssets,
2179
- entryAssets
2180
- };
2181
- }
2182
- const generatePreloadAssetsPlugin = function() {
2183
- return {
2184
- name: 'generate-preload-assets-plugin',
2185
- async generatePreloadAssets (args) {
2186
- const { origin, preloadOptions, remoteInfo, remote, globalSnapshot, remoteSnapshot } = args;
2187
- if (isRemoteInfoWithEntry(remote) && isPureRemoteEntry(remote)) {
2188
- return {
2189
- cssAssets: [],
2190
- jsAssetsWithoutEntry: [],
2191
- entryAssets: [
2192
- {
2193
- name: remote.name,
2194
- url: remote.entry,
2195
- moduleInfo: {
2196
- name: remoteInfo.name,
2197
- entry: remote.entry,
2198
- type: 'global',
2199
- entryGlobalName: '',
2200
- shareScope: ''
2201
- }
2202
- }
2203
- ]
2204
- };
2205
- }
2206
- assignRemoteInfo(remoteInfo, remoteSnapshot);
2207
- const assets = generatePreloadAssets(origin, preloadOptions, remoteInfo, globalSnapshot, remoteSnapshot);
2208
- return assets;
2209
- }
2210
- };
2211
- };
2212
- function getGlobalRemoteInfo(moduleInfo, origin) {
2213
- const hostGlobalSnapshot = getGlobalSnapshotInfoByModuleInfo({
2214
- name: origin.options.name,
2215
- version: origin.options.version
2216
- });
2217
- const globalRemoteInfo = hostGlobalSnapshot && 'remotesInfo' in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, moduleInfo.name).value;
2218
- if (globalRemoteInfo && globalRemoteInfo.matchedVersion) {
2219
- return {
2220
- hostGlobalSnapshot,
2221
- globalSnapshot: getGlobalSnapshot(),
2222
- remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
2223
- name: moduleInfo.name,
2224
- version: globalRemoteInfo.matchedVersion
2225
- })
2226
- };
2227
- }
2228
- return {
2229
- hostGlobalSnapshot: undefined,
2230
- globalSnapshot: getGlobalSnapshot(),
2231
- remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
2232
- name: moduleInfo.name,
2233
- version: 'version' in moduleInfo ? moduleInfo.version : undefined
2234
- })
2235
- };
2236
- }
2237
- class SnapshotHandler {
2238
- async loadSnapshot(moduleInfo) {
2239
- const { options } = this.HostInstance;
2240
- const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
2241
- const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
2242
- options,
2243
- moduleInfo,
2244
- hostGlobalSnapshot,
2245
- remoteSnapshot,
2246
- globalSnapshot
2247
- });
2248
- return {
2249
- remoteSnapshot: globalRemoteSnapshot,
2250
- globalSnapshot: globalSnapshotRes
2251
- };
2252
- }
2253
- async loadRemoteSnapshotInfo(moduleInfo) {
2254
- const { options } = this.HostInstance;
2255
- await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({
2256
- options,
2257
- moduleInfo
2258
- });
2259
- let hostSnapshot = getGlobalSnapshotInfoByModuleInfo({
2260
- name: this.HostInstance.options.name,
2261
- version: this.HostInstance.options.version
2262
- });
2263
- if (!hostSnapshot) {
2264
- hostSnapshot = {
2265
- version: this.HostInstance.options.version || '',
2266
- remoteEntry: '',
2267
- remotesInfo: {}
2268
- };
2269
- addGlobalSnapshot({
2270
- [this.HostInstance.options.name]: hostSnapshot
2271
- });
2272
- }
2273
- if (hostSnapshot && 'remotesInfo' in hostSnapshot && !getInfoWithoutType(hostSnapshot.remotesInfo, moduleInfo.name).value) {
2274
- if ('version' in moduleInfo || 'entry' in moduleInfo) {
2275
- hostSnapshot.remotesInfo = _({}, hostSnapshot == null ? void 0 : hostSnapshot.remotesInfo, {
2276
- [moduleInfo.name]: {
2277
- matchedVersion: 'version' in moduleInfo ? moduleInfo.version : moduleInfo.entry
2278
- }
2279
- });
2280
- }
2281
- }
2282
- const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
2283
- const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
2284
- options,
2285
- moduleInfo,
2286
- hostGlobalSnapshot,
2287
- remoteSnapshot,
2288
- globalSnapshot
2289
- });
2290
- if (globalRemoteSnapshot) {
2291
- if (isManifestProvider(globalRemoteSnapshot)) {
2292
- const remoteEntry = isBrowserEnv() ? globalRemoteSnapshot.remoteEntry : globalRemoteSnapshot.ssrRemoteEntry || globalRemoteSnapshot.remoteEntry || '';
2293
- const moduleSnapshot = await this.getManifestJson(remoteEntry, moduleInfo, {});
2294
- const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo(_({}, moduleInfo, {
2295
- entry: remoteEntry
2296
- }), moduleSnapshot);
2297
- return {
2298
- remoteSnapshot: moduleSnapshot,
2299
- globalSnapshot: globalSnapshotRes
2300
- };
2301
- } else {
2302
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2303
- options: this.HostInstance.options,
2304
- moduleInfo,
2305
- remoteSnapshot: globalRemoteSnapshot,
2306
- from: 'global'
2307
- });
2308
- return {
2309
- remoteSnapshot: remoteSnapshotRes,
2310
- globalSnapshot: globalSnapshotRes
2311
- };
2312
- }
2313
- } else {
2314
- if (isRemoteInfoWithEntry(moduleInfo)) {
2315
- const moduleSnapshot = await this.getManifestJson(moduleInfo.entry, moduleInfo, {});
2316
- const globalSnapshotRes = setGlobalSnapshotInfoByModuleInfo(moduleInfo, moduleSnapshot);
2317
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2318
- options: this.HostInstance.options,
2319
- moduleInfo,
2320
- remoteSnapshot: moduleSnapshot,
2321
- from: 'global'
2322
- });
2323
- return {
2324
- remoteSnapshot: remoteSnapshotRes,
2325
- globalSnapshot: globalSnapshotRes
2326
- };
2327
- } else {
2328
- error(`
2329
- Cannot get remoteSnapshot with the name: '${moduleInfo.name}', version: '${moduleInfo.version}' from __FEDERATION__.moduleInfo. The following reasons may be causing the problem:\n
2330
- 1. The Deploy platform did not deliver the correct data. You can use __FEDERATION__.moduleInfo to check the remoteInfo.\n
2331
- 2. The remote '${moduleInfo.name}' version '${moduleInfo.version}' is not released.\n
2332
- The transformed module info: ${JSON.stringify(globalSnapshotRes)}
2333
- `);
2334
- }
2335
- }
2336
- }
2337
- getGlobalRemoteInfo(moduleInfo) {
2338
- return getGlobalRemoteInfo(moduleInfo, this.HostInstance);
2339
- }
2340
- async getManifestJson(manifestUrl, moduleInfo, extraOptions) {
2341
- const getManifest = async ()=>{
2342
- let manifestJson = this.manifestCache.get(manifestUrl);
2343
- if (manifestJson) {
2344
- return manifestJson;
2345
- }
2346
- try {
2347
- let res = await this.loaderHook.lifecycle.fetch.emit(manifestUrl, {});
2348
- if (!res || !(res instanceof Response)) {
2349
- res = await fetch(manifestUrl, {});
2350
- }
2351
- manifestJson = await res.json();
2352
- assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
2353
- this.manifestCache.set(manifestUrl, manifestJson);
2354
- return manifestJson;
2355
- } catch (err) {
2356
- delete this.manifestLoading[manifestUrl];
2357
- error(`Failed to get manifestJson for ${moduleInfo.name}. The manifest URL is ${manifestUrl}. Please ensure that the manifestUrl is accessible.
2358
- \n Error message:
2359
- \n ${err}`);
2360
- }
2361
- };
2362
- const asyncLoadProcess = async ()=>{
2363
- const manifestJson = await getManifest();
2364
- const remoteSnapshot = generateSnapshotFromManifest(manifestJson, {
2365
- version: manifestUrl
2366
- });
2367
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2368
- options: this.HostInstance.options,
2369
- moduleInfo,
2370
- manifestJson,
2371
- remoteSnapshot,
2372
- manifestUrl,
2373
- from: 'manifest'
2374
- });
2375
- return remoteSnapshotRes;
2376
- };
2377
- if (!this.manifestLoading[manifestUrl]) {
2378
- this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res)=>res);
2379
- }
2380
- return this.manifestLoading[manifestUrl];
2381
- }
2382
- constructor(HostInstance){
2383
- this.loadingHostSnapshot = null;
2384
- this.manifestCache = new Map();
2385
- this.hooks = new PluginSystem({
2386
- beforeLoadRemoteSnapshot: new AsyncHook('beforeLoadRemoteSnapshot'),
2387
- loadSnapshot: new AsyncWaterfallHook('loadGlobalSnapshot'),
2388
- loadRemoteSnapshot: new AsyncWaterfallHook('loadRemoteSnapshot')
2389
- });
2390
- this.manifestLoading = Global.__FEDERATION__.__MANIFEST_LOADING__;
2391
- this.HostInstance = HostInstance;
2392
- this.loaderHook = HostInstance.loaderHook;
2393
- }
2394
- }
2395
- class SharedHandler {
2396
- registerShared(globalOptions, userOptions) {
2397
- const { shareInfos, shared } = formatShareConfigs(globalOptions, userOptions);
2398
- const sharedKeys = Object.keys(shareInfos);
2399
- sharedKeys.forEach((sharedKey)=>{
2400
- const sharedVals = shareInfos[sharedKey];
2401
- sharedVals.forEach((sharedVal)=>{
2402
- const registeredShared = getRegisteredShare(this.shareScopeMap, sharedKey, sharedVal, this.hooks.lifecycle.resolveShare);
2403
- if (!registeredShared && sharedVal && sharedVal.lib) {
2404
- this.setShared({
2405
- pkgName: sharedKey,
2406
- lib: sharedVal.lib,
2407
- get: sharedVal.get,
2408
- loaded: true,
2409
- shared: sharedVal,
2410
- from: userOptions.name
2411
- });
2412
- }
2413
- });
2414
- });
2415
- return {
2416
- shareInfos,
2417
- shared
2418
- };
2419
- }
2420
- async loadShare(pkgName, extraOptions) {
2421
- const { host } = this;
2422
- const shareInfo = getTargetSharedOptions({
2423
- pkgName,
2424
- extraOptions,
2425
- shareInfos: host.options.shared
2426
- });
2427
- if (shareInfo == null ? void 0 : shareInfo.scope) {
2428
- await Promise.all(shareInfo.scope.map(async (shareScope)=>{
2429
- await Promise.all(this.initializeSharing(shareScope, {
2430
- strategy: shareInfo.strategy
2431
- }));
2432
- return;
2433
- }));
2434
- }
2435
- const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
2436
- pkgName,
2437
- shareInfo,
2438
- shared: host.options.shared,
2439
- origin: host
2440
- });
2441
- const { shareInfo: shareInfoRes } = loadShareRes;
2442
- assert(shareInfoRes, `Cannot find ${pkgName} Share in the ${host.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
2443
- const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2444
- const addUseIn = (shared)=>{
2445
- if (!shared.useIn) {
2446
- shared.useIn = [];
2447
- }
2448
- addUniqueItem(shared.useIn, host.options.name);
2449
- };
2450
- if (registeredShared && registeredShared.lib) {
2451
- addUseIn(registeredShared);
2452
- return registeredShared.lib;
2453
- } else if (registeredShared && registeredShared.loading && !registeredShared.loaded) {
2454
- const factory = await registeredShared.loading;
2455
- registeredShared.loaded = true;
2456
- if (!registeredShared.lib) {
2457
- registeredShared.lib = factory;
2458
- }
2459
- addUseIn(registeredShared);
2460
- return factory;
2461
- } else if (registeredShared) {
2462
- const asyncLoadProcess = async ()=>{
2463
- const factory = await registeredShared.get();
2464
- shareInfoRes.lib = factory;
2465
- shareInfoRes.loaded = true;
2466
- addUseIn(shareInfoRes);
2467
- const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2468
- if (gShared) {
2469
- gShared.lib = factory;
2470
- gShared.loaded = true;
2471
- }
2472
- return factory;
2473
- };
2474
- const loading = asyncLoadProcess();
2475
- this.setShared({
2476
- pkgName,
2477
- loaded: false,
2478
- shared: registeredShared,
2479
- from: host.options.name,
2480
- lib: null,
2481
- loading
2482
- });
2483
- return loading;
2484
- } else {
2485
- if (extraOptions == null ? void 0 : extraOptions.customShareInfo) {
2486
- return false;
2487
- }
2488
- const asyncLoadProcess = async ()=>{
2489
- const factory = await shareInfoRes.get();
2490
- shareInfoRes.lib = factory;
2491
- shareInfoRes.loaded = true;
2492
- addUseIn(shareInfoRes);
2493
- const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2494
- if (gShared) {
2495
- gShared.lib = factory;
2496
- gShared.loaded = true;
2497
- }
2498
- return factory;
2499
- };
2500
- const loading = asyncLoadProcess();
2501
- this.setShared({
2502
- pkgName,
2503
- loaded: false,
2504
- shared: shareInfoRes,
2505
- from: host.options.name,
2506
- lib: null,
2507
- loading
2508
- });
2509
- return loading;
2510
- }
2511
- }
2512
- initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
2513
- const { host } = this;
2514
- const from = extraOptions == null ? void 0 : extraOptions.from;
2515
- const strategy = extraOptions == null ? void 0 : extraOptions.strategy;
2516
- let initScope = extraOptions == null ? void 0 : extraOptions.initScope;
2517
- const promises = [];
2518
- if (from !== 'build') {
2519
- const { initTokens } = this;
2520
- if (!initScope) initScope = [];
2521
- let initToken = initTokens[shareScopeName];
2522
- if (!initToken) initToken = initTokens[shareScopeName] = {
2523
- from: this.host.name
2524
- };
2525
- if (initScope.indexOf(initToken) >= 0) return promises;
2526
- initScope.push(initToken);
2527
- }
2528
- const shareScope = this.shareScopeMap;
2529
- const hostName = host.options.name;
2530
- if (!shareScope[shareScopeName]) {
2531
- shareScope[shareScopeName] = {};
2532
- }
2533
- const scope = shareScope[shareScopeName];
2534
- const register = (name, shared)=>{
2535
- var _activeVersion_shareConfig;
2536
- const { version, eager } = shared;
2537
- scope[name] = scope[name] || {};
2538
- const versions = scope[name];
2539
- const activeVersion = versions[version];
2540
- const activeVersionEager = Boolean(activeVersion && (activeVersion.eager || ((_activeVersion_shareConfig = activeVersion.shareConfig) == null ? void 0 : _activeVersion_shareConfig.eager)));
2541
- if (!activeVersion || activeVersion.strategy !== 'loaded-first' && !activeVersion.loaded && (Boolean(!eager) !== !activeVersionEager ? eager : hostName > activeVersion.from)) {
2542
- versions[version] = shared;
2543
- }
2544
- };
2545
- const initFn = (mod)=>mod && mod.init && mod.init(shareScope[shareScopeName], initScope);
2546
- const initRemoteModule = async (key)=>{
2547
- const { module } = await host.remoteHandler.getRemoteModuleAndOptions({
2548
- id: key
2549
- });
2550
- if (module.getEntry) {
2551
- const entry = await module.getEntry();
2552
- if (!module.inited) {
2553
- await initFn(entry);
2554
- module.inited = true;
2555
- }
2556
- }
2557
- };
2558
- Object.keys(host.options.shared).forEach((shareName)=>{
2559
- const sharedArr = host.options.shared[shareName];
2560
- sharedArr.forEach((shared)=>{
2561
- if (shared.scope.includes(shareScopeName)) {
2562
- register(shareName, shared);
2563
- }
2564
- });
2565
- });
2566
- if (host.options.shareStrategy === 'version-first' || strategy === 'version-first') {
2567
- host.options.remotes.forEach((remote)=>{
2568
- if (remote.shareScope === shareScopeName) {
2569
- promises.push(initRemoteModule(remote.name));
2570
- }
2571
- });
2572
- }
2573
- return promises;
2574
- }
2575
- loadShareSync(pkgName, extraOptions) {
2576
- const { host } = this;
2577
- const shareInfo = getTargetSharedOptions({
2578
- pkgName,
2579
- extraOptions,
2580
- shareInfos: host.options.shared
2581
- });
2582
- if (shareInfo == null ? void 0 : shareInfo.scope) {
2583
- shareInfo.scope.forEach((shareScope)=>{
2584
- this.initializeSharing(shareScope, {
2585
- strategy: shareInfo.strategy
2586
- });
2587
- });
2588
- }
2589
- const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfo, this.hooks.lifecycle.resolveShare);
2590
- const addUseIn = (shared)=>{
2591
- if (!shared.useIn) {
2592
- shared.useIn = [];
2593
- }
2594
- addUniqueItem(shared.useIn, host.options.name);
2595
- };
2596
- if (registeredShared) {
2597
- if (typeof registeredShared.lib === 'function') {
2598
- addUseIn(registeredShared);
2599
- if (!registeredShared.loaded) {
2600
- registeredShared.loaded = true;
2601
- if (registeredShared.from === host.options.name) {
2602
- shareInfo.loaded = true;
2603
- }
2604
- }
2605
- return registeredShared.lib;
2606
- }
2607
- if (typeof registeredShared.get === 'function') {
2608
- const module = registeredShared.get();
2609
- if (!(module instanceof Promise)) {
2610
- addUseIn(registeredShared);
2611
- this.setShared({
2612
- pkgName,
2613
- loaded: true,
2614
- from: host.options.name,
2615
- lib: module,
2616
- shared: registeredShared
2617
- });
2618
- return module;
2619
- }
2620
- }
2621
- }
2622
- if (shareInfo.lib) {
2623
- if (!shareInfo.loaded) {
2624
- shareInfo.loaded = true;
2625
- }
2626
- return shareInfo.lib;
2627
- }
2628
- if (shareInfo.get) {
2629
- const module = shareInfo.get();
2630
- if (module instanceof Promise) {
2631
- throw new Error(`
2632
- The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${host.options.name}.
2633
- Possible reasons for failure: \n
2634
- 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
2635
- 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
2636
- `);
2637
- }
2638
- shareInfo.lib = module;
2639
- this.setShared({
2640
- pkgName,
2641
- loaded: true,
2642
- from: host.options.name,
2643
- lib: shareInfo.lib,
2644
- shared: shareInfo
2645
- });
2646
- return shareInfo.lib;
2647
- }
2648
- throw new Error(`
2649
- The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${host.options.name}.
2650
- Possible reasons for failure: \n
2651
- 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
2652
- 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
2653
- `);
2654
- }
2655
- initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
2656
- const { host } = this;
2657
- this.shareScopeMap[scopeName] = shareScope;
2658
- this.hooks.lifecycle.initContainerShareScopeMap.emit({
2659
- shareScope,
2660
- options: host.options,
2661
- origin: host,
2662
- scopeName,
2663
- hostShareScopeMap: extraOptions.hostShareScopeMap
2664
- });
2665
- }
2666
- setShared({ pkgName, shared, from, lib, loading, loaded, get }) {
2667
- const { version, scope = 'default' } = shared, shareInfo = _$1(shared, [
2668
- "version",
2669
- "scope"
2670
- ]);
2671
- const scopes = Array.isArray(scope) ? scope : [
2672
- scope
2673
- ];
2674
- scopes.forEach((sc)=>{
2675
- if (!this.shareScopeMap[sc]) {
2676
- this.shareScopeMap[sc] = {};
2677
- }
2678
- if (!this.shareScopeMap[sc][pkgName]) {
2679
- this.shareScopeMap[sc][pkgName] = {};
2680
- }
2681
- if (this.shareScopeMap[sc][pkgName][version]) {
2682
- return;
2683
- }
2684
- this.shareScopeMap[sc][pkgName][version] = _({
2685
- version,
2686
- scope: [
2687
- 'default'
2688
- ]
2689
- }, shareInfo, {
2690
- lib,
2691
- loaded,
2692
- loading
2693
- });
2694
- if (get) {
2695
- this.shareScopeMap[sc][pkgName][version].get = get;
2696
- }
2697
- });
2698
- }
2699
- _setGlobalShareScopeMap(hostOptions) {
2700
- const globalShareScopeMap = getGlobalShareScope();
2701
- const identifier = hostOptions.id || hostOptions.name;
2702
- if (identifier && !globalShareScopeMap[identifier]) {
2703
- globalShareScopeMap[identifier] = this.shareScopeMap;
2704
- }
2705
- }
2706
- constructor(host){
2707
- this.hooks = new PluginSystem({
2708
- afterResolve: new AsyncWaterfallHook('afterResolve'),
2709
- beforeLoadShare: new AsyncWaterfallHook('beforeLoadShare'),
2710
- loadShare: new AsyncHook(),
2711
- resolveShare: new SyncWaterfallHook('resolveShare'),
2712
- initContainerShareScopeMap: new SyncWaterfallHook('initContainerShareScopeMap')
2713
- });
2714
- this.host = host;
2715
- this.shareScopeMap = {};
2716
- this.initTokens = {};
2717
- this._setGlobalShareScopeMap(host.options);
2718
- }
2719
- }
2720
- class RemoteHandler {
2721
- formatAndRegisterRemote(globalOptions, userOptions) {
2722
- const userRemotes = userOptions.remotes || [];
2723
- return userRemotes.reduce((res, remote)=>{
2724
- this.registerRemote(remote, res, {
2725
- force: false
2726
- });
2727
- return res;
2728
- }, globalOptions.remotes);
2729
- }
2730
- setIdToRemoteMap(id, remoteMatchInfo) {
2731
- const { remote, expose } = remoteMatchInfo;
2732
- const { name, alias } = remote;
2733
- this.idToRemoteMap[id] = {
2734
- name: remote.name,
2735
- expose
2736
- };
2737
- if (alias && id.startsWith(name)) {
2738
- const idWithAlias = id.replace(name, alias);
2739
- this.idToRemoteMap[idWithAlias] = {
2740
- name: remote.name,
2741
- expose
2742
- };
2743
- return;
2744
- }
2745
- if (alias && id.startsWith(alias)) {
2746
- const idWithName = id.replace(alias, name);
2747
- this.idToRemoteMap[idWithName] = {
2748
- name: remote.name,
2749
- expose
2750
- };
2751
- }
2752
- }
2753
- async loadRemote(id, options) {
2754
- const { host } = this;
2755
- try {
2756
- const { loadFactory = true } = options || {
2757
- loadFactory: true
2758
- };
2759
- const { module, moduleOptions, remoteMatchInfo } = await this.getRemoteModuleAndOptions({
2760
- id
2761
- });
2762
- const { pkgNameOrAlias, remote, expose, id: idRes } = remoteMatchInfo;
2763
- const moduleOrFactory = await module.get(idRes, expose, options);
2764
- const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
2765
- id: idRes,
2766
- pkgNameOrAlias,
2767
- expose,
2768
- exposeModule: loadFactory ? moduleOrFactory : undefined,
2769
- exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
2770
- remote,
2771
- options: moduleOptions,
2772
- moduleInstance: module,
2773
- origin: host
2774
- });
2775
- this.setIdToRemoteMap(id, remoteMatchInfo);
2776
- if (typeof moduleWrapper === 'function') {
2777
- return moduleWrapper;
2778
- }
2779
- return moduleOrFactory;
2780
- } catch (error) {
2781
- const { from = 'runtime' } = options || {
2782
- from: 'runtime'
2783
- };
2784
- const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
2785
- id,
2786
- error,
2787
- from,
2788
- lifecycle: 'onLoad',
2789
- origin: host
2790
- });
2791
- if (!failOver) {
2792
- throw error;
2793
- }
2794
- return failOver;
2795
- }
2796
- }
2797
- async preloadRemote(preloadOptions) {
2798
- const { host } = this;
2799
- await this.hooks.lifecycle.beforePreloadRemote.emit({
2800
- preloadOps: preloadOptions,
2801
- options: host.options,
2802
- origin: host
2803
- });
2804
- const preloadOps = formatPreloadArgs(host.options.remotes, preloadOptions);
2805
- await Promise.all(preloadOps.map(async (ops)=>{
2806
- const { remote } = ops;
2807
- const remoteInfo = getRemoteInfo(remote);
2808
- const { globalSnapshot, remoteSnapshot } = await host.snapshotHandler.loadRemoteSnapshotInfo(remote);
2809
- const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
2810
- origin: host,
2811
- preloadOptions: ops,
2812
- remote,
2813
- remoteInfo,
2814
- globalSnapshot,
2815
- remoteSnapshot
2816
- });
2817
- if (!assets) {
2818
- return;
2819
- }
2820
- preloadAssets(remoteInfo, host, assets);
2821
- }));
2822
- }
2823
- registerRemotes(remotes, options) {
2824
- const { host } = this;
2825
- remotes.forEach((remote)=>{
2826
- this.registerRemote(remote, host.options.remotes, {
2827
- force: options == null ? void 0 : options.force
2828
- });
2829
- });
2830
- }
2831
- async getRemoteModuleAndOptions(options) {
2832
- const { host } = this;
2833
- const { id } = options;
2834
- let loadRemoteArgs;
2835
- try {
2836
- loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
2837
- id,
2838
- options: host.options,
2839
- origin: host
2840
- });
2841
- } catch (error) {
2842
- loadRemoteArgs = await this.hooks.lifecycle.errorLoadRemote.emit({
2843
- id,
2844
- options: host.options,
2845
- origin: host,
2846
- from: 'runtime',
2847
- error,
2848
- lifecycle: 'beforeRequest'
2849
- });
2850
- if (!loadRemoteArgs) {
2851
- throw error;
2852
- }
2853
- }
2854
- const { id: idRes } = loadRemoteArgs;
2855
- const remoteSplitInfo = matchRemoteWithNameAndExpose(host.options.remotes, idRes);
2856
- assert(remoteSplitInfo, `
2857
- Unable to locate ${idRes} in ${host.options.name}. Potential reasons for failure include:\n
2858
- 1. ${idRes} was not included in the 'remotes' parameter of ${host.options.name || 'the host'}.\n
2859
- 2. ${idRes} could not be found in the 'remotes' of ${host.options.name} with either 'name' or 'alias' attributes.
2860
- 3. ${idRes} is not online, injected, or loaded.
2861
- 4. ${idRes} cannot be accessed on the expected.
2862
- 5. The 'beforeRequest' hook was provided but did not return the correct 'remoteInfo' when attempting to load ${idRes}.
2863
- `);
2864
- const { remote: rawRemote } = remoteSplitInfo;
2865
- const remoteInfo = getRemoteInfo(rawRemote);
2866
- const matchInfo = await host.sharedHandler.hooks.lifecycle.afterResolve.emit(_({
2867
- id: idRes
2868
- }, remoteSplitInfo, {
2869
- options: host.options,
2870
- origin: host,
2871
- remoteInfo
2872
- }));
2873
- const { remote, expose } = matchInfo;
2874
- assert(remote && expose, `The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
2875
- let module = host.moduleCache.get(remote.name);
2876
- const moduleOptions = {
2877
- host: host,
2878
- remoteInfo
2879
- };
2880
- if (!module) {
2881
- module = new Module(moduleOptions);
2882
- host.moduleCache.set(remote.name, module);
2883
- }
2884
- return {
2885
- module,
2886
- moduleOptions,
2887
- remoteMatchInfo: matchInfo
2888
- };
2889
- }
2890
- registerRemote(remote, targetRemotes, options) {
2891
- const { host } = this;
2892
- const normalizeRemote = ()=>{
2893
- if (remote.alias) {
2894
- const findEqual = targetRemotes.find((item)=>{
2895
- var _item_alias;
2896
- return remote.alias && (item.name.startsWith(remote.alias) || ((_item_alias = item.alias) == null ? void 0 : _item_alias.startsWith(remote.alias)));
2897
- });
2898
- assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
2899
- }
2900
- if ('entry' in remote) {
2901
- if (isBrowserEnv() && !remote.entry.startsWith('http')) {
2902
- remote.entry = new URL(remote.entry, window.location.origin).href;
2903
- }
2904
- }
2905
- if (!remote.shareScope) {
2906
- remote.shareScope = DEFAULT_SCOPE;
2907
- }
2908
- if (!remote.type) {
2909
- remote.type = DEFAULT_REMOTE_TYPE;
2910
- }
2911
- };
2912
- this.hooks.lifecycle.beforeRegisterRemote.emit({
2913
- remote,
2914
- origin: host
2915
- });
2916
- const registeredRemote = targetRemotes.find((item)=>item.name === remote.name);
2917
- if (!registeredRemote) {
2918
- normalizeRemote();
2919
- targetRemotes.push(remote);
2920
- this.hooks.lifecycle.registerRemote.emit({
2921
- remote,
2922
- origin: host
2923
- });
2924
- } else {
2925
- const messages = [
2926
- `The remote "${remote.name}" is already registered.`,
2927
- (options == null ? void 0 : options.force) ? 'Hope you have known that OVERRIDE it may have some unexpected errors' : 'If you want to merge the remote, you can set "force: true".'
2928
- ];
2929
- if (options == null ? void 0 : options.force) {
2930
- this.removeRemote(registeredRemote);
2931
- normalizeRemote();
2932
- targetRemotes.push(remote);
2933
- this.hooks.lifecycle.registerRemote.emit({
2934
- remote,
2935
- origin: host
2936
- });
2937
- }
2938
- warn$1(messages.join(' '));
2939
- }
2940
- }
2941
- removeRemote(remote) {
2942
- try {
2943
- const { host } = this;
2944
- const { name } = remote;
2945
- const remoteIndex = host.options.remotes.findIndex((item)=>item.name === name);
2946
- if (remoteIndex !== -1) {
2947
- host.options.remotes.splice(remoteIndex, 1);
2948
- }
2949
- const loadedModule = host.moduleCache.get(remote.name);
2950
- if (loadedModule) {
2951
- const remoteInfo = loadedModule.remoteInfo;
2952
- const key = remoteInfo.entryGlobalName;
2953
- if (globalThis[key]) {
2954
- var _Object_getOwnPropertyDescriptor;
2955
- if ((_Object_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(globalThis, key)) == null ? void 0 : _Object_getOwnPropertyDescriptor.configurable) {
2956
- delete globalThis[key];
2957
- } else {
2958
- globalThis[key] = undefined;
2959
- }
2960
- }
2961
- const remoteEntryUniqueKey = getRemoteEntryUniqueKey(loadedModule.remoteInfo);
2962
- if (globalLoading[remoteEntryUniqueKey]) {
2963
- delete globalLoading[remoteEntryUniqueKey];
2964
- }
2965
- host.snapshotHandler.manifestCache.delete(remoteInfo.entry);
2966
- let remoteInsId = remoteInfo.buildVersion ? composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion) : remoteInfo.name;
2967
- const remoteInsIndex = globalThis.__FEDERATION__.__INSTANCES__.findIndex((ins)=>{
2968
- if (remoteInfo.buildVersion) {
2969
- return ins.options.id === remoteInsId;
2970
- } else {
2971
- return ins.name === remoteInsId;
2972
- }
2973
- });
2974
- if (remoteInsIndex !== -1) {
2975
- const remoteIns = globalThis.__FEDERATION__.__INSTANCES__[remoteInsIndex];
2976
- remoteInsId = remoteIns.options.id || remoteInsId;
2977
- const globalShareScopeMap = getGlobalShareScope();
2978
- let isAllSharedNotUsed = true;
2979
- const needDeleteKeys = [];
2980
- Object.keys(globalShareScopeMap).forEach((instId)=>{
2981
- const shareScopeMap = globalShareScopeMap[instId];
2982
- shareScopeMap && Object.keys(shareScopeMap).forEach((shareScope)=>{
2983
- const shareScopeVal = shareScopeMap[shareScope];
2984
- shareScopeVal && Object.keys(shareScopeVal).forEach((shareName)=>{
2985
- const sharedPkgs = shareScopeVal[shareName];
2986
- sharedPkgs && Object.keys(sharedPkgs).forEach((shareVersion)=>{
2987
- const shared = sharedPkgs[shareVersion];
2988
- if (shared && typeof shared === 'object' && shared.from === remoteInfo.name) {
2989
- if (shared.loaded || shared.loading) {
2990
- shared.useIn = shared.useIn.filter((usedHostName)=>usedHostName !== remoteInfo.name);
2991
- if (shared.useIn.length) {
2992
- isAllSharedNotUsed = false;
2993
- } else {
2994
- needDeleteKeys.push([
2995
- instId,
2996
- shareScope,
2997
- shareName,
2998
- shareVersion
2999
- ]);
3000
- }
3001
- } else {
3002
- needDeleteKeys.push([
3003
- instId,
3004
- shareScope,
3005
- shareName,
3006
- shareVersion
3007
- ]);
3008
- }
3009
- }
3010
- });
3011
- });
3012
- });
3013
- });
3014
- if (isAllSharedNotUsed) {
3015
- remoteIns.shareScopeMap = {};
3016
- delete globalShareScopeMap[remoteInsId];
3017
- }
3018
- needDeleteKeys.forEach(([insId, shareScope, shareName, shareVersion])=>{
3019
- var _globalShareScopeMap_insId_shareScope_shareName, _globalShareScopeMap_insId_shareScope, _globalShareScopeMap_insId;
3020
- (_globalShareScopeMap_insId = globalShareScopeMap[insId]) == null ? true : (_globalShareScopeMap_insId_shareScope = _globalShareScopeMap_insId[shareScope]) == null ? true : (_globalShareScopeMap_insId_shareScope_shareName = _globalShareScopeMap_insId_shareScope[shareName]) == null ? true : delete _globalShareScopeMap_insId_shareScope_shareName[shareVersion];
3021
- });
3022
- globalThis.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
3023
- }
3024
- const { hostGlobalSnapshot } = getGlobalRemoteInfo(remote, host);
3025
- if (hostGlobalSnapshot) {
3026
- const remoteKey = hostGlobalSnapshot && 'remotesInfo' in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, remote.name).key;
3027
- if (remoteKey) {
3028
- delete hostGlobalSnapshot.remotesInfo[remoteKey];
3029
- if (Boolean(Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey])) {
3030
- delete Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey];
3031
- }
3032
- }
3033
- }
3034
- host.moduleCache.delete(remote.name);
3035
- }
3036
- } catch (err) {
3037
- console.log('removeRemote fail: ', err);
3038
- }
3039
- }
3040
- constructor(host){
3041
- this.hooks = new PluginSystem({
3042
- beforeRegisterRemote: new SyncWaterfallHook('beforeRegisterRemote'),
3043
- registerRemote: new SyncWaterfallHook('registerRemote'),
3044
- beforeRequest: new AsyncWaterfallHook('beforeRequest'),
3045
- onLoad: new AsyncHook('onLoad'),
3046
- handlePreloadModule: new SyncHook('handlePreloadModule'),
3047
- errorLoadRemote: new AsyncHook('errorLoadRemote'),
3048
- beforePreloadRemote: new AsyncHook('beforePreloadRemote'),
3049
- generatePreloadAssets: new AsyncHook('generatePreloadAssets'),
3050
- afterPreloadRemote: new AsyncHook(),
3051
- loadEntry: new AsyncHook()
3052
- });
3053
- this.host = host;
3054
- this.idToRemoteMap = {};
3055
- }
3056
- }
3057
- class FederationHost {
3058
- initOptions(userOptions) {
3059
- this.registerPlugins(userOptions.plugins);
3060
- const options = this.formatOptions(this.options, userOptions);
3061
- this.options = options;
3062
- return options;
3063
- }
3064
- async loadShare(pkgName, extraOptions) {
3065
- return this.sharedHandler.loadShare(pkgName, extraOptions);
3066
- }
3067
- loadShareSync(pkgName, extraOptions) {
3068
- return this.sharedHandler.loadShareSync(pkgName, extraOptions);
3069
- }
3070
- initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
3071
- return this.sharedHandler.initializeSharing(shareScopeName, extraOptions);
3072
- }
3073
- initRawContainer(name, url, container) {
3074
- const remoteInfo = getRemoteInfo({
3075
- name,
3076
- entry: url
3077
- });
3078
- const module = new Module({
3079
- host: this,
3080
- remoteInfo
3081
- });
3082
- module.remoteEntryExports = container;
3083
- this.moduleCache.set(name, module);
3084
- return module;
3085
- }
3086
- async loadRemote(id, options) {
3087
- return this.remoteHandler.loadRemote(id, options);
3088
- }
3089
- async preloadRemote(preloadOptions) {
3090
- return this.remoteHandler.preloadRemote(preloadOptions);
3091
- }
3092
- initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
3093
- this.sharedHandler.initShareScopeMap(scopeName, shareScope, extraOptions);
3094
- }
3095
- formatOptions(globalOptions, userOptions) {
3096
- const { shared } = formatShareConfigs(globalOptions, userOptions);
3097
- const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
3098
- origin: this,
3099
- userOptions,
3100
- options: globalOptions,
3101
- shareInfo: shared
3102
- });
3103
- const remotes = this.remoteHandler.formatAndRegisterRemote(globalOptionsRes, userOptionsRes);
3104
- const { shared: handledShared } = this.sharedHandler.registerShared(globalOptionsRes, userOptionsRes);
3105
- const plugins = [
3106
- ...globalOptionsRes.plugins
3107
- ];
3108
- if (userOptionsRes.plugins) {
3109
- userOptionsRes.plugins.forEach((plugin)=>{
3110
- if (!plugins.includes(plugin)) {
3111
- plugins.push(plugin);
3112
- }
3113
- });
3114
- }
3115
- const optionsRes = _({}, globalOptions, userOptions, {
3116
- plugins,
3117
- remotes,
3118
- shared: handledShared
3119
- });
3120
- this.hooks.lifecycle.init.emit({
3121
- origin: this,
3122
- options: optionsRes
3123
- });
3124
- return optionsRes;
3125
- }
3126
- registerPlugins(plugins) {
3127
- const pluginRes = registerPlugins$1(plugins, [
3128
- this.hooks,
3129
- this.remoteHandler.hooks,
3130
- this.sharedHandler.hooks,
3131
- this.snapshotHandler.hooks,
3132
- this.loaderHook
3133
- ]);
3134
- this.options.plugins = this.options.plugins.reduce((res, plugin)=>{
3135
- if (!plugin) return res;
3136
- if (res && !res.find((item)=>item.name === plugin.name)) {
3137
- res.push(plugin);
3138
- }
3139
- return res;
3140
- }, pluginRes || []);
3141
- }
3142
- registerRemotes(remotes, options) {
3143
- return this.remoteHandler.registerRemotes(remotes, options);
3144
- }
3145
- constructor(userOptions){
3146
- this.hooks = new PluginSystem({
3147
- beforeInit: new SyncWaterfallHook('beforeInit'),
3148
- init: new SyncHook(),
3149
- beforeInitContainer: new AsyncWaterfallHook('beforeInitContainer'),
3150
- initContainer: new AsyncWaterfallHook('initContainer')
3151
- });
3152
- this.version = "0.6.0";
3153
- this.moduleCache = new Map();
3154
- this.loaderHook = new PluginSystem({
3155
- getModuleInfo: new SyncHook(),
3156
- createScript: new SyncHook(),
3157
- createLink: new SyncHook(),
3158
- fetch: new AsyncHook()
3159
- });
3160
- const defaultOptions = {
3161
- id: getBuilderId(),
3162
- name: userOptions.name,
3163
- plugins: [
3164
- snapshotPlugin(),
3165
- generatePreloadAssetsPlugin()
3166
- ],
3167
- remotes: [],
3168
- shared: {},
3169
- inBrowser: isBrowserEnv()
3170
- };
3171
- this.name = userOptions.name;
3172
- this.options = defaultOptions;
3173
- this.snapshotHandler = new SnapshotHandler(this);
3174
- this.sharedHandler = new SharedHandler(this);
3175
- this.remoteHandler = new RemoteHandler(this);
3176
- this.shareScopeMap = this.sharedHandler.shareScopeMap;
3177
- this.registerPlugins([
3178
- ...defaultOptions.plugins,
3179
- ...userOptions.plugins || []
3180
- ]);
3181
- this.options = this.formatOptions(defaultOptions, userOptions);
3182
- }
3183
- }
3184
- let FederationInstance = null;
3185
- function init(options) {
3186
- const instance = getGlobalFederationInstance(options.name, options.version);
3187
- if (!instance) {
3188
- const FederationConstructor = getGlobalFederationConstructor() || FederationHost;
3189
- FederationInstance = new FederationConstructor(options);
3190
- setGlobalFederationInstance(FederationInstance);
3191
- return FederationInstance;
3192
- } else {
3193
- instance.initOptions(options);
3194
- if (!FederationInstance) {
3195
- FederationInstance = instance;
3196
- }
3197
- return instance;
3198
- }
3199
- }
3200
- function loadRemote(...args) {
3201
- assert(FederationInstance, 'Please call init first');
3202
- const loadRemote1 = FederationInstance.loadRemote;
3203
- return loadRemote1.apply(FederationInstance, args);
3204
- }
3205
- function loadShare(...args) {
3206
- assert(FederationInstance, 'Please call init first');
3207
- const loadShare1 = FederationInstance.loadShare;
3208
- return loadShare1.apply(FederationInstance, args);
3209
- }
3210
- function loadShareSync(...args) {
3211
- assert(FederationInstance, 'Please call init first');
3212
- const loadShareSync1 = FederationInstance.loadShareSync;
3213
- return loadShareSync1.apply(FederationInstance, args);
3214
- }
3215
- function preloadRemote(...args) {
3216
- assert(FederationInstance, 'Please call init first');
3217
- return FederationInstance.preloadRemote.apply(FederationInstance, args);
3218
- }
3219
- function registerRemotes(...args) {
3220
- assert(FederationInstance, 'Please call init first');
3221
- return FederationInstance.registerRemotes.apply(FederationInstance, args);
3222
- }
3223
- function registerPlugins(...args) {
3224
- assert(FederationInstance, 'Please call init first');
3225
- return FederationInstance.registerPlugins.apply(FederationInstance, args);
3226
- }
3227
- function getInstance() {
3228
- return FederationInstance;
3229
- }
3230
- setGlobalFederationConstructor(FederationHost);
3231
-
3232
- var runtime = /*#__PURE__*/Object.freeze({
3233
- __proto__: null,
3234
- FederationHost: FederationHost,
3235
- getInstance: getInstance,
3236
- getRemoteEntry: getRemoteEntry,
3237
- getRemoteInfo: getRemoteInfo,
3238
- init: init,
3239
- loadRemote: loadRemote,
3240
- loadScript: loadScript,
3241
- loadScriptNode: loadScriptNode,
3242
- loadShare: loadShare,
3243
- loadShareSync: loadShareSync,
3244
- preloadRemote: preloadRemote,
3245
- registerGlobalPlugins: registerGlobalPlugins,
3246
- registerPlugins: registerPlugins,
3247
- registerRemotes: registerRemotes
3248
- });
3249
-
3250
- function attachShareScopeMap(webpackRequire) {
3251
- if (!webpackRequire.S || webpackRequire.federation.hasAttachShareScopeMap || !webpackRequire.federation.instance || !webpackRequire.federation.instance.shareScopeMap) {
3252
- return;
3253
- }
3254
- webpackRequire.S = webpackRequire.federation.instance.shareScopeMap;
3255
- webpackRequire.federation.hasAttachShareScopeMap = true;
3256
- }
3257
-
3258
- const FEDERATION_SUPPORTED_TYPES = [
3259
- 'script'
3260
- ];
3261
-
3262
- function remotes(options) {
3263
- const { chunkId, promises, chunkMapping, idToExternalAndNameMapping, webpackRequire, idToRemoteMap } = options;
3264
- attachShareScopeMap(webpackRequire);
3265
- if (webpackRequire.o(chunkMapping, chunkId)) {
3266
- chunkMapping[chunkId].forEach((id)=>{
3267
- let getScope = webpackRequire.R;
3268
- if (!getScope) {
3269
- getScope = [];
3270
- }
3271
- const data = idToExternalAndNameMapping[id];
3272
- const remoteInfos = idToRemoteMap[id];
3273
- if (getScope.indexOf(data) >= 0) {
3274
- return;
3275
- }
3276
- getScope.push(data);
3277
- if (data.p) {
3278
- return promises.push(data.p);
3279
- }
3280
- const onError = (error)=>{
3281
- if (!error) {
3282
- error = new Error('Container missing');
3283
- }
3284
- if (typeof error.message === 'string') {
3285
- error.message += `\nwhile loading "${data[1]}" from ${data[2]}`;
3286
- }
3287
- webpackRequire.m[id] = ()=>{
3288
- throw error;
3289
- };
3290
- data.p = 0;
3291
- };
3292
- const handleFunction = (fn, arg1, arg2, d, next, first)=>{
3293
- try {
3294
- const promise = fn(arg1, arg2);
3295
- if (promise && promise.then) {
3296
- const p = promise.then((result)=>next(result, d), onError);
3297
- if (first) {
3298
- promises.push(data.p = p);
3299
- } else {
3300
- return p;
3301
- }
3302
- } else {
3303
- return next(promise, d, first);
3304
- }
3305
- } catch (error) {
3306
- onError(error);
3307
- }
3308
- };
3309
- const onExternal = (external, _, first)=>external ? handleFunction(webpackRequire.I, data[0], 0, external, onInitialized, first) : onError();
3310
- var onInitialized = (_, external, first)=>handleFunction(external.get, data[1], getScope, 0, onFactory, first);
3311
- var onFactory = (factory)=>{
3312
- data.p = 1;
3313
- webpackRequire.m[id] = (module)=>{
3314
- module.exports = factory();
3315
- };
3316
- };
3317
- const onRemoteLoaded = ()=>{
3318
- try {
3319
- const remoteName = decodeName(remoteInfos[0].name, ENCODE_NAME_PREFIX);
3320
- const remoteModuleName = remoteName + data[1].slice(1);
3321
- return webpackRequire.federation.instance.loadRemote(remoteModuleName, {
3322
- loadFactory: false,
3323
- from: 'build'
3324
- });
3325
- } catch (error) {
3326
- onError(error);
3327
- }
3328
- };
3329
- const useRuntimeLoad = remoteInfos.length === 1 && FEDERATION_SUPPORTED_TYPES.includes(remoteInfos[0].externalType) && remoteInfos[0].name;
3330
- if (useRuntimeLoad) {
3331
- handleFunction(onRemoteLoaded, data[2], 0, 0, onFactory, 1);
3332
- } else {
3333
- handleFunction(webpackRequire, data[2], 0, 0, onExternal, 1);
3334
- }
3335
- });
3336
- }
3337
- }
3338
-
3339
- function consumes(options) {
3340
- const { chunkId, promises, chunkMapping, installedModules, moduleToHandlerMapping, webpackRequire } = options;
3341
- attachShareScopeMap(webpackRequire);
3342
- if (webpackRequire.o(chunkMapping, chunkId)) {
3343
- chunkMapping[chunkId].forEach((id)=>{
3344
- if (webpackRequire.o(installedModules, id)) {
3345
- return promises.push(installedModules[id]);
3346
- }
3347
- const onFactory = (factory)=>{
3348
- installedModules[id] = 0;
3349
- webpackRequire.m[id] = (module)=>{
3350
- delete webpackRequire.c[id];
3351
- module.exports = factory();
3352
- };
3353
- };
3354
- const onError = (error)=>{
3355
- delete installedModules[id];
3356
- webpackRequire.m[id] = (module)=>{
3357
- delete webpackRequire.c[id];
3358
- throw error;
3359
- };
3360
- };
3361
- try {
3362
- const federationInstance = webpackRequire.federation.instance;
3363
- if (!federationInstance) {
3364
- throw new Error('Federation instance not found!');
3365
- }
3366
- const { shareKey, getter, shareInfo } = moduleToHandlerMapping[id];
3367
- const promise = federationInstance.loadShare(shareKey, {
3368
- customShareInfo: shareInfo
3369
- }).then((factory)=>{
3370
- if (factory === false) {
3371
- return getter();
3372
- }
3373
- return factory;
3374
- });
3375
- if (promise.then) {
3376
- promises.push(installedModules[id] = promise.then(onFactory).catch(onError));
3377
- } else {
3378
- onFactory(promise);
3379
- }
3380
- } catch (e) {
3381
- onError(e);
3382
- }
3383
- });
3384
- }
3385
- }
3386
-
3387
- function initializeSharing({ shareScopeName, webpackRequire, initPromises, initTokens, initScope }) {
3388
- if (!initScope) initScope = [];
3389
- const mfInstance = webpackRequire.federation.instance;
3390
- var initToken = initTokens[shareScopeName];
3391
- if (!initToken) initToken = initTokens[shareScopeName] = {
3392
- from: mfInstance.name
3393
- };
3394
- if (initScope.indexOf(initToken) >= 0) return;
3395
- initScope.push(initToken);
3396
- const promise = initPromises[shareScopeName];
3397
- if (promise) return promise;
3398
- var warn = (msg)=>typeof console !== 'undefined' && console.warn && console.warn(msg);
3399
- var initExternal = (id)=>{
3400
- var handleError = (err)=>warn('Initialization of sharing external failed: ' + err);
3401
- try {
3402
- var module = webpackRequire(id);
3403
- if (!module) return;
3404
- var initFn = (module)=>module && module.init && module.init(webpackRequire.S[shareScopeName], initScope);
3405
- if (module.then) return promises.push(module.then(initFn, handleError));
3406
- var initResult = initFn(module);
3407
- if (initResult && typeof initResult !== 'boolean' && initResult.then) return promises.push(initResult['catch'](handleError));
3408
- } catch (err) {
3409
- handleError(err);
3410
- }
3411
- };
3412
- const promises = mfInstance.initializeSharing(shareScopeName, {
3413
- strategy: mfInstance.options.shareStrategy,
3414
- initScope,
3415
- from: 'build'
3416
- });
3417
- attachShareScopeMap(webpackRequire);
3418
- const bundlerRuntimeRemotesOptions = webpackRequire.federation.bundlerRuntimeOptions.remotes;
3419
- if (bundlerRuntimeRemotesOptions) {
3420
- Object.keys(bundlerRuntimeRemotesOptions.idToRemoteMap).forEach((moduleId)=>{
3421
- const info = bundlerRuntimeRemotesOptions.idToRemoteMap[moduleId];
3422
- const externalModuleId = bundlerRuntimeRemotesOptions.idToExternalAndNameMapping[moduleId][2];
3423
- if (info.length > 1) {
3424
- initExternal(externalModuleId);
3425
- } else if (info.length === 1) {
3426
- const remoteInfo = info[0];
3427
- if (!FEDERATION_SUPPORTED_TYPES.includes(remoteInfo.externalType)) {
3428
- initExternal(externalModuleId);
3429
- }
3430
- }
3431
- });
3432
- }
3433
- if (!promises.length) {
3434
- return initPromises[shareScopeName] = true;
3435
- }
3436
- return initPromises[shareScopeName] = Promise.all(promises).then(()=>initPromises[shareScopeName] = true);
3437
- }
3438
-
3439
- function handleInitialConsumes(options) {
3440
- const { moduleId, moduleToHandlerMapping, webpackRequire } = options;
3441
- const federationInstance = webpackRequire.federation.instance;
3442
- if (!federationInstance) {
3443
- throw new Error('Federation instance not found!');
3444
- }
3445
- const { shareKey, shareInfo } = moduleToHandlerMapping[moduleId];
3446
- try {
3447
- return federationInstance.loadShareSync(shareKey, {
3448
- customShareInfo: shareInfo
3449
- });
3450
- } catch (err) {
3451
- console.error('loadShareSync failed! The function should not be called unless you set "eager:true". If you do not set it, and encounter this issue, you can check whether an async boundary is implemented.');
3452
- console.error('The original error message is as follows: ');
3453
- throw err;
3454
- }
3455
- }
3456
- function installInitialConsumes(options) {
3457
- const { moduleToHandlerMapping, webpackRequire, installedModules, initialConsumes } = options;
3458
- initialConsumes.forEach((id)=>{
3459
- webpackRequire.m[id] = (module)=>{
3460
- installedModules[id] = 0;
3461
- delete webpackRequire.c[id];
3462
- const factory = handleInitialConsumes({
3463
- moduleId: id,
3464
- moduleToHandlerMapping,
3465
- webpackRequire
3466
- });
3467
- if (typeof factory !== 'function') {
3468
- throw new Error(`Shared module is not available for eager consumption: ${id}`);
3469
- }
3470
- module.exports = factory();
3471
- };
3472
- });
3473
- }
3474
-
3475
- function initContainerEntry(options) {
3476
- const { webpackRequire, shareScope, initScope, shareScopeKey, remoteEntryInitOptions } = options;
3477
- if (!webpackRequire.S) return;
3478
- if (!webpackRequire.federation || !webpackRequire.federation.instance || !webpackRequire.federation.initOptions) return;
3479
- const federationInstance = webpackRequire.federation.instance;
3480
- var name = shareScopeKey || 'default';
3481
- federationInstance.initOptions({
3482
- name: webpackRequire.federation.initOptions.name,
3483
- remotes: [],
3484
- ...remoteEntryInitOptions
3485
- });
3486
- federationInstance.initShareScopeMap(name, shareScope, {
3487
- hostShareScopeMap: remoteEntryInitOptions?.shareScopeMap || {}
3488
- });
3489
- if (webpackRequire.federation.attachShareScopeMap) {
3490
- webpackRequire.federation.attachShareScopeMap(webpackRequire);
3491
- }
3492
- return webpackRequire.I(name, initScope);
3493
- }
3494
-
3495
- const federation = {
3496
- runtime,
3497
- instance: undefined,
3498
- initOptions: undefined,
3499
- bundlerRuntime: {
3500
- remotes,
3501
- consumes,
3502
- I: initializeSharing,
3503
- S: {},
3504
- installInitialConsumes,
3505
- initContainerEntry
3506
- },
3507
- attachShareScopeMap,
3508
- bundlerRuntimeOptions: {}
3509
- };
3510
-
3511
- export { federation as default };