@module-federation/bridge-react 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/base.cjs.js +4 -4
  3. package/dist/base.es.js +5 -5
  4. package/dist/{bridge-base-CIgEZf8X.mjs → bridge-base-B7EKIpJ7.mjs} +1 -1
  5. package/dist/{bridge-base-1Grpgans.js → bridge-base-BLno0Ytr.js} +1 -1
  6. package/dist/{createHelpers-C9qvVTND.mjs → createHelpers-4fOvXdyD.mjs} +2 -2
  7. package/dist/{createHelpers-2UBGLdcA.js → createHelpers-DVr-JIwn.js} +2 -2
  8. package/dist/data-fetch-server-middleware.cjs.js +4 -4
  9. package/dist/data-fetch-server-middleware.es.js +2 -2
  10. package/dist/data-fetch-utils.cjs.js +2 -2
  11. package/dist/data-fetch-utils.es.js +4 -4
  12. package/dist/{index-DyQNwY2M.mjs → index-CafhxM-l.mjs} +1 -1
  13. package/dist/{index-DRSBaSu3.js → index-Cmp3JjCw.js} +2 -2
  14. package/dist/index.cjs.js +5 -5
  15. package/dist/index.es.js +6 -6
  16. package/dist/{lazy-load-component-plugin-9KkACgWW.js → lazy-load-component-plugin-B0jL1C-H.js} +2 -2
  17. package/dist/{lazy-load-component-plugin-GtenP5tG.mjs → lazy-load-component-plugin-CXfIn_mH.mjs} +2 -2
  18. package/dist/lazy-load-component-plugin.cjs.js +2 -2
  19. package/dist/lazy-load-component-plugin.es.js +2 -2
  20. package/dist/lazy-utils.cjs.js +2 -2
  21. package/dist/lazy-utils.es.js +7 -7
  22. package/dist/logger-BWq2gts-.mjs +138 -0
  23. package/dist/logger-DT66A_Pv.js +137 -0
  24. package/dist/prefetch-CmkSilpl.mjs +861 -0
  25. package/dist/prefetch-CvCACzJH.js +860 -0
  26. package/dist/router-v5.cjs.js +1 -1
  27. package/dist/router-v5.es.js +1 -1
  28. package/dist/router-v6.cjs.js +1 -1
  29. package/dist/router-v6.es.js +1 -1
  30. package/dist/router-v7.cjs.js +1 -1
  31. package/dist/router-v7.es.js +1 -1
  32. package/dist/router.cjs.js +1 -1
  33. package/dist/router.es.js +1 -1
  34. package/dist/{utils-tM9yE73c.js → utils-BelRTG4G.js} +18 -4
  35. package/dist/{utils--qTri1IN.mjs → utils-DYUQLv_v.mjs} +21 -7
  36. package/dist/v18.cjs.js +1 -1
  37. package/dist/v18.es.js +1 -1
  38. package/dist/v19.cjs.js +1 -1
  39. package/dist/v19.es.js +1 -1
  40. package/package.json +6 -6
  41. package/dist/index.esm-BWaKho-8.js +0 -491
  42. package/dist/index.esm-CPwSeCvw.mjs +0 -492
  43. package/dist/prefetch-BvksZRMd.js +0 -1390
  44. package/dist/prefetch-Cj92jrl5.mjs +0 -1391
@@ -0,0 +1,861 @@
1
+ import { A as warn, x as DATA_FETCH_FUNCTION, F as FS_HREF, l as logger, e as getDataFetchMap, i as initDataFetchMap, n as getDataFetchItem, M as MF_DATA_FETCH_STATUS, p as MF_DATA_FETCH_TYPE, B as DOWNGRADE_KEY, G as callAllDowngrade, H as callDowngrade, I as getDowngradeTag, J as composeKeyWithSeparator, k as getDataFetchInfo, m as getDataFetchMapKey } from "./utils-DYUQLv_v.mjs";
2
+ import { i as isBrowserEnv } from "./logger-BWq2gts-.mjs";
3
+ async function safeWrapper(callback, disableWarn) {
4
+ try {
5
+ return await callback();
6
+ } catch (e) {
7
+ warn(e);
8
+ return;
9
+ }
10
+ }
11
+ function isStaticResourcesEqual(url1, url2) {
12
+ const REG_EXP = /^(https?:)?\/\//i;
13
+ return url1.replace(REG_EXP, "").replace(/\/$/, "") === url2.replace(REG_EXP, "").replace(/\/$/, "");
14
+ }
15
+ function createScript(info) {
16
+ let script = null;
17
+ let needAttach = true;
18
+ let timeout = 2e4;
19
+ let timeoutId;
20
+ const scripts = document.getElementsByTagName("script");
21
+ for (let i = 0; i < scripts.length; i++) {
22
+ const s = scripts[i];
23
+ const scriptSrc = s.getAttribute("src");
24
+ if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {
25
+ script = s;
26
+ needAttach = false;
27
+ break;
28
+ }
29
+ }
30
+ if (!script) {
31
+ const attrs = info.attrs;
32
+ script = document.createElement("script");
33
+ script.type = (attrs == null ? void 0 : attrs["type"]) === "module" ? "module" : "text/javascript";
34
+ let createScriptRes = void 0;
35
+ if (info.createScriptHook) {
36
+ createScriptRes = info.createScriptHook(info.url, info.attrs);
37
+ if (createScriptRes instanceof HTMLScriptElement) script = createScriptRes;
38
+ else if (typeof createScriptRes === "object") {
39
+ if ("script" in createScriptRes && createScriptRes.script) script = createScriptRes.script;
40
+ if ("timeout" in createScriptRes && createScriptRes.timeout) timeout = createScriptRes.timeout;
41
+ }
42
+ }
43
+ if (!script.src) script.src = info.url;
44
+ if (attrs && !createScriptRes) Object.keys(attrs).forEach((name) => {
45
+ if (script) {
46
+ if (name === "async" || name === "defer") script[name] = attrs[name];
47
+ else if (!script.getAttribute(name)) script.setAttribute(name, attrs[name]);
48
+ }
49
+ });
50
+ }
51
+ const onScriptComplete = async (prev, event) => {
52
+ clearTimeout(timeoutId);
53
+ const onScriptCompleteCallback = () => {
54
+ if ((event == null ? void 0 : event.type) === "error") (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
55
+ else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
56
+ };
57
+ if (script) {
58
+ script.onerror = null;
59
+ script.onload = null;
60
+ safeWrapper(() => {
61
+ const { needDeleteScript = true } = info;
62
+ if (needDeleteScript) (script == null ? void 0 : script.parentNode) && script.parentNode.removeChild(script);
63
+ });
64
+ if (prev && typeof prev === "function") {
65
+ const result = prev(event);
66
+ if (result instanceof Promise) {
67
+ const res = await result;
68
+ onScriptCompleteCallback();
69
+ return res;
70
+ }
71
+ onScriptCompleteCallback();
72
+ return result;
73
+ }
74
+ }
75
+ onScriptCompleteCallback();
76
+ };
77
+ script.onerror = onScriptComplete.bind(null, script.onerror);
78
+ script.onload = onScriptComplete.bind(null, script.onload);
79
+ timeoutId = setTimeout(() => {
80
+ onScriptComplete(null, /* @__PURE__ */ new Error(`Remote script "${info.url}" time-outed.`));
81
+ }, timeout);
82
+ return {
83
+ script,
84
+ needAttach
85
+ };
86
+ }
87
+ function createLink(info) {
88
+ let link = null;
89
+ let needAttach = true;
90
+ const links = document.getElementsByTagName("link");
91
+ for (let i = 0; i < links.length; i++) {
92
+ const l = links[i];
93
+ const linkHref = l.getAttribute("href");
94
+ const linkRel = l.getAttribute("rel");
95
+ if (linkHref && isStaticResourcesEqual(linkHref, info.url) && linkRel === info.attrs["rel"]) {
96
+ link = l;
97
+ needAttach = false;
98
+ break;
99
+ }
100
+ }
101
+ if (!link) {
102
+ link = document.createElement("link");
103
+ link.setAttribute("href", info.url);
104
+ let createLinkRes = void 0;
105
+ const attrs = info.attrs;
106
+ if (info.createLinkHook) {
107
+ createLinkRes = info.createLinkHook(info.url, attrs);
108
+ if (createLinkRes instanceof HTMLLinkElement) link = createLinkRes;
109
+ }
110
+ if (attrs && !createLinkRes) Object.keys(attrs).forEach((name) => {
111
+ if (link && !link.getAttribute(name)) link.setAttribute(name, attrs[name]);
112
+ });
113
+ }
114
+ const onLinkComplete = (prev, event) => {
115
+ const onLinkCompleteCallback = () => {
116
+ if ((event == null ? void 0 : event.type) === "error") (info == null ? void 0 : info.onErrorCallback) && (info == null ? void 0 : info.onErrorCallback(event));
117
+ else (info == null ? void 0 : info.cb) && (info == null ? void 0 : info.cb());
118
+ };
119
+ if (link) {
120
+ link.onerror = null;
121
+ link.onload = null;
122
+ safeWrapper(() => {
123
+ const { needDeleteLink = true } = info;
124
+ if (needDeleteLink) (link == null ? void 0 : link.parentNode) && link.parentNode.removeChild(link);
125
+ });
126
+ if (prev) {
127
+ const res = prev(event);
128
+ onLinkCompleteCallback();
129
+ return res;
130
+ }
131
+ }
132
+ onLinkCompleteCallback();
133
+ };
134
+ link.onerror = onLinkComplete.bind(null, link.onerror);
135
+ link.onload = onLinkComplete.bind(null, link.onload);
136
+ return {
137
+ link,
138
+ needAttach
139
+ };
140
+ }
141
+ function loadScript(url, info) {
142
+ const { attrs = {}, createScriptHook } = info;
143
+ return new Promise((resolve, reject) => {
144
+ const { script, needAttach } = createScript({
145
+ url,
146
+ cb: resolve,
147
+ onErrorCallback: reject,
148
+ attrs: {
149
+ fetchpriority: "high",
150
+ ...attrs
151
+ },
152
+ createScriptHook,
153
+ needDeleteScript: true
154
+ });
155
+ needAttach && document.head.appendChild(script);
156
+ });
157
+ }
158
+ const sdkImportCache = /* @__PURE__ */ new Map();
159
+ function importNodeModule(name) {
160
+ if (!name) throw new Error("import specifier is required");
161
+ if (sdkImportCache.has(name)) return sdkImportCache.get(name);
162
+ const promise = new Function("name", `return import(name)`)(name).then((res) => res).catch((error2) => {
163
+ console.error(`Error importing module ${name}:`, error2);
164
+ sdkImportCache.delete(name);
165
+ throw error2;
166
+ });
167
+ sdkImportCache.set(name, promise);
168
+ return promise;
169
+ }
170
+ const loadNodeFetch = async () => {
171
+ const fetchModule = await importNodeModule("node-fetch");
172
+ return fetchModule.default || fetchModule;
173
+ };
174
+ const lazyLoaderHookFetch = async (input, init, loaderHook) => {
175
+ const hook = (url, init2) => {
176
+ return loaderHook.lifecycle.fetch.emit(url, init2);
177
+ };
178
+ const res = await hook(input, init || {});
179
+ if (!res || !(res instanceof Response)) return (typeof fetch === "undefined" ? await loadNodeFetch() : fetch)(input, init || {});
180
+ return res;
181
+ };
182
+ const createScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, cb, attrs, loaderHook) => {
183
+ if (loaderHook == null ? void 0 : loaderHook.createScriptHook) {
184
+ const hookResult = loaderHook.createScriptHook(url);
185
+ if (hookResult && typeof hookResult === "object" && "url" in hookResult) url = hookResult.url;
186
+ }
187
+ let urlObj;
188
+ try {
189
+ urlObj = new URL(url);
190
+ } catch (e) {
191
+ console.error("Error constructing URL:", e);
192
+ cb(/* @__PURE__ */ new Error(`Invalid URL: ${e}`));
193
+ return;
194
+ }
195
+ const getFetch = async () => {
196
+ if (loaderHook == null ? void 0 : loaderHook.fetch) return (input, init) => lazyLoaderHookFetch(input, init, loaderHook);
197
+ return typeof fetch === "undefined" ? loadNodeFetch() : fetch;
198
+ };
199
+ const handleScriptFetch = async (f, urlObj2) => {
200
+ var _a;
201
+ try {
202
+ const res = await f(urlObj2.href);
203
+ const data = await res.text();
204
+ const [path, vm] = await Promise.all([importNodeModule("path"), importNodeModule("vm")]);
205
+ const scriptContext = {
206
+ exports: {},
207
+ module: { exports: {} }
208
+ };
209
+ const urlDirname = urlObj2.pathname.split("/").slice(0, -1).join("/");
210
+ const filename = path.basename(urlObj2.pathname);
211
+ const script = new vm.Script(`(function(exports, module, require, __dirname, __filename) {${data}
212
+ })`, {
213
+ filename,
214
+ importModuleDynamically: ((_a = vm.constants) == null ? void 0 : _a.USE_MAIN_CONTEXT_DEFAULT_LOADER) ?? importNodeModule
215
+ });
216
+ let requireFn;
217
+ requireFn = (await importNodeModule("node:module")).createRequire(urlObj2.protocol === "file:" || urlObj2.protocol === "node:" ? urlObj2.href : path.join(process.cwd(), "__mf_require_base__.js"));
218
+ script.runInThisContext()(scriptContext.exports, scriptContext.module, requireFn, urlDirname, filename);
219
+ const exportedInterface = scriptContext.module.exports || scriptContext.exports;
220
+ if (attrs && exportedInterface && attrs["globalName"]) {
221
+ cb(void 0, exportedInterface[attrs["globalName"]] || exportedInterface);
222
+ return;
223
+ }
224
+ cb(void 0, exportedInterface);
225
+ } catch (e) {
226
+ cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
227
+ }
228
+ };
229
+ getFetch().then(async (f) => {
230
+ if ((attrs == null ? void 0 : attrs["type"]) === "esm" || (attrs == null ? void 0 : attrs["type"]) === "module") return loadModule(urlObj.href, {
231
+ fetch: f,
232
+ vm: await importNodeModule("vm")
233
+ }).then(async (module) => {
234
+ await module.evaluate();
235
+ cb(void 0, module.namespace);
236
+ }).catch((e) => {
237
+ cb(e instanceof Error ? e : /* @__PURE__ */ new Error(`Script execution error: ${e}`));
238
+ });
239
+ handleScriptFetch(f, urlObj);
240
+ }).catch((err) => {
241
+ cb(err);
242
+ });
243
+ } : (url, cb, attrs, loaderHook) => {
244
+ cb(/* @__PURE__ */ new Error("createScriptNode is disabled in non-Node.js environment"));
245
+ };
246
+ const loadScriptNode = typeof ENV_TARGET === "undefined" || ENV_TARGET !== "web" ? (url, info) => {
247
+ return new Promise((resolve, reject) => {
248
+ createScriptNode(url, (error2, scriptContext) => {
249
+ var _a, _b;
250
+ if (error2) reject(error2);
251
+ else {
252
+ const remoteEntryKey = ((_a = info == null ? void 0 : info.attrs) == null ? void 0 : _a["globalName"]) || `__FEDERATION_${(_b = info == null ? void 0 : info.attrs) == null ? void 0 : _b["name"]}:custom__`;
253
+ resolve(globalThis[remoteEntryKey] = scriptContext);
254
+ }
255
+ }, info.attrs, info.loaderHook);
256
+ });
257
+ } : (url, info) => {
258
+ throw new Error("loadScriptNode is disabled in non-Node.js environment");
259
+ };
260
+ const esmModuleCache = /* @__PURE__ */ new Map();
261
+ async function loadModule(url, options) {
262
+ if (esmModuleCache.has(url)) return esmModuleCache.get(url);
263
+ const { fetch: fetch2, vm } = options;
264
+ const code = await (await fetch2(url)).text();
265
+ const module = new vm.SourceTextModule(code, { importModuleDynamically: async (specifier, script) => {
266
+ const resolvedUrl = new URL(specifier, url).href;
267
+ return loadModule(resolvedUrl, options);
268
+ } });
269
+ esmModuleCache.set(url, module);
270
+ await module.link(async (specifier) => {
271
+ const resolvedUrl = new URL(specifier, url).href;
272
+ return await loadModule(resolvedUrl, options);
273
+ });
274
+ return module;
275
+ }
276
+ const dataFetchFunction = async function(options) {
277
+ var _a, _b;
278
+ const [id, data, downgrade] = options;
279
+ logger.debug("==========call data fetch function!");
280
+ if (data) {
281
+ if (!id) {
282
+ throw new Error("id is required!");
283
+ }
284
+ if (!getDataFetchMap()) {
285
+ initDataFetchMap();
286
+ }
287
+ const dataFetchItem = getDataFetchItem(id);
288
+ if (dataFetchItem) {
289
+ (_b = (_a = dataFetchItem[1]) == null ? void 0 : _a[1]) == null ? void 0 : _b.call(_a, data);
290
+ dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;
291
+ return;
292
+ }
293
+ if (!dataFetchItem) {
294
+ const dataFetchMap = getDataFetchMap();
295
+ let res;
296
+ let rej;
297
+ const p = new Promise((resolve, reject) => {
298
+ res = resolve;
299
+ rej = reject;
300
+ });
301
+ dataFetchMap[id] = [
302
+ [
303
+ async () => async () => {
304
+ return "";
305
+ },
306
+ MF_DATA_FETCH_TYPE.FETCH_SERVER
307
+ ],
308
+ [p, res, rej],
309
+ MF_DATA_FETCH_STATUS.LOADED
310
+ ];
311
+ res && res(data);
312
+ return;
313
+ }
314
+ }
315
+ if (downgrade) {
316
+ const mfDowngrade2 = getDowngradeTag();
317
+ if (!mfDowngrade2) {
318
+ globalThis[DOWNGRADE_KEY] = id ? [id] : true;
319
+ } else if (Array.isArray(mfDowngrade2) && id && !mfDowngrade2.includes(id)) {
320
+ mfDowngrade2.push(id);
321
+ }
322
+ }
323
+ const mfDowngrade = getDowngradeTag();
324
+ if (typeof mfDowngrade === "boolean") {
325
+ return callAllDowngrade();
326
+ }
327
+ if (Array.isArray(mfDowngrade)) {
328
+ if (!id) {
329
+ globalThis[DOWNGRADE_KEY] = true;
330
+ return callAllDowngrade();
331
+ }
332
+ if (!mfDowngrade.includes(id)) {
333
+ mfDowngrade.push(id);
334
+ }
335
+ return callDowngrade(id);
336
+ }
337
+ };
338
+ function injectDataFetch() {
339
+ var _a;
340
+ globalThis[_a = DATA_FETCH_FUNCTION] || (globalThis[_a] = []);
341
+ const dataFetch = globalThis[DATA_FETCH_FUNCTION];
342
+ if (dataFetch.push === dataFetchFunction) {
343
+ return;
344
+ }
345
+ if (typeof window === "undefined") {
346
+ return;
347
+ }
348
+ globalThis[FS_HREF] = window.location.href;
349
+ dataFetch.push = dataFetchFunction;
350
+ }
351
+ const LOG_CATEGORY = "[ Federation Runtime ]";
352
+ function assert(condition, msg) {
353
+ if (!condition) error(msg);
354
+ }
355
+ function error(msg) {
356
+ if (msg instanceof Error) {
357
+ if (!msg.message.startsWith(LOG_CATEGORY)) msg.message = `${LOG_CATEGORY}: ${msg.message}`;
358
+ throw msg;
359
+ }
360
+ throw new Error(`${LOG_CATEGORY}: ${msg}`);
361
+ }
362
+ const CurrentGlobal = typeof globalThis === "object" ? globalThis : window;
363
+ const nativeGlobal = (() => {
364
+ try {
365
+ return document.defaultView;
366
+ } catch {
367
+ return CurrentGlobal;
368
+ }
369
+ })();
370
+ function definePropertyGlobalVal(target, key, val) {
371
+ Object.defineProperty(target, key, {
372
+ value: val,
373
+ configurable: false,
374
+ writable: true
375
+ });
376
+ }
377
+ function includeOwnProperty(target, key) {
378
+ return Object.hasOwnProperty.call(target, key);
379
+ }
380
+ if (!includeOwnProperty(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__")) definePropertyGlobalVal(CurrentGlobal, "__GLOBAL_LOADING_REMOTE_ENTRY__", {});
381
+ const globalLoading = CurrentGlobal.__GLOBAL_LOADING_REMOTE_ENTRY__;
382
+ function setGlobalDefaultVal(target) {
383
+ var _a, _b, _c, _d, _e, _f;
384
+ if (includeOwnProperty(target, "__VMOK__") && !includeOwnProperty(target, "__FEDERATION__")) definePropertyGlobalVal(target, "__FEDERATION__", target.__VMOK__);
385
+ if (!includeOwnProperty(target, "__FEDERATION__")) {
386
+ definePropertyGlobalVal(target, "__FEDERATION__", {
387
+ __GLOBAL_PLUGIN__: [],
388
+ __INSTANCES__: [],
389
+ moduleInfo: {},
390
+ __SHARE__: {},
391
+ __MANIFEST_LOADING__: {},
392
+ __PRELOADED_MAP__: /* @__PURE__ */ new Map()
393
+ });
394
+ definePropertyGlobalVal(target, "__VMOK__", target.__FEDERATION__);
395
+ }
396
+ (_a = target.__FEDERATION__).__GLOBAL_PLUGIN__ ?? (_a.__GLOBAL_PLUGIN__ = []);
397
+ (_b = target.__FEDERATION__).__INSTANCES__ ?? (_b.__INSTANCES__ = []);
398
+ (_c = target.__FEDERATION__).moduleInfo ?? (_c.moduleInfo = {});
399
+ (_d = target.__FEDERATION__).__SHARE__ ?? (_d.__SHARE__ = {});
400
+ (_e = target.__FEDERATION__).__MANIFEST_LOADING__ ?? (_e.__MANIFEST_LOADING__ = {});
401
+ (_f = target.__FEDERATION__).__PRELOADED_MAP__ ?? (_f.__PRELOADED_MAP__ = /* @__PURE__ */ new Map());
402
+ }
403
+ setGlobalDefaultVal(CurrentGlobal);
404
+ setGlobalDefaultVal(nativeGlobal);
405
+ const getRemoteEntryExports = (name, globalName) => {
406
+ const remoteEntryKey = globalName || `__FEDERATION_${name}:custom__`;
407
+ return {
408
+ remoteEntryKey,
409
+ entryExports: CurrentGlobal[remoteEntryKey]
410
+ };
411
+ };
412
+ const DEFAULT_SCOPE = "default";
413
+ const DEFAULT_REMOTE_TYPE = "global";
414
+ function matchRemoteWithNameAndExpose(remotes, id) {
415
+ for (const remote of remotes) {
416
+ const isNameMatched = id.startsWith(remote.name);
417
+ let expose = id.replace(remote.name, "");
418
+ if (isNameMatched) {
419
+ if (expose.startsWith("/")) {
420
+ const pkgNameOrAlias = remote.name;
421
+ expose = `.${expose}`;
422
+ return {
423
+ pkgNameOrAlias,
424
+ expose,
425
+ remote
426
+ };
427
+ } else if (expose === "") return {
428
+ pkgNameOrAlias: remote.name,
429
+ expose: ".",
430
+ remote
431
+ };
432
+ }
433
+ const isAliasMatched = remote.alias && id.startsWith(remote.alias);
434
+ let exposeWithAlias = remote.alias && id.replace(remote.alias, "");
435
+ if (remote.alias && isAliasMatched) {
436
+ if (exposeWithAlias && exposeWithAlias.startsWith("/")) {
437
+ const pkgNameOrAlias = remote.alias;
438
+ exposeWithAlias = `.${exposeWithAlias}`;
439
+ return {
440
+ pkgNameOrAlias,
441
+ expose: exposeWithAlias,
442
+ remote
443
+ };
444
+ } else if (exposeWithAlias === "") return {
445
+ pkgNameOrAlias: remote.alias,
446
+ expose: ".",
447
+ remote
448
+ };
449
+ }
450
+ }
451
+ }
452
+ const RUNTIME_001 = "RUNTIME-001";
453
+ const RUNTIME_002 = "RUNTIME-002";
454
+ const RUNTIME_003 = "RUNTIME-003";
455
+ const RUNTIME_004 = "RUNTIME-004";
456
+ const RUNTIME_005 = "RUNTIME-005";
457
+ const RUNTIME_006 = "RUNTIME-006";
458
+ const RUNTIME_007 = "RUNTIME-007";
459
+ const RUNTIME_008 = "RUNTIME-008";
460
+ const RUNTIME_009 = "RUNTIME-009";
461
+ const RUNTIME_010 = "RUNTIME-010";
462
+ const getDocsUrl = (errorCode) => {
463
+ return `View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${errorCode.split("-")[0].toLowerCase()}#${errorCode.toLowerCase()}`;
464
+ };
465
+ const getShortErrorMsg = (errorCode, errorDescMap, args, originalErrorMsg) => {
466
+ const msg = [`${[errorDescMap[errorCode]]} #${errorCode}`];
467
+ args && msg.push(`args: ${JSON.stringify(args)}`);
468
+ msg.push(getDocsUrl(errorCode));
469
+ return msg.join("\n");
470
+ };
471
+ const runtimeDescMap = {
472
+ [RUNTIME_001]: "Failed to get remoteEntry exports.",
473
+ [RUNTIME_002]: 'The remote entry interface does not contain "init"',
474
+ [RUNTIME_003]: "Failed to get manifest.",
475
+ [RUNTIME_004]: "Failed to locate remote.",
476
+ [RUNTIME_005]: "Invalid loadShareSync function call from bundler runtime",
477
+ [RUNTIME_006]: "Invalid loadShareSync function call from runtime",
478
+ [RUNTIME_007]: "Failed to get remote snapshot.",
479
+ [RUNTIME_008]: "Failed to load script resources.",
480
+ [RUNTIME_009]: "Please call createInstance first.",
481
+ [RUNTIME_010]: 'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.'
482
+ };
483
+ ({
484
+ ...runtimeDescMap
485
+ });
486
+ const importCallback = ".then(callbacks[0]).catch(callbacks[1])";
487
+ async function loadEsmEntry({ entry, remoteEntryExports }) {
488
+ return new Promise((resolve, reject) => {
489
+ try {
490
+ if (!remoteEntryExports) if (typeof FEDERATION_ALLOW_NEW_FUNCTION !== "undefined") new Function("callbacks", `import("${entry}")${importCallback}`)([resolve, reject]);
491
+ else import(
492
+ /* webpackIgnore: true */
493
+ /* @vite-ignore */
494
+ entry
495
+ ).then(resolve).catch(reject);
496
+ else resolve(remoteEntryExports);
497
+ } catch (e) {
498
+ reject(e);
499
+ }
500
+ });
501
+ }
502
+ async function loadSystemJsEntry({ entry, remoteEntryExports }) {
503
+ return new Promise((resolve, reject) => {
504
+ try {
505
+ if (!remoteEntryExports) if (typeof __system_context__ === "undefined") System.import(entry).then(resolve).catch(reject);
506
+ else new Function("callbacks", `System.import("${entry}")${importCallback}`)([resolve, reject]);
507
+ else resolve(remoteEntryExports);
508
+ } catch (e) {
509
+ reject(e);
510
+ }
511
+ });
512
+ }
513
+ function handleRemoteEntryLoaded(name, globalName, entry) {
514
+ const { remoteEntryKey, entryExports } = getRemoteEntryExports(name, globalName);
515
+ assert(entryExports, getShortErrorMsg(RUNTIME_001, runtimeDescMap, {
516
+ remoteName: name,
517
+ remoteEntryUrl: entry,
518
+ remoteEntryKey
519
+ }));
520
+ return entryExports;
521
+ }
522
+ async function loadEntryScript({ name, globalName, entry, loaderHook, getEntryUrl }) {
523
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
524
+ if (remoteEntryExports) return remoteEntryExports;
525
+ return loadScript(getEntryUrl ? getEntryUrl(entry) : entry, {
526
+ attrs: {},
527
+ createScriptHook: (url, attrs) => {
528
+ const res = loaderHook.lifecycle.createScript.emit({
529
+ url,
530
+ attrs
531
+ });
532
+ if (!res) return;
533
+ if (res instanceof HTMLScriptElement) return res;
534
+ if ("script" in res || "timeout" in res) return res;
535
+ }
536
+ }).then(() => {
537
+ return handleRemoteEntryLoaded(name, globalName, entry);
538
+ }).catch((e) => {
539
+ assert(void 0, getShortErrorMsg(RUNTIME_008, runtimeDescMap, {
540
+ remoteName: name,
541
+ resourceUrl: entry
542
+ }));
543
+ throw e;
544
+ });
545
+ }
546
+ async function loadEntryDom({ remoteInfo, remoteEntryExports, loaderHook, getEntryUrl }) {
547
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
548
+ switch (type) {
549
+ case "esm":
550
+ case "module":
551
+ return loadEsmEntry({
552
+ entry,
553
+ remoteEntryExports
554
+ });
555
+ case "system":
556
+ return loadSystemJsEntry({
557
+ entry,
558
+ remoteEntryExports
559
+ });
560
+ default:
561
+ return loadEntryScript({
562
+ entry,
563
+ globalName,
564
+ name,
565
+ loaderHook,
566
+ getEntryUrl
567
+ });
568
+ }
569
+ }
570
+ async function loadEntryNode({ remoteInfo, loaderHook }) {
571
+ const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
572
+ const { entryExports: remoteEntryExports } = getRemoteEntryExports(name, globalName);
573
+ if (remoteEntryExports) return remoteEntryExports;
574
+ return loadScriptNode(entry, {
575
+ attrs: {
576
+ name,
577
+ globalName,
578
+ type
579
+ },
580
+ loaderHook: { createScriptHook: (url, attrs = {}) => {
581
+ const res = loaderHook.lifecycle.createScript.emit({
582
+ url,
583
+ attrs
584
+ });
585
+ if (!res) return;
586
+ if ("url" in res) return res;
587
+ } }
588
+ }).then(() => {
589
+ return handleRemoteEntryLoaded(name, globalName, entry);
590
+ }).catch((e) => {
591
+ throw e;
592
+ });
593
+ }
594
+ function getRemoteEntryUniqueKey(remoteInfo) {
595
+ const { entry, name } = remoteInfo;
596
+ return composeKeyWithSeparator(name, entry);
597
+ }
598
+ async function getRemoteEntry(params) {
599
+ const { origin, remoteEntryExports, remoteInfo, getEntryUrl, _inErrorHandling = false } = params;
600
+ const uniqueKey = getRemoteEntryUniqueKey(remoteInfo);
601
+ if (remoteEntryExports) return remoteEntryExports;
602
+ if (!globalLoading[uniqueKey]) {
603
+ const loadEntryHook = origin.remoteHandler.hooks.lifecycle.loadEntry;
604
+ const loaderHook = origin.loaderHook;
605
+ globalLoading[uniqueKey] = loadEntryHook.emit({
606
+ loaderHook,
607
+ remoteInfo,
608
+ remoteEntryExports
609
+ }).then((res) => {
610
+ if (res) return res;
611
+ return (typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : isBrowserEnv()) ? loadEntryDom({
612
+ remoteInfo,
613
+ remoteEntryExports,
614
+ loaderHook,
615
+ getEntryUrl
616
+ }) : loadEntryNode({
617
+ remoteInfo,
618
+ loaderHook
619
+ });
620
+ }).catch(async (err) => {
621
+ const uniqueKey2 = getRemoteEntryUniqueKey(remoteInfo);
622
+ if (err instanceof Error && err.message.includes(RUNTIME_008) && !_inErrorHandling) {
623
+ const wrappedGetRemoteEntry = (params2) => {
624
+ return getRemoteEntry({
625
+ ...params2,
626
+ _inErrorHandling: true
627
+ });
628
+ };
629
+ const RemoteEntryExports = await origin.loaderHook.lifecycle.loadEntryError.emit({
630
+ getRemoteEntry: wrappedGetRemoteEntry,
631
+ origin,
632
+ remoteInfo,
633
+ remoteEntryExports,
634
+ globalLoading,
635
+ uniqueKey: uniqueKey2
636
+ });
637
+ if (RemoteEntryExports) return RemoteEntryExports;
638
+ }
639
+ throw err;
640
+ });
641
+ }
642
+ return globalLoading[uniqueKey];
643
+ }
644
+ function getRemoteInfo(remote) {
645
+ return {
646
+ ...remote,
647
+ entry: "entry" in remote ? remote.entry : "",
648
+ type: remote.type || DEFAULT_REMOTE_TYPE,
649
+ entryGlobalName: remote.entryGlobalName || remote.name,
650
+ shareScope: remote.shareScope || DEFAULT_SCOPE
651
+ };
652
+ }
653
+ function preloadAssets(remoteInfo, host, assets, useLinkPreload = true) {
654
+ const { cssAssets, jsAssetsWithoutEntry, entryAssets } = assets;
655
+ if (host.options.inBrowser) {
656
+ entryAssets.forEach((asset) => {
657
+ const { moduleInfo } = asset;
658
+ const module = host.moduleCache.get(remoteInfo.name);
659
+ if (module) getRemoteEntry({
660
+ origin: host,
661
+ remoteInfo: moduleInfo,
662
+ remoteEntryExports: module.remoteEntryExports
663
+ });
664
+ else getRemoteEntry({
665
+ origin: host,
666
+ remoteInfo: moduleInfo,
667
+ remoteEntryExports: void 0
668
+ });
669
+ });
670
+ if (useLinkPreload) {
671
+ const defaultAttrs = {
672
+ rel: "preload",
673
+ as: "style"
674
+ };
675
+ cssAssets.forEach((cssUrl) => {
676
+ const { link: cssEl, needAttach } = createLink({
677
+ url: cssUrl,
678
+ cb: () => {
679
+ },
680
+ attrs: defaultAttrs,
681
+ createLinkHook: (url, attrs) => {
682
+ const res = host.loaderHook.lifecycle.createLink.emit({
683
+ url,
684
+ attrs
685
+ });
686
+ if (res instanceof HTMLLinkElement) return res;
687
+ }
688
+ });
689
+ needAttach && document.head.appendChild(cssEl);
690
+ });
691
+ } else {
692
+ const defaultAttrs = {
693
+ rel: "stylesheet",
694
+ type: "text/css"
695
+ };
696
+ cssAssets.forEach((cssUrl) => {
697
+ const { link: cssEl, needAttach } = createLink({
698
+ url: cssUrl,
699
+ cb: () => {
700
+ },
701
+ attrs: defaultAttrs,
702
+ createLinkHook: (url, attrs) => {
703
+ const res = host.loaderHook.lifecycle.createLink.emit({
704
+ url,
705
+ attrs
706
+ });
707
+ if (res instanceof HTMLLinkElement) return res;
708
+ },
709
+ needDeleteLink: false
710
+ });
711
+ needAttach && document.head.appendChild(cssEl);
712
+ });
713
+ }
714
+ if (useLinkPreload) {
715
+ const defaultAttrs = {
716
+ rel: "preload",
717
+ as: "script"
718
+ };
719
+ jsAssetsWithoutEntry.forEach((jsUrl) => {
720
+ const { link: linkEl, needAttach } = createLink({
721
+ url: jsUrl,
722
+ cb: () => {
723
+ },
724
+ attrs: defaultAttrs,
725
+ createLinkHook: (url, attrs) => {
726
+ const res = host.loaderHook.lifecycle.createLink.emit({
727
+ url,
728
+ attrs
729
+ });
730
+ if (res instanceof HTMLLinkElement) return res;
731
+ }
732
+ });
733
+ needAttach && document.head.appendChild(linkEl);
734
+ });
735
+ } else {
736
+ const defaultAttrs = {
737
+ fetchpriority: "high",
738
+ type: (remoteInfo == null ? void 0 : remoteInfo.type) === "module" ? "module" : "text/javascript"
739
+ };
740
+ jsAssetsWithoutEntry.forEach((jsUrl) => {
741
+ const { script: scriptEl, needAttach } = createScript({
742
+ url: jsUrl,
743
+ cb: () => {
744
+ },
745
+ attrs: defaultAttrs,
746
+ createScriptHook: (url, attrs) => {
747
+ const res = host.loaderHook.lifecycle.createScript.emit({
748
+ url,
749
+ attrs
750
+ });
751
+ if (res instanceof HTMLScriptElement) return res;
752
+ },
753
+ needDeleteScript: true
754
+ });
755
+ needAttach && document.head.appendChild(scriptEl);
756
+ });
757
+ }
758
+ }
759
+ }
760
+ var helpers_default = {
761
+ utils: {
762
+ matchRemoteWithNameAndExpose,
763
+ preloadAssets,
764
+ getRemoteInfo
765
+ }
766
+ };
767
+ typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN === "boolean" ? !FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN : true;
768
+ const helpers = helpers_default;
769
+ const utils = helpers.utils;
770
+ const runtimeHelpers = {
771
+ utils
772
+ };
773
+ async function prefetch(options) {
774
+ const { instance, id, dataFetchParams, preloadComponentResource } = options;
775
+ if (!id) {
776
+ logger.error("id is required for prefetch!");
777
+ return;
778
+ }
779
+ if (!instance) {
780
+ logger.error("instance is required for prefetch!");
781
+ return;
782
+ }
783
+ const matchedRemoteInfo = runtimeHelpers.utils.matchRemoteWithNameAndExpose(
784
+ instance.options.remotes,
785
+ id
786
+ );
787
+ if (!matchedRemoteInfo) {
788
+ logger.error(`Can not found '${id}' in instance.options.remotes!`);
789
+ return;
790
+ }
791
+ const { remote, expose } = matchedRemoteInfo;
792
+ const { remoteSnapshot, globalSnapshot } = await instance.snapshotHandler.loadRemoteSnapshotInfo({
793
+ moduleInfo: remote,
794
+ id,
795
+ expose
796
+ });
797
+ if (preloadComponentResource) {
798
+ const remoteInfo = runtimeHelpers.utils.getRemoteInfo(remote);
799
+ Promise.resolve(
800
+ instance.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({
801
+ origin: instance,
802
+ preloadOptions: {
803
+ remote,
804
+ preloadConfig: {
805
+ nameOrAlias: remote.name,
806
+ exposes: [expose]
807
+ }
808
+ },
809
+ remote,
810
+ remoteInfo,
811
+ globalSnapshot,
812
+ remoteSnapshot
813
+ })
814
+ ).then((assets) => {
815
+ if (assets) {
816
+ runtimeHelpers.utils.preloadAssets(remoteInfo, instance, assets);
817
+ }
818
+ });
819
+ }
820
+ const dataFetchMap = getDataFetchMap();
821
+ if (!dataFetchMap) {
822
+ return;
823
+ }
824
+ const dataFetchInfo = getDataFetchInfo({
825
+ name: remote.name,
826
+ alias: remote.alias,
827
+ id,
828
+ remoteSnapshot
829
+ });
830
+ const dataFetchMapKey = getDataFetchMapKey(dataFetchInfo, {
831
+ name: instance.name,
832
+ version: instance.options.version
833
+ });
834
+ if (!dataFetchMapKey) {
835
+ return;
836
+ }
837
+ const dataFetchItem = dataFetchMap[dataFetchMapKey];
838
+ if (!dataFetchItem) {
839
+ return;
840
+ }
841
+ const [getDataFetchGetter, _type, getDataFetchPromise] = dataFetchItem[0];
842
+ let _getDataFetchPromise = getDataFetchPromise;
843
+ if (!getDataFetchPromise) {
844
+ if (!getDataFetchGetter) {
845
+ return;
846
+ }
847
+ _getDataFetchPromise = getDataFetchGetter();
848
+ }
849
+ _getDataFetchPromise.then((dataFetchFn) => {
850
+ return dataFetchFn({
851
+ ...dataFetchParams,
852
+ _id: dataFetchMapKey,
853
+ isDowngrade: false
854
+ });
855
+ });
856
+ }
857
+ export {
858
+ dataFetchFunction as d,
859
+ injectDataFetch as i,
860
+ prefetch as p
861
+ };