@module-federation/runtime 0.0.0-canary-1701669627295

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 (47) hide show
  1. package/LICENSE +21 -0
  2. package/helpers.cjs.d.ts +2 -0
  3. package/helpers.cjs.js +33 -0
  4. package/helpers.esm.js +31 -0
  5. package/index.cjs.d.ts +1 -0
  6. package/index.cjs.js +1612 -0
  7. package/index.esm.js +1603 -0
  8. package/package.json +40 -0
  9. package/share.cjs.js +771 -0
  10. package/share.esm.js +734 -0
  11. package/src/constant.d.ts +2 -0
  12. package/src/core.d.ts +120 -0
  13. package/src/global.d.ts +57 -0
  14. package/src/helpers.d.ts +32 -0
  15. package/src/index.d.ts +10 -0
  16. package/src/module/index.d.ts +25 -0
  17. package/src/plugins/generate-preload-assets.d.ts +8 -0
  18. package/src/plugins/snapshot/SnapshotHandler.d.ts +43 -0
  19. package/src/plugins/snapshot/index.d.ts +5 -0
  20. package/src/type/config.d.ts +94 -0
  21. package/src/type/index.d.ts +3 -0
  22. package/src/type/plugin.d.ts +20 -0
  23. package/src/type/preload.d.ts +26 -0
  24. package/src/types.d.ts +1 -0
  25. package/src/utils/env.d.ts +4 -0
  26. package/src/utils/hooks/asyncHook.d.ts +6 -0
  27. package/src/utils/hooks/asyncWaterfallHooks.d.ts +10 -0
  28. package/src/utils/hooks/index.d.ts +6 -0
  29. package/src/utils/hooks/pluginSystem.d.ts +15 -0
  30. package/src/utils/hooks/syncHook.d.ts +12 -0
  31. package/src/utils/hooks/syncWaterfallHook.d.ts +9 -0
  32. package/src/utils/index.d.ts +5 -0
  33. package/src/utils/load.d.ts +17 -0
  34. package/src/utils/logger.d.ts +3 -0
  35. package/src/utils/manifest.d.ts +7 -0
  36. package/src/utils/plugin.d.ts +4 -0
  37. package/src/utils/preload.d.ts +6 -0
  38. package/src/utils/semver/compare.d.ts +9 -0
  39. package/src/utils/semver/constants.d.ts +10 -0
  40. package/src/utils/semver/index.d.ts +2 -0
  41. package/src/utils/semver/parser.d.ts +9 -0
  42. package/src/utils/semver/utils.d.ts +11 -0
  43. package/src/utils/share.d.ts +7 -0
  44. package/src/utils/tool.d.ts +12 -0
  45. package/type.cjs.d.ts +1 -0
  46. package/type.cjs.js +2 -0
  47. package/type.esm.js +1 -0
package/index.esm.js ADDED
@@ -0,0 +1,1603 @@
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 loadRemoteMatch (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
+ const res = await fetch(manifestUrl);
1034
+ manifestJson = await res.json();
1035
+ assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
1036
+ this.manifestCache.set(manifestUrl, manifestJson);
1037
+ return manifestJson;
1038
+ } catch (err) {
1039
+ error(`Failed to get manifestJson for ${moduleInfo.name}. The manifest URL is ${manifestUrl}. Please ensure that the manifestUrl is accessible.
1040
+ \n Error message:
1041
+ \n ${err}`);
1042
+ }
1043
+ };
1044
+ const asyncLoadProcess = async ()=>{
1045
+ const manifestJson = await getManifest();
1046
+ const remoteSnapshot = generateSnapshotFromManifest(manifestJson, {
1047
+ version: manifestUrl
1048
+ });
1049
+ const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
1050
+ options: this.HostInstance.options,
1051
+ moduleInfo,
1052
+ manifestJson,
1053
+ remoteSnapshot,
1054
+ manifestUrl,
1055
+ from: 'manifest'
1056
+ });
1057
+ return remoteSnapshotRes;
1058
+ };
1059
+ if (!this.manifestLoading[manifestUrl]) {
1060
+ this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res)=>res);
1061
+ }
1062
+ return this.manifestLoading[manifestUrl];
1063
+ }
1064
+ constructor(HostInstance){
1065
+ this.loadingHostSnapshot = null;
1066
+ this.manifestCache = new Map();
1067
+ this.hooks = new PluginSystem({
1068
+ beforeLoadRemoteSnapshot: new AsyncHook('beforeLoadRemoteSnapshot'),
1069
+ loadSnapshot: new AsyncWaterfallHook('loadGlobalSnapshot'),
1070
+ loadRemoteSnapshot: new AsyncWaterfallHook('loadRemoteSnapshot')
1071
+ });
1072
+ this.manifestLoading = Global.__FEDERATION__.__MANIFEST_LOADING__;
1073
+ this.HostInstance = HostInstance;
1074
+ }
1075
+ }
1076
+
1077
+ function _extends() {
1078
+ _extends = Object.assign || function(target) {
1079
+ for(var i = 1; i < arguments.length; i++){
1080
+ var source = arguments[i];
1081
+ for(var key in source){
1082
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
1083
+ target[key] = source[key];
1084
+ }
1085
+ }
1086
+ }
1087
+ return target;
1088
+ };
1089
+ return _extends.apply(this, arguments);
1090
+ }
1091
+ function _object_without_properties_loose(source, excluded) {
1092
+ if (source == null) return {};
1093
+ var target = {};
1094
+ var sourceKeys = Object.keys(source);
1095
+ var key, i;
1096
+ for(i = 0; i < sourceKeys.length; i++){
1097
+ key = sourceKeys[i];
1098
+ if (excluded.indexOf(key) >= 0) continue;
1099
+ target[key] = source[key];
1100
+ }
1101
+ return target;
1102
+ }
1103
+ class FederationHost {
1104
+ initOptions(userOptions) {
1105
+ this.registerPlugins(userOptions.plugins);
1106
+ const options = this.formatOptions(this.options, userOptions);
1107
+ this.options = options;
1108
+ return options;
1109
+ }
1110
+ // overrideSharedOptions(shareScope: GlobalShareScope[string]): void {}
1111
+ async loadShare(pkgName, customShareInfo) {
1112
+ var _this_options_shared;
1113
+ // This function performs the following steps:
1114
+ // 1. Checks if the currently loaded share already exists, if not, it throws an error
1115
+ // 2. Searches globally for a matching share, if found, it uses it directly
1116
+ // 3. If not found, it retrieves it from the current share and stores the obtained share globally.
1117
+ const shareInfo = Object.assign({}, (_this_options_shared = this.options.shared) == null ? void 0 : _this_options_shared[pkgName], customShareInfo);
1118
+ const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
1119
+ pkgName,
1120
+ shareInfo,
1121
+ shared: this.options.shared,
1122
+ origin: this
1123
+ });
1124
+ const { shareInfo: shareInfoRes } = loadShareRes;
1125
+ // Assert that shareInfoRes exists, if not, throw an error
1126
+ assert(shareInfoRes, `Cannot find ${pkgName} Share in the ${this.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
1127
+ // Retrieve from cache
1128
+ const globalShare = getGlobalShare(pkgName, shareInfoRes);
1129
+ if (globalShare && globalShare.lib) {
1130
+ addUniqueItem(globalShare.useIn, this.options.name);
1131
+ return globalShare.lib;
1132
+ } else if (globalShare && globalShare.loading) {
1133
+ const factory = await globalShare.loading;
1134
+ addUniqueItem(globalShare.useIn, this.options.name);
1135
+ return factory;
1136
+ } else if (globalShare) {
1137
+ const asyncLoadProcess = async ()=>{
1138
+ const factory = await globalShare.get();
1139
+ shareInfoRes.lib = factory;
1140
+ addUniqueItem(shareInfoRes.useIn, this.options.name);
1141
+ const gShared = getGlobalShare(pkgName, shareInfoRes);
1142
+ if (gShared) {
1143
+ gShared.lib = factory;
1144
+ }
1145
+ return factory;
1146
+ };
1147
+ const loading = asyncLoadProcess();
1148
+ this.setShared({
1149
+ pkgName,
1150
+ loaded: true,
1151
+ shared: shareInfoRes,
1152
+ from: this.options.name,
1153
+ lib: null,
1154
+ loading
1155
+ });
1156
+ return loading;
1157
+ } else {
1158
+ if (customShareInfo) {
1159
+ return false;
1160
+ }
1161
+ const asyncLoadProcess = async ()=>{
1162
+ const factory = await shareInfoRes.get();
1163
+ shareInfoRes.lib = factory;
1164
+ addUniqueItem(shareInfoRes.useIn, this.options.name);
1165
+ const gShared = getGlobalShare(pkgName, shareInfoRes);
1166
+ if (gShared) {
1167
+ gShared.lib = factory;
1168
+ }
1169
+ return factory;
1170
+ };
1171
+ const loading = asyncLoadProcess();
1172
+ this.setShared({
1173
+ pkgName,
1174
+ loaded: true,
1175
+ shared: shareInfoRes,
1176
+ from: this.options.name,
1177
+ lib: null,
1178
+ loading
1179
+ });
1180
+ return loading;
1181
+ }
1182
+ }
1183
+ // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
1184
+ // 1. If the loaded shared already exists globally, then it will be reused
1185
+ // 2. If lib exists in local shared, it will be used directly
1186
+ // 3. If the local get returns something other than Promise, then it will be used directly
1187
+ loadShareSync(pkgName) {
1188
+ var _this_options_shared;
1189
+ const shareInfo = (_this_options_shared = this.options.shared) == null ? void 0 : _this_options_shared[pkgName];
1190
+ const globalShare = getGlobalShare(pkgName, shareInfo);
1191
+ if (globalShare && typeof globalShare.lib === 'function') {
1192
+ addUniqueItem(globalShare.useIn, this.options.name);
1193
+ if (!globalShare.loaded) {
1194
+ globalShare.loaded = true;
1195
+ if (globalShare.from === this.options.name) {
1196
+ shareInfo.loaded = true;
1197
+ }
1198
+ }
1199
+ return globalShare.lib;
1200
+ }
1201
+ if (shareInfo.lib) {
1202
+ if (!shareInfo.loaded) {
1203
+ shareInfo.loaded = true;
1204
+ }
1205
+ return shareInfo.lib;
1206
+ }
1207
+ if (shareInfo.get) {
1208
+ const module = shareInfo.get();
1209
+ if (module instanceof Promise) {
1210
+ throw new Error(`
1211
+ The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${this.options.name}.
1212
+ Possible reasons for failure: \n
1213
+ 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
1214
+ 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
1215
+ `);
1216
+ }
1217
+ shareInfo.lib = module;
1218
+ this.setShared({
1219
+ pkgName,
1220
+ loaded: true,
1221
+ from: this.options.name,
1222
+ lib: shareInfo.lib,
1223
+ shared: shareInfo
1224
+ });
1225
+ return shareInfo.lib;
1226
+ }
1227
+ throw new Error(`
1228
+ The loadShareSync function was unable to load ${pkgName}. The ${pkgName} could not be found in ${this.options.name}.
1229
+ Possible reasons for failure: \n
1230
+ 1. The ${pkgName} share was registered with the 'get' attribute, but loadShare was not used beforehand.\n
1231
+ 2. The ${pkgName} share was not registered with the 'lib' attribute.\n
1232
+ `);
1233
+ }
1234
+ async _getRemoteModuleAndOptions(id) {
1235
+ const loadRemoteArgs = await this.hooks.lifecycle.beforeLoadRemote.emit({
1236
+ id,
1237
+ options: this.options,
1238
+ origin: this
1239
+ });
1240
+ const { id: idRes } = loadRemoteArgs;
1241
+ const remoteSplitInfo = matchRemoteWithNameAndExpose(this.options.remotes, idRes);
1242
+ assert(remoteSplitInfo, `
1243
+ Unable to locate ${idRes} in ${this.options.name}. Potential reasons for failure include:\n
1244
+ 1. ${idRes} was not included in the 'remotes' parameter of ${this.options.name}.\n
1245
+ 2. ${idRes} could not be found in the 'remotes' of ${this.options.name} with either 'name' or 'alias' attributes.
1246
+ 3. The 'beforeLoadRemote' hook was provided but did not return the correct 'remoteInfo' when attempting to load ${idRes}.
1247
+ `);
1248
+ const { remote: rawRemote } = remoteSplitInfo;
1249
+ const remoteInfo = getRemoteInfo(rawRemote);
1250
+ const matchInfo = await this.hooks.lifecycle.loadRemoteMatch.emit(_extends({
1251
+ id: idRes
1252
+ }, remoteSplitInfo, {
1253
+ options: this.options,
1254
+ origin: this,
1255
+ remoteInfo
1256
+ }));
1257
+ const { remote, expose } = matchInfo;
1258
+ assert(remote && expose, `The 'beforeLoadRemote' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
1259
+ let module = this.moduleCache.get(remote.name);
1260
+ const moduleOptions = {
1261
+ hostInfo: {
1262
+ name: this.options.name,
1263
+ version: this.options.version || 'custom'
1264
+ },
1265
+ remoteInfo,
1266
+ shared: this.options.shared || {},
1267
+ plugins: this.options.plugins,
1268
+ loaderHook: this.loaderHook
1269
+ };
1270
+ if (!module) {
1271
+ module = new Module(moduleOptions);
1272
+ this.moduleCache.set(remote.name, module);
1273
+ }
1274
+ return {
1275
+ module,
1276
+ moduleOptions,
1277
+ remoteMatchInfo: matchInfo
1278
+ };
1279
+ }
1280
+ // eslint-disable-next-line max-lines-per-function
1281
+ // eslint-disable-next-line @typescript-eslint/member-ordering
1282
+ async loadRemote(id, options) {
1283
+ try {
1284
+ const { loadFactory = true } = options || {
1285
+ loadFactory: true
1286
+ };
1287
+ // 1. Validate the parameters of the retrieved module. There are two module request methods: pkgName + expose and alias + expose.
1288
+ // 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.
1289
+ // 3. Retrieve the detailed information of the current module from global (remoteEntry address, expose resource address)
1290
+ // 4. After retrieving remoteEntry, call the init of the module, and then retrieve the exported content of the module through get
1291
+ // id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
1292
+ // id: alias(app1) + expose(button) = app1/button
1293
+ // id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
1294
+ const { module, moduleOptions, remoteMatchInfo } = await this._getRemoteModuleAndOptions(id);
1295
+ const { pkgNameOrAlias, remote, expose, id: idRes } = remoteMatchInfo;
1296
+ const moduleOrFactory = await module.get(expose, options);
1297
+ await this.hooks.lifecycle.loadRemote.emit({
1298
+ id: idRes,
1299
+ pkgNameOrAlias,
1300
+ expose,
1301
+ exposeModule: loadFactory ? moduleOrFactory : undefined,
1302
+ exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
1303
+ remote,
1304
+ options: moduleOptions,
1305
+ moduleInstance: module,
1306
+ origin: this
1307
+ });
1308
+ return moduleOrFactory;
1309
+ } catch (error) {
1310
+ this.hooks.lifecycle.errorLoadRemote.emit({
1311
+ id,
1312
+ error
1313
+ });
1314
+ throw error;
1315
+ }
1316
+ }
1317
+ // eslint-disable-next-line @typescript-eslint/member-ordering
1318
+ async preloadRemote(preloadOptions) {
1319
+ await this.hooks.lifecycle.beforePreloadRemote.emit({
1320
+ preloadOptions,
1321
+ options: this.options,
1322
+ origin: this
1323
+ });
1324
+ const preloadOps = formatPreloadArgs(this.options.remotes, preloadOptions);
1325
+ await Promise.all(preloadOps.map(async (ops)=>{
1326
+ const { remote } = ops;
1327
+ const remoteInfo = getRemoteInfo(remote);
1328
+ const { globalSnapshot, remoteSnapshot } = await this.snapshotHandler.loadRemoteSnapshotInfo(remote);
1329
+ const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
1330
+ origin: this,
1331
+ preloadOptions: ops,
1332
+ remote,
1333
+ remoteInfo,
1334
+ globalSnapshot,
1335
+ remoteSnapshot
1336
+ });
1337
+ if (!assets) {
1338
+ return;
1339
+ }
1340
+ preloadAssets(remoteInfo, this, assets);
1341
+ }));
1342
+ }
1343
+ /**
1344
+ * This function initializes the sharing sequence (executed only once per share scope).
1345
+ * It accepts one argument, the name of the share scope.
1346
+ * If the share scope does not exist, it creates one.
1347
+ */ // eslint-disable-next-line @typescript-eslint/member-ordering
1348
+ initializeSharing(shareScopeName = DEFAULT_SCOPE) {
1349
+ const shareScopeLoading = Global.__FEDERATION__.__SHARE_SCOPE_LOADING__;
1350
+ const shareScope = Global.__FEDERATION__.__SHARE__;
1351
+ const hostName = this.options.name;
1352
+ // Executes only once
1353
+ if (shareScopeLoading[shareScopeName]) {
1354
+ return shareScopeLoading[shareScopeName];
1355
+ }
1356
+ // Creates a new share scope if necessary
1357
+ if (!shareScope[shareScopeName]) {
1358
+ shareScope[shareScopeName] = {};
1359
+ }
1360
+ // Executes all initialization snippets from all accessible modules
1361
+ const scope = shareScope[shareScopeName];
1362
+ const register = (name, shared)=>{
1363
+ const { version, eager } = shared;
1364
+ scope[name] = scope[name] || {};
1365
+ const versions = scope[name];
1366
+ const activeVersion = versions[version];
1367
+ const activeVersionEager = Boolean(activeVersion && (activeVersion.eager || activeVersion.shareConfig.eager));
1368
+ if (!activeVersion || !activeVersion.loaded && (Boolean(!eager) !== !activeVersionEager ? eager : hostName > activeVersion.from)) {
1369
+ versions[version] = shared;
1370
+ }
1371
+ };
1372
+ const promises = [];
1373
+ const initRemoteModule = async (key)=>{
1374
+ const { module } = await this._getRemoteModuleAndOptions(key);
1375
+ const initFn = (mod)=>mod && mod.init && mod.init(shareScope[shareScopeName]);
1376
+ const entry = await module.getEntry();
1377
+ initFn(entry);
1378
+ };
1379
+ Object.keys(this.options.shared).forEach((shareName)=>{
1380
+ const shared = this.options.shared[shareName];
1381
+ if (shared.scope.includes(shareScopeName)) {
1382
+ register(shareName, shared);
1383
+ }
1384
+ });
1385
+ this.options.remotes.forEach((remote)=>{
1386
+ if (remote.shareScope === shareScopeName) {
1387
+ promises.push(initRemoteModule(remote.name));
1388
+ }
1389
+ });
1390
+ if (!promises.length) {
1391
+ return shareScopeLoading[shareScopeName] = true;
1392
+ }
1393
+ return shareScopeLoading[shareScopeName] = Promise.all(promises).then(()=>shareScopeLoading[shareScopeName] = true);
1394
+ }
1395
+ formatOptions(globalOptions, userOptions) {
1396
+ const formatShareOptions = formatShareConfigs(userOptions.shared || {}, userOptions.name);
1397
+ const shared = _extends({}, globalOptions.shared, formatShareOptions);
1398
+ const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
1399
+ origin: this,
1400
+ userOptions,
1401
+ options: globalOptions,
1402
+ shareInfo: shared
1403
+ });
1404
+ const userRemotes = userOptionsRes.remotes || [];
1405
+ const remotes = userRemotes.reduce((res, remote)=>{
1406
+ if (!res.find((item)=>item.name === remote.name)) {
1407
+ if (remote.alias) {
1408
+ // Validate if alias equals the prefix of remote.name and remote.alias, if so, throw an error
1409
+ // As multi-level path references cannot guarantee unique names, alias being a prefix of remote.name is not supported
1410
+ const findEqual = res.find((item)=>{
1411
+ var _item_alias;
1412
+ return remote.alias && (item.name.startsWith(remote.alias) || ((_item_alias = item.alias) == null ? void 0 : _item_alias.startsWith(remote.alias)));
1413
+ });
1414
+ assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
1415
+ }
1416
+ // Set the remote entry to a complete path
1417
+ if ('entry' in remote) {
1418
+ if (isBrowserEnv()) {
1419
+ remote.entry = new URL(remote.entry, window.location.origin).href;
1420
+ }
1421
+ }
1422
+ if (!remote.shareScope) {
1423
+ remote.shareScope = DEFAULT_SCOPE;
1424
+ }
1425
+ if (!remote.type) {
1426
+ // FIXME: The build plugin needs to support this field
1427
+ remote.type = DEFAULT_REMOTE_TYPE;
1428
+ }
1429
+ res.push(remote);
1430
+ }
1431
+ return res;
1432
+ }, globalOptionsRes.remotes);
1433
+ // register shared include lib
1434
+ const sharedKeys = Object.keys(formatShareOptions);
1435
+ sharedKeys.forEach((sharedKey)=>{
1436
+ const sharedVal = formatShareOptions[sharedKey];
1437
+ const globalShare = getGlobalShare(sharedKey, sharedVal);
1438
+ if (!globalShare && sharedVal && sharedVal.lib) {
1439
+ this.setShared({
1440
+ pkgName: sharedKey,
1441
+ lib: sharedVal.lib,
1442
+ get: sharedVal.get,
1443
+ shared: sharedVal,
1444
+ from: userOptions.name
1445
+ });
1446
+ }
1447
+ });
1448
+ const plugins = [
1449
+ ...globalOptionsRes.plugins
1450
+ ];
1451
+ if (userOptionsRes.plugins) {
1452
+ userOptionsRes.plugins.forEach((plugin)=>{
1453
+ if (!plugins.includes(plugin)) {
1454
+ plugins.push(plugin);
1455
+ }
1456
+ });
1457
+ }
1458
+ const optionsRes = _extends({}, globalOptions, userOptions, {
1459
+ plugins,
1460
+ remotes,
1461
+ shared
1462
+ });
1463
+ this.hooks.lifecycle.init.emit({
1464
+ origin: this,
1465
+ options: optionsRes
1466
+ });
1467
+ return optionsRes;
1468
+ }
1469
+ registerPlugins(plugins) {
1470
+ registerPlugins(plugins, [
1471
+ this.hooks,
1472
+ this.snapshotHandler.hooks,
1473
+ this.loaderHook
1474
+ ]);
1475
+ }
1476
+ setShared({ pkgName, shared, from, lib, loading, loaded, get }) {
1477
+ const target = getGlobalShareScope();
1478
+ const { version, scope = 'default' } = shared, shareInfo = _object_without_properties_loose(shared, [
1479
+ "version",
1480
+ "scope"
1481
+ ]);
1482
+ const scopes = Array.isArray(scope) ? scope : [
1483
+ scope
1484
+ ];
1485
+ scopes.forEach((sc)=>{
1486
+ if (!target[sc]) {
1487
+ target[sc] = {};
1488
+ }
1489
+ if (!target[sc][pkgName]) {
1490
+ target[sc][pkgName] = {};
1491
+ }
1492
+ if (target[sc][pkgName][version]) {
1493
+ warn(// eslint-disable-next-line max-len
1494
+ `The share \n ${safeToString({
1495
+ scope: sc,
1496
+ pkgName,
1497
+ version,
1498
+ from: target[sc][pkgName][version].from
1499
+ })} has been registered`);
1500
+ return;
1501
+ }
1502
+ target[sc][pkgName][version] = _extends({
1503
+ version,
1504
+ scope: [
1505
+ 'default'
1506
+ ]
1507
+ }, shareInfo, {
1508
+ lib,
1509
+ loaded,
1510
+ loading
1511
+ });
1512
+ if (get) {
1513
+ target[sc][pkgName][version].get = get;
1514
+ }
1515
+ });
1516
+ }
1517
+ constructor(userOptions){
1518
+ this.hooks = new PluginSystem({
1519
+ beforeInit: new SyncWaterfallHook('beforeInit'),
1520
+ init: new SyncHook(),
1521
+ beforeLoadRemote: new AsyncWaterfallHook('beforeLoadRemote'),
1522
+ loadRemoteMatch: new AsyncWaterfallHook('loadRemoteMatch'),
1523
+ loadRemote: new AsyncHook('loadRemote'),
1524
+ handlePreloadModule: new SyncHook('handlePreloadModule'),
1525
+ errorLoadRemote: new AsyncHook('errorLoadRemote'),
1526
+ beforeLoadShare: new AsyncWaterfallHook('beforeLoadShare'),
1527
+ loadShare: new AsyncHook(),
1528
+ beforePreloadRemote: new AsyncHook(),
1529
+ generatePreloadAssets: new AsyncHook('generatePreloadAssets'),
1530
+ afterPreloadRemote: new AsyncHook()
1531
+ });
1532
+ this.version = '1.0.0-canary.5';
1533
+ this.moduleCache = new Map();
1534
+ this.loaderHook = new PluginSystem({
1535
+ // FIXME: may not be suitable
1536
+ getModuleInfo: new SyncHook(),
1537
+ createScript: new SyncHook()
1538
+ });
1539
+ this.loadingShare = {};
1540
+ // TODO: Validate the details of the options
1541
+ // Initialize options with default values
1542
+ const defaultOptions = {
1543
+ id: getBuilderId(),
1544
+ name: userOptions.name,
1545
+ plugins: [
1546
+ snapshotPlugin(),
1547
+ generatePreloadAssetsPlugin()
1548
+ ],
1549
+ remotes: [],
1550
+ shared: {},
1551
+ inBrowser: isBrowserEnv()
1552
+ };
1553
+ this.name = userOptions.name;
1554
+ this.options = defaultOptions;
1555
+ this.snapshotHandler = new SnapshotHandler(this);
1556
+ this.registerPlugins([
1557
+ ...defaultOptions.plugins,
1558
+ ...userOptions.plugins || []
1559
+ ]);
1560
+ this.options = this.formatOptions(defaultOptions, userOptions);
1561
+ }
1562
+ }
1563
+
1564
+ let FederationInstance = null;
1565
+ function init(options) {
1566
+ // Retrieve the same instance with the same name
1567
+ const instance = getGlobalFederationInstance(options.name, options.version);
1568
+ if (!instance) {
1569
+ // Retrieve debug constructor
1570
+ const FederationConstructor = getGlobalFederationConstructor() || FederationHost;
1571
+ FederationInstance = new FederationConstructor(options);
1572
+ setGlobalFederationInstance(FederationInstance);
1573
+ return FederationInstance;
1574
+ } else {
1575
+ // Merge options
1576
+ instance.initOptions(options);
1577
+ return instance;
1578
+ }
1579
+ }
1580
+ function loadRemote(...args) {
1581
+ assert(FederationInstance, 'Please call init first');
1582
+ // eslint-disable-next-line prefer-spread
1583
+ return FederationInstance.loadRemote.apply(FederationInstance, args);
1584
+ }
1585
+ function loadShare(...args) {
1586
+ assert(FederationInstance, 'Please call init first');
1587
+ // eslint-disable-next-line prefer-spread
1588
+ return FederationInstance.loadShare.apply(FederationInstance, args);
1589
+ }
1590
+ function loadShareSync(...args) {
1591
+ assert(FederationInstance, 'Please call init first');
1592
+ // eslint-disable-next-line prefer-spread
1593
+ return FederationInstance.loadShareSync.apply(FederationInstance, args);
1594
+ }
1595
+ function preloadRemote(...args) {
1596
+ assert(FederationInstance, 'Please call init first');
1597
+ // eslint-disable-next-line prefer-spread
1598
+ return FederationInstance.preloadRemote.apply(FederationInstance, args);
1599
+ }
1600
+ // Inject for debug
1601
+ setGlobalFederationConstructor(FederationHost);
1602
+
1603
+ export { FederationHost, init, loadRemote, loadShare, loadShareSync, preloadRemote };