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