@module-federation/bridge-react 0.0.0-next-20241113115843 → 0.0.0-next-20241114041727

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.
package/dist/index.es.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import * as React from "react";
2
2
  import React__default, { createContext, Component, createElement, isValidElement, forwardRef, useRef, useEffect, useContext, useState } from "react";
3
- import { c as createLogger, i as isDebugMode, a as isBrowserEnv, b as isManifestProvider, w as warn$1, d as composeKeyWithSeparator, s as safeToString, e as createLink, f as createScript, g as getResourceUrl, h as generateSnapshotFromManifest, l as loadScriptNode, j as loadScript, L as LoggerInstance, k as getRootDomDefaultClassName, p as pathJoin, m as atLeastReact18, R as RouterContext } from "./context-3_giwitw.js";
3
+ import { L as LoggerInstance, g as getRootDomDefaultClassName, p as pathJoin, a as atLeastReact18, R as RouterContext } from "./context-CUbFnlO5.js";
4
4
  import * as ReactRouterDOM from "react-router-dom";
5
+ import { getInstance } from "@module-federation/runtime";
5
6
  import ReactDOM from "react-dom";
6
7
  const ErrorBoundaryContext = createContext(null);
7
8
  const initialState = {
@@ -14,17 +15,17 @@ class ErrorBoundary extends Component {
14
15
  this.resetErrorBoundary = this.resetErrorBoundary.bind(this);
15
16
  this.state = initialState;
16
17
  }
17
- static getDerivedStateFromError(error2) {
18
+ static getDerivedStateFromError(error) {
18
19
  return {
19
20
  didCatch: true,
20
- error: error2
21
+ error
21
22
  };
22
23
  }
23
24
  resetErrorBoundary() {
24
25
  const {
25
- error: error2
26
+ error
26
27
  } = this.state;
27
- if (error2 !== null) {
28
+ if (error !== null) {
28
29
  var _this$props$onReset, _this$props;
29
30
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
30
31
  args[_key] = arguments[_key];
@@ -36,9 +37,9 @@ class ErrorBoundary extends Component {
36
37
  this.setState(initialState);
37
38
  }
38
39
  }
39
- componentDidCatch(error2, info) {
40
+ componentDidCatch(error, info) {
40
41
  var _this$props$onError, _this$props2;
41
- (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error2, info);
42
+ (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error, info);
42
43
  }
43
44
  componentDidUpdate(prevProps, prevState) {
44
45
  const {
@@ -66,12 +67,12 @@ class ErrorBoundary extends Component {
66
67
  } = this.props;
67
68
  const {
68
69
  didCatch,
69
- error: error2
70
+ error
70
71
  } = this.state;
71
72
  let childToRender = children;
72
73
  if (didCatch) {
73
74
  const props = {
74
- error: error2,
75
+ error,
75
76
  resetErrorBoundary: this.resetErrorBoundary
76
77
  };
77
78
  if (typeof fallbackRender === "function") {
@@ -81,13 +82,13 @@ class ErrorBoundary extends Component {
81
82
  } else if (fallback === null || isValidElement(fallback)) {
82
83
  childToRender = fallback;
83
84
  } else {
84
- throw error2;
85
+ throw error;
85
86
  }
86
87
  }
87
88
  return createElement(ErrorBoundaryContext.Provider, {
88
89
  value: {
89
90
  didCatch,
90
- error: error2,
91
+ error,
91
92
  resetErrorBoundary: this.resetErrorBoundary
92
93
  }
93
94
  }, childToRender);
@@ -102,2839 +103,6 @@ function e() {
102
103
  const t = new PopStateEvent("popstate", { state: window.history.state });
103
104
  window.dispatchEvent(t);
104
105
  }
105
- function _extends$1() {
106
- _extends$1 = Object.assign || function assign(target) {
107
- for (var i = 1; i < arguments.length; i++) {
108
- var source = arguments[i];
109
- for (var key in source)
110
- if (Object.prototype.hasOwnProperty.call(source, key))
111
- target[key] = source[key];
112
- }
113
- return target;
114
- };
115
- return _extends$1.apply(this, arguments);
116
- }
117
- function _object_without_properties_loose(source, excluded) {
118
- if (source == null)
119
- return {};
120
- var target = {};
121
- var sourceKeys = Object.keys(source);
122
- var key, i;
123
- for (i = 0; i < sourceKeys.length; i++) {
124
- key = sourceKeys[i];
125
- if (excluded.indexOf(key) >= 0)
126
- continue;
127
- target[key] = source[key];
128
- }
129
- return target;
130
- }
131
- function getBuilderId() {
132
- return typeof FEDERATION_BUILD_IDENTIFIER !== "undefined" ? FEDERATION_BUILD_IDENTIFIER : "";
133
- }
134
- const LOG_CATEGORY = "[ Federation Runtime ]";
135
- const logger = createLogger(LOG_CATEGORY);
136
- function assert(condition, msg) {
137
- if (!condition) {
138
- error(msg);
139
- }
140
- }
141
- function error(msg) {
142
- if (msg instanceof Error) {
143
- msg.message = `${LOG_CATEGORY}: ${msg.message}`;
144
- throw msg;
145
- }
146
- throw new Error(`${LOG_CATEGORY}: ${msg}`);
147
- }
148
- function warn(msg) {
149
- if (msg instanceof Error) {
150
- msg.message = `${LOG_CATEGORY}: ${msg.message}`;
151
- logger.warn(msg);
152
- } else {
153
- logger.warn(msg);
154
- }
155
- }
156
- function addUniqueItem(arr, item) {
157
- if (arr.findIndex((name2) => name2 === item) === -1) {
158
- arr.push(item);
159
- }
160
- return arr;
161
- }
162
- function getFMId(remoteInfo) {
163
- if ("version" in remoteInfo && remoteInfo.version) {
164
- return `${remoteInfo.name}:${remoteInfo.version}`;
165
- } else if ("entry" in remoteInfo && remoteInfo.entry) {
166
- return `${remoteInfo.name}:${remoteInfo.entry}`;
167
- } else {
168
- return `${remoteInfo.name}`;
169
- }
170
- }
171
- function isRemoteInfoWithEntry(remote) {
172
- return typeof remote.entry !== "undefined";
173
- }
174
- function isPureRemoteEntry(remote) {
175
- return !remote.entry.includes(".json") && remote.entry.includes(".js");
176
- }
177
- function isObject(val) {
178
- return val && typeof val === "object";
179
- }
180
- const objectToString = Object.prototype.toString;
181
- function isPlainObject(val) {
182
- return objectToString.call(val) === "[object Object]";
183
- }
184
- function arrayOptions(options) {
185
- return Array.isArray(options) ? options : [
186
- options
187
- ];
188
- }
189
- function getRemoteEntryInfoFromSnapshot(snapshot) {
190
- const defaultRemoteEntryInfo = {
191
- url: "",
192
- type: "global",
193
- globalName: ""
194
- };
195
- if (isBrowserEnv()) {
196
- return "remoteEntry" in snapshot ? {
197
- url: snapshot.remoteEntry,
198
- type: snapshot.remoteEntryType,
199
- globalName: snapshot.globalName
200
- } : defaultRemoteEntryInfo;
201
- }
202
- if ("ssrRemoteEntry" in snapshot) {
203
- return {
204
- url: snapshot.ssrRemoteEntry || defaultRemoteEntryInfo.url,
205
- type: snapshot.ssrRemoteEntryType || defaultRemoteEntryInfo.type,
206
- globalName: snapshot.globalName
207
- };
208
- }
209
- return defaultRemoteEntryInfo;
210
- }
211
- const processModuleAlias = (name2, subPath) => {
212
- let moduleName;
213
- if (name2.endsWith("/")) {
214
- moduleName = name2.slice(0, -1);
215
- } else {
216
- moduleName = name2;
217
- }
218
- if (subPath.startsWith(".")) {
219
- subPath = subPath.slice(1);
220
- }
221
- moduleName = moduleName + subPath;
222
- return moduleName;
223
- };
224
- const CurrentGlobal = typeof globalThis === "object" ? globalThis : window;
225
- const nativeGlobal = (() => {
226
- try {
227
- return document.defaultView;
228
- } catch (e2) {
229
- return CurrentGlobal;
230
- }
231
- })();
232
- const Global = nativeGlobal;
233
- function definePropertyGlobalVal(target, key, val) {
234
- Object.defineProperty(target, key, {
235
- value: val,
236
- configurable: false,
237
- writable: true
238
- });
239
- }
240
- function includeOwnProperty(target, key) {
241
- return Object.hasOwnProperty.call(target, key);
242
- }
243
- if (!includeOwnProperty(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__")) {
244
- definePropertyGlobalVal(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__", {});
245
- }
246
- const globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;
247
- function setGlobalDefaultVal(target) {
248
- var _target___FEDERATION__, _target___FEDERATION__1, _target___FEDERATION__2, _target___FEDERATION__3, _target___FEDERATION__4, _target___FEDERATION__5;
249
- if (includeOwnProperty(target, "__VMOK__") && !includeOwnProperty(target, "__FEDERATION__")) {
250
- definePropertyGlobalVal(target, "__FEDERATION__", target.__VMOK__);
251
- }
252
- if (!includeOwnProperty(target, "__FEDERATION__")) {
253
- definePropertyGlobalVal(target, "__FEDERATION__", {
254
- __GLOBAL_PLUGIN__: [],
255
- __INSTANCES__: [],
256
- moduleInfo: {},
257
- __SHARE__: {},
258
- __MANIFEST_LOADING__: {},
259
- __PRELOADED_MAP__: /* @__PURE__ */ new Map()
260
- });
261
- definePropertyGlobalVal(target, "__VMOK__", target.__FEDERATION__);
262
- }
263
- var ___GLOBAL_PLUGIN__;
264
- (___GLOBAL_PLUGIN__ = (_target___FEDERATION__ = target.__FEDERATION__).__GLOBAL_PLUGIN__) != null ? ___GLOBAL_PLUGIN__ : _target___FEDERATION__.__GLOBAL_PLUGIN__ = [];
265
- var ___INSTANCES__;
266
- (___INSTANCES__ = (_target___FEDERATION__1 = target.__FEDERATION__).__INSTANCES__) != null ? ___INSTANCES__ : _target___FEDERATION__1.__INSTANCES__ = [];
267
- var _moduleInfo;
268
- (_moduleInfo = (_target___FEDERATION__2 = target.__FEDERATION__).moduleInfo) != null ? _moduleInfo : _target___FEDERATION__2.moduleInfo = {};
269
- var ___SHARE__;
270
- (___SHARE__ = (_target___FEDERATION__3 = target.__FEDERATION__).__SHARE__) != null ? ___SHARE__ : _target___FEDERATION__3.__SHARE__ = {};
271
- var ___MANIFEST_LOADING__;
272
- (___MANIFEST_LOADING__ = (_target___FEDERATION__4 = target.__FEDERATION__).__MANIFEST_LOADING__) != null ? ___MANIFEST_LOADING__ : _target___FEDERATION__4.__MANIFEST_LOADING__ = {};
273
- var ___PRELOADED_MAP__;
274
- (___PRELOADED_MAP__ = (_target___FEDERATION__5 = target.__FEDERATION__).__PRELOADED_MAP__) != null ? ___PRELOADED_MAP__ : _target___FEDERATION__5.__PRELOADED_MAP__ = /* @__PURE__ */ new Map();
275
- }
276
- setGlobalDefaultVal(CurrentGlobal);
277
- setGlobalDefaultVal(nativeGlobal);
278
- function setGlobalFederationConstructor(FederationConstructor, isDebug = isDebugMode()) {
279
- if (isDebug) {
280
- CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR__ = FederationConstructor;
281
- CurrentGlobal.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__ = "0.7.3";
282
- }
283
- }
284
- function getInfoWithoutType(target, key) {
285
- if (typeof key === "string") {
286
- const keyRes = target[key];
287
- if (keyRes) {
288
- return {
289
- value: target[key],
290
- key
291
- };
292
- } else {
293
- const targetKeys = Object.keys(target);
294
- for (const targetKey of targetKeys) {
295
- const [targetTypeOrName, _] = targetKey.split(":");
296
- const nKey = `${targetTypeOrName}:${key}`;
297
- const typeWithKeyRes = target[nKey];
298
- if (typeWithKeyRes) {
299
- return {
300
- value: typeWithKeyRes,
301
- key: nKey
302
- };
303
- }
304
- }
305
- return {
306
- value: void 0,
307
- key
308
- };
309
- }
310
- } else {
311
- throw new Error("key must be string");
312
- }
313
- }
314
- const getGlobalSnapshot = () => nativeGlobal.__FEDERATION__.moduleInfo;
315
- const getTargetSnapshotInfoByModuleInfo = (moduleInfo, snapshot) => {
316
- const moduleKey = getFMId(moduleInfo);
317
- const getModuleInfo = getInfoWithoutType(snapshot, moduleKey).value;
318
- if (getModuleInfo && !getModuleInfo.version && "version" in moduleInfo && moduleInfo["version"]) {
319
- getModuleInfo.version = moduleInfo["version"];
320
- }
321
- if (getModuleInfo) {
322
- return getModuleInfo;
323
- }
324
- if ("version" in moduleInfo && moduleInfo["version"]) {
325
- const { version } = moduleInfo, resModuleInfo = _object_without_properties_loose(moduleInfo, [
326
- "version"
327
- ]);
328
- const moduleKeyWithoutVersion = getFMId(resModuleInfo);
329
- const getModuleInfoWithoutVersion = getInfoWithoutType(nativeGlobal.__FEDERATION__.moduleInfo, moduleKeyWithoutVersion).value;
330
- if ((getModuleInfoWithoutVersion == null ? void 0 : getModuleInfoWithoutVersion.version) === version) {
331
- return getModuleInfoWithoutVersion;
332
- }
333
- }
334
- return;
335
- };
336
- const getGlobalSnapshotInfoByModuleInfo = (moduleInfo) => getTargetSnapshotInfoByModuleInfo(moduleInfo, nativeGlobal.__FEDERATION__.moduleInfo);
337
- const setGlobalSnapshotInfoByModuleInfo = (remoteInfo, moduleDetailInfo) => {
338
- const moduleKey = getFMId(remoteInfo);
339
- nativeGlobal.__FEDERATION__.moduleInfo[moduleKey] = moduleDetailInfo;
340
- return nativeGlobal.__FEDERATION__.moduleInfo;
341
- };
342
- const addGlobalSnapshot = (moduleInfos) => {
343
- nativeGlobal.__FEDERATION__.moduleInfo = _extends$1({}, nativeGlobal.__FEDERATION__.moduleInfo, moduleInfos);
344
- return () => {
345
- const keys = Object.keys(moduleInfos);
346
- for (const key of keys) {
347
- delete nativeGlobal.__FEDERATION__.moduleInfo[key];
348
- }
349
- };
350
- };
351
- const getRemoteEntryExports = (name2, globalName) => {
352
- const remoteEntryKey = globalName || `__FEDERATION_${name2}:custom__`;
353
- const entryExports = CurrentGlobal[remoteEntryKey];
354
- return {
355
- remoteEntryKey,
356
- entryExports
357
- };
358
- };
359
- const getGlobalHostPlugins = () => nativeGlobal.__FEDERATION__.__GLOBAL_PLUGIN__;
360
- const getPreloaded = (id) => CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.get(id);
361
- const setPreloaded = (id) => CurrentGlobal.__FEDERATION__.__PRELOADED_MAP__.set(id, true);
362
- const DEFAULT_SCOPE = "default";
363
- const DEFAULT_REMOTE_TYPE = "global";
364
- const buildIdentifier = "[0-9A-Za-z-]+";
365
- const build = `(?:\\+(${buildIdentifier}(?:\\.${buildIdentifier})*))`;
366
- const numericIdentifier = "0|[1-9]\\d*";
367
- const numericIdentifierLoose = "[0-9]+";
368
- const nonNumericIdentifier = "\\d*[a-zA-Z-][a-zA-Z0-9-]*";
369
- const preReleaseIdentifierLoose = `(?:${numericIdentifierLoose}|${nonNumericIdentifier})`;
370
- const preReleaseLoose = `(?:-?(${preReleaseIdentifierLoose}(?:\\.${preReleaseIdentifierLoose})*))`;
371
- const preReleaseIdentifier = `(?:${numericIdentifier}|${nonNumericIdentifier})`;
372
- const preRelease = `(?:-(${preReleaseIdentifier}(?:\\.${preReleaseIdentifier})*))`;
373
- const xRangeIdentifier = `${numericIdentifier}|x|X|\\*`;
374
- const xRangePlain = `[v=\\s]*(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:\\.(${xRangeIdentifier})(?:${preRelease})?${build}?)?)?`;
375
- const hyphenRange = `^\\s*(${xRangePlain})\\s+-\\s+(${xRangePlain})\\s*$`;
376
- const mainVersionLoose = `(${numericIdentifierLoose})\\.(${numericIdentifierLoose})\\.(${numericIdentifierLoose})`;
377
- const loosePlain = `[v=\\s]*${mainVersionLoose}${preReleaseLoose}?${build}?`;
378
- const gtlt = "((?:<|>)?=?)";
379
- const comparatorTrim = `(\\s*)${gtlt}\\s*(${loosePlain}|${xRangePlain})`;
380
- const loneTilde = "(?:~>?)";
381
- const tildeTrim = `(\\s*)${loneTilde}\\s+`;
382
- const loneCaret = "(?:\\^)";
383
- const caretTrim = `(\\s*)${loneCaret}\\s+`;
384
- const star = "(<|>)?=?\\s*\\*";
385
- const caret = `^${loneCaret}${xRangePlain}$`;
386
- const mainVersion = `(${numericIdentifier})\\.(${numericIdentifier})\\.(${numericIdentifier})`;
387
- const fullPlain = `v?${mainVersion}${preRelease}?${build}?`;
388
- const tilde = `^${loneTilde}${xRangePlain}$`;
389
- const xRange = `^${gtlt}\\s*${xRangePlain}$`;
390
- const comparator = `^${gtlt}\\s*(${fullPlain})$|^$`;
391
- const gte0 = "^\\s*>=\\s*0.0.0\\s*$";
392
- function parseRegex(source) {
393
- return new RegExp(source);
394
- }
395
- function isXVersion(version) {
396
- return !version || version.toLowerCase() === "x" || version === "*";
397
- }
398
- function pipe(...fns) {
399
- return (x) => fns.reduce((v, f) => f(v), x);
400
- }
401
- function extractComparator(comparatorString) {
402
- return comparatorString.match(parseRegex(comparator));
403
- }
404
- function combineVersion(major, minor, patch, preRelease2) {
405
- const mainVersion2 = `${major}.${minor}.${patch}`;
406
- if (preRelease2) {
407
- return `${mainVersion2}-${preRelease2}`;
408
- }
409
- return mainVersion2;
410
- }
411
- function parseHyphen(range) {
412
- return range.replace(parseRegex(hyphenRange), (_range, from, fromMajor, fromMinor, fromPatch, _fromPreRelease, _fromBuild, to, toMajor, toMinor, toPatch, toPreRelease) => {
413
- if (isXVersion(fromMajor)) {
414
- from = "";
415
- } else if (isXVersion(fromMinor)) {
416
- from = `>=${fromMajor}.0.0`;
417
- } else if (isXVersion(fromPatch)) {
418
- from = `>=${fromMajor}.${fromMinor}.0`;
419
- } else {
420
- from = `>=${from}`;
421
- }
422
- if (isXVersion(toMajor)) {
423
- to = "";
424
- } else if (isXVersion(toMinor)) {
425
- to = `<${Number(toMajor) + 1}.0.0-0`;
426
- } else if (isXVersion(toPatch)) {
427
- to = `<${toMajor}.${Number(toMinor) + 1}.0-0`;
428
- } else if (toPreRelease) {
429
- to = `<=${toMajor}.${toMinor}.${toPatch}-${toPreRelease}`;
430
- } else {
431
- to = `<=${to}`;
432
- }
433
- return `${from} ${to}`.trim();
434
- });
435
- }
436
- function parseComparatorTrim(range) {
437
- return range.replace(parseRegex(comparatorTrim), "$1$2$3");
438
- }
439
- function parseTildeTrim(range) {
440
- return range.replace(parseRegex(tildeTrim), "$1~");
441
- }
442
- function parseCaretTrim(range) {
443
- return range.replace(parseRegex(caretTrim), "$1^");
444
- }
445
- function parseCarets(range) {
446
- return range.trim().split(/\s+/).map((rangeVersion) => rangeVersion.replace(parseRegex(caret), (_, major, minor, patch, preRelease2) => {
447
- if (isXVersion(major)) {
448
- return "";
449
- } else if (isXVersion(minor)) {
450
- return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
451
- } else if (isXVersion(patch)) {
452
- if (major === "0") {
453
- return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
454
- } else {
455
- return `>=${major}.${minor}.0 <${Number(major) + 1}.0.0-0`;
456
- }
457
- } else if (preRelease2) {
458
- if (major === "0") {
459
- if (minor === "0") {
460
- return `>=${major}.${minor}.${patch}-${preRelease2} <${major}.${minor}.${Number(patch) + 1}-0`;
461
- } else {
462
- return `>=${major}.${minor}.${patch}-${preRelease2} <${major}.${Number(minor) + 1}.0-0`;
463
- }
464
- } else {
465
- return `>=${major}.${minor}.${patch}-${preRelease2} <${Number(major) + 1}.0.0-0`;
466
- }
467
- } else {
468
- if (major === "0") {
469
- if (minor === "0") {
470
- return `>=${major}.${minor}.${patch} <${major}.${minor}.${Number(patch) + 1}-0`;
471
- } else {
472
- return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
473
- }
474
- }
475
- return `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0-0`;
476
- }
477
- })).join(" ");
478
- }
479
- function parseTildes(range) {
480
- return range.trim().split(/\s+/).map((rangeVersion) => rangeVersion.replace(parseRegex(tilde), (_, major, minor, patch, preRelease2) => {
481
- if (isXVersion(major)) {
482
- return "";
483
- } else if (isXVersion(minor)) {
484
- return `>=${major}.0.0 <${Number(major) + 1}.0.0-0`;
485
- } else if (isXVersion(patch)) {
486
- return `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0-0`;
487
- } else if (preRelease2) {
488
- return `>=${major}.${minor}.${patch}-${preRelease2} <${major}.${Number(minor) + 1}.0-0`;
489
- }
490
- return `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
491
- })).join(" ");
492
- }
493
- function parseXRanges(range) {
494
- return range.split(/\s+/).map((rangeVersion) => rangeVersion.trim().replace(parseRegex(xRange), (ret, gtlt2, major, minor, patch, preRelease2) => {
495
- const isXMajor = isXVersion(major);
496
- const isXMinor = isXMajor || isXVersion(minor);
497
- const isXPatch = isXMinor || isXVersion(patch);
498
- if (gtlt2 === "=" && isXPatch) {
499
- gtlt2 = "";
500
- }
501
- preRelease2 = "";
502
- if (isXMajor) {
503
- if (gtlt2 === ">" || gtlt2 === "<") {
504
- return "<0.0.0-0";
505
- } else {
506
- return "*";
507
- }
508
- } else if (gtlt2 && isXPatch) {
509
- if (isXMinor) {
510
- minor = 0;
511
- }
512
- patch = 0;
513
- if (gtlt2 === ">") {
514
- gtlt2 = ">=";
515
- if (isXMinor) {
516
- major = Number(major) + 1;
517
- minor = 0;
518
- patch = 0;
519
- } else {
520
- minor = Number(minor) + 1;
521
- patch = 0;
522
- }
523
- } else if (gtlt2 === "<=") {
524
- gtlt2 = "<";
525
- if (isXMinor) {
526
- major = Number(major) + 1;
527
- } else {
528
- minor = Number(minor) + 1;
529
- }
530
- }
531
- if (gtlt2 === "<") {
532
- preRelease2 = "-0";
533
- }
534
- return `${gtlt2 + major}.${minor}.${patch}${preRelease2}`;
535
- } else if (isXMinor) {
536
- return `>=${major}.0.0${preRelease2} <${Number(major) + 1}.0.0-0`;
537
- } else if (isXPatch) {
538
- return `>=${major}.${minor}.0${preRelease2} <${major}.${Number(minor) + 1}.0-0`;
539
- }
540
- return ret;
541
- })).join(" ");
542
- }
543
- function parseStar(range) {
544
- return range.trim().replace(parseRegex(star), "");
545
- }
546
- function parseGTE0(comparatorString) {
547
- return comparatorString.trim().replace(parseRegex(gte0), "");
548
- }
549
- function compareAtom(rangeAtom, versionAtom) {
550
- rangeAtom = Number(rangeAtom) || rangeAtom;
551
- versionAtom = Number(versionAtom) || versionAtom;
552
- if (rangeAtom > versionAtom) {
553
- return 1;
554
- }
555
- if (rangeAtom === versionAtom) {
556
- return 0;
557
- }
558
- return -1;
559
- }
560
- function comparePreRelease(rangeAtom, versionAtom) {
561
- const { preRelease: rangePreRelease } = rangeAtom;
562
- const { preRelease: versionPreRelease } = versionAtom;
563
- if (rangePreRelease === void 0 && Boolean(versionPreRelease)) {
564
- return 1;
565
- }
566
- if (Boolean(rangePreRelease) && versionPreRelease === void 0) {
567
- return -1;
568
- }
569
- if (rangePreRelease === void 0 && versionPreRelease === void 0) {
570
- return 0;
571
- }
572
- for (let i = 0, n = rangePreRelease.length; i <= n; i++) {
573
- const rangeElement = rangePreRelease[i];
574
- const versionElement = versionPreRelease[i];
575
- if (rangeElement === versionElement) {
576
- continue;
577
- }
578
- if (rangeElement === void 0 && versionElement === void 0) {
579
- return 0;
580
- }
581
- if (!rangeElement) {
582
- return 1;
583
- }
584
- if (!versionElement) {
585
- return -1;
586
- }
587
- return compareAtom(rangeElement, versionElement);
588
- }
589
- return 0;
590
- }
591
- function compareVersion(rangeAtom, versionAtom) {
592
- return compareAtom(rangeAtom.major, versionAtom.major) || compareAtom(rangeAtom.minor, versionAtom.minor) || compareAtom(rangeAtom.patch, versionAtom.patch) || comparePreRelease(rangeAtom, versionAtom);
593
- }
594
- function eq(rangeAtom, versionAtom) {
595
- return rangeAtom.version === versionAtom.version;
596
- }
597
- function compare(rangeAtom, versionAtom) {
598
- switch (rangeAtom.operator) {
599
- case "":
600
- case "=":
601
- return eq(rangeAtom, versionAtom);
602
- case ">":
603
- return compareVersion(rangeAtom, versionAtom) < 0;
604
- case ">=":
605
- return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) < 0;
606
- case "<":
607
- return compareVersion(rangeAtom, versionAtom) > 0;
608
- case "<=":
609
- return eq(rangeAtom, versionAtom) || compareVersion(rangeAtom, versionAtom) > 0;
610
- case void 0: {
611
- return true;
612
- }
613
- default:
614
- return false;
615
- }
616
- }
617
- function parseComparatorString(range) {
618
- return pipe(
619
- // handle caret
620
- // ^ --> * (any, kinda silly)
621
- // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
622
- // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
623
- // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
624
- // ^1.2.3 --> >=1.2.3 <2.0.0-0
625
- // ^1.2.0 --> >=1.2.0 <2.0.0-0
626
- parseCarets,
627
- // handle tilde
628
- // ~, ~> --> * (any, kinda silly)
629
- // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
630
- // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
631
- // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
632
- // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
633
- // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
634
- parseTildes,
635
- parseXRanges,
636
- parseStar
637
- )(range);
638
- }
639
- function parseRange(range) {
640
- return pipe(
641
- // handle hyphenRange
642
- // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
643
- parseHyphen,
644
- // handle trim comparator
645
- // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
646
- parseComparatorTrim,
647
- // handle trim tilde
648
- // `~ 1.2.3` => `~1.2.3`
649
- parseTildeTrim,
650
- // handle trim caret
651
- // `^ 1.2.3` => `^1.2.3`
652
- parseCaretTrim
653
- )(range.trim()).split(/\s+/).join(" ");
654
- }
655
- function satisfy(version, range) {
656
- if (!version) {
657
- return false;
658
- }
659
- const parsedRange = parseRange(range);
660
- const parsedComparator = parsedRange.split(" ").map((rangeVersion) => parseComparatorString(rangeVersion)).join(" ");
661
- const comparators = parsedComparator.split(/\s+/).map((comparator2) => parseGTE0(comparator2));
662
- const extractedVersion = extractComparator(version);
663
- if (!extractedVersion) {
664
- return false;
665
- }
666
- const [, versionOperator, , versionMajor, versionMinor, versionPatch, versionPreRelease] = extractedVersion;
667
- const versionAtom = {
668
- operator: versionOperator,
669
- version: combineVersion(versionMajor, versionMinor, versionPatch, versionPreRelease),
670
- major: versionMajor,
671
- minor: versionMinor,
672
- patch: versionPatch,
673
- preRelease: versionPreRelease == null ? void 0 : versionPreRelease.split(".")
674
- };
675
- for (const comparator2 of comparators) {
676
- const extractedComparator = extractComparator(comparator2);
677
- if (!extractedComparator) {
678
- return false;
679
- }
680
- const [, rangeOperator, , rangeMajor, rangeMinor, rangePatch, rangePreRelease] = extractedComparator;
681
- const rangeAtom = {
682
- operator: rangeOperator,
683
- version: combineVersion(rangeMajor, rangeMinor, rangePatch, rangePreRelease),
684
- major: rangeMajor,
685
- minor: rangeMinor,
686
- patch: rangePatch,
687
- preRelease: rangePreRelease == null ? void 0 : rangePreRelease.split(".")
688
- };
689
- if (!compare(rangeAtom, versionAtom)) {
690
- return false;
691
- }
692
- }
693
- return true;
694
- }
695
- function formatShare(shareArgs, from, name2, shareStrategy) {
696
- let get;
697
- if ("get" in shareArgs) {
698
- get = shareArgs.get;
699
- } else if ("lib" in shareArgs) {
700
- get = () => Promise.resolve(shareArgs.lib);
701
- } else {
702
- get = () => Promise.resolve(() => {
703
- throw new Error(`Can not get shared '${name2}'!`);
704
- });
705
- }
706
- if (shareArgs.strategy) {
707
- warn(`"shared.strategy is deprecated, please set in initOptions.shareStrategy instead!"`);
708
- }
709
- var _shareArgs_version, _shareArgs_scope, _shareArgs_strategy;
710
- return _extends$1({
711
- deps: [],
712
- useIn: [],
713
- from,
714
- loading: null
715
- }, shareArgs, {
716
- shareConfig: _extends$1({
717
- requiredVersion: `^${shareArgs.version}`,
718
- singleton: false,
719
- eager: false,
720
- strictVersion: false
721
- }, shareArgs.shareConfig),
722
- get,
723
- loaded: (shareArgs == null ? void 0 : shareArgs.loaded) || "lib" in shareArgs ? true : void 0,
724
- version: (_shareArgs_version = shareArgs.version) != null ? _shareArgs_version : "0",
725
- scope: Array.isArray(shareArgs.scope) ? shareArgs.scope : [
726
- (_shareArgs_scope = shareArgs.scope) != null ? _shareArgs_scope : "default"
727
- ],
728
- strategy: ((_shareArgs_strategy = shareArgs.strategy) != null ? _shareArgs_strategy : shareStrategy) || "version-first"
729
- });
730
- }
731
- function formatShareConfigs(globalOptions, userOptions) {
732
- const shareArgs = userOptions.shared || {};
733
- const from = userOptions.name;
734
- const shareInfos = Object.keys(shareArgs).reduce((res, pkgName) => {
735
- const arrayShareArgs = arrayOptions(shareArgs[pkgName]);
736
- res[pkgName] = res[pkgName] || [];
737
- arrayShareArgs.forEach((shareConfig) => {
738
- res[pkgName].push(formatShare(shareConfig, from, pkgName, userOptions.shareStrategy));
739
- });
740
- return res;
741
- }, {});
742
- const shared = _extends$1({}, globalOptions.shared);
743
- Object.keys(shareInfos).forEach((shareKey) => {
744
- if (!shared[shareKey]) {
745
- shared[shareKey] = shareInfos[shareKey];
746
- } else {
747
- shareInfos[shareKey].forEach((newUserSharedOptions) => {
748
- const isSameVersion = shared[shareKey].find((sharedVal) => sharedVal.version === newUserSharedOptions.version);
749
- if (!isSameVersion) {
750
- shared[shareKey].push(newUserSharedOptions);
751
- }
752
- });
753
- }
754
- });
755
- return {
756
- shared,
757
- shareInfos
758
- };
759
- }
760
- function versionLt(a, b) {
761
- const transformInvalidVersion = (version) => {
762
- const isNumberVersion = !Number.isNaN(Number(version));
763
- if (isNumberVersion) {
764
- const splitArr = version.split(".");
765
- let validVersion = version;
766
- for (let i = 0; i < 3 - splitArr.length; i++) {
767
- validVersion += ".0";
768
- }
769
- return validVersion;
770
- }
771
- return version;
772
- };
773
- if (satisfy(transformInvalidVersion(a), `<=${transformInvalidVersion(b)}`)) {
774
- return true;
775
- } else {
776
- return false;
777
- }
778
- }
779
- const findVersion = (shareVersionMap, cb) => {
780
- const callback = cb || function(prev, cur) {
781
- return versionLt(prev, cur);
782
- };
783
- return Object.keys(shareVersionMap).reduce((prev, cur) => {
784
- if (!prev) {
785
- return cur;
786
- }
787
- if (callback(prev, cur)) {
788
- return cur;
789
- }
790
- if (prev === "0") {
791
- return cur;
792
- }
793
- return prev;
794
- }, 0);
795
- };
796
- const isLoaded = (shared) => {
797
- return Boolean(shared.loaded) || typeof shared.lib === "function";
798
- };
799
- const isLoading = (shared) => {
800
- return Boolean(shared.loading);
801
- };
802
- function findSingletonVersionOrderByVersion(shareScopeMap, scope, pkgName) {
803
- const versions = shareScopeMap[scope][pkgName];
804
- const callback = function(prev, cur) {
805
- return !isLoaded(versions[prev]) && versionLt(prev, cur);
806
- };
807
- return findVersion(shareScopeMap[scope][pkgName], callback);
808
- }
809
- function findSingletonVersionOrderByLoaded(shareScopeMap, scope, pkgName) {
810
- const versions = shareScopeMap[scope][pkgName];
811
- const callback = function(prev, cur) {
812
- const isLoadingOrLoaded = (shared) => {
813
- return isLoaded(shared) || isLoading(shared);
814
- };
815
- if (isLoadingOrLoaded(versions[cur])) {
816
- if (isLoadingOrLoaded(versions[prev])) {
817
- return Boolean(versionLt(prev, cur));
818
- } else {
819
- return true;
820
- }
821
- }
822
- if (isLoadingOrLoaded(versions[prev])) {
823
- return false;
824
- }
825
- return versionLt(prev, cur);
826
- };
827
- return findVersion(shareScopeMap[scope][pkgName], callback);
828
- }
829
- function getFindShareFunction(strategy) {
830
- if (strategy === "loaded-first") {
831
- return findSingletonVersionOrderByLoaded;
832
- }
833
- return findSingletonVersionOrderByVersion;
834
- }
835
- function getRegisteredShare(localShareScopeMap, pkgName, shareInfo, resolveShare) {
836
- if (!localShareScopeMap) {
837
- return;
838
- }
839
- const { shareConfig, scope = DEFAULT_SCOPE, strategy } = shareInfo;
840
- const scopes = Array.isArray(scope) ? scope : [
841
- scope
842
- ];
843
- for (const sc of scopes) {
844
- if (shareConfig && localShareScopeMap[sc] && localShareScopeMap[sc][pkgName]) {
845
- const { requiredVersion } = shareConfig;
846
- const findShareFunction = getFindShareFunction(strategy);
847
- const maxOrSingletonVersion = findShareFunction(localShareScopeMap, sc, pkgName);
848
- const defaultResolver = () => {
849
- if (shareConfig.singleton) {
850
- if (typeof requiredVersion === "string" && !satisfy(maxOrSingletonVersion, requiredVersion)) {
851
- const msg = `Version ${maxOrSingletonVersion} from ${maxOrSingletonVersion && localShareScopeMap[sc][pkgName][maxOrSingletonVersion].from} of shared singleton module ${pkgName} does not satisfy the requirement of ${shareInfo.from} which needs ${requiredVersion})`;
852
- if (shareConfig.strictVersion) {
853
- error(msg);
854
- } else {
855
- warn(msg);
856
- }
857
- }
858
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
859
- } else {
860
- if (requiredVersion === false || requiredVersion === "*") {
861
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
862
- }
863
- if (satisfy(maxOrSingletonVersion, requiredVersion)) {
864
- return localShareScopeMap[sc][pkgName][maxOrSingletonVersion];
865
- }
866
- for (const [versionKey, versionValue] of Object.entries(localShareScopeMap[sc][pkgName])) {
867
- if (satisfy(versionKey, requiredVersion)) {
868
- return versionValue;
869
- }
870
- }
871
- }
872
- };
873
- const params = {
874
- shareScopeMap: localShareScopeMap,
875
- scope: sc,
876
- pkgName,
877
- version: maxOrSingletonVersion,
878
- GlobalFederation: Global.__FEDERATION__,
879
- resolver: defaultResolver
880
- };
881
- const resolveShared = resolveShare.emit(params) || params;
882
- return resolveShared.resolver();
883
- }
884
- }
885
- }
886
- function getGlobalShareScope() {
887
- return Global.__FEDERATION__.__SHARE__;
888
- }
889
- function getTargetSharedOptions(options) {
890
- const { pkgName, extraOptions, shareInfos } = options;
891
- const defaultResolver = (sharedOptions) => {
892
- if (!sharedOptions) {
893
- return void 0;
894
- }
895
- const shareVersionMap = {};
896
- sharedOptions.forEach((shared) => {
897
- shareVersionMap[shared.version] = shared;
898
- });
899
- const callback = function(prev, cur) {
900
- return !isLoaded(shareVersionMap[prev]) && versionLt(prev, cur);
901
- };
902
- const maxVersion = findVersion(shareVersionMap, callback);
903
- return shareVersionMap[maxVersion];
904
- };
905
- var _extraOptions_resolver;
906
- const resolver = (_extraOptions_resolver = extraOptions == null ? void 0 : extraOptions.resolver) != null ? _extraOptions_resolver : defaultResolver;
907
- return Object.assign({}, resolver(shareInfos[pkgName]), extraOptions == null ? void 0 : extraOptions.customShareInfo);
908
- }
909
- const RUNTIME_001 = "RUNTIME-001";
910
- const RUNTIME_002 = "RUNTIME-002";
911
- const RUNTIME_003 = "RUNTIME-003";
912
- const RUNTIME_004 = "RUNTIME-004";
913
- const RUNTIME_005 = "RUNTIME-005";
914
- const RUNTIME_006 = "RUNTIME-006";
915
- const RUNTIME_007 = "RUNTIME-007";
916
- const TYPE_001 = "TYPE-001";
917
- const getDocsUrl = (errorCode) => {
918
- const type = errorCode.split("-")[0].toLowerCase();
919
- return `https://module-federation.io/guide/troubleshooting/${type}/${errorCode}`;
920
- };
921
- const getShortErrorMsg = (errorCode, errorDescMap, args, originalErrorMsg) => {
922
- const msg = [
923
- `${[
924
- errorDescMap[errorCode]
925
- ]} #${errorCode}`
926
- ];
927
- args && msg.push(`args: ${JSON.stringify(args)}`);
928
- msg.push(getDocsUrl(errorCode));
929
- originalErrorMsg && msg.push(`Original Error Message:
930
- ${originalErrorMsg}`);
931
- return msg.join("\n");
932
- };
933
- function _extends() {
934
- _extends = Object.assign || function assign(target) {
935
- for (var i = 1; i < arguments.length; i++) {
936
- var source = arguments[i];
937
- for (var key in source)
938
- if (Object.prototype.hasOwnProperty.call(source, key))
939
- target[key] = source[key];
940
- }
941
- return target;
942
- };
943
- return _extends.apply(this, arguments);
944
- }
945
- const runtimeDescMap = {
946
- [RUNTIME_001]: "Failed to get remoteEntry exports.",
947
- [RUNTIME_002]: 'The remote entry interface does not contain "init"',
948
- [RUNTIME_003]: "Failed to get manifest.",
949
- [RUNTIME_004]: "Failed to locate remote.",
950
- [RUNTIME_005]: "Invalid loadShareSync function call from bundler runtime",
951
- [RUNTIME_006]: "Invalid loadShareSync function call from runtime",
952
- [RUNTIME_007]: "Failed to get remote snapshot."
953
- };
954
- const typeDescMap = {
955
- [TYPE_001]: "Failed to generate type declaration."
956
- };
957
- _extends({}, runtimeDescMap, typeDescMap);
958
- function matchRemoteWithNameAndExpose(remotes, id) {
959
- for (const remote of remotes) {
960
- const isNameMatched = id.startsWith(remote.name);
961
- let expose = id.replace(remote.name, "");
962
- if (isNameMatched) {
963
- if (expose.startsWith("/")) {
964
- const pkgNameOrAlias = remote.name;
965
- expose = `.${expose}`;
966
- return {
967
- pkgNameOrAlias,
968
- expose,
969
- remote
970
- };
971
- } else if (expose === "") {
972
- return {
973
- pkgNameOrAlias: remote.name,
974
- expose: ".",
975
- remote
976
- };
977
- }
978
- }
979
- const isAliasMatched = remote.alias && id.startsWith(remote.alias);
980
- let exposeWithAlias = remote.alias && id.replace(remote.alias, "");
981
- if (remote.alias && isAliasMatched) {
982
- if (exposeWithAlias && exposeWithAlias.startsWith("/")) {
983
- const pkgNameOrAlias = remote.alias;
984
- exposeWithAlias = `.${exposeWithAlias}`;
985
- return {
986
- pkgNameOrAlias,
987
- expose: exposeWithAlias,
988
- remote
989
- };
990
- } else if (exposeWithAlias === "") {
991
- return {
992
- pkgNameOrAlias: remote.alias,
993
- expose: ".",
994
- remote
995
- };
996
- }
997
- }
998
- }
999
- return;
1000
- }
1001
- function matchRemote(remotes, nameOrAlias) {
1002
- for (const remote of remotes) {
1003
- const isNameMatched = nameOrAlias === remote.name;
1004
- if (isNameMatched) {
1005
- return remote;
1006
- }
1007
- const isAliasMatched = remote.alias && nameOrAlias === remote.alias;
1008
- if (isAliasMatched) {
1009
- return remote;
1010
- }
1011
- }
1012
- return;
1013
- }
1014
- function registerPlugins$1(plugins, hookInstances) {
1015
- const globalPlugins = getGlobalHostPlugins();
1016
- if (globalPlugins.length > 0) {
1017
- globalPlugins.forEach((plugin) => {
1018
- if (plugins == null ? void 0 : plugins.find((item) => item.name !== plugin.name)) {
1019
- plugins.push(plugin);
1020
- }
1021
- });
1022
- }
1023
- if (plugins && plugins.length > 0) {
1024
- plugins.forEach((plugin) => {
1025
- hookInstances.forEach((hookInstance) => {
1026
- hookInstance.applyPlugin(plugin);
1027
- });
1028
- });
1029
- }
1030
- return plugins;
1031
- }
1032
- async function loadEsmEntry({ entry, remoteEntryExports }) {
1033
- return new Promise((resolve, reject) => {
1034
- try {
1035
- if (!remoteEntryExports) {
1036
- import(
1037
- /* webpackIgnore: true */
1038
- entry
1039
- ).then(resolve).catch(reject);
1040
- } else {
1041
- resolve(remoteEntryExports);
1042
- }
1043
- } catch (e2) {
1044
- reject(e2);
1045
- }
1046
- });
1047
- }
1048
- async function loadSystemJsEntry({ entry, remoteEntryExports }) {
1049
- return new Promise((resolve, reject) => {
1050
- try {
1051
- if (!remoteEntryExports) {
1052
- if (typeof __system_context__ === "undefined") {
1053
- System.import(entry).then(resolve).catch(reject);
1054
- } else {
1055
- new Function("callbacks", `System.import("${entry}").then(callbacks[0]).catch(callbacks[1])`)([
1056
- resolve,
1057
- reject
1058
- ]);
1059
- }
1060
- } else {
1061
- resolve(remoteEntryExports);
1062
- }
1063
- } catch (e2) {
1064
- reject(e2);
1065
- }
1066
- });
1067
- }
1068
- async function loadEntryScript({ name: name2, globalName, entry, loaderHook }) {
1069
- const { entryExports: remoteEntryExports } = getRemoteEntryExports(name2, globalName);
1070
- if (remoteEntryExports) {
1071
- return remoteEntryExports;
1072
- }
1073
- return loadScript(entry, {
1074
- attrs: {},
1075
- createScriptHook: (url, attrs) => {
1076
- const res = loaderHook.lifecycle.createScript.emit({
1077
- url,
1078
- attrs
1079
- });
1080
- if (!res)
1081
- return;
1082
- if (res instanceof HTMLScriptElement) {
1083
- return res;
1084
- }
1085
- if ("script" in res || "timeout" in res) {
1086
- return res;
1087
- }
1088
- return;
1089
- }
1090
- }).then(() => {
1091
- const { remoteEntryKey, entryExports } = getRemoteEntryExports(name2, globalName);
1092
- assert(entryExports, getShortErrorMsg(RUNTIME_001, runtimeDescMap, {
1093
- remoteName: name2,
1094
- remoteEntryUrl: entry,
1095
- remoteEntryKey
1096
- }));
1097
- return entryExports;
1098
- }).catch((e2) => {
1099
- throw e2;
1100
- });
1101
- }
1102
- async function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook }) {
1103
- const { entry, entryGlobalName: globalName, name: name2, type } = remoteInfo;
1104
- switch (type) {
1105
- case "esm":
1106
- case "module":
1107
- return loadEsmEntry({
1108
- entry,
1109
- remoteEntryExports
1110
- });
1111
- case "system":
1112
- return loadSystemJsEntry({
1113
- entry,
1114
- remoteEntryExports
1115
- });
1116
- default:
1117
- return loadEntryScript({
1118
- entry,
1119
- globalName,
1120
- name: name2,
1121
- loaderHook
1122
- });
1123
- }
1124
- }
1125
- async function loadEntryNode({ remoteInfo, loaderHook }) {
1126
- const { entry, entryGlobalName: globalName, name: name2, type } = remoteInfo;
1127
- const { entryExports: remoteEntryExports } = getRemoteEntryExports(name2, globalName);
1128
- if (remoteEntryExports) {
1129
- return remoteEntryExports;
1130
- }
1131
- return loadScriptNode(entry, {
1132
- attrs: {
1133
- name: name2,
1134
- globalName,
1135
- type
1136
- },
1137
- loaderHook: {
1138
- createScriptHook: (url, attrs = {}) => {
1139
- const res = loaderHook.lifecycle.createScript.emit({
1140
- url,
1141
- attrs
1142
- });
1143
- if (!res)
1144
- return;
1145
- if ("url" in res) {
1146
- return res;
1147
- }
1148
- return;
1149
- }
1150
- }
1151
- }).then(() => {
1152
- const { remoteEntryKey, entryExports } = getRemoteEntryExports(name2, globalName);
1153
- assert(entryExports, getShortErrorMsg(RUNTIME_001, runtimeDescMap, {
1154
- remoteName: name2,
1155
- remoteEntryUrl: entry,
1156
- remoteEntryKey
1157
- }));
1158
- return entryExports;
1159
- }).catch((e2) => {
1160
- throw e2;
1161
- });
1162
- }
1163
- function getRemoteEntryUniqueKey(remoteInfo) {
1164
- const { entry, name: name2 } = remoteInfo;
1165
- return composeKeyWithSeparator(name2, entry);
1166
- }
1167
- async function getRemoteEntry({ origin, remoteEntryExports, remoteInfo }) {
1168
- const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
1169
- if (remoteEntryExports) {
1170
- return remoteEntryExports;
1171
- }
1172
- if (!globalLoading[uniqueKey]) {
1173
- const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;
1174
- origin.loaderHook.lifecycle.createScript;
1175
- const loaderHook = origin.loaderHook;
1176
- globalLoading[uniqueKey] = loadEntryHook.emit({
1177
- loaderHook,
1178
- remoteInfo,
1179
- remoteEntryExports
1180
- }).then((res) => {
1181
- if (res) {
1182
- return res;
1183
- }
1184
- return isBrowserEnv() ? loadEntryDom({
1185
- remoteInfo,
1186
- remoteEntryExports,
1187
- loaderHook
1188
- }) : loadEntryNode({
1189
- remoteInfo,
1190
- loaderHook
1191
- });
1192
- });
1193
- }
1194
- return globalLoading[uniqueKey];
1195
- }
1196
- function getRemoteInfo(remote) {
1197
- return _extends$1({}, remote, {
1198
- entry: "entry" in remote ? remote.entry : "",
1199
- type: remote.type || DEFAULT_REMOTE_TYPE,
1200
- entryGlobalName: remote.entryGlobalName || remote.name,
1201
- shareScope: remote.shareScope || DEFAULT_SCOPE
1202
- });
1203
- }
1204
- let Module = class Module2 {
1205
- async getEntry() {
1206
- if (this.remoteEntryExports) {
1207
- return this.remoteEntryExports;
1208
- }
1209
- const remoteEntryExports = await getRemoteEntry({
1210
- origin: this.host,
1211
- remoteInfo: this.remoteInfo,
1212
- remoteEntryExports: this.remoteEntryExports
1213
- });
1214
- assert(remoteEntryExports, `remoteEntryExports is undefined
1215
- ${safeToString(this.remoteInfo)}`);
1216
- this.remoteEntryExports = remoteEntryExports;
1217
- return this.remoteEntryExports;
1218
- }
1219
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
1220
- async get(id, expose, options, remoteSnapshot) {
1221
- const { loadFactory = true } = options || {
1222
- loadFactory: true
1223
- };
1224
- const remoteEntryExports = await this.getEntry();
1225
- if (!this.inited) {
1226
- const localShareScopeMap = this.host.shareScopeMap;
1227
- const remoteShareScope = this.remoteInfo.shareScope || "default";
1228
- if (!localShareScopeMap[remoteShareScope]) {
1229
- localShareScopeMap[remoteShareScope] = {};
1230
- }
1231
- const shareScope = localShareScopeMap[remoteShareScope];
1232
- const initScope = [];
1233
- const remoteEntryInitOptions = {
1234
- version: this.remoteInfo.version || ""
1235
- };
1236
- Object.defineProperty(remoteEntryInitOptions, "shareScopeMap", {
1237
- value: localShareScopeMap,
1238
- // remoteEntryInitOptions will be traversed and assigned during container init, ,so this attribute is not allowed to be traversed
1239
- enumerable: false
1240
- });
1241
- const initContainerOptions = await this.host.hooks.lifecycle.beforeInitContainer.emit({
1242
- shareScope,
1243
- // @ts-ignore shareScopeMap will be set by Object.defineProperty
1244
- remoteEntryInitOptions,
1245
- initScope,
1246
- remoteInfo: this.remoteInfo,
1247
- origin: this.host
1248
- });
1249
- if (typeof (remoteEntryExports == null ? void 0 : remoteEntryExports.init) === "undefined") {
1250
- error(getShortErrorMsg(RUNTIME_002, runtimeDescMap, {
1251
- remoteName: name,
1252
- remoteEntryUrl: this.remoteInfo.entry,
1253
- remoteEntryKey: this.remoteInfo.entryGlobalName
1254
- }));
1255
- }
1256
- await remoteEntryExports.init(initContainerOptions.shareScope, initContainerOptions.initScope, initContainerOptions.remoteEntryInitOptions);
1257
- await this.host.hooks.lifecycle.initContainer.emit(_extends$1({}, initContainerOptions, {
1258
- id,
1259
- remoteSnapshot,
1260
- remoteEntryExports
1261
- }));
1262
- }
1263
- this.lib = remoteEntryExports;
1264
- this.inited = true;
1265
- let moduleFactory;
1266
- moduleFactory = await this.host.loaderHook.lifecycle.getModuleFactory.emit({
1267
- remoteEntryExports,
1268
- expose,
1269
- moduleInfo: this.remoteInfo
1270
- });
1271
- if (!moduleFactory) {
1272
- moduleFactory = await remoteEntryExports.get(expose);
1273
- }
1274
- assert(moduleFactory, `${getFMId(this.remoteInfo)} remote don't export ${expose}.`);
1275
- const symbolName = processModuleAlias(this.remoteInfo.name, expose);
1276
- const wrapModuleFactory = this.wraperFactory(moduleFactory, symbolName);
1277
- if (!loadFactory) {
1278
- return wrapModuleFactory;
1279
- }
1280
- const exposeContent = await wrapModuleFactory();
1281
- return exposeContent;
1282
- }
1283
- wraperFactory(moduleFactory, id) {
1284
- function defineModuleId(res, id2) {
1285
- if (res && typeof res === "object" && Object.isExtensible(res) && !Object.getOwnPropertyDescriptor(res, Symbol.for("mf_module_id"))) {
1286
- Object.defineProperty(res, Symbol.for("mf_module_id"), {
1287
- value: id2,
1288
- enumerable: false
1289
- });
1290
- }
1291
- }
1292
- if (moduleFactory instanceof Promise) {
1293
- return async () => {
1294
- const res = await moduleFactory();
1295
- defineModuleId(res, id);
1296
- return res;
1297
- };
1298
- } else {
1299
- return () => {
1300
- const res = moduleFactory();
1301
- defineModuleId(res, id);
1302
- return res;
1303
- };
1304
- }
1305
- }
1306
- constructor({ remoteInfo, host }) {
1307
- this.inited = false;
1308
- this.lib = void 0;
1309
- this.remoteInfo = remoteInfo;
1310
- this.host = host;
1311
- }
1312
- };
1313
- class SyncHook {
1314
- on(fn) {
1315
- if (typeof fn === "function") {
1316
- this.listeners.add(fn);
1317
- }
1318
- }
1319
- once(fn) {
1320
- const self = this;
1321
- this.on(function wrapper(...args) {
1322
- self.remove(wrapper);
1323
- return fn.apply(null, args);
1324
- });
1325
- }
1326
- emit(...data) {
1327
- let result;
1328
- if (this.listeners.size > 0) {
1329
- this.listeners.forEach((fn) => {
1330
- result = fn(...data);
1331
- });
1332
- }
1333
- return result;
1334
- }
1335
- remove(fn) {
1336
- this.listeners.delete(fn);
1337
- }
1338
- removeAll() {
1339
- this.listeners.clear();
1340
- }
1341
- constructor(type) {
1342
- this.type = "";
1343
- this.listeners = /* @__PURE__ */ new Set();
1344
- if (type) {
1345
- this.type = type;
1346
- }
1347
- }
1348
- }
1349
- class AsyncHook extends SyncHook {
1350
- emit(...data) {
1351
- let result;
1352
- const ls = Array.from(this.listeners);
1353
- if (ls.length > 0) {
1354
- let i = 0;
1355
- const call = (prev) => {
1356
- if (prev === false) {
1357
- return false;
1358
- } else if (i < ls.length) {
1359
- return Promise.resolve(ls[i++].apply(null, data)).then(call);
1360
- } else {
1361
- return prev;
1362
- }
1363
- };
1364
- result = call();
1365
- }
1366
- return Promise.resolve(result);
1367
- }
1368
- }
1369
- function checkReturnData(originalData, returnedData) {
1370
- if (!isObject(returnedData)) {
1371
- return false;
1372
- }
1373
- if (originalData !== returnedData) {
1374
- for (const key in originalData) {
1375
- if (!(key in returnedData)) {
1376
- return false;
1377
- }
1378
- }
1379
- }
1380
- return true;
1381
- }
1382
- class SyncWaterfallHook extends SyncHook {
1383
- emit(data) {
1384
- if (!isObject(data)) {
1385
- error(`The data for the "${this.type}" hook should be an object.`);
1386
- }
1387
- for (const fn of this.listeners) {
1388
- try {
1389
- const tempData = fn(data);
1390
- if (checkReturnData(data, tempData)) {
1391
- data = tempData;
1392
- } else {
1393
- this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);
1394
- break;
1395
- }
1396
- } catch (e2) {
1397
- warn(e2);
1398
- this.onerror(e2);
1399
- }
1400
- }
1401
- return data;
1402
- }
1403
- constructor(type) {
1404
- super(), this.onerror = error;
1405
- this.type = type;
1406
- }
1407
- }
1408
- class AsyncWaterfallHook extends SyncHook {
1409
- emit(data) {
1410
- if (!isObject(data)) {
1411
- error(`The response data for the "${this.type}" hook must be an object.`);
1412
- }
1413
- const ls = Array.from(this.listeners);
1414
- if (ls.length > 0) {
1415
- let i = 0;
1416
- const processError = (e2) => {
1417
- warn(e2);
1418
- this.onerror(e2);
1419
- return data;
1420
- };
1421
- const call = (prevData) => {
1422
- if (checkReturnData(data, prevData)) {
1423
- data = prevData;
1424
- if (i < ls.length) {
1425
- try {
1426
- return Promise.resolve(ls[i++](data)).then(call, processError);
1427
- } catch (e2) {
1428
- return processError(e2);
1429
- }
1430
- }
1431
- } else {
1432
- this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);
1433
- }
1434
- return data;
1435
- };
1436
- return Promise.resolve(call(data));
1437
- }
1438
- return Promise.resolve(data);
1439
- }
1440
- constructor(type) {
1441
- super(), this.onerror = error;
1442
- this.type = type;
1443
- }
1444
- }
1445
- class PluginSystem {
1446
- applyPlugin(plugin) {
1447
- assert(isPlainObject(plugin), "Plugin configuration is invalid.");
1448
- const pluginName = plugin.name;
1449
- assert(pluginName, "A name must be provided by the plugin.");
1450
- if (!this.registerPlugins[pluginName]) {
1451
- this.registerPlugins[pluginName] = plugin;
1452
- Object.keys(this.lifecycle).forEach((key) => {
1453
- const pluginLife = plugin[key];
1454
- if (pluginLife) {
1455
- this.lifecycle[key].on(pluginLife);
1456
- }
1457
- });
1458
- }
1459
- }
1460
- removePlugin(pluginName) {
1461
- assert(pluginName, "A name is required.");
1462
- const plugin = this.registerPlugins[pluginName];
1463
- assert(plugin, `The plugin "${pluginName}" is not registered.`);
1464
- Object.keys(plugin).forEach((key) => {
1465
- if (key !== "name") {
1466
- this.lifecycle[key].remove(plugin[key]);
1467
- }
1468
- });
1469
- }
1470
- // eslint-disable-next-line @typescript-eslint/no-shadow
1471
- inherit({ lifecycle, registerPlugins }) {
1472
- Object.keys(lifecycle).forEach((hookName) => {
1473
- assert(!this.lifecycle[hookName], `The hook "${hookName}" has a conflict and cannot be inherited.`);
1474
- this.lifecycle[hookName] = lifecycle[hookName];
1475
- });
1476
- Object.keys(registerPlugins).forEach((pluginName) => {
1477
- assert(!this.registerPlugins[pluginName], `The plugin "${pluginName}" has a conflict and cannot be inherited.`);
1478
- this.applyPlugin(registerPlugins[pluginName]);
1479
- });
1480
- }
1481
- constructor(lifecycle) {
1482
- this.registerPlugins = {};
1483
- this.lifecycle = lifecycle;
1484
- this.lifecycleKeys = Object.keys(lifecycle);
1485
- }
1486
- }
1487
- function defaultPreloadArgs(preloadConfig) {
1488
- return _extends$1({
1489
- resourceCategory: "sync",
1490
- share: true,
1491
- depsRemote: true,
1492
- prefetchInterface: false
1493
- }, preloadConfig);
1494
- }
1495
- function formatPreloadArgs(remotes, preloadArgs) {
1496
- return preloadArgs.map((args) => {
1497
- const remoteInfo = matchRemote(remotes, args.nameOrAlias);
1498
- assert(remoteInfo, `Unable to preload ${args.nameOrAlias} as it is not included in ${!remoteInfo && safeToString({
1499
- remoteInfo,
1500
- remotes
1501
- })}`);
1502
- return {
1503
- remote: remoteInfo,
1504
- preloadConfig: defaultPreloadArgs(args)
1505
- };
1506
- });
1507
- }
1508
- function normalizePreloadExposes(exposes) {
1509
- if (!exposes) {
1510
- return [];
1511
- }
1512
- return exposes.map((expose) => {
1513
- if (expose === ".") {
1514
- return expose;
1515
- }
1516
- if (expose.startsWith("./")) {
1517
- return expose.replace("./", "");
1518
- }
1519
- return expose;
1520
- });
1521
- }
1522
- function preloadAssets(remoteInfo, host, assets, useLinkPreload = true) {
1523
- const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
1524
- if (host.options.inBrowser) {
1525
- entryAssets.forEach((asset) => {
1526
- const { moduleInfo } = asset;
1527
- const module = host.moduleCache.get(remoteInfo.name);
1528
- if (module) {
1529
- getRemoteEntry({
1530
- origin: host,
1531
- remoteInfo: moduleInfo,
1532
- remoteEntryExports: module.remoteEntryExports
1533
- });
1534
- } else {
1535
- getRemoteEntry({
1536
- origin: host,
1537
- remoteInfo: moduleInfo,
1538
- remoteEntryExports: void 0
1539
- });
1540
- }
1541
- });
1542
- if (useLinkPreload) {
1543
- const defaultAttrs = {
1544
- rel: "preload",
1545
- as: "style"
1546
- };
1547
- cssAssets.forEach((cssUrl) => {
1548
- const { link: cssEl, needAttach } = createLink({
1549
- url: cssUrl,
1550
- cb: () => {
1551
- },
1552
- attrs: defaultAttrs,
1553
- createLinkHook: (url, attrs) => {
1554
- const res = host.loaderHook.lifecycle.createLink.emit({
1555
- url,
1556
- attrs
1557
- });
1558
- if (res instanceof HTMLLinkElement) {
1559
- return res;
1560
- }
1561
- return;
1562
- }
1563
- });
1564
- needAttach && document.head.appendChild(cssEl);
1565
- });
1566
- } else {
1567
- const defaultAttrs = {
1568
- rel: "stylesheet",
1569
- type: "text/css"
1570
- };
1571
- cssAssets.forEach((cssUrl) => {
1572
- const { link: cssEl, needAttach } = createLink({
1573
- url: cssUrl,
1574
- cb: () => {
1575
- },
1576
- attrs: defaultAttrs,
1577
- createLinkHook: (url, attrs) => {
1578
- const res = host.loaderHook.lifecycle.createLink.emit({
1579
- url,
1580
- attrs
1581
- });
1582
- if (res instanceof HTMLLinkElement) {
1583
- return res;
1584
- }
1585
- return;
1586
- },
1587
- needDeleteLink: false
1588
- });
1589
- needAttach && document.head.appendChild(cssEl);
1590
- });
1591
- }
1592
- if (useLinkPreload) {
1593
- const defaultAttrs = {
1594
- rel: "preload",
1595
- as: "script"
1596
- };
1597
- jsAssetsWithoutEntry.forEach((jsUrl) => {
1598
- const { link: linkEl, needAttach } = createLink({
1599
- url: jsUrl,
1600
- cb: () => {
1601
- },
1602
- attrs: defaultAttrs,
1603
- createLinkHook: (url, attrs) => {
1604
- const res = host.loaderHook.lifecycle.createLink.emit({
1605
- url,
1606
- attrs
1607
- });
1608
- if (res instanceof HTMLLinkElement) {
1609
- return res;
1610
- }
1611
- return;
1612
- }
1613
- });
1614
- needAttach && document.head.appendChild(linkEl);
1615
- });
1616
- } else {
1617
- const defaultAttrs = {
1618
- fetchpriority: "high",
1619
- type: (remoteInfo == null ? void 0 : remoteInfo.type) === "module" ? "module" : "text/javascript"
1620
- };
1621
- jsAssetsWithoutEntry.forEach((jsUrl) => {
1622
- const { script: scriptEl, needAttach } = createScript({
1623
- url: jsUrl,
1624
- cb: () => {
1625
- },
1626
- attrs: defaultAttrs,
1627
- createScriptHook: (url, attrs) => {
1628
- const res = host.loaderHook.lifecycle.createScript.emit({
1629
- url,
1630
- attrs
1631
- });
1632
- if (res instanceof HTMLScriptElement) {
1633
- return res;
1634
- }
1635
- return;
1636
- },
1637
- needDeleteScript: true
1638
- });
1639
- needAttach && document.head.appendChild(scriptEl);
1640
- });
1641
- }
1642
- }
1643
- }
1644
- function assignRemoteInfo(remoteInfo, remoteSnapshot) {
1645
- const remoteEntryInfo = getRemoteEntryInfoFromSnapshot(remoteSnapshot);
1646
- if (!remoteEntryInfo.url) {
1647
- error(`The attribute remoteEntry of ${remoteInfo.name} must not be undefined.`);
1648
- }
1649
- let entryUrl = getResourceUrl(remoteSnapshot, remoteEntryInfo.url);
1650
- if (!isBrowserEnv() && !entryUrl.startsWith("http")) {
1651
- entryUrl = `https:${entryUrl}`;
1652
- }
1653
- remoteInfo.type = remoteEntryInfo.type;
1654
- remoteInfo.entryGlobalName = remoteEntryInfo.globalName;
1655
- remoteInfo.entry = entryUrl;
1656
- remoteInfo.version = remoteSnapshot.version;
1657
- remoteInfo.buildVersion = remoteSnapshot.buildVersion;
1658
- }
1659
- function snapshotPlugin() {
1660
- return {
1661
- name: "snapshot-plugin",
1662
- async afterResolve(args) {
1663
- const { remote, pkgNameOrAlias, expose, origin, remoteInfo } = args;
1664
- if (!isRemoteInfoWithEntry(remote) || !isPureRemoteEntry(remote)) {
1665
- const { remoteSnapshot, globalSnapshot } = await origin.snapshotHandler.loadRemoteSnapshotInfo(remote);
1666
- assignRemoteInfo(remoteInfo, remoteSnapshot);
1667
- const preloadOptions = {
1668
- remote,
1669
- preloadConfig: {
1670
- nameOrAlias: pkgNameOrAlias,
1671
- exposes: [
1672
- expose
1673
- ],
1674
- resourceCategory: "sync",
1675
- share: false,
1676
- depsRemote: false
1677
- }
1678
- };
1679
- const assets = await origin.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({
1680
- origin,
1681
- preloadOptions,
1682
- remoteInfo,
1683
- remote,
1684
- remoteSnapshot,
1685
- globalSnapshot
1686
- });
1687
- if (assets) {
1688
- preloadAssets(remoteInfo, origin, assets, false);
1689
- }
1690
- return _extends$1({}, args, {
1691
- remoteSnapshot
1692
- });
1693
- }
1694
- return args;
1695
- }
1696
- };
1697
- }
1698
- function splitId(id) {
1699
- const splitInfo = id.split(":");
1700
- if (splitInfo.length === 1) {
1701
- return {
1702
- name: splitInfo[0],
1703
- version: void 0
1704
- };
1705
- } else if (splitInfo.length === 2) {
1706
- return {
1707
- name: splitInfo[0],
1708
- version: splitInfo[1]
1709
- };
1710
- } else {
1711
- return {
1712
- name: splitInfo[1],
1713
- version: splitInfo[2]
1714
- };
1715
- }
1716
- }
1717
- function traverseModuleInfo(globalSnapshot, remoteInfo, traverse, isRoot, memo = {}, remoteSnapshot) {
1718
- const id = getFMId(remoteInfo);
1719
- const { value: snapshotValue } = getInfoWithoutType(globalSnapshot, id);
1720
- const effectiveRemoteSnapshot = remoteSnapshot || snapshotValue;
1721
- if (effectiveRemoteSnapshot && !isManifestProvider(effectiveRemoteSnapshot)) {
1722
- traverse(effectiveRemoteSnapshot, remoteInfo, isRoot);
1723
- if (effectiveRemoteSnapshot.remotesInfo) {
1724
- const remoteKeys = Object.keys(effectiveRemoteSnapshot.remotesInfo);
1725
- for (const key of remoteKeys) {
1726
- if (memo[key]) {
1727
- continue;
1728
- }
1729
- memo[key] = true;
1730
- const subRemoteInfo = splitId(key);
1731
- const remoteValue = effectiveRemoteSnapshot.remotesInfo[key];
1732
- traverseModuleInfo(globalSnapshot, {
1733
- name: subRemoteInfo.name,
1734
- version: remoteValue.matchedVersion
1735
- }, traverse, false, memo, void 0);
1736
- }
1737
- }
1738
- }
1739
- }
1740
- function generatePreloadAssets(origin, preloadOptions, remote, globalSnapshot, remoteSnapshot) {
1741
- const cssAssets = [];
1742
- const jsAssets = [];
1743
- const entryAssets = [];
1744
- const loadedSharedJsAssets = /* @__PURE__ */ new Set();
1745
- const loadedSharedCssAssets = /* @__PURE__ */ new Set();
1746
- const { options } = origin;
1747
- const { preloadConfig: rootPreloadConfig } = preloadOptions;
1748
- const { depsRemote } = rootPreloadConfig;
1749
- const memo = {};
1750
- traverseModuleInfo(globalSnapshot, remote, (moduleInfoSnapshot, remoteInfo, isRoot) => {
1751
- let preloadConfig;
1752
- if (isRoot) {
1753
- preloadConfig = rootPreloadConfig;
1754
- } else {
1755
- if (Array.isArray(depsRemote)) {
1756
- const findPreloadConfig = depsRemote.find((remoteConfig) => {
1757
- if (remoteConfig.nameOrAlias === remoteInfo.name || remoteConfig.nameOrAlias === remoteInfo.alias) {
1758
- return true;
1759
- }
1760
- return false;
1761
- });
1762
- if (!findPreloadConfig) {
1763
- return;
1764
- }
1765
- preloadConfig = defaultPreloadArgs(findPreloadConfig);
1766
- } else if (depsRemote === true) {
1767
- preloadConfig = rootPreloadConfig;
1768
- } else {
1769
- return;
1770
- }
1771
- }
1772
- const remoteEntryUrl = getResourceUrl(moduleInfoSnapshot, getRemoteEntryInfoFromSnapshot(moduleInfoSnapshot).url);
1773
- if (remoteEntryUrl) {
1774
- entryAssets.push({
1775
- name: remoteInfo.name,
1776
- moduleInfo: {
1777
- name: remoteInfo.name,
1778
- entry: remoteEntryUrl,
1779
- type: "remoteEntryType" in moduleInfoSnapshot ? moduleInfoSnapshot.remoteEntryType : "global",
1780
- entryGlobalName: "globalName" in moduleInfoSnapshot ? moduleInfoSnapshot.globalName : remoteInfo.name,
1781
- shareScope: "",
1782
- version: "version" in moduleInfoSnapshot ? moduleInfoSnapshot.version : void 0
1783
- },
1784
- url: remoteEntryUrl
1785
- });
1786
- }
1787
- let moduleAssetsInfo = "modules" in moduleInfoSnapshot ? moduleInfoSnapshot.modules : [];
1788
- const normalizedPreloadExposes = normalizePreloadExposes(preloadConfig.exposes);
1789
- if (normalizedPreloadExposes.length && "modules" in moduleInfoSnapshot) {
1790
- var _moduleInfoSnapshot_modules;
1791
- moduleAssetsInfo = moduleInfoSnapshot == null ? void 0 : (_moduleInfoSnapshot_modules = moduleInfoSnapshot.modules) == null ? void 0 : _moduleInfoSnapshot_modules.reduce((assets, moduleAssetInfo) => {
1792
- if ((normalizedPreloadExposes == null ? void 0 : normalizedPreloadExposes.indexOf(moduleAssetInfo.moduleName)) !== -1) {
1793
- assets.push(moduleAssetInfo);
1794
- }
1795
- return assets;
1796
- }, []);
1797
- }
1798
- function handleAssets(assets) {
1799
- const assetsRes = assets.map((asset) => getResourceUrl(moduleInfoSnapshot, asset));
1800
- if (preloadConfig.filter) {
1801
- return assetsRes.filter(preloadConfig.filter);
1802
- }
1803
- return assetsRes;
1804
- }
1805
- if (moduleAssetsInfo) {
1806
- const assetsLength = moduleAssetsInfo.length;
1807
- for (let index = 0; index < assetsLength; index++) {
1808
- const assetsInfo = moduleAssetsInfo[index];
1809
- const exposeFullPath = `${remoteInfo.name}/${assetsInfo.moduleName}`;
1810
- origin.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({
1811
- id: assetsInfo.moduleName === "." ? remoteInfo.name : exposeFullPath,
1812
- name: remoteInfo.name,
1813
- remoteSnapshot: moduleInfoSnapshot,
1814
- preloadConfig,
1815
- remote: remoteInfo,
1816
- origin
1817
- });
1818
- const preloaded = getPreloaded(exposeFullPath);
1819
- if (preloaded) {
1820
- continue;
1821
- }
1822
- if (preloadConfig.resourceCategory === "all") {
1823
- cssAssets.push(...handleAssets(assetsInfo.assets.css.async));
1824
- cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
1825
- jsAssets.push(...handleAssets(assetsInfo.assets.js.async));
1826
- jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
1827
- } else if (preloadConfig.resourceCategory = "sync") {
1828
- cssAssets.push(...handleAssets(assetsInfo.assets.css.sync));
1829
- jsAssets.push(...handleAssets(assetsInfo.assets.js.sync));
1830
- }
1831
- setPreloaded(exposeFullPath);
1832
- }
1833
- }
1834
- }, true, memo, remoteSnapshot);
1835
- if (remoteSnapshot.shared) {
1836
- const collectSharedAssets = (shareInfo, snapshotShared) => {
1837
- const registeredShared = getRegisteredShare(origin.shareScopeMap, snapshotShared.sharedName, shareInfo, origin.sharedHandler.hooks.lifecycle.resolveShare);
1838
- if (registeredShared && typeof registeredShared.lib === "function") {
1839
- snapshotShared.assets.js.sync.forEach((asset) => {
1840
- loadedSharedJsAssets.add(asset);
1841
- });
1842
- snapshotShared.assets.css.sync.forEach((asset) => {
1843
- loadedSharedCssAssets.add(asset);
1844
- });
1845
- }
1846
- };
1847
- remoteSnapshot.shared.forEach((shared) => {
1848
- var _options_shared;
1849
- const shareInfos = (_options_shared = options.shared) == null ? void 0 : _options_shared[shared.sharedName];
1850
- if (!shareInfos) {
1851
- return;
1852
- }
1853
- const sharedOptions = shared.version ? shareInfos.find((s) => s.version === shared.version) : shareInfos;
1854
- if (!sharedOptions) {
1855
- return;
1856
- }
1857
- const arrayShareInfo = arrayOptions(sharedOptions);
1858
- arrayShareInfo.forEach((s) => {
1859
- collectSharedAssets(s, shared);
1860
- });
1861
- });
1862
- }
1863
- const needPreloadJsAssets = jsAssets.filter((asset) => !loadedSharedJsAssets.has(asset));
1864
- const needPreloadCssAssets = cssAssets.filter((asset) => !loadedSharedCssAssets.has(asset));
1865
- return {
1866
- cssAssets: needPreloadCssAssets,
1867
- jsAssetsWithoutEntry: needPreloadJsAssets,
1868
- entryAssets
1869
- };
1870
- }
1871
- const generatePreloadAssetsPlugin = function() {
1872
- return {
1873
- name: "generate-preload-assets-plugin",
1874
- async generatePreloadAssets(args) {
1875
- const { origin, preloadOptions, remoteInfo, remote, globalSnapshot, remoteSnapshot } = args;
1876
- if (isRemoteInfoWithEntry(remote) && isPureRemoteEntry(remote)) {
1877
- return {
1878
- cssAssets: [],
1879
- jsAssetsWithoutEntry: [],
1880
- entryAssets: [
1881
- {
1882
- name: remote.name,
1883
- url: remote.entry,
1884
- moduleInfo: {
1885
- name: remoteInfo.name,
1886
- entry: remote.entry,
1887
- type: remoteInfo.type || "global",
1888
- entryGlobalName: "",
1889
- shareScope: ""
1890
- }
1891
- }
1892
- ]
1893
- };
1894
- }
1895
- assignRemoteInfo(remoteInfo, remoteSnapshot);
1896
- const assets = generatePreloadAssets(origin, preloadOptions, remoteInfo, globalSnapshot, remoteSnapshot);
1897
- return assets;
1898
- }
1899
- };
1900
- };
1901
- function getGlobalRemoteInfo(moduleInfo, origin) {
1902
- const hostGlobalSnapshot = getGlobalSnapshotInfoByModuleInfo({
1903
- name: origin.options.name,
1904
- version: origin.options.version
1905
- });
1906
- const globalRemoteInfo = hostGlobalSnapshot && "remotesInfo" in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, moduleInfo.name).value;
1907
- if (globalRemoteInfo && globalRemoteInfo.matchedVersion) {
1908
- return {
1909
- hostGlobalSnapshot,
1910
- globalSnapshot: getGlobalSnapshot(),
1911
- remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
1912
- name: moduleInfo.name,
1913
- version: globalRemoteInfo.matchedVersion
1914
- })
1915
- };
1916
- }
1917
- return {
1918
- hostGlobalSnapshot: void 0,
1919
- globalSnapshot: getGlobalSnapshot(),
1920
- remoteSnapshot: getGlobalSnapshotInfoByModuleInfo({
1921
- name: moduleInfo.name,
1922
- version: "version" in moduleInfo ? moduleInfo.version : void 0
1923
- })
1924
- };
1925
- }
1926
- class SnapshotHandler {
1927
- async loadSnapshot(moduleInfo) {
1928
- const { options } = this.HostInstance;
1929
- const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
1930
- const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
1931
- options,
1932
- moduleInfo,
1933
- hostGlobalSnapshot,
1934
- remoteSnapshot,
1935
- globalSnapshot
1936
- });
1937
- return {
1938
- remoteSnapshot: globalRemoteSnapshot,
1939
- globalSnapshot: globalSnapshotRes
1940
- };
1941
- }
1942
- // eslint-disable-next-line max-lines-per-function
1943
- async loadRemoteSnapshotInfo(moduleInfo) {
1944
- const { options } = this.HostInstance;
1945
- await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({
1946
- options,
1947
- moduleInfo
1948
- });
1949
- let hostSnapshot = getGlobalSnapshotInfoByModuleInfo({
1950
- name: this.HostInstance.options.name,
1951
- version: this.HostInstance.options.version
1952
- });
1953
- if (!hostSnapshot) {
1954
- hostSnapshot = {
1955
- version: this.HostInstance.options.version || "",
1956
- remoteEntry: "",
1957
- remotesInfo: {}
1958
- };
1959
- addGlobalSnapshot({
1960
- [this.HostInstance.options.name]: hostSnapshot
1961
- });
1962
- }
1963
- if (hostSnapshot && "remotesInfo" in hostSnapshot && !getInfoWithoutType(hostSnapshot.remotesInfo, moduleInfo.name).value) {
1964
- if ("version" in moduleInfo || "entry" in moduleInfo) {
1965
- hostSnapshot.remotesInfo = _extends$1({}, hostSnapshot == null ? void 0 : hostSnapshot.remotesInfo, {
1966
- [moduleInfo.name]: {
1967
- matchedVersion: "version" in moduleInfo ? moduleInfo.version : moduleInfo.entry
1968
- }
1969
- });
1970
- }
1971
- }
1972
- const { hostGlobalSnapshot, remoteSnapshot, globalSnapshot } = this.getGlobalRemoteInfo(moduleInfo);
1973
- const { remoteSnapshot: globalRemoteSnapshot, globalSnapshot: globalSnapshotRes } = await this.hooks.lifecycle.loadSnapshot.emit({
1974
- options,
1975
- moduleInfo,
1976
- hostGlobalSnapshot,
1977
- remoteSnapshot,
1978
- globalSnapshot
1979
- });
1980
- let mSnapshot;
1981
- let gSnapshot;
1982
- if (globalRemoteSnapshot) {
1983
- if (isManifestProvider(globalRemoteSnapshot)) {
1984
- const remoteEntry = isBrowserEnv() ? globalRemoteSnapshot.remoteEntry : globalRemoteSnapshot.ssrRemoteEntry || globalRemoteSnapshot.remoteEntry || "";
1985
- const moduleSnapshot = await this.getManifestJson(remoteEntry, moduleInfo, {});
1986
- const globalSnapshotRes2 = setGlobalSnapshotInfoByModuleInfo(_extends$1({}, moduleInfo, {
1987
- // The global remote may be overridden
1988
- // Therefore, set the snapshot key to the global address of the actual request
1989
- entry: remoteEntry
1990
- }), moduleSnapshot);
1991
- mSnapshot = moduleSnapshot;
1992
- gSnapshot = globalSnapshotRes2;
1993
- } else {
1994
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
1995
- options: this.HostInstance.options,
1996
- moduleInfo,
1997
- remoteSnapshot: globalRemoteSnapshot,
1998
- from: "global"
1999
- });
2000
- mSnapshot = remoteSnapshotRes;
2001
- gSnapshot = globalSnapshotRes;
2002
- }
2003
- } else {
2004
- if (isRemoteInfoWithEntry(moduleInfo)) {
2005
- const moduleSnapshot = await this.getManifestJson(moduleInfo.entry, moduleInfo, {});
2006
- const globalSnapshotRes2 = setGlobalSnapshotInfoByModuleInfo(moduleInfo, moduleSnapshot);
2007
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2008
- options: this.HostInstance.options,
2009
- moduleInfo,
2010
- remoteSnapshot: moduleSnapshot,
2011
- from: "global"
2012
- });
2013
- mSnapshot = remoteSnapshotRes;
2014
- gSnapshot = globalSnapshotRes2;
2015
- } else {
2016
- error(getShortErrorMsg(RUNTIME_007, runtimeDescMap, {
2017
- hostName: moduleInfo.name,
2018
- hostVersion: moduleInfo.version,
2019
- globalSnapshot: JSON.stringify(globalSnapshotRes)
2020
- }));
2021
- }
2022
- }
2023
- await this.hooks.lifecycle.afterLoadSnapshot.emit({
2024
- options,
2025
- moduleInfo,
2026
- remoteSnapshot: mSnapshot
2027
- });
2028
- return {
2029
- remoteSnapshot: mSnapshot,
2030
- globalSnapshot: gSnapshot
2031
- };
2032
- }
2033
- getGlobalRemoteInfo(moduleInfo) {
2034
- return getGlobalRemoteInfo(moduleInfo, this.HostInstance);
2035
- }
2036
- async getManifestJson(manifestUrl, moduleInfo, extraOptions) {
2037
- const getManifest = async () => {
2038
- let manifestJson = this.manifestCache.get(manifestUrl);
2039
- if (manifestJson) {
2040
- return manifestJson;
2041
- }
2042
- try {
2043
- let res = await this.loaderHook.lifecycle.fetch.emit(manifestUrl, {});
2044
- if (!res || !(res instanceof Response)) {
2045
- res = await fetch(manifestUrl, {});
2046
- }
2047
- manifestJson = await res.json();
2048
- assert(manifestJson.metaData && manifestJson.exposes && manifestJson.shared, `${manifestUrl} is not a federation manifest`);
2049
- this.manifestCache.set(manifestUrl, manifestJson);
2050
- return manifestJson;
2051
- } catch (err) {
2052
- delete this.manifestLoading[manifestUrl];
2053
- error(getShortErrorMsg(RUNTIME_003, runtimeDescMap, {
2054
- manifestUrl,
2055
- moduleName: moduleInfo.name
2056
- }, `${err}`));
2057
- }
2058
- };
2059
- const asyncLoadProcess = async () => {
2060
- const manifestJson = await getManifest();
2061
- const remoteSnapshot = generateSnapshotFromManifest(manifestJson, {
2062
- version: manifestUrl
2063
- });
2064
- const { remoteSnapshot: remoteSnapshotRes } = await this.hooks.lifecycle.loadRemoteSnapshot.emit({
2065
- options: this.HostInstance.options,
2066
- moduleInfo,
2067
- manifestJson,
2068
- remoteSnapshot,
2069
- manifestUrl,
2070
- from: "manifest"
2071
- });
2072
- return remoteSnapshotRes;
2073
- };
2074
- if (!this.manifestLoading[manifestUrl]) {
2075
- this.manifestLoading[manifestUrl] = asyncLoadProcess().then((res) => res);
2076
- }
2077
- return this.manifestLoading[manifestUrl];
2078
- }
2079
- constructor(HostInstance) {
2080
- this.loadingHostSnapshot = null;
2081
- this.manifestCache = /* @__PURE__ */ new Map();
2082
- this.hooks = new PluginSystem({
2083
- beforeLoadRemoteSnapshot: new AsyncHook("beforeLoadRemoteSnapshot"),
2084
- loadSnapshot: new AsyncWaterfallHook("loadGlobalSnapshot"),
2085
- loadRemoteSnapshot: new AsyncWaterfallHook("loadRemoteSnapshot"),
2086
- afterLoadSnapshot: new AsyncWaterfallHook("afterLoadSnapshot")
2087
- });
2088
- this.manifestLoading = Global.__FEDERATION__.__MANIFEST_LOADING__;
2089
- this.HostInstance = HostInstance;
2090
- this.loaderHook = HostInstance.loaderHook;
2091
- }
2092
- }
2093
- class SharedHandler {
2094
- // register shared in shareScopeMap
2095
- registerShared(globalOptions, userOptions) {
2096
- const { shareInfos, shared } = formatShareConfigs(globalOptions, userOptions);
2097
- const sharedKeys = Object.keys(shareInfos);
2098
- sharedKeys.forEach((sharedKey) => {
2099
- const sharedVals = shareInfos[sharedKey];
2100
- sharedVals.forEach((sharedVal) => {
2101
- const registeredShared = getRegisteredShare(this.shareScopeMap, sharedKey, sharedVal, this.hooks.lifecycle.resolveShare);
2102
- if (!registeredShared && sharedVal && sharedVal.lib) {
2103
- this.setShared({
2104
- pkgName: sharedKey,
2105
- lib: sharedVal.lib,
2106
- get: sharedVal.get,
2107
- loaded: true,
2108
- shared: sharedVal,
2109
- from: userOptions.name
2110
- });
2111
- }
2112
- });
2113
- });
2114
- return {
2115
- shareInfos,
2116
- shared
2117
- };
2118
- }
2119
- async loadShare(pkgName, extraOptions) {
2120
- const { host } = this;
2121
- const shareInfo = getTargetSharedOptions({
2122
- pkgName,
2123
- extraOptions,
2124
- shareInfos: host.options.shared
2125
- });
2126
- if (shareInfo == null ? void 0 : shareInfo.scope) {
2127
- await Promise.all(shareInfo.scope.map(async (shareScope) => {
2128
- await Promise.all(this.initializeSharing(shareScope, {
2129
- strategy: shareInfo.strategy
2130
- }));
2131
- return;
2132
- }));
2133
- }
2134
- const loadShareRes = await this.hooks.lifecycle.beforeLoadShare.emit({
2135
- pkgName,
2136
- shareInfo,
2137
- shared: host.options.shared,
2138
- origin: host
2139
- });
2140
- const { shareInfo: shareInfoRes } = loadShareRes;
2141
- assert(shareInfoRes, `Cannot find ${pkgName} Share in the ${host.options.name}. Please ensure that the ${pkgName} Share parameters have been injected`);
2142
- const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2143
- const addUseIn = (shared) => {
2144
- if (!shared.useIn) {
2145
- shared.useIn = [];
2146
- }
2147
- addUniqueItem(shared.useIn, host.options.name);
2148
- };
2149
- if (registeredShared && registeredShared.lib) {
2150
- addUseIn(registeredShared);
2151
- return registeredShared.lib;
2152
- } else if (registeredShared && registeredShared.loading && !registeredShared.loaded) {
2153
- const factory = await registeredShared.loading;
2154
- registeredShared.loaded = true;
2155
- if (!registeredShared.lib) {
2156
- registeredShared.lib = factory;
2157
- }
2158
- addUseIn(registeredShared);
2159
- return factory;
2160
- } else if (registeredShared) {
2161
- const asyncLoadProcess = async () => {
2162
- const factory = await registeredShared.get();
2163
- shareInfoRes.lib = factory;
2164
- shareInfoRes.loaded = true;
2165
- addUseIn(shareInfoRes);
2166
- const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2167
- if (gShared) {
2168
- gShared.lib = factory;
2169
- gShared.loaded = true;
2170
- }
2171
- return factory;
2172
- };
2173
- const loading = asyncLoadProcess();
2174
- this.setShared({
2175
- pkgName,
2176
- loaded: false,
2177
- shared: registeredShared,
2178
- from: host.options.name,
2179
- lib: null,
2180
- loading
2181
- });
2182
- return loading;
2183
- } else {
2184
- if (extraOptions == null ? void 0 : extraOptions.customShareInfo) {
2185
- return false;
2186
- }
2187
- const asyncLoadProcess = async () => {
2188
- const factory = await shareInfoRes.get();
2189
- shareInfoRes.lib = factory;
2190
- shareInfoRes.loaded = true;
2191
- addUseIn(shareInfoRes);
2192
- const gShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfoRes, this.hooks.lifecycle.resolveShare);
2193
- if (gShared) {
2194
- gShared.lib = factory;
2195
- gShared.loaded = true;
2196
- }
2197
- return factory;
2198
- };
2199
- const loading = asyncLoadProcess();
2200
- this.setShared({
2201
- pkgName,
2202
- loaded: false,
2203
- shared: shareInfoRes,
2204
- from: host.options.name,
2205
- lib: null,
2206
- loading
2207
- });
2208
- return loading;
2209
- }
2210
- }
2211
- /**
2212
- * This function initializes the sharing sequence (executed only once per share scope).
2213
- * It accepts one argument, the name of the share scope.
2214
- * If the share scope does not exist, it creates one.
2215
- */
2216
- // eslint-disable-next-line @typescript-eslint/member-ordering
2217
- initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
2218
- const { host } = this;
2219
- const from = extraOptions == null ? void 0 : extraOptions.from;
2220
- const strategy = extraOptions == null ? void 0 : extraOptions.strategy;
2221
- let initScope = extraOptions == null ? void 0 : extraOptions.initScope;
2222
- const promises = [];
2223
- if (from !== "build") {
2224
- const { initTokens } = this;
2225
- if (!initScope)
2226
- initScope = [];
2227
- let initToken = initTokens[shareScopeName];
2228
- if (!initToken)
2229
- initToken = initTokens[shareScopeName] = {
2230
- from: this.host.name
2231
- };
2232
- if (initScope.indexOf(initToken) >= 0)
2233
- return promises;
2234
- initScope.push(initToken);
2235
- }
2236
- const shareScope = this.shareScopeMap;
2237
- const hostName = host.options.name;
2238
- if (!shareScope[shareScopeName]) {
2239
- shareScope[shareScopeName] = {};
2240
- }
2241
- const scope = shareScope[shareScopeName];
2242
- const register = (name2, shared) => {
2243
- var _activeVersion_shareConfig;
2244
- const { version, eager } = shared;
2245
- scope[name2] = scope[name2] || {};
2246
- const versions = scope[name2];
2247
- const activeVersion = versions[version];
2248
- const activeVersionEager = Boolean(activeVersion && (activeVersion.eager || ((_activeVersion_shareConfig = activeVersion.shareConfig) == null ? void 0 : _activeVersion_shareConfig.eager)));
2249
- if (!activeVersion || activeVersion.strategy !== "loaded-first" && !activeVersion.loaded && (Boolean(!eager) !== !activeVersionEager ? eager : hostName > activeVersion.from)) {
2250
- versions[version] = shared;
2251
- }
2252
- };
2253
- const initFn = (mod) => mod && mod.init && mod.init(shareScope[shareScopeName], initScope);
2254
- const initRemoteModule = async (key) => {
2255
- const { module } = await host.remoteHandler.getRemoteModuleAndOptions({
2256
- id: key
2257
- });
2258
- if (module.getEntry) {
2259
- let remoteEntryExports;
2260
- try {
2261
- remoteEntryExports = await module.getEntry();
2262
- } catch (error2) {
2263
- remoteEntryExports = await host.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({
2264
- id: key,
2265
- error: error2,
2266
- from: "runtime",
2267
- lifecycle: "beforeLoadShare",
2268
- origin: host
2269
- });
2270
- }
2271
- if (!module.inited) {
2272
- await initFn(remoteEntryExports);
2273
- module.inited = true;
2274
- }
2275
- }
2276
- };
2277
- Object.keys(host.options.shared).forEach((shareName) => {
2278
- const sharedArr = host.options.shared[shareName];
2279
- sharedArr.forEach((shared) => {
2280
- if (shared.scope.includes(shareScopeName)) {
2281
- register(shareName, shared);
2282
- }
2283
- });
2284
- });
2285
- if (host.options.shareStrategy === "version-first" || strategy === "version-first") {
2286
- host.options.remotes.forEach((remote) => {
2287
- if (remote.shareScope === shareScopeName) {
2288
- promises.push(initRemoteModule(remote.name));
2289
- }
2290
- });
2291
- }
2292
- return promises;
2293
- }
2294
- // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
2295
- // 1. If the loaded shared already exists globally, then it will be reused
2296
- // 2. If lib exists in local shared, it will be used directly
2297
- // 3. If the local get returns something other than Promise, then it will be used directly
2298
- loadShareSync(pkgName, extraOptions) {
2299
- const { host } = this;
2300
- const shareInfo = getTargetSharedOptions({
2301
- pkgName,
2302
- extraOptions,
2303
- shareInfos: host.options.shared
2304
- });
2305
- if (shareInfo == null ? void 0 : shareInfo.scope) {
2306
- shareInfo.scope.forEach((shareScope) => {
2307
- this.initializeSharing(shareScope, {
2308
- strategy: shareInfo.strategy
2309
- });
2310
- });
2311
- }
2312
- const registeredShared = getRegisteredShare(this.shareScopeMap, pkgName, shareInfo, this.hooks.lifecycle.resolveShare);
2313
- const addUseIn = (shared) => {
2314
- if (!shared.useIn) {
2315
- shared.useIn = [];
2316
- }
2317
- addUniqueItem(shared.useIn, host.options.name);
2318
- };
2319
- if (registeredShared) {
2320
- if (typeof registeredShared.lib === "function") {
2321
- addUseIn(registeredShared);
2322
- if (!registeredShared.loaded) {
2323
- registeredShared.loaded = true;
2324
- if (registeredShared.from === host.options.name) {
2325
- shareInfo.loaded = true;
2326
- }
2327
- }
2328
- return registeredShared.lib;
2329
- }
2330
- if (typeof registeredShared.get === "function") {
2331
- const module = registeredShared.get();
2332
- if (!(module instanceof Promise)) {
2333
- addUseIn(registeredShared);
2334
- this.setShared({
2335
- pkgName,
2336
- loaded: true,
2337
- from: host.options.name,
2338
- lib: module,
2339
- shared: registeredShared
2340
- });
2341
- return module;
2342
- }
2343
- }
2344
- }
2345
- if (shareInfo.lib) {
2346
- if (!shareInfo.loaded) {
2347
- shareInfo.loaded = true;
2348
- }
2349
- return shareInfo.lib;
2350
- }
2351
- if (shareInfo.get) {
2352
- const module = shareInfo.get();
2353
- if (module instanceof Promise) {
2354
- const errorCode = (extraOptions == null ? void 0 : extraOptions.from) === "build" ? RUNTIME_005 : RUNTIME_006;
2355
- throw new Error(getShortErrorMsg(errorCode, runtimeDescMap, {
2356
- hostName: host.options.name,
2357
- sharedPkgName: pkgName
2358
- }));
2359
- }
2360
- shareInfo.lib = module;
2361
- this.setShared({
2362
- pkgName,
2363
- loaded: true,
2364
- from: host.options.name,
2365
- lib: shareInfo.lib,
2366
- shared: shareInfo
2367
- });
2368
- return shareInfo.lib;
2369
- }
2370
- throw new Error(getShortErrorMsg(RUNTIME_006, runtimeDescMap, {
2371
- hostName: host.options.name,
2372
- sharedPkgName: pkgName
2373
- }));
2374
- }
2375
- initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
2376
- const { host } = this;
2377
- this.shareScopeMap[scopeName] = shareScope;
2378
- this.hooks.lifecycle.initContainerShareScopeMap.emit({
2379
- shareScope,
2380
- options: host.options,
2381
- origin: host,
2382
- scopeName,
2383
- hostShareScopeMap: extraOptions.hostShareScopeMap
2384
- });
2385
- }
2386
- setShared({ pkgName, shared, from, lib, loading, loaded, get }) {
2387
- const { version, scope = "default" } = shared, shareInfo = _object_without_properties_loose(shared, [
2388
- "version",
2389
- "scope"
2390
- ]);
2391
- const scopes = Array.isArray(scope) ? scope : [
2392
- scope
2393
- ];
2394
- scopes.forEach((sc) => {
2395
- if (!this.shareScopeMap[sc]) {
2396
- this.shareScopeMap[sc] = {};
2397
- }
2398
- if (!this.shareScopeMap[sc][pkgName]) {
2399
- this.shareScopeMap[sc][pkgName] = {};
2400
- }
2401
- if (!this.shareScopeMap[sc][pkgName][version]) {
2402
- this.shareScopeMap[sc][pkgName][version] = _extends$1({
2403
- version,
2404
- scope: [
2405
- "default"
2406
- ]
2407
- }, shareInfo, {
2408
- lib,
2409
- loaded,
2410
- loading
2411
- });
2412
- if (get) {
2413
- this.shareScopeMap[sc][pkgName][version].get = get;
2414
- }
2415
- return;
2416
- }
2417
- const registeredShared = this.shareScopeMap[sc][pkgName][version];
2418
- if (loading && !registeredShared.loading) {
2419
- registeredShared.loading = loading;
2420
- }
2421
- });
2422
- }
2423
- _setGlobalShareScopeMap(hostOptions) {
2424
- const globalShareScopeMap = getGlobalShareScope();
2425
- const identifier = hostOptions.id || hostOptions.name;
2426
- if (identifier && !globalShareScopeMap[identifier]) {
2427
- globalShareScopeMap[identifier] = this.shareScopeMap;
2428
- }
2429
- }
2430
- constructor(host) {
2431
- this.hooks = new PluginSystem({
2432
- afterResolve: new AsyncWaterfallHook("afterResolve"),
2433
- beforeLoadShare: new AsyncWaterfallHook("beforeLoadShare"),
2434
- // not used yet
2435
- loadShare: new AsyncHook(),
2436
- resolveShare: new SyncWaterfallHook("resolveShare"),
2437
- // maybe will change, temporarily for internal use only
2438
- initContainerShareScopeMap: new SyncWaterfallHook("initContainerShareScopeMap")
2439
- });
2440
- this.host = host;
2441
- this.shareScopeMap = {};
2442
- this.initTokens = {};
2443
- this._setGlobalShareScopeMap(host.options);
2444
- }
2445
- }
2446
- class RemoteHandler {
2447
- formatAndRegisterRemote(globalOptions, userOptions) {
2448
- const userRemotes = userOptions.remotes || [];
2449
- return userRemotes.reduce((res, remote) => {
2450
- this.registerRemote(remote, res, {
2451
- force: false
2452
- });
2453
- return res;
2454
- }, globalOptions.remotes);
2455
- }
2456
- setIdToRemoteMap(id, remoteMatchInfo) {
2457
- const { remote, expose } = remoteMatchInfo;
2458
- const { name: name2, alias } = remote;
2459
- this.idToRemoteMap[id] = {
2460
- name: remote.name,
2461
- expose
2462
- };
2463
- if (alias && id.startsWith(name2)) {
2464
- const idWithAlias = id.replace(name2, alias);
2465
- this.idToRemoteMap[idWithAlias] = {
2466
- name: remote.name,
2467
- expose
2468
- };
2469
- return;
2470
- }
2471
- if (alias && id.startsWith(alias)) {
2472
- const idWithName = id.replace(alias, name2);
2473
- this.idToRemoteMap[idWithName] = {
2474
- name: remote.name,
2475
- expose
2476
- };
2477
- }
2478
- }
2479
- // eslint-disable-next-line max-lines-per-function
2480
- // eslint-disable-next-line @typescript-eslint/member-ordering
2481
- async loadRemote(id, options) {
2482
- const { host } = this;
2483
- try {
2484
- const { loadFactory = true } = options || {
2485
- loadFactory: true
2486
- };
2487
- const { module, moduleOptions, remoteMatchInfo } = await this.getRemoteModuleAndOptions({
2488
- id
2489
- });
2490
- const { pkgNameOrAlias, remote, expose, id: idRes, remoteSnapshot } = remoteMatchInfo;
2491
- const moduleOrFactory = await module.get(idRes, expose, options, remoteSnapshot);
2492
- const moduleWrapper = await this.hooks.lifecycle.onLoad.emit({
2493
- id: idRes,
2494
- pkgNameOrAlias,
2495
- expose,
2496
- exposeModule: loadFactory ? moduleOrFactory : void 0,
2497
- exposeModuleFactory: loadFactory ? void 0 : moduleOrFactory,
2498
- remote,
2499
- options: moduleOptions,
2500
- moduleInstance: module,
2501
- origin: host
2502
- });
2503
- this.setIdToRemoteMap(id, remoteMatchInfo);
2504
- if (typeof moduleWrapper === "function") {
2505
- return moduleWrapper;
2506
- }
2507
- return moduleOrFactory;
2508
- } catch (error2) {
2509
- const { from = "runtime" } = options || {
2510
- from: "runtime"
2511
- };
2512
- const failOver = await this.hooks.lifecycle.errorLoadRemote.emit({
2513
- id,
2514
- error: error2,
2515
- from,
2516
- lifecycle: "onLoad",
2517
- origin: host
2518
- });
2519
- if (!failOver) {
2520
- throw error2;
2521
- }
2522
- return failOver;
2523
- }
2524
- }
2525
- // eslint-disable-next-line @typescript-eslint/member-ordering
2526
- async preloadRemote(preloadOptions) {
2527
- const { host } = this;
2528
- await this.hooks.lifecycle.beforePreloadRemote.emit({
2529
- preloadOps: preloadOptions,
2530
- options: host.options,
2531
- origin: host
2532
- });
2533
- const preloadOps = formatPreloadArgs(host.options.remotes, preloadOptions);
2534
- await Promise.all(preloadOps.map(async (ops) => {
2535
- const { remote } = ops;
2536
- const remoteInfo = getRemoteInfo(remote);
2537
- const { globalSnapshot, remoteSnapshot } = await host.snapshotHandler.loadRemoteSnapshotInfo(remote);
2538
- const assets = await this.hooks.lifecycle.generatePreloadAssets.emit({
2539
- origin: host,
2540
- preloadOptions: ops,
2541
- remote,
2542
- remoteInfo,
2543
- globalSnapshot,
2544
- remoteSnapshot
2545
- });
2546
- if (!assets) {
2547
- return;
2548
- }
2549
- preloadAssets(remoteInfo, host, assets);
2550
- }));
2551
- }
2552
- registerRemotes(remotes, options) {
2553
- const { host } = this;
2554
- remotes.forEach((remote) => {
2555
- this.registerRemote(remote, host.options.remotes, {
2556
- force: options == null ? void 0 : options.force
2557
- });
2558
- });
2559
- }
2560
- async getRemoteModuleAndOptions(options) {
2561
- const { host } = this;
2562
- const { id } = options;
2563
- let loadRemoteArgs;
2564
- try {
2565
- loadRemoteArgs = await this.hooks.lifecycle.beforeRequest.emit({
2566
- id,
2567
- options: host.options,
2568
- origin: host
2569
- });
2570
- } catch (error2) {
2571
- loadRemoteArgs = await this.hooks.lifecycle.errorLoadRemote.emit({
2572
- id,
2573
- options: host.options,
2574
- origin: host,
2575
- from: "runtime",
2576
- error: error2,
2577
- lifecycle: "beforeRequest"
2578
- });
2579
- if (!loadRemoteArgs) {
2580
- throw error2;
2581
- }
2582
- }
2583
- const { id: idRes } = loadRemoteArgs;
2584
- const remoteSplitInfo = matchRemoteWithNameAndExpose(host.options.remotes, idRes);
2585
- assert(remoteSplitInfo, getShortErrorMsg(RUNTIME_004, runtimeDescMap, {
2586
- hostName: host.options.name,
2587
- requestId: idRes
2588
- }));
2589
- const { remote: rawRemote } = remoteSplitInfo;
2590
- const remoteInfo = getRemoteInfo(rawRemote);
2591
- const matchInfo = await host.sharedHandler.hooks.lifecycle.afterResolve.emit(_extends$1({
2592
- id: idRes
2593
- }, remoteSplitInfo, {
2594
- options: host.options,
2595
- origin: host,
2596
- remoteInfo
2597
- }));
2598
- const { remote, expose } = matchInfo;
2599
- assert(remote && expose, `The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${idRes}.`);
2600
- let module = host.moduleCache.get(remote.name);
2601
- const moduleOptions = {
2602
- host,
2603
- remoteInfo
2604
- };
2605
- if (!module) {
2606
- module = new Module(moduleOptions);
2607
- host.moduleCache.set(remote.name, module);
2608
- }
2609
- return {
2610
- module,
2611
- moduleOptions,
2612
- remoteMatchInfo: matchInfo
2613
- };
2614
- }
2615
- registerRemote(remote, targetRemotes, options) {
2616
- const { host } = this;
2617
- const normalizeRemote = () => {
2618
- if (remote.alias) {
2619
- const findEqual = targetRemotes.find((item) => {
2620
- var _item_alias;
2621
- return remote.alias && (item.name.startsWith(remote.alias) || ((_item_alias = item.alias) == null ? void 0 : _item_alias.startsWith(remote.alias)));
2622
- });
2623
- assert(!findEqual, `The alias ${remote.alias} of remote ${remote.name} is not allowed to be the prefix of ${findEqual && findEqual.name} name or alias`);
2624
- }
2625
- if ("entry" in remote) {
2626
- if (isBrowserEnv() && !remote.entry.startsWith("http")) {
2627
- remote.entry = new URL(remote.entry, window.location.origin).href;
2628
- }
2629
- }
2630
- if (!remote.shareScope) {
2631
- remote.shareScope = DEFAULT_SCOPE;
2632
- }
2633
- if (!remote.type) {
2634
- remote.type = DEFAULT_REMOTE_TYPE;
2635
- }
2636
- };
2637
- this.hooks.lifecycle.beforeRegisterRemote.emit({
2638
- remote,
2639
- origin: host
2640
- });
2641
- const registeredRemote = targetRemotes.find((item) => item.name === remote.name);
2642
- if (!registeredRemote) {
2643
- normalizeRemote();
2644
- targetRemotes.push(remote);
2645
- this.hooks.lifecycle.registerRemote.emit({
2646
- remote,
2647
- origin: host
2648
- });
2649
- } else {
2650
- const messages = [
2651
- `The remote "${remote.name}" is already registered.`,
2652
- (options == null ? void 0 : options.force) ? "Hope you have known that OVERRIDE it may have some unexpected errors" : 'If you want to merge the remote, you can set "force: true".'
2653
- ];
2654
- if (options == null ? void 0 : options.force) {
2655
- this.removeRemote(registeredRemote);
2656
- normalizeRemote();
2657
- targetRemotes.push(remote);
2658
- this.hooks.lifecycle.registerRemote.emit({
2659
- remote,
2660
- origin: host
2661
- });
2662
- }
2663
- warn$1(messages.join(" "));
2664
- }
2665
- }
2666
- removeRemote(remote) {
2667
- try {
2668
- const { host } = this;
2669
- const { name: name2 } = remote;
2670
- const remoteIndex = host.options.remotes.findIndex((item) => item.name === name2);
2671
- if (remoteIndex !== -1) {
2672
- host.options.remotes.splice(remoteIndex, 1);
2673
- }
2674
- const loadedModule = host.moduleCache.get(remote.name);
2675
- if (loadedModule) {
2676
- const remoteInfo = loadedModule.remoteInfo;
2677
- const key = remoteInfo.entryGlobalName;
2678
- if (CurrentGlobal[key]) {
2679
- var _Object_getOwnPropertyDescriptor;
2680
- if ((_Object_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor(CurrentGlobal, key)) == null ? void 0 : _Object_getOwnPropertyDescriptor.configurable) {
2681
- delete CurrentGlobal[key];
2682
- } else {
2683
- CurrentGlobal[key] = void 0;
2684
- }
2685
- }
2686
- const remoteEntryUniqueKey = getRemoteEntryUniqueKey(loadedModule.remoteInfo);
2687
- if (globalLoading[remoteEntryUniqueKey]) {
2688
- delete globalLoading[remoteEntryUniqueKey];
2689
- }
2690
- host.snapshotHandler.manifestCache.delete(remoteInfo.entry);
2691
- let remoteInsId = remoteInfo.buildVersion ? composeKeyWithSeparator(remoteInfo.name, remoteInfo.buildVersion) : remoteInfo.name;
2692
- const remoteInsIndex = CurrentGlobal.__FEDERATION__.__INSTANCES__.findIndex((ins) => {
2693
- if (remoteInfo.buildVersion) {
2694
- return ins.options.id === remoteInsId;
2695
- } else {
2696
- return ins.name === remoteInsId;
2697
- }
2698
- });
2699
- if (remoteInsIndex !== -1) {
2700
- const remoteIns = CurrentGlobal.__FEDERATION__.__INSTANCES__[remoteInsIndex];
2701
- remoteInsId = remoteIns.options.id || remoteInsId;
2702
- const globalShareScopeMap = getGlobalShareScope();
2703
- let isAllSharedNotUsed = true;
2704
- const needDeleteKeys = [];
2705
- Object.keys(globalShareScopeMap).forEach((instId) => {
2706
- const shareScopeMap = globalShareScopeMap[instId];
2707
- shareScopeMap && Object.keys(shareScopeMap).forEach((shareScope) => {
2708
- const shareScopeVal = shareScopeMap[shareScope];
2709
- shareScopeVal && Object.keys(shareScopeVal).forEach((shareName) => {
2710
- const sharedPkgs = shareScopeVal[shareName];
2711
- sharedPkgs && Object.keys(sharedPkgs).forEach((shareVersion) => {
2712
- const shared = sharedPkgs[shareVersion];
2713
- if (shared && typeof shared === "object" && shared.from === remoteInfo.name) {
2714
- if (shared.loaded || shared.loading) {
2715
- shared.useIn = shared.useIn.filter((usedHostName) => usedHostName !== remoteInfo.name);
2716
- if (shared.useIn.length) {
2717
- isAllSharedNotUsed = false;
2718
- } else {
2719
- needDeleteKeys.push([
2720
- instId,
2721
- shareScope,
2722
- shareName,
2723
- shareVersion
2724
- ]);
2725
- }
2726
- } else {
2727
- needDeleteKeys.push([
2728
- instId,
2729
- shareScope,
2730
- shareName,
2731
- shareVersion
2732
- ]);
2733
- }
2734
- }
2735
- });
2736
- });
2737
- });
2738
- });
2739
- if (isAllSharedNotUsed) {
2740
- remoteIns.shareScopeMap = {};
2741
- delete globalShareScopeMap[remoteInsId];
2742
- }
2743
- needDeleteKeys.forEach(([insId, shareScope, shareName, shareVersion]) => {
2744
- var _globalShareScopeMap_insId_shareScope_shareName, _globalShareScopeMap_insId_shareScope, _globalShareScopeMap_insId;
2745
- (_globalShareScopeMap_insId = globalShareScopeMap[insId]) == null ? true : (_globalShareScopeMap_insId_shareScope = _globalShareScopeMap_insId[shareScope]) == null ? true : (_globalShareScopeMap_insId_shareScope_shareName = _globalShareScopeMap_insId_shareScope[shareName]) == null ? true : delete _globalShareScopeMap_insId_shareScope_shareName[shareVersion];
2746
- });
2747
- CurrentGlobal.__FEDERATION__.__INSTANCES__.splice(remoteInsIndex, 1);
2748
- }
2749
- const { hostGlobalSnapshot } = getGlobalRemoteInfo(remote, host);
2750
- if (hostGlobalSnapshot) {
2751
- const remoteKey = hostGlobalSnapshot && "remotesInfo" in hostGlobalSnapshot && hostGlobalSnapshot.remotesInfo && getInfoWithoutType(hostGlobalSnapshot.remotesInfo, remote.name).key;
2752
- if (remoteKey) {
2753
- delete hostGlobalSnapshot.remotesInfo[remoteKey];
2754
- if (
2755
- //eslint-disable-next-line no-extra-boolean-cast
2756
- Boolean(Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey])
2757
- ) {
2758
- delete Global.__FEDERATION__.__MANIFEST_LOADING__[remoteKey];
2759
- }
2760
- }
2761
- }
2762
- host.moduleCache.delete(remote.name);
2763
- }
2764
- } catch (err) {
2765
- logger.log("removeRemote fail: ", err);
2766
- }
2767
- }
2768
- constructor(host) {
2769
- this.hooks = new PluginSystem({
2770
- beforeRegisterRemote: new SyncWaterfallHook("beforeRegisterRemote"),
2771
- registerRemote: new SyncWaterfallHook("registerRemote"),
2772
- beforeRequest: new AsyncWaterfallHook("beforeRequest"),
2773
- onLoad: new AsyncHook("onLoad"),
2774
- handlePreloadModule: new SyncHook("handlePreloadModule"),
2775
- errorLoadRemote: new AsyncHook("errorLoadRemote"),
2776
- beforePreloadRemote: new AsyncHook("beforePreloadRemote"),
2777
- generatePreloadAssets: new AsyncHook("generatePreloadAssets"),
2778
- // not used yet
2779
- afterPreloadRemote: new AsyncHook(),
2780
- loadEntry: new AsyncHook()
2781
- });
2782
- this.host = host;
2783
- this.idToRemoteMap = {};
2784
- }
2785
- }
2786
- class FederationHost {
2787
- initOptions(userOptions) {
2788
- this.registerPlugins(userOptions.plugins);
2789
- const options = this.formatOptions(this.options, userOptions);
2790
- this.options = options;
2791
- return options;
2792
- }
2793
- async loadShare(pkgName, extraOptions) {
2794
- return this.sharedHandler.loadShare(pkgName, extraOptions);
2795
- }
2796
- // The lib function will only be available if the shared set by eager or runtime init is set or the shared is successfully loaded.
2797
- // 1. If the loaded shared already exists globally, then it will be reused
2798
- // 2. If lib exists in local shared, it will be used directly
2799
- // 3. If the local get returns something other than Promise, then it will be used directly
2800
- loadShareSync(pkgName, extraOptions) {
2801
- return this.sharedHandler.loadShareSync(pkgName, extraOptions);
2802
- }
2803
- initializeSharing(shareScopeName = DEFAULT_SCOPE, extraOptions) {
2804
- return this.sharedHandler.initializeSharing(shareScopeName, extraOptions);
2805
- }
2806
- initRawContainer(name2, url, container) {
2807
- const remoteInfo = getRemoteInfo({
2808
- name: name2,
2809
- entry: url
2810
- });
2811
- const module = new Module({
2812
- host: this,
2813
- remoteInfo
2814
- });
2815
- module.remoteEntryExports = container;
2816
- this.moduleCache.set(name2, module);
2817
- return module;
2818
- }
2819
- // eslint-disable-next-line max-lines-per-function
2820
- // eslint-disable-next-line @typescript-eslint/member-ordering
2821
- async loadRemote(id, options) {
2822
- return this.remoteHandler.loadRemote(id, options);
2823
- }
2824
- // eslint-disable-next-line @typescript-eslint/member-ordering
2825
- async preloadRemote(preloadOptions) {
2826
- return this.remoteHandler.preloadRemote(preloadOptions);
2827
- }
2828
- initShareScopeMap(scopeName, shareScope, extraOptions = {}) {
2829
- this.sharedHandler.initShareScopeMap(scopeName, shareScope, extraOptions);
2830
- }
2831
- formatOptions(globalOptions, userOptions) {
2832
- const { shared } = formatShareConfigs(globalOptions, userOptions);
2833
- const { userOptions: userOptionsRes, options: globalOptionsRes } = this.hooks.lifecycle.beforeInit.emit({
2834
- origin: this,
2835
- userOptions,
2836
- options: globalOptions,
2837
- shareInfo: shared
2838
- });
2839
- const remotes = this.remoteHandler.formatAndRegisterRemote(globalOptionsRes, userOptionsRes);
2840
- const { shared: handledShared } = this.sharedHandler.registerShared(globalOptionsRes, userOptionsRes);
2841
- const plugins = [
2842
- ...globalOptionsRes.plugins
2843
- ];
2844
- if (userOptionsRes.plugins) {
2845
- userOptionsRes.plugins.forEach((plugin) => {
2846
- if (!plugins.includes(plugin)) {
2847
- plugins.push(plugin);
2848
- }
2849
- });
2850
- }
2851
- const optionsRes = _extends$1({}, globalOptions, userOptions, {
2852
- plugins,
2853
- remotes,
2854
- shared: handledShared
2855
- });
2856
- this.hooks.lifecycle.init.emit({
2857
- origin: this,
2858
- options: optionsRes
2859
- });
2860
- return optionsRes;
2861
- }
2862
- registerPlugins(plugins) {
2863
- const pluginRes = registerPlugins$1(plugins, [
2864
- this.hooks,
2865
- this.remoteHandler.hooks,
2866
- this.sharedHandler.hooks,
2867
- this.snapshotHandler.hooks,
2868
- this.loaderHook,
2869
- this.bridgeHook
2870
- ]);
2871
- this.options.plugins = this.options.plugins.reduce((res, plugin) => {
2872
- if (!plugin)
2873
- return res;
2874
- if (res && !res.find((item) => item.name === plugin.name)) {
2875
- res.push(plugin);
2876
- }
2877
- return res;
2878
- }, pluginRes || []);
2879
- }
2880
- registerRemotes(remotes, options) {
2881
- return this.remoteHandler.registerRemotes(remotes, options);
2882
- }
2883
- constructor(userOptions) {
2884
- this.hooks = new PluginSystem({
2885
- beforeInit: new SyncWaterfallHook("beforeInit"),
2886
- init: new SyncHook(),
2887
- // maybe will change, temporarily for internal use only
2888
- beforeInitContainer: new AsyncWaterfallHook("beforeInitContainer"),
2889
- // maybe will change, temporarily for internal use only
2890
- initContainer: new AsyncWaterfallHook("initContainer")
2891
- });
2892
- this.version = "0.7.3";
2893
- this.moduleCache = /* @__PURE__ */ new Map();
2894
- this.loaderHook = new PluginSystem({
2895
- // FIXME: may not be suitable , not open to the public yet
2896
- getModuleInfo: new SyncHook(),
2897
- createScript: new SyncHook(),
2898
- createLink: new SyncHook(),
2899
- // only work for manifest , so not open to the public yet
2900
- fetch: new AsyncHook(),
2901
- getModuleFactory: new AsyncHook()
2902
- });
2903
- this.bridgeHook = new PluginSystem({
2904
- beforeBridgeRender: new SyncHook(),
2905
- afterBridgeRender: new SyncHook(),
2906
- beforeBridgeDestroy: new SyncHook(),
2907
- afterBridgeDestroy: new SyncHook()
2908
- });
2909
- const defaultOptions = {
2910
- id: getBuilderId(),
2911
- name: userOptions.name,
2912
- plugins: [
2913
- snapshotPlugin(),
2914
- generatePreloadAssetsPlugin()
2915
- ],
2916
- remotes: [],
2917
- shared: {},
2918
- inBrowser: isBrowserEnv()
2919
- };
2920
- this.name = userOptions.name;
2921
- this.options = defaultOptions;
2922
- this.snapshotHandler = new SnapshotHandler(this);
2923
- this.sharedHandler = new SharedHandler(this);
2924
- this.remoteHandler = new RemoteHandler(this);
2925
- this.shareScopeMap = this.sharedHandler.shareScopeMap;
2926
- this.registerPlugins([
2927
- ...defaultOptions.plugins,
2928
- ...userOptions.plugins || []
2929
- ]);
2930
- this.options = this.formatOptions(defaultOptions, userOptions);
2931
- }
2932
- }
2933
- let FederationInstance = null;
2934
- function getInstance() {
2935
- return FederationInstance;
2936
- }
2937
- setGlobalFederationConstructor(FederationHost);
2938
106
  const RemoteAppWrapper = forwardRef(function(props, ref) {
2939
107
  const RemoteApp2 = () => {
2940
108
  LoggerInstance.log(`RemoteAppWrapper RemoteApp props >>>`, { props });
@@ -2955,6 +123,7 @@ const RemoteAppWrapper = forwardRef(function(props, ref) {
2955
123
  LoggerInstance.log(`RemoteAppWrapper hostInstance >>>`, hostInstance);
2956
124
  useEffect(() => {
2957
125
  const renderTimeout = setTimeout(() => {
126
+ var _a, _b, _c, _d, _e, _f;
2958
127
  const providerReturn = providerInfo();
2959
128
  providerInfoRef.current = providerReturn;
2960
129
  let renderProps = {
@@ -2974,23 +143,44 @@ const RemoteAppWrapper = forwardRef(function(props, ref) {
2974
143
  `createRemoteComponent LazyComponent hostInstance >>>`,
2975
144
  hostInstance
2976
145
  );
2977
- const beforeBridgeRenderRes = {};
146
+ const beforeBridgeRenderRes = ((_c = (_b = (_a = hostInstance == null ? void 0 : hostInstance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeRender) == null ? void 0 : _c.emit(
147
+ renderProps
148
+ )) || {};
2978
149
  renderProps = { ...renderProps, ...beforeBridgeRenderRes.extraProps };
2979
150
  providerReturn.render(renderProps);
151
+ (_f = (_e = (_d = hostInstance == null ? void 0 : hostInstance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeRender) == null ? void 0 : _f.emit(
152
+ renderProps
153
+ );
2980
154
  });
2981
155
  return () => {
2982
156
  clearTimeout(renderTimeout);
2983
157
  setTimeout(() => {
2984
- var _a, _b;
158
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2985
159
  if ((_a = providerInfoRef.current) == null ? void 0 : _a.destroy) {
2986
160
  LoggerInstance.log(
2987
161
  `createRemoteComponent LazyComponent destroy >>>`,
2988
162
  { moduleName, basename, dom: renderDom.current }
2989
163
  );
2990
- (_b = providerInfoRef.current) == null ? void 0 : _b.destroy({
164
+ (_d = (_c = (_b = hostInstance == null ? void 0 : hostInstance.bridgeHook) == null ? void 0 : _b.lifecycle) == null ? void 0 : _c.beforeBridgeDestroy) == null ? void 0 : _d.emit({
165
+ moduleName,
166
+ dom: renderDom.current,
167
+ basename,
168
+ memoryRoute,
169
+ fallback,
170
+ ...resProps
171
+ });
172
+ (_e = providerInfoRef.current) == null ? void 0 : _e.destroy({
2991
173
  moduleName,
2992
174
  dom: renderDom.current
2993
175
  });
176
+ (_h = (_g = (_f = hostInstance == null ? void 0 : hostInstance.bridgeHook) == null ? void 0 : _f.lifecycle) == null ? void 0 : _g.afterBridgeDestroy) == null ? void 0 : _h.emit({
177
+ moduleName,
178
+ dom: renderDom.current,
179
+ basename,
180
+ memoryRoute,
181
+ fallback,
182
+ ...resProps
183
+ });
2994
184
  }
2995
185
  });
2996
186
  };
@@ -3117,8 +307,8 @@ function createLazyRemoteComponent(info) {
3117
307
  )}`
3118
308
  );
3119
309
  }
3120
- } catch (error2) {
3121
- throw error2;
310
+ } catch (error) {
311
+ throw error;
3122
312
  }
3123
313
  });
3124
314
  }
@@ -3173,6 +363,7 @@ function createBridgeComponent(bridgeInfo) {
3173
363
  };
3174
364
  return {
3175
365
  async render(info) {
366
+ var _a, _b, _c, _d, _e, _f;
3176
367
  LoggerInstance.log(`createBridgeComponent render Info`, info);
3177
368
  const {
3178
369
  moduleName,
@@ -3182,7 +373,7 @@ function createBridgeComponent(bridgeInfo) {
3182
373
  fallback,
3183
374
  ...propsInfo
3184
375
  } = info;
3185
- const beforeBridgeRenderRes = {};
376
+ const beforeBridgeRenderRes = ((_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeRender) == null ? void 0 : _c.emit(info)) || {};
3186
377
  const rootComponentWithErrorBoundary = (
3187
378
  // set ErrorBoundary for RawComponent rendering error, usually caused by user app rendering error
3188
379
  /* @__PURE__ */ React.createElement(ErrorBoundary, { FallbackComponent: fallback }, /* @__PURE__ */ React.createElement(
@@ -3211,11 +402,14 @@ function createBridgeComponent(bridgeInfo) {
3211
402
  const renderFn = (bridgeInfo == null ? void 0 : bridgeInfo.render) || ReactDOM.render;
3212
403
  renderFn == null ? void 0 : renderFn(rootComponentWithErrorBoundary, info.dom);
3213
404
  }
405
+ ((_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeRender) == null ? void 0 : _f.emit(info)) || {};
3214
406
  },
3215
407
  async destroy(info) {
408
+ var _a, _b, _c, _d, _e, _f;
3216
409
  LoggerInstance.log(`createBridgeComponent destroy Info`, {
3217
410
  dom: info.dom
3218
411
  });
412
+ (_c = (_b = (_a = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _a.lifecycle) == null ? void 0 : _b.beforeBridgeDestroy) == null ? void 0 : _c.emit(info);
3219
413
  if (atLeastReact18(React)) {
3220
414
  const root = rootMap.get(info.dom);
3221
415
  root == null ? void 0 : root.unmount();
@@ -3223,6 +417,7 @@ function createBridgeComponent(bridgeInfo) {
3223
417
  } else {
3224
418
  ReactDOM.unmountComponentAtNode(info.dom);
3225
419
  }
420
+ (_f = (_e = (_d = instance == null ? void 0 : instance.bridgeHook) == null ? void 0 : _d.lifecycle) == null ? void 0 : _e.afterBridgeDestroy) == null ? void 0 : _f.emit(info);
3226
421
  },
3227
422
  rawComponent: bridgeInfo.rootComponent,
3228
423
  __BRIDGE_FN__: (_args) => {