@module-federation/runtime 1.1.0-canary.1 → 2.0.0

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