-
-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathindex.ts
More file actions
649 lines (605 loc) · 19.1 KB
/
index.ts
File metadata and controls
649 lines (605 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import {
isBrowserEnv,
warn,
composeKeyWithSeparator,
ModuleInfo,
GlobalModuleInfo,
} from '@module-federation/sdk';
import {
getShortErrorMsg,
RUNTIME_004,
runtimeDescMap,
} from '@module-federation/error-codes';
import {
Global,
getInfoWithoutType,
globalLoading,
CurrentGlobal,
} from '../global';
import {
Options,
UserOptions,
PreloadAssets,
PreloadOptions,
PreloadRemoteArgs,
Remote,
RemoteInfo,
RemoteEntryExports,
CallFrom,
} from '../type';
import { ModuleFederation } from '../core';
import {
PluginSystem,
AsyncHook,
AsyncWaterfallHook,
SyncHook,
SyncWaterfallHook,
} from '../utils/hooks';
import {
assert,
getRemoteInfo,
getRemoteEntryUniqueKey,
matchRemoteWithNameAndExpose,
logger,
} from '../utils';
import { DEFAULT_REMOTE_TYPE, DEFAULT_SCOPE } from '../constant';
import { Module, ModuleOptions } from '../module';
import { formatPreloadArgs, preloadAssets } from '../utils/preload';
import { getGlobalShareScope } from '../utils/share';
import { getGlobalRemoteInfo } from '../plugins/snapshot/SnapshotHandler';
export interface LoadRemoteMatch {
id: string;
pkgNameOrAlias: string;
expose: string;
remote: Remote;
options: Options;
origin: ModuleFederation;
remoteInfo: RemoteInfo;
remoteSnapshot?: ModuleInfo;
}
export class RemoteHandler {
host: ModuleFederation;
idToRemoteMap: Record<string, { name: string; expose: string }>;
hooks = new PluginSystem({
beforeRegisterRemote: new SyncWaterfallHook<{
remote: Remote;
origin: ModuleFederation;
}>('beforeRegisterRemote'),
registerRemote: new SyncWaterfallHook<{
remote: Remote;
origin: ModuleFederation;
}>('registerRemote'),
afterRemoveRemote: new SyncHook<
[
{
remote: Remote;
origin: ModuleFederation;
},
],
void
>('afterRemoveRemote'),
beforeRequest: new AsyncWaterfallHook<{
id: string;
options: Options;
origin: ModuleFederation;
}>('beforeRequest'),
onLoad: new AsyncHook<
[
{
id: string;
expose: string;
pkgNameOrAlias: string;
remote: Remote;
options: ModuleOptions;
origin: ModuleFederation;
exposeModule: any;
exposeModuleFactory: any;
moduleInstance: Module;
},
],
void
>('onLoad'),
handlePreloadModule: new SyncHook<
[
{
id: string;
name: string;
remote: Remote;
remoteSnapshot: ModuleInfo;
preloadConfig: PreloadRemoteArgs;
origin: ModuleFederation;
},
],
void
>('handlePreloadModule'),
errorLoadRemote: new AsyncHook<
[
{
id: string;
error: unknown;
options?: any;
from: CallFrom;
lifecycle:
| 'beforeRequest'
| 'beforeLoadShare'
| 'afterResolve'
| 'onLoad';
origin: ModuleFederation;
},
],
void | unknown
>('errorLoadRemote'),
beforePreloadRemote: new AsyncHook<
[
{
preloadOps: Array<PreloadRemoteArgs>;
options: Options;
origin: ModuleFederation;
},
]
>('beforePreloadRemote'),
generatePreloadAssets: new AsyncHook<
[
{
origin: ModuleFederation;
preloadOptions: PreloadOptions[number];
remote: Remote;
remoteInfo: RemoteInfo;
remoteSnapshot: ModuleInfo;
globalSnapshot: GlobalModuleInfo;
},
],
Promise<PreloadAssets>
>('generatePreloadAssets'),
// not used yet
afterPreloadRemote: new AsyncHook<{
preloadOps: Array<PreloadRemoteArgs>;
options: Options;
origin: ModuleFederation;
}>(),
// TODO: Move to loaderHook
loadEntry: new AsyncHook<
[
{
loaderHook: ModuleFederation['loaderHook'];
remoteInfo: RemoteInfo;
remoteEntryExports?: RemoteEntryExports;
},
],
Promise<RemoteEntryExports>
>(),
});
constructor(host: ModuleFederation) {
this.host = host;
this.idToRemoteMap = {};
}
formatAndRegisterRemote(globalOptions: Options, userOptions: UserOptions) {
const userRemotes = userOptions.remotes || [];
return userRemotes.reduce((res, remote) => {
this.registerRemote(remote, res, { force: false });
return res;
}, globalOptions.remotes);
}
setIdToRemoteMap(id: string, remoteMatchInfo: LoadRemoteMatch) {
const { remote, expose } = remoteMatchInfo;
const { name, alias } = remote;
this.idToRemoteMap[id] = { name: remote.name, expose };
if (alias && id.startsWith(name)) {
const idWithAlias = id.replace(name, alias);
this.idToRemoteMap[idWithAlias] = { name: remote.name, expose };
return;
}
if (alias && id.startsWith(alias)) {
const idWithName = id.replace(alias, name);
this.idToRemoteMap[idWithName] = { name: remote.name, expose };
}
}
unloadRemote(nameOrAlias: string): boolean {
const remote = this.host.options.remotes.find(
(item) => item.name === nameOrAlias || item.alias === nameOrAlias,
);
if (!remote) {
return false;
}
this.removeRemote(remote);
return true;
}
// eslint-disable-next-line max-lines-per-function
// eslint-disable-next-line @typescript-eslint/member-ordering
async loadRemote<T>(
id: string,
options?: { loadFactory?: boolean; from: CallFrom },
): Promise<T | null> {
const { host } = this;
try {
const { loadFactory = true } = options || {
loadFactory: true,
};
// 1. Validate the parameters of the retrieved module. There are two module request methods: pkgName + expose and alias + expose.
// 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.
// 3. Retrieve the detailed information of the current module from global (remoteEntry address, expose resource address)
// 4. After retrieving remoteEntry, call the init of the module, and then retrieve the exported content of the module through get
// id: pkgName(@federation/app1) + expose(button) = @federation/app1/button
// id: alias(app1) + expose(button) = app1/button
// id: alias(app1/utils) + expose(loadash/sort) = app1/utils/loadash/sort
const { module, moduleOptions, remoteMatchInfo } =
await this.getRemoteModuleAndOptions({
id,
});
const {
pkgNameOrAlias,
remote,
expose,
id: idRes,
remoteSnapshot,
} = remoteMatchInfo;
const moduleOrFactory = (await module.get(
idRes,
expose,
options,
remoteSnapshot,
)) as T;
const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
id: idRes,
pkgNameOrAlias,
expose,
exposeModule: loadFactory ? moduleOrFactory : undefined,
exposeModuleFactory: loadFactory ? undefined : moduleOrFactory,
remote,
options: moduleOptions,
moduleInstance: module,
origin: host,
});
this.setIdToRemoteMap(id, remoteMatchInfo);
if (typeof moduleWrapper === 'function') {
return moduleWrapper as T;
}
return moduleOrFactory;
} catch (error) {
const { from = 'runtime' } = options || { from: 'runtime' };
const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
id,
error,
from,
lifecycle: 'onLoad',
origin: host,
});
if (!failOver) {
throw error;
}
return failOver as T;
}
}
// eslint-disable-next-line @typescript-eslint/member-ordering
async preloadRemote(preloadOptions: Array<PreloadRemoteArgs>): Promise<void> {
const { host } = this;
await this.hooks.lifecycle.beforePreloadRemote.emit({
preloadOps: preloadOptions,
options: host.options,
origin: host,
});
const preloadOps: PreloadOptions = formatPreloadArgs(
host.options.remotes,
preloadOptions,
);
await Promise.all(
preloadOps.map(async (ops) => {
const { remote } = ops;
const remoteInfo = getRemoteInfo(remote);
const { globalSnapshot, remoteSnapshot } =
await host.snapshotHandler.loadRemoteSnapshotInfo({
moduleInfo: remote,
});
const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
origin: host,
preloadOptions: ops,
remote,
remoteInfo,
globalSnapshot,
remoteSnapshot,
});
if (!assets) {
return;
}
preloadAssets(remoteInfo, host, assets);
}),
);
}
registerRemotes(remotes: Remote[], options?: { force?: boolean }): void {
const { host } = this;
remotes.forEach((remote) => {
this.registerRemote(remote, host.options.remotes, {
force: options?.force,
});
});
}
async getRemoteModuleAndOptions(options: { id: string }): Promise<{
module: Module;
moduleOptions: ModuleOptions;
remoteMatchInfo: LoadRemoteMatch;
}> {
const { host } = this;
const { id } = options;
let loadRemoteArgs;
try {
loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
id,
options: host.options,
origin: host,
});
} catch (error) {
loadRemoteArgs = (await this.hooks.lifecycle.errorLoadRemote.emit({
id,
options: host.options,
origin: host,
from: 'runtime',
error,
lifecycle: 'beforeRequest',
})) as {
id: string;
options: Options;
origin: ModuleFederation;
};
if (!loadRemoteArgs) {
throw error;
}
}
const { id: idRes } = loadRemoteArgs;
const remoteSplitInfo = matchRemoteWithNameAndExpose(
host.options.remotes,
idRes,
);
assert(
remoteSplitInfo,
getShortErrorMsg(RUNTIME_004, runtimeDescMap, {
hostName: host.options.name,
requestId: idRes,
}),
);
const { remote: rawRemote } = remoteSplitInfo;
const remoteInfo = getRemoteInfo(rawRemote);
const matchInfo =
await host.sharedHandler.hooks.lifecycle.afterResolve.emit({
id: idRes,
...remoteSplitInfo,
options: host.options,
origin: host,
remoteInfo,
});
const { remote, expose } = matchInfo;
assert(
remote && expose,
`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`,
);
let module: Module | undefined = host.moduleCache.get(remote.name);
const moduleOptions: ModuleOptions = {
host: host,
remoteInfo,
};
if (!module) {
module = new Module(moduleOptions);
host.moduleCache.set(remote.name, module);
}
return {
module,
moduleOptions,
remoteMatchInfo: matchInfo,
};
}
registerRemote(
remote: Remote,
targetRemotes: Remote[],
options?: { force?: boolean },
): void {
const { host } = this;
const normalizeRemote = () => {
if (remote.alias) {
// Validate if alias equals the prefix of remote.name and remote.alias, if so, throw an error
// As multi-level path references cannot guarantee unique names, alias being a prefix of remote.name is not supported
const findEqual = targetRemotes.find(
(item) =>
remote.alias &&
(item.name.startsWith(remote.alias) ||
item.alias?.startsWith(remote.alias)),
);
assert(
!findEqual,
`The alias ${remote.alias} of remote ${
remote.name
} is not allowed to be the prefix of ${
findEqual && findEqual.name
} name or alias`,
);
}
// Set the remote entry to a complete path
if ('entry' in remote) {
if (isBrowserEnv() && !remote.entry.startsWith('http')) {
remote.entry = new URL(remote.entry, window.location.origin).href;
}
}
if (!remote.shareScope) {
remote.shareScope = DEFAULT_SCOPE;
}
if (!remote.type) {
remote.type = DEFAULT_REMOTE_TYPE;
}
};
this.hooks.lifecycle.beforeRegisterRemote.emit({ remote, origin: host });
const registeredRemote = targetRemotes.find(
(item) => item.name === remote.name,
);
if (!registeredRemote) {
normalizeRemote();
targetRemotes.push(remote);
this.hooks.lifecycle.registerRemote.emit({ remote, origin: host });
} else {
const messages = [
`The remote "${remote.name}" is already registered.`,
'Please note that overriding it may cause unexpected errors.',
];
if (options?.force) {
// remove registered remote
this.removeRemote(registeredRemote);
normalizeRemote();
targetRemotes.push(remote);
this.hooks.lifecycle.registerRemote.emit({ remote, origin: host });
warn(messages.join(' '));
}
}
}
private removeRemote(remote: Remote): void {
try {
const { host } = this;
const { name } = remote;
const remoteIndex = host.options.remotes.findIndex(
(item) => item.name === name,
);
if (remoteIndex !== -1) {
host.options.remotes.splice(remoteIndex, 1);
}
const loadedModule = host.moduleCache.get(remote.name);
const remoteInfo = loadedModule
? loadedModule.remoteInfo
: getRemoteInfo(remote);
if (remoteInfo.entry) {
host.snapshotHandler.manifestCache.delete(remoteInfo.entry);
}
// Only clean global/share state when this host actually loaded the remote.
if (loadedModule) {
const key = remoteInfo.entryGlobalName as keyof typeof CurrentGlobal;
if (CurrentGlobal[key]) {
if (
Object.getOwnPropertyDescriptor(CurrentGlobal, key)?.configurable
) {
delete CurrentGlobal[key];
} else {
// @ts-ignore
CurrentGlobal[key] = undefined;
}
}
const remoteEntryUniqueKey = getRemoteEntryUniqueKey(remoteInfo);
if (globalLoading[remoteEntryUniqueKey]) {
delete globalLoading[remoteEntryUniqueKey];
}
// delete unloaded shared and instance
let remoteInsId = remoteInfo.buildVersion
? composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion)
: remoteInfo.name;
const remoteInsIndex =
CurrentGlobal.__FEDERATION__.__INSTANCES__.findIndex((ins) => {
if (remoteInfo.buildVersion) {
return ins.options.id === remoteInsId;
} else {
return ins.name === remoteInsId;
}
});
if (remoteInsIndex !== -1) {
const remoteIns =
CurrentGlobal.__FEDERATION__.__INSTANCES__[remoteInsIndex];
remoteInsId = remoteIns.options.id || remoteInsId;
const globalShareScopeMap = getGlobalShareScope();
let isAllSharedNotUsed = true;
const needDeleteKeys: Array<[string, string, string, string]> = [];
Object.keys(globalShareScopeMap).forEach((instId) => {
const shareScopeMap = globalShareScopeMap[instId];
shareScopeMap &&
Object.keys(shareScopeMap).forEach((shareScope) => {
const shareScopeVal = shareScopeMap[shareScope];
shareScopeVal &&
Object.keys(shareScopeVal).forEach((shareName) => {
const sharedPkgs = shareScopeVal[shareName];
sharedPkgs &&
Object.keys(sharedPkgs).forEach((shareVersion) => {
const shared = sharedPkgs[shareVersion];
if (
shared &&
typeof shared === 'object' &&
shared.from === remoteInfo.name
) {
if (shared.loaded || shared.loading) {
shared.useIn = shared.useIn.filter(
(usedHostName) =>
usedHostName !== remoteInfo.name,
);
if (shared.useIn.length) {
isAllSharedNotUsed = false;
} else {
needDeleteKeys.push([
instId,
shareScope,
shareName,
shareVersion,
]);
}
} else {
needDeleteKeys.push([
instId,
shareScope,
shareName,
shareVersion,
]);
}
}
});
});
});
});
if (isAllSharedNotUsed) {
remoteIns.shareScopeMap = {};
delete globalShareScopeMap[remoteInsId];
}
needDeleteKeys.forEach(
([insId, shareScope, shareName, shareVersion]) => {
delete globalShareScopeMap[insId]?.[shareScope]?.[shareName]?.[
shareVersion
];
},
);
CurrentGlobal.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
}
}
host.moduleCache.delete(remote.name);
Object.keys(this.idToRemoteMap).forEach((id) => {
if (this.idToRemoteMap[id]?.name === remote.name) {
delete this.idToRemoteMap[id];
}
});
const remotePrefixes = [remote.name, remote.alias].filter(
Boolean,
) as string[];
const preloadedMap = Global.__FEDERATION__.__PRELOADED_MAP__;
Array.from(preloadedMap.keys()).forEach((key) => {
if (
remotePrefixes.some(
(prefix) => key === prefix || key.startsWith(`${prefix}/`),
)
) {
preloadedMap.delete(key);
}
});
const { hostGlobalSnapshot } = getGlobalRemoteInfo(remote, host);
if (hostGlobalSnapshot) {
const remoteKey =
hostGlobalSnapshot &&
'remotesInfo' in hostGlobalSnapshot &&
hostGlobalSnapshot.remotesInfo &&
getInfoWithoutType(hostGlobalSnapshot.remotesInfo, remote.name).key;
if (remoteKey) {
delete hostGlobalSnapshot.remotesInfo[remoteKey];
if (
//eslint-disable-next-line no-extra-boolean-cast
Boolean(Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey])
) {
delete Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey];
}
}
}
this.hooks.lifecycle.afterRemoveRemote.emit({
remote,
origin: host,
});
} catch (err) {
logger.log('removeRemote fail: ', err);
}
}
}