@module-federation/runtime 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/LICENSE +21 -0
  2. package/dist/helpers.cjs.d.ts +2 -0
  3. package/dist/helpers.cjs.js +34 -0
  4. package/dist/helpers.esm.js +32 -0
  5. package/dist/index.cjs.d.ts +1 -0
  6. package/dist/index.cjs.js +1808 -0
  7. package/dist/index.esm.js +1788 -0
  8. package/dist/package.json +50 -0
  9. package/dist/share.cjs.js +878 -0
  10. package/dist/share.esm.js +839 -0
  11. package/dist/src/constant.d.ts +2 -0
  12. package/dist/src/core.d.ts +170 -0
  13. package/dist/src/global.d.ts +43 -0
  14. package/dist/src/helpers.d.ts +33 -0
  15. package/dist/src/index.d.ts +15 -0
  16. package/dist/src/module/index.d.ts +19 -0
  17. package/dist/src/plugins/generate-preload-assets.d.ts +8 -0
  18. package/dist/src/plugins/snapshot/SnapshotHandler.d.ts +44 -0
  19. package/dist/src/plugins/snapshot/index.d.ts +5 -0
  20. package/dist/src/type/config.d.ts +104 -0
  21. package/dist/src/type/index.d.ts +3 -0
  22. package/dist/src/type/plugin.d.ts +20 -0
  23. package/dist/src/type/preload.d.ts +26 -0
  24. package/dist/src/types.d.ts +1 -0
  25. package/dist/src/utils/env.d.ts +4 -0
  26. package/dist/src/utils/hooks/asyncHook.d.ts +6 -0
  27. package/dist/src/utils/hooks/asyncWaterfallHooks.d.ts +10 -0
  28. package/dist/src/utils/hooks/index.d.ts +6 -0
  29. package/dist/src/utils/hooks/pluginSystem.d.ts +15 -0
  30. package/dist/src/utils/hooks/syncHook.d.ts +12 -0
  31. package/dist/src/utils/hooks/syncWaterfallHook.d.ts +9 -0
  32. package/dist/src/utils/index.d.ts +6 -0
  33. package/dist/src/utils/load.d.ts +18 -0
  34. package/dist/src/utils/logger.d.ts +3 -0
  35. package/dist/src/utils/manifest.d.ts +7 -0
  36. package/dist/src/utils/plugin.d.ts +4 -0
  37. package/dist/src/utils/preload.d.ts +6 -0
  38. package/dist/src/utils/semver/compare.d.ts +9 -0
  39. package/dist/src/utils/semver/constants.d.ts +10 -0
  40. package/dist/src/utils/semver/index.d.ts +2 -0
  41. package/dist/src/utils/semver/parser.d.ts +9 -0
  42. package/dist/src/utils/semver/utils.d.ts +11 -0
  43. package/dist/src/utils/share.d.ts +22 -0
  44. package/dist/src/utils/tool.d.ts +13 -0
  45. package/dist/types.cjs.d.ts +1 -0
  46. package/dist/types.cjs.js +2 -0
  47. package/dist/types.esm.js +1 -0
  48. package/package.json +2 -2
@@ -0,0 +1,1808 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var share = require('./share.cjs.js');
6
+ var sdk = require('@module-federation/sdk');
7
+
8
+ // Function to match a remote with its name and expose
9
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
10
+ // id: alias(app1) + expose(button) = app1/button
11
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
12
+ function matchRemoteWithNameAndExpose(remotes, id) {
13
+ for (const remote of remotes){
14
+ // match pkgName
15
+ const isNameMatched = id.startsWith(remote.name);
16
+ let expose = id.replace(remote.name, '');
17
+ if (isNameMatched) {
18
+ if (expose.startsWith('/')) {
19
+ const pkgNameOrAlias = remote.name;
20
+ expose = `.${expose}`;
21
+ return {
22
+ pkgNameOrAlias,
23
+ expose,
24
+ remote
25
+ };
26
+ } else if (expose === '') {
27
+ return {
28
+ pkgNameOrAlias: remote.name,
29
+ expose: '.',
30
+ remote
31
+ };
32
+ }
33
+ }
34
+ // match alias
35
+ const isAliasMatched = remote.alias && id.startsWith(remote.alias);
36
+ let exposeWithAlias = remote.alias && id.replace(remote.alias, '');
37
+ if (remote.alias && isAliasMatched) {
38
+ if (exposeWithAlias && exposeWithAlias.startsWith('/')) {
39
+ const pkgNameOrAlias = remote.alias;
40
+ exposeWithAlias = `.${exposeWithAlias}`;
41
+ return {
42
+ pkgNameOrAlias,
43
+ expose: exposeWithAlias,
44
+ remote
45
+ };
46
+ } else if (exposeWithAlias === '') {
47
+ return {
48
+ pkgNameOrAlias: remote.alias,
49
+ expose: '.',
50
+ remote
51
+ };
52
+ }
53
+ }
54
+ }
55
+ return;
56
+ }
57
+ // Function to match a remote with its name or alias
58
+ function matchRemote(remotes, nameOrAlias) {
59
+ for (const remote of remotes){
60
+ const isNameMatched = nameOrAlias === remote.name;
61
+ if (isNameMatched) {
62
+ return remote;
63
+ }
64
+ const isAliasMatched = remote.alias && nameOrAlias === remote.alias;
65
+ if (isAliasMatched) {
66
+ return remote;
67
+ }
68
+ }
69
+ return;
70
+ }
71
+
72
+ function registerPlugins$1(plugins, hookInstances) {
73
+ const globalPlugins = share.getGlobalHostPlugins();
74
+ // Incorporate global plugins
75
+ if (globalPlugins.length > 0) {
76
+ globalPlugins.forEach((plugin)=>{
77
+ if (plugins == null ? void 0 : plugins.find((item)=>item.name !== plugin.name)) {
78
+ plugins.push(plugin);
79
+ }
80
+ });
81
+ }
82
+ if (plugins && plugins.length > 0) {
83
+ plugins.forEach((plugin)=>{
84
+ hookInstances.forEach((hookInstance)=>{
85
+ hookInstance.applyPlugin(plugin);
86
+ });
87
+ });
88
+ }
89
+ return plugins;
90
+ }
91
+
92
+ function _extends$5() {
93
+ _extends$5 = Object.assign || function(target) {
94
+ for(var i = 1; i < arguments.length; i++){
95
+ var source = arguments[i];
96
+ for(var key in source){
97
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
98
+ target[key] = source[key];
99
+ }
100
+ }
101
+ }
102
+ return target;
103
+ };
104
+ return _extends$5.apply(this, arguments);
105
+ }
106
+ async function loadEsmEntry({ entry, remoteEntryExports }) {
107
+ return new Promise((resolve, reject)=>{
108
+ try {
109
+ if (!remoteEntryExports) {
110
+ // eslint-disable-next-line no-eval
111
+ new Function('callbacks', `import("${entry}").then(callbacks[0]).catch(callbacks[1])`)([
112
+ resolve,
113
+ reject
114
+ ]);
115
+ } else {
116
+ resolve(remoteEntryExports);
117
+ }
118
+ } catch (e) {
119
+ reject(e);
120
+ }
121
+ });
122
+ }
123
+ async function loadEntryScript({ name, globalName, entry, createScriptHook }) {
124
+ const { entryExports: remoteEntryExports } = share.getRemoteEntryExports(name, globalName);
125
+ if (remoteEntryExports) {
126
+ return remoteEntryExports;
127
+ }
128
+ if (typeof document === 'undefined') {
129
+ return sdk.loadScriptNode(entry, {
130
+ attrs: {
131
+ name,
132
+ globalName
133
+ },
134
+ createScriptHook
135
+ }).then(()=>{
136
+ const { remoteEntryKey, entryExports } = share.getRemoteEntryExports(name, globalName);
137
+ share.assert(entryExports, `
138
+ Unable to use the ${name}'s '${entry}' URL with ${remoteEntryKey}'s globalName to get remoteEntry exports.
139
+ Possible reasons could be:\n
140
+ 1. '${entry}' is not the correct URL, or the remoteEntry resource or name is incorrect.\n
141
+ 2. ${remoteEntryKey} cannot be used to get remoteEntry exports in the window object.
142
+ `);
143
+ return entryExports;
144
+ }).catch((e)=>{
145
+ return e;
146
+ });
147
+ }
148
+ return sdk.loadScript(entry, {
149
+ attrs: {},
150
+ createScriptHook
151
+ }).then(()=>{
152
+ const { remoteEntryKey, entryExports } = share.getRemoteEntryExports(name, globalName);
153
+ share.assert(entryExports, `
154
+ Unable to use the ${name}'s '${entry}' URL with ${remoteEntryKey}'s globalName to get remoteEntry exports.
155
+ Possible reasons could be:\n
156
+ 1. '${entry}' is not the correct URL, or the remoteEntry resource or name is incorrect.\n
157
+ 2. ${remoteEntryKey} cannot be used to get remoteEntry exports in the window object.
158
+ `);
159
+ return entryExports;
160
+ }).catch((e)=>{
161
+ return e;
162
+ });
163
+ }
164
+ function getRemoteEntryUniqueKey(remoteInfo) {
165
+ const { entry, name } = remoteInfo;
166
+ return sdk.composeKeyWithSeparator(name, entry);
167
+ }
168
+ async function getRemoteEntry({ remoteEntryExports, remoteInfo, createScriptHook }) {
169
+ const { entry, name, type, entryGlobalName } = remoteInfo;
170
+ const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
171
+ if (remoteEntryExports) {
172
+ return remoteEntryExports;
173
+ }
174
+ if (!share.globalLoading[uniqueKey]) {
175
+ if (type === 'esm') {
176
+ share.globalLoading[uniqueKey] = loadEsmEntry({
177
+ entry,
178
+ remoteEntryExports
179
+ });
180
+ } else {
181
+ share.globalLoading[uniqueKey] = loadEntryScript({
182
+ name,
183
+ globalName: entryGlobalName,
184
+ entry,
185
+ createScriptHook
186
+ });
187
+ }
188
+ }
189
+ return share.globalLoading[uniqueKey];
190
+ }
191
+ function getRemoteInfo(remote) {
192
+ return _extends$5({}, remote, {
193
+ entry: 'entry' in remote ? remote.entry : '',
194
+ type: remote.type || share.DEFAULT_REMOTE_TYPE,
195
+ entryGlobalName: remote.entryGlobalName || remote.name,
196
+ shareScope: remote.shareScope || share.DEFAULT_SCOPE
197
+ });
198
+ }
199
+
200
+ function _extends$4() {
201
+ _extends$4 = Object.assign || function(target) {
202
+ for(var i = 1; i < arguments.length; i++){
203
+ var source = arguments[i];
204
+ for(var key in source){
205
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
206
+ target[key] = source[key];
207
+ }
208
+ }
209
+ }
210
+ return target;
211
+ };
212
+ return _extends$4.apply(this, arguments);
213
+ }
214
+ let Module = class Module {
215
+ async getEntry() {
216
+ if (this.remoteEntryExports) {
217
+ return this.remoteEntryExports;
218
+ }
219
+ // Get remoteEntry.js
220
+ const remoteEntryExports = await getRemoteEntry({
221
+ remoteInfo: this.remoteInfo,
222
+ remoteEntryExports: this.remoteEntryExports,
223
+ createScriptHook: (url)=>{
224
+ const res = this.host.loaderHook.lifecycle.createScript.emit({
225
+ url
226
+ });
227
+ if (typeof document === 'undefined') {
228
+ //todo: needs real fix
229
+ return res;
230
+ }
231
+ if (res instanceof HTMLScriptElement) {
232
+ return res;
233
+ }
234
+ return;
235
+ }
236
+ });
237
+ share.assert(remoteEntryExports, `remoteEntryExports is undefined \n ${share.safeToString(this.remoteInfo)}`);
238
+ this.remoteEntryExports = remoteEntryExports;
239
+ return this.remoteEntryExports;
240
+ }
241
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
242
+ async get(expose, options) {
243
+ const { loadFactory = true } = options || {
244
+ loadFactory: true
245
+ };
246
+ // Get remoteEntry.js
247
+ const remoteEntryExports = await this.getEntry();
248
+ if (!this.inited) {
249
+ const localShareScopeMap = this.host.shareScopeMap;
250
+ const remoteShareScope = this.remoteInfo.shareScope || 'default';
251
+ if (!localShareScopeMap[remoteShareScope]) {
252
+ localShareScopeMap[remoteShareScope] = {};
253
+ }
254
+ const shareScope = localShareScopeMap[remoteShareScope];
255
+ const initScope = [];
256
+ const remoteEntryInitOptions = {
257
+ version: this.remoteInfo.version || ''
258
+ };
259
+ // Help to find host instance
260
+ Object.defineProperty(remoteEntryInitOptions, 'hostId', {
261
+ value: this.host.options.id || this.host.name,
262
+ // remoteEntryInitOptions will be traversed and assigned during container init, ,so this attribute is not allowed to be traversed
263
+ enumerable: false
264
+ });
265
+ const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({
266
+ shareScope,
267
+ // @ts-ignore hostId will be set by Object.defineProperty
268
+ remoteEntryInitOptions,
269
+ initScope,
270
+ remoteInfo: this.remoteInfo,
271
+ origin: this.host
272
+ });
273
+ await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);
274
+ await this.host.hooks.lifecycle.initContainer.emit(_extends$4({}, initContainerOptions, {
275
+ remoteEntryExports
276
+ }));
277
+ }
278
+ this.lib = remoteEntryExports;
279
+ this.inited = true;
280
+ // get exposeGetter
281
+ const moduleFactory = await remoteEntryExports.get(expose);
282
+ share.assert(moduleFactory, `${share.getFMId(this.remoteInfo)} remote don't export ${expose}.`);
283
+ if (!loadFactory) {
284
+ return moduleFactory;
285
+ }
286
+ const exposeContent = await moduleFactory();
287
+ return exposeContent;
288
+ }
289
+ constructor({ remoteInfo, host }){
290
+ this.inited = false;
291
+ this.lib = undefined;
292
+ this.remoteInfo = remoteInfo;
293
+ this.host = host;
294
+ }
295
+ };
296
+
297
+ class SyncHook {
298
+ on(fn) {
299
+ if (typeof fn === 'function') {
300
+ this.listeners.add(fn);
301
+ }
302
+ }
303
+ once(fn) {
304
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
305
+ const self = this;
306
+ this.on(function wrapper(...args) {
307
+ self.remove(wrapper);
308
+ // eslint-disable-next-line prefer-spread
309
+ return fn.apply(null, args);
310
+ });
311
+ }
312
+ emit(...data) {
313
+ let result;
314
+ if (this.listeners.size > 0) {
315
+ // eslint-disable-next-line prefer-spread
316
+ this.listeners.forEach((fn)=>{
317
+ result = fn(...data);
318
+ });
319
+ }
320
+ return result;
321
+ }
322
+ remove(fn) {
323
+ this.listeners.delete(fn);
324
+ }
325
+ removeAll() {
326
+ this.listeners.clear();
327
+ }
328
+ constructor(type){
329
+ this.type = '';
330
+ this.listeners = new Set();
331
+ if (type) {
332
+ this.type = type;
333
+ }
334
+ }
335
+ }
336
+
337
+ class AsyncHook extends SyncHook {
338
+ emit(...data) {
339
+ let result;
340
+ const ls = Array.from(this.listeners);
341
+ if (ls.length > 0) {
342
+ let i = 0;
343
+ const call = (prev)=>{
344
+ if (prev === false) {
345
+ return false; // Abort process
346
+ } else if (i < ls.length) {
347
+ return Promise.resolve(ls[i++].apply(null, data)).then(call);
348
+ } else {
349
+ return prev;
350
+ }
351
+ };
352
+ result = call();
353
+ }
354
+ return Promise.resolve(result);
355
+ }
356
+ }
357
+
358
+ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
359
+ function checkReturnData(originalData, returnedData) {
360
+ if (!share.isObject(returnedData)) {
361
+ return false;
362
+ }
363
+ if (originalData !== returnedData) {
364
+ // eslint-disable-next-line no-restricted-syntax
365
+ for(const key in originalData){
366
+ if (!(key in returnedData)) {
367
+ return false;
368
+ }
369
+ }
370
+ }
371
+ return true;
372
+ }
373
+ class SyncWaterfallHook extends SyncHook {
374
+ emit(data) {
375
+ if (!share.isObject(data)) {
376
+ share.error(`The data for the "${this.type}" hook should be an object.`);
377
+ }
378
+ for (const fn of this.listeners){
379
+ try {
380
+ const tempData = fn(data);
381
+ if (checkReturnData(data, tempData)) {
382
+ data = tempData;
383
+ } else {
384
+ this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);
385
+ break;
386
+ }
387
+ } catch (e) {
388
+ share.warn(e);
389
+ this.onerror(e);
390
+ }
391
+ }
392
+ return data;
393
+ }
394
+ constructor(type){
395
+ super();
396
+ this.onerror = share.error;
397
+ this.type = type;
398
+ }
399
+ }
400
+
401
+ class AsyncWaterfallHook extends SyncHook {
402
+ emit(data) {
403
+ if (!share.isObject(data)) {
404
+ share.error(`The response data for the "${this.type}" hook must be an object.`);
405
+ }
406
+ const ls = Array.from(this.listeners);
407
+ if (ls.length > 0) {
408
+ let i = 0;
409
+ const processError = (e)=>{
410
+ share.warn(e);
411
+ this.onerror(e);
412
+ return data;
413
+ };
414
+ const call = (prevData)=>{
415
+ if (checkReturnData(data, prevData)) {
416
+ data = prevData;
417
+ if (i < ls.length) {
418
+ try {
419
+ return Promise.resolve(ls[i++](data)).then(call, processError);
420
+ } catch (e) {
421
+ return processError(e);
422
+ }
423
+ }
424
+ } else {
425
+ this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);
426
+ }
427
+ return data;
428
+ };
429
+ return Promise.resolve(call(data));
430
+ }
431
+ return Promise.resolve(data);
432
+ }
433
+ constructor(type){
434
+ super();
435
+ this.onerror = share.error;
436
+ this.type = type;
437
+ }
438
+ }
439
+
440
+ class PluginSystem {
441
+ applyPlugin(plugin) {
442
+ share.assert(share.isPlainObject(plugin), 'Plugin configuration is invalid.');
443
+ // The plugin's name is mandatory and must be unique
444
+ const pluginName = plugin.name;
445
+ share.assert(pluginName, 'A name must be provided by the plugin.');
446
+ if (!this.registerPlugins[pluginName]) {
447
+ this.registerPlugins[pluginName] = plugin;
448
+ Object.keys(this.lifecycle).forEach((key)=>{
449
+ const pluginLife = plugin[key];
450
+ if (pluginLife) {
451
+ this.lifecycle[key].on(pluginLife);
452
+ }
453
+ });
454
+ }
455
+ }
456
+ removePlugin(pluginName) {
457
+ share.assert(pluginName, 'A name is required.');
458
+ const plugin = this.registerPlugins[pluginName];
459
+ share.assert(plugin, `The plugin "${pluginName}" is not registered.`);
460
+ Object.keys(plugin).forEach((key)=>{
461
+ if (key !== 'name') {
462
+ this.lifecycle[key].remove(plugin[key]);
463
+ }
464
+ });
465
+ }
466
+ // eslint-disable-next-line @typescript-eslint/no-shadow
467
+ inherit({ lifecycle, registerPlugins }) {
468
+ Object.keys(lifecycle).forEach((hookName)=>{
469
+ share.assert(!this.lifecycle[hookName], `The hook "${hookName}" has a conflict and cannot be inherited.`);
470
+ this.lifecycle[hookName] = lifecycle[hookName];
471
+ });
472
+ Object.keys(registerPlugins).forEach((pluginName)=>{
473
+ share.assert(!this.registerPlugins[pluginName], `The plugin "${pluginName}" has a conflict and cannot be inherited.`);
474
+ this.applyPlugin(registerPlugins[pluginName]);
475
+ });
476
+ }
477
+ constructor(lifecycle){
478
+ this.registerPlugins = {};
479
+ this.lifecycle = lifecycle;
480
+ this.lifecycleKeys = Object.keys(lifecycle);
481
+ }
482
+ }
483
+
484
+ function _extends$3() {
485
+ _extends$3 = Object.assign || function(target) {
486
+ for(var i = 1; i < arguments.length; i++){
487
+ var source = arguments[i];
488
+ for(var key in source){
489
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
490
+ target[key] = source[key];
491
+ }
492
+ }
493
+ }
494
+ return target;
495
+ };
496
+ return _extends$3.apply(this, arguments);
497
+ }
498
+ function defaultPreloadArgs(preloadConfig) {
499
+ return _extends$3({
500
+ resourceCategory: 'sync',
501
+ share: true,
502
+ depsRemote: true,
503
+ prefetchInterface: false
504
+ }, preloadConfig);
505
+ }
506
+ function formatPreloadArgs(remotes, preloadArgs) {
507
+ return preloadArgs.map((args)=>{
508
+ const remoteInfo = matchRemote(remotes, args.nameOrAlias);
509
+ share.assert(remoteInfo, `Unable to preload ${args.nameOrAlias} as it is not included in ${!remoteInfo && share.safeToString({
510
+ remoteInfo,
511
+ remotes
512
+ })}`);
513
+ return {
514
+ remote: remoteInfo,
515
+ preloadConfig: defaultPreloadArgs(args)
516
+ };
517
+ });
518
+ }
519
+ function normalizePreloadExposes(exposes) {
520
+ if (!exposes) {
521
+ return [];
522
+ }
523
+ return exposes.map((expose)=>{
524
+ if (expose === '.') {
525
+ return expose;
526
+ }
527
+ if (expose.startsWith('./')) {
528
+ return expose.replace('./', '');
529
+ }
530
+ return expose;
531
+ });
532
+ }
533
+ function preloadAssets(remoteInfo, host, assets) {
534
+ const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
535
+ if (host.options.inBrowser) {
536
+ entryAssets.forEach((asset)=>{
537
+ const { moduleInfo } = asset;
538
+ const module = host.moduleCache.get(remoteInfo.name);
539
+ if (module) {
540
+ getRemoteEntry({
541
+ remoteInfo: moduleInfo,
542
+ remoteEntryExports: module.remoteEntryExports,
543
+ createScriptHook: (url)=>{
544
+ const res = host.loaderHook.lifecycle.createScript.emit({
545
+ url
546
+ });
547
+ if (res instanceof HTMLScriptElement) {
548
+ return res;
549
+ }
550
+ return;
551
+ }
552
+ });
553
+ } else {
554
+ getRemoteEntry({
555
+ remoteInfo: moduleInfo,
556
+ remoteEntryExports: undefined,
557
+ createScriptHook: (url)=>{
558
+ const res = host.loaderHook.lifecycle.createScript.emit({
559
+ url
560
+ });
561
+ if (res instanceof HTMLScriptElement) {
562
+ return res;
563
+ }
564
+ return;
565
+ }
566
+ });
567
+ }
568
+ });
569
+ const fragment = document.createDocumentFragment();
570
+ cssAssets.forEach((cssUrl)=>{
571
+ const { link: cssEl, needAttach } = sdk.createLink(cssUrl, ()=>{}, {
572
+ rel: 'preload',
573
+ as: 'style'
574
+ }, (url)=>{
575
+ const res = host.loaderHook.lifecycle.createLink.emit({
576
+ url
577
+ });
578
+ if (res instanceof HTMLLinkElement) {
579
+ return res;
580
+ }
581
+ return;
582
+ });
583
+ needAttach && fragment.appendChild(cssEl);
584
+ });
585
+ jsAssetsWithoutEntry.forEach((jsUrl)=>{
586
+ const { link: linkEl, needAttach } = sdk.createLink(jsUrl, ()=>{
587
+ // noop
588
+ }, {
589
+ rel: 'preload',
590
+ as: 'script'
591
+ }, (url)=>{
592
+ const res = host.loaderHook.lifecycle.createLink.emit({
593
+ url
594
+ });
595
+ if (res instanceof HTMLLinkElement) {
596
+ return res;
597
+ }
598
+ return;
599
+ });
600
+ needAttach && document.head.appendChild(linkEl);
601
+ });
602
+ document.head.appendChild(fragment);
603
+ }
604
+ }
605
+
606
+ function _extends$2() {
607
+ _extends$2 = Object.assign || function(target) {
608
+ for(var i = 1; i < arguments.length; i++){
609
+ var source = arguments[i];
610
+ for(var key in source){
611
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
612
+ target[key] = source[key];
613
+ }
614
+ }
615
+ }
616
+ return target;
617
+ };
618
+ return _extends$2.apply(this, arguments);
619
+ }
620
+ function assignRemoteInfo(remoteInfo, remoteSnapshot) {
621
+ if (!('remoteEntry' in remoteSnapshot) || !remoteSnapshot.remoteEntry) {
622
+ share.error(`The attribute remoteEntry of ${name} must not be undefined.`);
623
+ }
624
+ const { remoteEntry } = remoteSnapshot;
625
+ const entryUrl = sdk.getResourceUrl(remoteSnapshot, remoteEntry);
626
+ remoteInfo.type = remoteSnapshot.remoteEntryType;
627
+ remoteInfo.entryGlobalName = remoteSnapshot.globalName;
628
+ remoteInfo.entry = entryUrl;
629
+ remoteInfo.version = remoteSnapshot.version;
630
+ remoteInfo.buildVersion = remoteSnapshot.buildVersion;
631
+ }
632
+ function snapshotPlugin() {
633
+ return {
634
+ name: 'snapshot-plugin',
635
+ async afterResolve (args) {
636
+ const { remote, pkgNameOrAlias, expose, origin, remoteInfo } = args;
637
+ if (!share.isRemoteInfoWithEntry(remote) || !share.isPureRemoteEntry(remote)) {
638
+ const { remoteSnapshot, globalSnapshot } = await origin.snapshotHandler.loadRemoteSnapshotInfo(remote);
639
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
640
+ // preloading assets
641
+ const preloadOptions = {
642
+ remote,
643
+ preloadConfig: {
644
+ nameOrAlias: pkgNameOrAlias,
645
+ exposes: [
646
+ expose
647
+ ],
648
+ resourceCategory: 'sync',
649
+ share: false,
650
+ depsRemote: false
651
+ }
652
+ };
653
+ const assets = await origin.hooks.lifecycle.generatePreloadAssets.emit({
654
+ origin,
655
+ preloadOptions,
656
+ remoteInfo,
657
+ remote,
658
+ remoteSnapshot,
659
+ globalSnapshot
660
+ });
661
+ if (assets) {
662
+ preloadAssets(remoteInfo, origin, assets);
663
+ }
664
+ return _extends$2({}, args, {
665
+ remoteSnapshot
666
+ });
667
+ }
668
+ return args;
669
+ }
670
+ };
671
+ }
672
+
673
+ // name
674
+ // name:version
675
+ function splitId(id) {
676
+ const splitInfo = id.split(':');
677
+ if (splitInfo.length === 1) {
678
+ return {
679
+ name: splitInfo[0],
680
+ version: undefined
681
+ };
682
+ } else if (splitInfo.length === 2) {
683
+ return {
684
+ name: splitInfo[0],
685
+ version: splitInfo[1]
686
+ };
687
+ } else {
688
+ return {
689
+ name: splitInfo[1],
690
+ version: splitInfo[2]
691
+ };
692
+ }
693
+ }
694
+ // Traverse all nodes in moduleInfo and traverse the entire snapshot
695
+ function traverseModuleInfo(globalSnapshot, remoteInfo, traverse, isRoot, memo = {}, remoteSnapshot) {
696
+ const id = share.getFMId(remoteInfo);
697
+ const { value: snapshotValue } = share.getInfoWithoutType(globalSnapshot, id);
698
+ const effectiveRemoteSnapshot = remoteSnapshot || snapshotValue;
699
+ if (effectiveRemoteSnapshot && !sdk.isManifestProvider(effectiveRemoteSnapshot)) {
700
+ traverse(effectiveRemoteSnapshot, remoteInfo, isRoot);
701
+ if (effectiveRemoteSnapshot.remotesInfo) {
702
+ const remoteKeys = Object.keys(effectiveRemoteSnapshot.remotesInfo);
703
+ for (const key of remoteKeys){
704
+ if (memo[key]) {
705
+ continue;
706
+ }
707
+ memo[key] = true;
708
+ const subRemoteInfo = splitId(key);
709
+ const remoteValue = effectiveRemoteSnapshot.remotesInfo[key];
710
+ traverseModuleInfo(globalSnapshot, {
711
+ name: subRemoteInfo.name,
712
+ version: remoteValue.matchedVersion
713
+ }, traverse, false, memo, undefined);
714
+ }
715
+ }
716
+ }
717
+ }
718
+ // eslint-disable-next-line max-lines-per-function
719
+ function generatePreloadAssets(origin, preloadOptions, remote, globalSnapshot, remoteSnapshot) {
720
+ const cssAssets = [];
721
+ const jsAssets = [];
722
+ const entryAssets = [];
723
+ const loadedSharedJsAssets = new Set();
724
+ const loadedSharedCssAssets = new Set();
725
+ const { options } = origin;
726
+ const { preloadConfig: rootPreloadConfig } = preloadOptions;
727
+ const { depsRemote } = rootPreloadConfig;
728
+ const memo = {};
729
+ traverseModuleInfo(globalSnapshot, remote, (moduleInfoSnapshot, remoteInfo, isRoot)=>{
730
+ let preloadConfig;
731
+ if (isRoot) {
732
+ preloadConfig = rootPreloadConfig;
733
+ } else {
734
+ if (Array.isArray(depsRemote)) {
735
+ // eslint-disable-next-line array-callback-return
736
+ const findPreloadConfig = depsRemote.find((remoteConfig)=>{
737
+ if (remoteConfig.nameOrAlias === remoteInfo.name || remoteConfig.nameOrAlias === remoteInfo.alias) {
738
+ return true;
739
+ }
740
+ return false;
741
+ });
742
+ if (!findPreloadConfig) {
743
+ return;
744
+ }
745
+ preloadConfig = defaultPreloadArgs(findPreloadConfig);
746
+ } else if (depsRemote === true) {
747
+ preloadConfig = rootPreloadConfig;
748
+ } else {
749
+ return;
750
+ }
751
+ }
752
+ const remoteEntryUrl = sdk.getResourceUrl(moduleInfoSnapshot, 'remoteEntry' in moduleInfoSnapshot ? moduleInfoSnapshot.remoteEntry : '');
753
+ if (remoteEntryUrl) {
754
+ entryAssets.push({
755
+ name: remoteInfo.name,
756
+ moduleInfo: {
757
+ name: remoteInfo.name,
758
+ entry: remoteEntryUrl,
759
+ type: 'remoteEntryType' in moduleInfoSnapshot ? moduleInfoSnapshot.remoteEntryType : 'global',
760
+ entryGlobalName: 'globalName' in moduleInfoSnapshot ? moduleInfoSnapshot.globalName : remoteInfo.name,
761
+ shareScope: '',
762
+ version: 'version' in moduleInfoSnapshot ? moduleInfoSnapshot.version : undefined
763
+ },
764
+ url: remoteEntryUrl
765
+ });
766
+ }
767
+ let moduleAssetsInfo = 'modules' in moduleInfoSnapshot ? moduleInfoSnapshot.modules : [];
768
+ const normalizedPreloadExposes = normalizePreloadExposes(preloadConfig.exposes);
769
+ if (normalizedPreloadExposes.length && 'modules' in moduleInfoSnapshot) {
770
+ var _moduleInfoSnapshot_modules;
771
+ moduleAssetsInfo = moduleInfoSnapshot == null ? void 0 : (_moduleInfoSnapshot_modules = moduleInfoSnapshot.modules) == null ? void 0 : _moduleInfoSnapshot_modules.reduce((assets, moduleAssetInfo)=>{
772
+ if ((normalizedPreloadExposes == null ? void 0 : normalizedPreloadExposes.indexOf(moduleAssetInfo.moduleName)) !== -1) {
773
+ assets.push(moduleAssetInfo);
774
+ }
775
+ return assets;
776
+ }, []);
777
+ }
778
+ function handleAssets(assets) {
779
+ const assetsRes = assets.map((asset)=>sdk.getResourceUrl(moduleInfoSnapshot, asset));
780
+ if (preloadConfig.filter) {
781
+ return assetsRes.filter(preloadConfig.filter);
782
+ }
783
+ return assetsRes;
784
+ }
785
+ if (moduleAssetsInfo) {
786
+ const assetsLength = moduleAssetsInfo.length;
787
+ for(let index = 0; index < assetsLength; index++){
788
+ const assetsInfo = moduleAssetsInfo[index];
789
+ const exposeFullPath = `${remoteInfo.name}/${assetsInfo.moduleName}`;
790
+ origin.hooks.lifecycle.handlePreloadModule.emit({
791
+ id: assetsInfo.moduleName === '.' ? remoteInfo.name : exposeFullPath,
792
+ name: remoteInfo.name,
793
+ remoteSnapshot: moduleInfoSnapshot,
794
+ preloadConfig,
795
+ remote: remoteInfo,
796
+ origin
797
+ });
798
+ const preloaded = share.getPreloaded(exposeFullPath);
799
+ if (preloaded) {
800
+ continue;
801
+ }
802
+ if (preloadConfig.resourceCategory === 'all') {
803
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.async));
804
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
805
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.async));
806
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
807
+ // eslint-disable-next-line no-constant-condition
808
+ } else if (preloadConfig.resourceCategory = 'sync') {
809
+ cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
810
+ jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
811
+ }
812
+ share.setPreloaded(exposeFullPath);
813
+ }
814
+ }
815
+ }, true, memo, remoteSnapshot);
816
+ if (remoteSnapshot.shared) {
817
+ const collectSharedAssets = (shareInfo, snapshotShared)=>{
818
+ const registeredShared = share.getRegisteredShare(origin.shareScopeMap, snapshotShared.sharedName, shareInfo, origin.hooks.lifecycle.resolveShare);
819
+ // If the global share does not exist, or the lib function does not exist, it means that the shared has not been loaded yet and can be preloaded.
820
+ if (registeredShared && typeof registeredShared.lib === 'function') {
821
+ snapshotShared.assets.js.sync.forEach((asset)=>{
822
+ loadedSharedJsAssets.add(asset);
823
+ });
824
+ snapshotShared.assets.css.sync.forEach((asset)=>{
825
+ loadedSharedCssAssets.add(asset);
826
+ });
827
+ }
828
+ };
829
+ remoteSnapshot.shared.forEach((shared)=>{
830
+ var _options_shared;
831
+ const shareInfos = (_options_shared = options.shared) == null ? void 0 : _options_shared[shared.sharedName];
832
+ if (!shareInfos) {
833
+ return;
834
+ }
835
+ // if no version, preload all shared
836
+ const sharedOptions = shared.version ? shareInfos.find((s)=>s.version === shared.version) : shareInfos;
837
+ if (!sharedOptions) {
838
+ return;
839
+ }
840
+ const arrayShareInfo = share.arrayOptions(sharedOptions);
841
+ arrayShareInfo.forEach((s)=>{
842
+ collectSharedAssets(s, shared);
843
+ });
844
+ });
845
+ }
846
+ const needPreloadJsAssets = jsAssets.filter((asset)=>!loadedSharedJsAssets.has(asset));
847
+ const needPreloadCssAssets = cssAssets.filter((asset)=>!loadedSharedCssAssets.has(asset));
848
+ return {
849
+ cssAssets: needPreloadCssAssets,
850
+ jsAssetsWithoutEntry: needPreloadJsAssets,
851
+ entryAssets
852
+ };
853
+ }
854
+ const generatePreloadAssetsPlugin = function() {
855
+ return {
856
+ name: 'generate-preload-assets-plugin',
857
+ async generatePreloadAssets (args) {
858
+ const { origin, preloadOptions, remoteInfo, remote, globalSnapshot, remoteSnapshot } = args;
859
+ if (share.isRemoteInfoWithEntry(remote) && share.isPureRemoteEntry(remote)) {
860
+ return {
861
+ cssAssets: [],
862
+ jsAssetsWithoutEntry: [],
863
+ entryAssets: [
864
+ {
865
+ name: remote.name,
866
+ url: remote.entry,
867
+ moduleInfo: {
868
+ name: remoteInfo.name,
869
+ entry: remote.entry,
870
+ type: 'global',
871
+ entryGlobalName: '',
872
+ shareScope: ''
873
+ }
874
+ }
875
+ ]
876
+ };
877
+ }
878
+ assignRemoteInfo(remoteInfo, remoteSnapshot);
879
+ const assets = generatePreloadAssets(origin, preloadOptions, remoteInfo, globalSnapshot, remoteSnapshot);
880
+ return assets;
881
+ }
882
+ };
883
+ };
884
+
885
+ function _extends$1() {
886
+ _extends$1 = Object.assign || function(target) {
887
+ for(var i = 1; i < arguments.length; i++){
888
+ var source = arguments[i];
889
+ for(var key in source){
890
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
891
+ target[key] = source[key];
892
+ }
893
+ }
894
+ }
895
+ return target;
896
+ };
897
+ return _extends$1.apply(this, arguments);
898
+ }
899
+ class SnapshotHandler {
900
+ async loadSnapshot(moduleInfo) {
901
+ const { options } = this.HostInstance;
902
+ const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
903
+ const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
904
+ options,
905
+ moduleInfo,
906
+ hostGlobalSnapshot,
907
+ remoteSnapshot,
908
+ globalSnapshot
909
+ });
910
+ return {
911
+ remoteSnapshot: globalRemoteSnapshot,
912
+ globalSnapshot: globalSnapshotRes
913
+ };
914
+ }
915
+ // eslint-disable-next-line max-lines-per-function
916
+ async loadRemoteSnapshotInfo(moduleInfo) {
917
+ const { options } = this.HostInstance;
918
+ await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({
919
+ options,
920
+ moduleInfo
921
+ });
922
+ let hostSnapshot = share.getGlobalSnapshotInfoByModuleInfo({
923
+ name: this.HostInstance.options.name,
924
+ version: this.HostInstance.options.version
925
+ });
926
+ if (!hostSnapshot) {
927
+ hostSnapshot = {
928
+ version: this.HostInstance.options.version || '',
929
+ remoteEntry: '',
930
+ remotesInfo: {}
931
+ };
932
+ share.addGlobalSnapshot({
933
+ [this.HostInstance.options.name]: hostSnapshot
934
+ });
935
+ }
936
+ // In dynamic loadRemote scenarios, incomplete remotesInfo delivery may occur. In such cases, the remotesInfo in the host needs to be completed in the snapshot at runtime.
937
+ // This ensures the snapshot's integrity and helps the chrome plugin correctly identify all producer modules, ensuring that proxyable producer modules will not be missing.
938
+ if (hostSnapshot && 'remotesInfo' in hostSnapshot && !share.getInfoWithoutType(hostSnapshot.remotesInfo, moduleInfo.name).value) {
939
+ if ('version' in moduleInfo || 'entry' in moduleInfo) {
940
+ hostSnapshot.remotesInfo = _extends$1({}, hostSnapshot == null ? void 0 : hostSnapshot.remotesInfo, {
941
+ [moduleInfo.name]: {
942
+ matchedVersion: 'version' in moduleInfo ? moduleInfo.version : moduleInfo.entry
943
+ }
944
+ });
945
+ }
946
+ }
947
+ const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
948
+ const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
949
+ options,
950
+ moduleInfo,
951
+ hostGlobalSnapshot,
952
+ remoteSnapshot,
953
+ globalSnapshot
954
+ });
955
+ // global snapshot includes manifest or module info includes manifest
956
+ if (globalRemoteSnapshot) {
957
+ if (sdk.isManifestProvider(globalRemoteSnapshot)) {
958
+ const moduleSnapshot = await this.getManifestJson(globalRemoteSnapshot.remoteEntry, moduleInfo, {});
959
+ // eslint-disable-next-line @typescript-eslint/no-shadow
960
+ const globalSnapshotRes = share.setGlobalSnapshotInfoByModuleInfo(_extends$1({}, moduleInfo, {
961
+ // The global remote may be overridden
962
+ // Therefore, set the snapshot key to the global address of the actual request
963
+ entry: globalRemoteSnapshot.remoteEntry
964
+ }), moduleSnapshot);
965
+ return {
966
+ remoteSnapshot: moduleSnapshot,
967
+ globalSnapshot: globalSnapshotRes
968
+ };
969
+ } else {
970
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
971
+ options: this.HostInstance.options,
972
+ moduleInfo,
973
+ remoteSnapshot: globalRemoteSnapshot,
974
+ from: 'global'
975
+ });
976
+ return {
977
+ remoteSnapshot: remoteSnapshotRes,
978
+ globalSnapshot: globalSnapshotRes
979
+ };
980
+ }
981
+ } else {
982
+ if (share.isRemoteInfoWithEntry(moduleInfo)) {
983
+ // get from manifest.json and merge remote info from remote server
984
+ const moduleSnapshot = await this.getManifestJson(moduleInfo.entry, moduleInfo, {});
985
+ // eslint-disable-next-line @typescript-eslint/no-shadow
986
+ const globalSnapshotRes = share.setGlobalSnapshotInfoByModuleInfo(moduleInfo, moduleSnapshot);
987
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
988
+ options: this.HostInstance.options,
989
+ moduleInfo,
990
+ remoteSnapshot: moduleSnapshot,
991
+ from: 'global'
992
+ });
993
+ return {
994
+ remoteSnapshot: remoteSnapshotRes,
995
+ globalSnapshot: globalSnapshotRes
996
+ };
997
+ } else {
998
+ share.error(`
999
+ Cannot get remoteSnapshot with the name: '${moduleInfo.name}', version: '${moduleInfo.version}' from __FEDERATION__.moduleInfo. The following reasons may be causing the problem:\n
1000
+ 1. The Deploy platform did not deliver the correct data. You can use __FEDERATION__.moduleInfo to check the remoteInfo.\n
1001
+ 2. The remote '${moduleInfo.name}' version '${moduleInfo.version}' is not released.\n
1002
+ The transformed module info: ${JSON.stringify(globalSnapshotRes)}
1003
+ `);
1004
+ }
1005
+ }
1006
+ }
1007
+ getGlobalRemoteInfo(moduleInfo) {
1008
+ const hostGlobalSnapshot = share.getGlobalSnapshotInfoByModuleInfo({
1009
+ name: this.HostInstance.options.name,
1010
+ version: this.HostInstance.options.version
1011
+ });
1012
+ // get remote detail info from global
1013
+ const globalRemoteInfo = hostGlobalSnapshot && 'remotesInfo' in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && share.getInfoWithoutType(hostGlobalSnapshot.remotesInfo, moduleInfo.name).value;
1014
+ if (globalRemoteInfo && globalRemoteInfo.matchedVersion) {
1015
+ return {
1016
+ hostGlobalSnapshot,
1017
+ globalSnapshot: share.getGlobalSnapshot(),
1018
+ remoteSnapshot: share.getGlobalSnapshotInfoByModuleInfo({
1019
+ name: moduleInfo.name,
1020
+ version: globalRemoteInfo.matchedVersion
1021
+ })
1022
+ };
1023
+ }
1024
+ return {
1025
+ hostGlobalSnapshot: undefined,
1026
+ globalSnapshot: share.getGlobalSnapshot(),
1027
+ remoteSnapshot: share.getGlobalSnapshotInfoByModuleInfo({
1028
+ name: moduleInfo.name,
1029
+ version: 'version' in moduleInfo ? moduleInfo.version : undefined
1030
+ })
1031
+ };
1032
+ }
1033
+ async getManifestJson(manifestUrl, moduleInfo, extraOptions) {
1034
+ const getManifest = async ()=>{
1035
+ let manifestJson = this.manifestCache.get(manifestUrl);
1036
+ if (manifestJson) {
1037
+ return manifestJson;
1038
+ }
1039
+ try {
1040
+ let res = await this.loaderHook.lifecycle.fetch.emit(manifestUrl, {});
1041
+ if (!res || !(res instanceof Response)) {
1042
+ res = await fetch(manifestUrl, {});
1043
+ }
1044
+ manifestJson = await res.json();
1045
+ share.assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
1046
+ this.manifestCache.set(manifestUrl, manifestJson);
1047
+ return manifestJson;
1048
+ } catch (err) {
1049
+ share.error(`Failed to get manifestJson for ${moduleInfo.name}. The manifest URL is ${manifestUrl}. Please ensure that the manifestUrl is accessible.
1050
+ \n Error message:
1051
+ \n ${err}`);
1052
+ }
1053
+ };
1054
+ const asyncLoadProcess = async ()=>{
1055
+ const manifestJson = await getManifest();
1056
+ const remoteSnapshot = sdk.generateSnapshotFromManifest(manifestJson, {
1057
+ version: manifestUrl
1058
+ });
1059
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
1060
+ options: this.HostInstance.options,
1061
+ moduleInfo,
1062
+ manifestJson,
1063
+ remoteSnapshot,
1064
+ manifestUrl,
1065
+ from: 'manifest'
1066
+ });
1067
+ return remoteSnapshotRes;
1068
+ };
1069
+ if (!this.manifestLoading[manifestUrl]) {
1070
+ this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res)=>res);
1071
+ }
1072
+ return this.manifestLoading[manifestUrl];
1073
+ }
1074
+ constructor(HostInstance){
1075
+ this.loadingHostSnapshot = null;
1076
+ this.manifestCache = new Map();
1077
+ this.hooks = new PluginSystem({
1078
+ beforeLoadRemoteSnapshot: new AsyncHook('beforeLoadRemoteSnapshot'),
1079
+ loadSnapshot: new AsyncWaterfallHook('loadGlobalSnapshot'),
1080
+ loadRemoteSnapshot: new AsyncWaterfallHook('loadRemoteSnapshot')
1081
+ });
1082
+ this.manifestLoading = share.Global.__FEDERATION__.__MANIFEST_LOADING__;
1083
+ this.HostInstance = HostInstance;
1084
+ this.loaderHook = HostInstance.loaderHook;
1085
+ }
1086
+ }
1087
+
1088
+ function _extends() {
1089
+ _extends = Object.assign || function(target) {
1090
+ for(var i = 1; i < arguments.length; i++){
1091
+ var source = arguments[i];
1092
+ for(var key in source){
1093
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1094
+ target[key] = source[key];
1095
+ }
1096
+ }
1097
+ }
1098
+ return target;
1099
+ };
1100
+ return _extends.apply(this, arguments);
1101
+ }
1102
+ function _object_without_properties_loose(source, excluded) {
1103
+ if (source == null) return {};
1104
+ var target = {};
1105
+ var sourceKeys = Object.keys(source);
1106
+ var key, i;
1107
+ for(i = 0; i < sourceKeys.length; i++){
1108
+ key = sourceKeys[i];
1109
+ if (excluded.indexOf(key) >= 0) continue;
1110
+ target[key] = source[key];
1111
+ }
1112
+ return target;
1113
+ }
1114
+ class FederationHost {
1115
+ _setGlobalShareScopeMap() {
1116
+ const globalShareScopeMap = share.getGlobalShareScope();
1117
+ const identifier = this.options.id || this.options.name;
1118
+ if (identifier && !globalShareScopeMap[identifier]) {
1119
+ globalShareScopeMap[identifier] = this.shareScopeMap;
1120
+ }
1121
+ }
1122
+ initOptions(userOptions) {
1123
+ this.registerPlugins(userOptions.plugins);
1124
+ const options = this.formatOptions(this.options, userOptions);
1125
+ this.options = options;
1126
+ return options;
1127
+ }
1128
+ async loadShare(pkgName, extraOptions) {
1129
+ // This function performs the following steps:
1130
+ // 1. Checks if the currently loaded share already exists, if not, it throws an error
1131
+ // 2. Searches globally for a matching share, if found, it uses it directly
1132
+ // 3. If not found, it retrieves it from the current share and stores the obtained share globally.
1133
+ const shareInfo = share.getTargetSharedOptions({
1134
+ pkgName,
1135
+ extraOptions,
1136
+ shareInfos: this.options.shared
1137
+ });
1138
+ if (shareInfo == null ? void 0 : shareInfo.scope) {
1139
+ await Promise.all(shareInfo.scope.map(async (shareScope)=>{
1140
+ await Promise.all(this.initializeSharing(shareScope, shareInfo.strategy));
1141
+ return;
1142
+ }));
1143
+ }
1144
+ const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
1145
+ pkgName,
1146
+ shareInfo,
1147
+ shared: this.options.shared,
1148
+ origin: this
1149
+ });
1150
+ const { shareInfo: shareInfoRes } = loadShareRes;
1151
+ // Assert that shareInfoRes exists, if not, throw an error
1152
+ share.assert(shareInfoRes, `Cannot find ${pkgName} Share in the ${this.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
1153
+ // Retrieve from cache
1154
+ const registeredShared = share.getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
1155
+ const addUseIn = (shared)=>{
1156
+ if (!shared.useIn) {
1157
+ shared.useIn = [];
1158
+ }
1159
+ share.addUniqueItem(shared.useIn, this.options.name);
1160
+ };
1161
+ if (registeredShared && registeredShared.lib) {
1162
+ addUseIn(registeredShared);
1163
+ return registeredShared.lib;
1164
+ } else if (registeredShared && registeredShared.loading && !registeredShared.loaded) {
1165
+ const factory = await registeredShared.loading;
1166
+ registeredShared.loaded = true;
1167
+ if (!registeredShared.lib) {
1168
+ registeredShared.lib = factory;
1169
+ }
1170
+ addUseIn(registeredShared);
1171
+ return factory;
1172
+ } else if (registeredShared) {
1173
+ const asyncLoadProcess = async ()=>{
1174
+ const factory = await registeredShared.get();
1175
+ shareInfoRes.lib = factory;
1176
+ shareInfoRes.loaded = true;
1177
+ addUseIn(shareInfoRes);
1178
+ const gShared = share.getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
1179
+ if (gShared) {
1180
+ gShared.lib = factory;
1181
+ gShared.loaded = true;
1182
+ }
1183
+ return factory;
1184
+ };
1185
+ const loading = asyncLoadProcess();
1186
+ this.setShared({
1187
+ pkgName,
1188
+ loaded: false,
1189
+ shared: registeredShared,
1190
+ from: this.options.name,
1191
+ lib: null,
1192
+ loading
1193
+ });
1194
+ return loading;
1195
+ } else {
1196
+ if (extraOptions == null ? void 0 : extraOptions.customShareInfo) {
1197
+ return false;
1198
+ }
1199
+ const asyncLoadProcess = async ()=>{
1200
+ const factory = await shareInfoRes.get();
1201
+ shareInfoRes.lib = factory;
1202
+ shareInfoRes.loaded = true;
1203
+ addUseIn(shareInfoRes);
1204
+ const gShared = share.getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
1205
+ if (gShared) {
1206
+ gShared.lib = factory;
1207
+ gShared.loaded = true;
1208
+ }
1209
+ return factory;
1210
+ };
1211
+ const loading = asyncLoadProcess();
1212
+ this.setShared({
1213
+ pkgName,
1214
+ loaded: false,
1215
+ shared: shareInfoRes,
1216
+ from: this.options.name,
1217
+ lib: null,
1218
+ loading
1219
+ });
1220
+ return loading;
1221
+ }
1222
+ }
1223
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
1224
+ // 1. If the loaded shared already exists globally, then it will be reused
1225
+ // 2. If lib exists in local shared, it will be used directly
1226
+ // 3. If the local get returns something other than Promise, then it will be used directly
1227
+ loadShareSync(pkgName, extraOptions) {
1228
+ const shareInfo = share.getTargetSharedOptions({
1229
+ pkgName,
1230
+ extraOptions,
1231
+ shareInfos: this.options.shared
1232
+ });
1233
+ if (shareInfo == null ? void 0 : shareInfo.scope) {
1234
+ shareInfo.scope.forEach((shareScope)=>{
1235
+ this.initializeSharing(shareScope, shareInfo.strategy);
1236
+ });
1237
+ }
1238
+ const registeredShared = share.getRegisteredShare(this.shareScopeMap, pkgName, shareInfo, this.hooks.lifecycle.resolveShare);
1239
+ const addUseIn = (shared)=>{
1240
+ if (!shared.useIn) {
1241
+ shared.useIn = [];
1242
+ }
1243
+ share.addUniqueItem(shared.useIn, this.options.name);
1244
+ };
1245
+ if (registeredShared) {
1246
+ if (typeof registeredShared.lib === 'function') {
1247
+ addUseIn(registeredShared);
1248
+ if (!registeredShared.loaded) {
1249
+ registeredShared.loaded = true;
1250
+ if (registeredShared.from === this.options.name) {
1251
+ shareInfo.loaded = true;
1252
+ }
1253
+ }
1254
+ return registeredShared.lib;
1255
+ }
1256
+ if (typeof registeredShared.get === 'function') {
1257
+ const module = registeredShared.get();
1258
+ if (!(module instanceof Promise)) {
1259
+ addUseIn(registeredShared);
1260
+ this.setShared({
1261
+ pkgName,
1262
+ loaded: true,
1263
+ from: this.options.name,
1264
+ lib: module,
1265
+ shared: registeredShared
1266
+ });
1267
+ return module;
1268
+ }
1269
+ }
1270
+ }
1271
+ if (shareInfo.lib) {
1272
+ if (!shareInfo.loaded) {
1273
+ shareInfo.loaded = true;
1274
+ }
1275
+ return shareInfo.lib;
1276
+ }
1277
+ if (shareInfo.get) {
1278
+ const module = shareInfo.get();
1279
+ if (module instanceof Promise) {
1280
+ throw new Error(`
1281
+ The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${this.options.name}.
1282
+ Possible reasons for failure: \n
1283
+ 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
1284
+ 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
1285
+ `);
1286
+ }
1287
+ shareInfo.lib = module;
1288
+ this.setShared({
1289
+ pkgName,
1290
+ loaded: true,
1291
+ from: this.options.name,
1292
+ lib: shareInfo.lib,
1293
+ shared: shareInfo
1294
+ });
1295
+ return shareInfo.lib;
1296
+ }
1297
+ throw new Error(`
1298
+ The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${this.options.name}.
1299
+ Possible reasons for failure: \n
1300
+ 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
1301
+ 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
1302
+ `);
1303
+ }
1304
+ initRawContainer(name, url, container) {
1305
+ const remoteInfo = getRemoteInfo({
1306
+ name,
1307
+ entry: url
1308
+ });
1309
+ const module = new Module({
1310
+ host: this,
1311
+ remoteInfo
1312
+ });
1313
+ module.remoteEntryExports = container;
1314
+ this.moduleCache.set(name, module);
1315
+ return module;
1316
+ }
1317
+ async _getRemoteModuleAndOptions(id) {
1318
+ const loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
1319
+ id,
1320
+ options: this.options,
1321
+ origin: this
1322
+ });
1323
+ const { id: idRes } = loadRemoteArgs;
1324
+ const remoteSplitInfo = matchRemoteWithNameAndExpose(this.options.remotes, idRes);
1325
+ share.assert(remoteSplitInfo, `
1326
+ Unable to locate ${idRes} in ${this.options.name}. Potential reasons for failure include:\n
1327
+ 1. ${idRes} was not included in the 'remotes' parameter of ${this.options.name || 'the host'}.\n
1328
+ 2. ${idRes} could not be found in the 'remotes' of ${this.options.name} with either 'name' or 'alias' attributes.
1329
+ 3. ${idRes} is not online, injected, or loaded.
1330
+ 4. ${idRes} cannot be accessed on the expected.
1331
+ 5. The 'beforeRequest' hook was provided but did not return the correct 'remoteInfo' when attempting to load ${idRes}.
1332
+ `);
1333
+ const { remote: rawRemote } = remoteSplitInfo;
1334
+ const remoteInfo = getRemoteInfo(rawRemote);
1335
+ const matchInfo = await this.hooks.lifecycle.afterResolve.emit(_extends({
1336
+ id: idRes
1337
+ }, remoteSplitInfo, {
1338
+ options: this.options,
1339
+ origin: this,
1340
+ remoteInfo
1341
+ }));
1342
+ const { remote, expose } = matchInfo;
1343
+ share.assert(remote && expose, `The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
1344
+ let module = this.moduleCache.get(remote.name);
1345
+ const moduleOptions = {
1346
+ host: this,
1347
+ remoteInfo
1348
+ };
1349
+ if (!module) {
1350
+ module = new Module(moduleOptions);
1351
+ this.moduleCache.set(remote.name, module);
1352
+ }
1353
+ return {
1354
+ module,
1355
+ moduleOptions,
1356
+ remoteMatchInfo: matchInfo
1357
+ };
1358
+ }
1359
+ // eslint-disable-next-line max-lines-per-function
1360
+ // eslint-disable-next-line @typescript-eslint/member-ordering
1361
+ async loadRemote(id, options) {
1362
+ try {
1363
+ const { loadFactory = true } = options || {
1364
+ loadFactory: true
1365
+ };
1366
+ // 1. Validate the parameters of the retrieved module. There are two module request methods: pkgName + expose and alias + expose.
1367
+ // 2. Request the snapshot information of the current host and globally store the obtained snapshot information. The retrieved module information is partially offline and partially online. The online module information will retrieve the modules used online.
1368
+ // 3. Retrieve the detailed information of the current module from global (remoteEntry address, expose resource address)
1369
+ // 4. After retrieving remoteEntry, call the init of the module, and then retrieve the exported content of the module through get
1370
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
1371
+ // id: alias(app1) + expose(button) = app1/button
1372
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
1373
+ const { module, moduleOptions, remoteMatchInfo } = await this._getRemoteModuleAndOptions(id);
1374
+ const { pkgNameOrAlias, remote, expose, id: idRes } = remoteMatchInfo;
1375
+ const moduleOrFactory = await module.get(expose, options);
1376
+ const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
1377
+ id: idRes,
1378
+ pkgNameOrAlias,
1379
+ expose,
1380
+ exposeModule: loadFactory ? moduleOrFactory : undefined,
1381
+ exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
1382
+ remote,
1383
+ options: moduleOptions,
1384
+ moduleInstance: module,
1385
+ origin: this
1386
+ });
1387
+ if (typeof moduleWrapper === 'function') {
1388
+ return moduleWrapper;
1389
+ }
1390
+ return moduleOrFactory;
1391
+ } catch (error) {
1392
+ const { from = 'runtime' } = options || {
1393
+ from: 'runtime'
1394
+ };
1395
+ const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
1396
+ id,
1397
+ error,
1398
+ from,
1399
+ origin: this
1400
+ });
1401
+ if (!failOver) {
1402
+ throw error;
1403
+ }
1404
+ return failOver;
1405
+ }
1406
+ }
1407
+ // eslint-disable-next-line @typescript-eslint/member-ordering
1408
+ async preloadRemote(preloadOptions) {
1409
+ await this.hooks.lifecycle.beforePreloadRemote.emit({
1410
+ preloadOptions,
1411
+ options: this.options,
1412
+ origin: this
1413
+ });
1414
+ const preloadOps = formatPreloadArgs(this.options.remotes, preloadOptions);
1415
+ await Promise.all(preloadOps.map(async (ops)=>{
1416
+ const { remote } = ops;
1417
+ const remoteInfo = getRemoteInfo(remote);
1418
+ const { globalSnapshot, remoteSnapshot } = await this.snapshotHandler.loadRemoteSnapshotInfo(remote);
1419
+ const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
1420
+ origin: this,
1421
+ preloadOptions: ops,
1422
+ remote,
1423
+ remoteInfo,
1424
+ globalSnapshot,
1425
+ remoteSnapshot
1426
+ });
1427
+ if (!assets) {
1428
+ return;
1429
+ }
1430
+ preloadAssets(remoteInfo, this, assets);
1431
+ }));
1432
+ }
1433
+ /**
1434
+ * This function initializes the sharing sequence (executed only once per share scope).
1435
+ * It accepts one argument, the name of the share scope.
1436
+ * If the share scope does not exist, it creates one.
1437
+ */ // eslint-disable-next-line @typescript-eslint/member-ordering
1438
+ initializeSharing(shareScopeName = share.DEFAULT_SCOPE, strategy) {
1439
+ const shareScope = this.shareScopeMap;
1440
+ const hostName = this.options.name;
1441
+ // Creates a new share scope if necessary
1442
+ if (!shareScope[shareScopeName]) {
1443
+ shareScope[shareScopeName] = {};
1444
+ }
1445
+ // Executes all initialization snippets from all accessible modules
1446
+ const scope = shareScope[shareScopeName];
1447
+ const register = (name, shared)=>{
1448
+ var _activeVersion_shareConfig;
1449
+ const { version, eager } = shared;
1450
+ scope[name] = scope[name] || {};
1451
+ const versions = scope[name];
1452
+ const activeVersion = versions[version];
1453
+ const activeVersionEager = Boolean(activeVersion && (activeVersion.eager || ((_activeVersion_shareConfig = activeVersion.shareConfig) == null ? void 0 : _activeVersion_shareConfig.eager)));
1454
+ if (!activeVersion || activeVersion.strategy !== 'loaded-first' && !activeVersion.loaded && (Boolean(!eager) !== !activeVersionEager ? eager : hostName > activeVersion.from)) {
1455
+ versions[version] = shared;
1456
+ }
1457
+ };
1458
+ const promises = [];
1459
+ const initFn = (mod)=>mod && mod.init && mod.init(shareScope[shareScopeName]);
1460
+ const initRemoteModule = async (key)=>{
1461
+ const { module } = await this._getRemoteModuleAndOptions(key);
1462
+ if (module.getEntry) {
1463
+ const entry = await module.getEntry();
1464
+ if (!module.inited) {
1465
+ initFn(entry);
1466
+ module.inited = true;
1467
+ }
1468
+ }
1469
+ };
1470
+ Object.keys(this.options.shared).forEach((shareName)=>{
1471
+ const sharedArr = this.options.shared[shareName];
1472
+ sharedArr.forEach((shared)=>{
1473
+ if (shared.scope.includes(shareScopeName)) {
1474
+ register(shareName, shared);
1475
+ }
1476
+ });
1477
+ });
1478
+ if (strategy === 'version-first') {
1479
+ this.options.remotes.forEach((remote)=>{
1480
+ if (remote.shareScope === shareScopeName) {
1481
+ promises.push(initRemoteModule(remote.name));
1482
+ }
1483
+ });
1484
+ }
1485
+ return promises;
1486
+ }
1487
+ initShareScopeMap(scopeName, shareScope) {
1488
+ this.shareScopeMap[scopeName] = shareScope;
1489
+ this.hooks.lifecycle.initContainerShareScopeMap.emit({
1490
+ shareScope,
1491
+ options: this.options,
1492
+ origin: this
1493
+ });
1494
+ }
1495
+ formatOptions(globalOptions, userOptions) {
1496
+ const formatShareOptions = share.formatShareConfigs(userOptions.shared || {}, userOptions.name);
1497
+ const shared = _extends({}, globalOptions.shared);
1498
+ Object.keys(formatShareOptions).forEach((shareKey)=>{
1499
+ if (!shared[shareKey]) {
1500
+ shared[shareKey] = formatShareOptions[shareKey];
1501
+ } else {
1502
+ formatShareOptions[shareKey].forEach((newUserSharedOptions)=>{
1503
+ const isSameVersion = shared[shareKey].find((sharedVal)=>sharedVal.version === newUserSharedOptions.version);
1504
+ if (!isSameVersion) {
1505
+ shared[shareKey].push(newUserSharedOptions);
1506
+ }
1507
+ });
1508
+ }
1509
+ });
1510
+ const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
1511
+ origin: this,
1512
+ userOptions,
1513
+ options: globalOptions,
1514
+ shareInfo: shared
1515
+ });
1516
+ const userRemotes = userOptionsRes.remotes || [];
1517
+ const remotes = userRemotes.reduce((res, remote)=>{
1518
+ this.registerRemote(remote, res, {
1519
+ force: false
1520
+ });
1521
+ return res;
1522
+ }, globalOptionsRes.remotes);
1523
+ // register shared in shareScopeMap
1524
+ const sharedKeys = Object.keys(formatShareOptions);
1525
+ sharedKeys.forEach((sharedKey)=>{
1526
+ const sharedVals = formatShareOptions[sharedKey];
1527
+ sharedVals.forEach((sharedVal)=>{
1528
+ const registeredShared = share.getRegisteredShare(this.shareScopeMap, sharedKey, sharedVal, this.hooks.lifecycle.resolveShare);
1529
+ if (!registeredShared && sharedVal && sharedVal.lib) {
1530
+ this.setShared({
1531
+ pkgName: sharedKey,
1532
+ lib: sharedVal.lib,
1533
+ get: sharedVal.get,
1534
+ loaded: true,
1535
+ shared: sharedVal,
1536
+ from: userOptions.name
1537
+ });
1538
+ }
1539
+ });
1540
+ });
1541
+ const plugins = [
1542
+ ...globalOptionsRes.plugins
1543
+ ];
1544
+ if (userOptionsRes.plugins) {
1545
+ userOptionsRes.plugins.forEach((plugin)=>{
1546
+ if (!plugins.includes(plugin)) {
1547
+ plugins.push(plugin);
1548
+ }
1549
+ });
1550
+ }
1551
+ const optionsRes = _extends({}, globalOptions, userOptions, {
1552
+ plugins,
1553
+ remotes,
1554
+ shared
1555
+ });
1556
+ this.hooks.lifecycle.init.emit({
1557
+ origin: this,
1558
+ options: optionsRes
1559
+ });
1560
+ return optionsRes;
1561
+ }
1562
+ registerPlugins(plugins) {
1563
+ const pluginRes = registerPlugins$1(plugins, [
1564
+ this.hooks,
1565
+ this.snapshotHandler.hooks,
1566
+ this.loaderHook
1567
+ ]);
1568
+ // Merge plugin
1569
+ this.options.plugins = this.options.plugins.reduce((res, plugin)=>{
1570
+ if (!plugin) return res;
1571
+ if (res && !res.find((item)=>item.name === plugin.name)) {
1572
+ res.push(plugin);
1573
+ }
1574
+ return res;
1575
+ }, pluginRes || []);
1576
+ }
1577
+ setShared({ pkgName, shared, from, lib, loading, loaded, get }) {
1578
+ const { version, scope = 'default' } = shared, shareInfo = _object_without_properties_loose(shared, [
1579
+ "version",
1580
+ "scope"
1581
+ ]);
1582
+ const scopes = Array.isArray(scope) ? scope : [
1583
+ scope
1584
+ ];
1585
+ scopes.forEach((sc)=>{
1586
+ if (!this.shareScopeMap[sc]) {
1587
+ this.shareScopeMap[sc] = {};
1588
+ }
1589
+ if (!this.shareScopeMap[sc][pkgName]) {
1590
+ this.shareScopeMap[sc][pkgName] = {};
1591
+ }
1592
+ if (this.shareScopeMap[sc][pkgName][version]) {
1593
+ return;
1594
+ }
1595
+ this.shareScopeMap[sc][pkgName][version] = _extends({
1596
+ version,
1597
+ scope: [
1598
+ 'default'
1599
+ ]
1600
+ }, shareInfo, {
1601
+ lib,
1602
+ loaded,
1603
+ loading
1604
+ });
1605
+ if (get) {
1606
+ this.shareScopeMap[sc][pkgName][version].get = get;
1607
+ }
1608
+ });
1609
+ }
1610
+ removeRemote(remote) {
1611
+ const { name } = remote;
1612
+ const remoteIndex = this.options.remotes.findIndex((item)=>item.name === name);
1613
+ if (remoteIndex !== -1) {
1614
+ this.options.remotes.splice(remoteIndex, 1);
1615
+ }
1616
+ const loadedModule = this.moduleCache.get(remote.name);
1617
+ if (loadedModule) {
1618
+ const key = loadedModule.remoteInfo.entryGlobalName;
1619
+ if (globalThis[key]) {
1620
+ delete globalThis[key];
1621
+ }
1622
+ const remoteEntryUniqueKey = getRemoteEntryUniqueKey(loadedModule.remoteInfo);
1623
+ if (share.globalLoading[remoteEntryUniqueKey]) {
1624
+ delete share.globalLoading[remoteEntryUniqueKey];
1625
+ }
1626
+ this.moduleCache.delete(remote.name);
1627
+ }
1628
+ }
1629
+ registerRemote(remote, targetRemotes, options) {
1630
+ const normalizeRemote = ()=>{
1631
+ if (remote.alias) {
1632
+ // Validate if alias equals the prefix of remote.name and remote.alias, if so, throw an error
1633
+ // As multi-level path references cannot guarantee unique names, alias being a prefix of remote.name is not supported
1634
+ const findEqual = targetRemotes.find((item)=>{
1635
+ var _item_alias;
1636
+ return remote.alias && (item.name.startsWith(remote.alias) || ((_item_alias = item.alias) == null ? void 0 : _item_alias.startsWith(remote.alias)));
1637
+ });
1638
+ share.assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
1639
+ }
1640
+ // Set the remote entry to a complete path
1641
+ if ('entry' in remote) {
1642
+ if (share.isBrowserEnv() && !remote.entry.startsWith('http')) {
1643
+ remote.entry = new URL(remote.entry, window.location.origin).href;
1644
+ }
1645
+ }
1646
+ if (!remote.shareScope) {
1647
+ remote.shareScope = share.DEFAULT_SCOPE;
1648
+ }
1649
+ if (!remote.type) {
1650
+ remote.type = share.DEFAULT_REMOTE_TYPE;
1651
+ }
1652
+ };
1653
+ const registeredRemote = targetRemotes.find((item)=>item.name === remote.name);
1654
+ if (!registeredRemote) {
1655
+ normalizeRemote();
1656
+ targetRemotes.push(remote);
1657
+ } else {
1658
+ const messages = [
1659
+ `The remote "${remote.name}" is already registered.`,
1660
+ (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".'
1661
+ ];
1662
+ if (options == null ? void 0 : options.force) {
1663
+ // remove registered remote
1664
+ this.removeRemote(registeredRemote);
1665
+ normalizeRemote();
1666
+ targetRemotes.push(remote);
1667
+ }
1668
+ share.warn(messages.join(' '));
1669
+ }
1670
+ }
1671
+ registerRemotes(remotes, options) {
1672
+ remotes.forEach((remote)=>{
1673
+ this.registerRemote(remote, this.options.remotes, {
1674
+ force: options == null ? void 0 : options.force
1675
+ });
1676
+ });
1677
+ }
1678
+ constructor(userOptions){
1679
+ this.hooks = new PluginSystem({
1680
+ beforeInit: new SyncWaterfallHook('beforeInit'),
1681
+ init: new SyncHook(),
1682
+ beforeRequest: new AsyncWaterfallHook('beforeRequest'),
1683
+ afterResolve: new AsyncWaterfallHook('afterResolve'),
1684
+ // maybe will change, temporarily for internal use only
1685
+ beforeInitContainer: new AsyncWaterfallHook('beforeInitContainer'),
1686
+ // maybe will change, temporarily for internal use only
1687
+ initContainerShareScopeMap: new AsyncWaterfallHook('initContainer'),
1688
+ // maybe will change, temporarily for internal use only
1689
+ initContainer: new AsyncWaterfallHook('initContainer'),
1690
+ onLoad: new AsyncHook('onLoad'),
1691
+ handlePreloadModule: new SyncHook('handlePreloadModule'),
1692
+ errorLoadRemote: new AsyncHook('errorLoadRemote'),
1693
+ beforeLoadShare: new AsyncWaterfallHook('beforeLoadShare'),
1694
+ // not used yet
1695
+ loadShare: new AsyncHook(),
1696
+ resolveShare: new SyncWaterfallHook('resolveShare'),
1697
+ beforePreloadRemote: new AsyncHook(),
1698
+ generatePreloadAssets: new AsyncHook('generatePreloadAssets'),
1699
+ // not used yet
1700
+ afterPreloadRemote: new AsyncHook()
1701
+ });
1702
+ this.version = "0.1.7";
1703
+ this.moduleCache = new Map();
1704
+ this.loaderHook = new PluginSystem({
1705
+ // FIXME: may not be suitable , not open to the public yet
1706
+ getModuleInfo: new SyncHook(),
1707
+ createScript: new SyncHook(),
1708
+ createLink: new SyncHook(),
1709
+ // only work for manifest , so not open to the public yet
1710
+ fetch: new AsyncHook('fetch')
1711
+ });
1712
+ // TODO: Validate the details of the options
1713
+ // Initialize options with default values
1714
+ const defaultOptions = {
1715
+ id: share.getBuilderId(),
1716
+ name: userOptions.name,
1717
+ plugins: [
1718
+ snapshotPlugin(),
1719
+ generatePreloadAssetsPlugin()
1720
+ ],
1721
+ remotes: [],
1722
+ shared: {},
1723
+ inBrowser: share.isBrowserEnv()
1724
+ };
1725
+ this.name = userOptions.name;
1726
+ this.options = defaultOptions;
1727
+ this.shareScopeMap = {};
1728
+ this._setGlobalShareScopeMap();
1729
+ this.snapshotHandler = new SnapshotHandler(this);
1730
+ this.registerPlugins([
1731
+ ...defaultOptions.plugins,
1732
+ ...userOptions.plugins || []
1733
+ ]);
1734
+ this.options = this.formatOptions(defaultOptions, userOptions);
1735
+ }
1736
+ }
1737
+
1738
+ let FederationInstance = null;
1739
+ function init(options) {
1740
+ // Retrieve the same instance with the same name
1741
+ const instance = share.getGlobalFederationInstance(options.name, options.version);
1742
+ if (!instance) {
1743
+ // Retrieve debug constructor
1744
+ const FederationConstructor = share.getGlobalFederationConstructor() || FederationHost;
1745
+ FederationInstance = new FederationConstructor(options);
1746
+ share.setGlobalFederationInstance(FederationInstance);
1747
+ return FederationInstance;
1748
+ } else {
1749
+ // Merge options
1750
+ instance.initOptions(options);
1751
+ if (!FederationInstance) {
1752
+ FederationInstance = instance;
1753
+ }
1754
+ return instance;
1755
+ }
1756
+ }
1757
+ function loadRemote(...args) {
1758
+ share.assert(FederationInstance, 'Please call init first');
1759
+ // eslint-disable-next-line prefer-spread
1760
+ return FederationInstance.loadRemote.apply(FederationInstance, args);
1761
+ }
1762
+ function loadShare(...args) {
1763
+ share.assert(FederationInstance, 'Please call init first');
1764
+ // eslint-disable-next-line prefer-spread
1765
+ return FederationInstance.loadShare.apply(FederationInstance, args);
1766
+ }
1767
+ function loadShareSync(...args) {
1768
+ share.assert(FederationInstance, 'Please call init first');
1769
+ // eslint-disable-next-line prefer-spread
1770
+ return FederationInstance.loadShareSync.apply(FederationInstance, args);
1771
+ }
1772
+ function preloadRemote(...args) {
1773
+ share.assert(FederationInstance, 'Please call init first');
1774
+ // eslint-disable-next-line prefer-spread
1775
+ return FederationInstance.preloadRemote.apply(FederationInstance, args);
1776
+ }
1777
+ function registerRemotes(...args) {
1778
+ share.assert(FederationInstance, 'Please call init first');
1779
+ // eslint-disable-next-line prefer-spread
1780
+ return FederationInstance.registerRemotes.apply(FederationInstance, args);
1781
+ }
1782
+ function registerPlugins(...args) {
1783
+ share.assert(FederationInstance, 'Please call init first');
1784
+ // eslint-disable-next-line prefer-spread
1785
+ return FederationInstance.registerPlugins.apply(FederationInstance, args);
1786
+ }
1787
+ // Inject for debug
1788
+ share.setGlobalFederationConstructor(FederationHost);
1789
+
1790
+ exports.registerGlobalPlugins = share.registerGlobalPlugins;
1791
+ Object.defineProperty(exports, 'loadScript', {
1792
+ enumerable: true,
1793
+ get: function () { return sdk.loadScript; }
1794
+ });
1795
+ Object.defineProperty(exports, 'loadScriptNode', {
1796
+ enumerable: true,
1797
+ get: function () { return sdk.loadScriptNode; }
1798
+ });
1799
+ exports.FederationHost = FederationHost;
1800
+ exports.getRemoteEntry = getRemoteEntry;
1801
+ exports.getRemoteInfo = getRemoteInfo;
1802
+ exports.init = init;
1803
+ exports.loadRemote = loadRemote;
1804
+ exports.loadShare = loadShare;
1805
+ exports.loadShareSync = loadShareSync;
1806
+ exports.preloadRemote = preloadRemote;
1807
+ exports.registerPlugins = registerPlugins;
1808
+ exports.registerRemotes = registerRemotes;