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