@module-federation/modern-js 0.0.0-next-20250526025159 → 0.0.0-next-20250526035905

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 (82) hide show
  1. package/dist/cjs/cli/configPlugin.js +6 -8
  2. package/dist/cjs/cli/configPlugin.spec.js +1 -3
  3. package/dist/cjs/{runtime/wrapNoSSR.js → cli/constant.js} +6 -13
  4. package/dist/cjs/{logger.js → cli/logger.js} +1 -1
  5. package/dist/cjs/cli/ssrPlugin.js +11 -27
  6. package/dist/cjs/cli/utils.js +0 -5
  7. package/dist/cjs/constant.js +2 -49
  8. package/dist/cjs/runtime/createRemoteSSRComponent.js +210 -0
  9. package/dist/cjs/runtime/index.js +2 -11
  10. package/dist/cjs/{interfaces/global.js → ssr-runtime/index.js} +8 -2
  11. package/dist/cjs/ssr-runtime/{devPlugin.js → plugin.js} +6 -9
  12. package/dist/esm/cli/configPlugin.js +7 -9
  13. package/dist/esm/cli/configPlugin.spec.js +1 -3
  14. package/dist/esm/cli/constant.js +4 -0
  15. package/dist/esm/{logger.js → cli/logger.js} +1 -1
  16. package/dist/esm/cli/ssrPlugin.js +7 -24
  17. package/dist/esm/cli/utils.js +0 -4
  18. package/dist/esm/constant.js +1 -37
  19. package/dist/esm/runtime/createRemoteSSRComponent.js +263 -0
  20. package/dist/esm/runtime/index.js +2 -10
  21. package/dist/esm/ssr-runtime/index.js +1 -0
  22. package/dist/esm/ssr-runtime/{devPlugin.js → plugin.js} +2 -5
  23. package/dist/esm-node/cli/configPlugin.js +7 -9
  24. package/dist/esm-node/cli/configPlugin.spec.js +1 -3
  25. package/dist/esm-node/cli/constant.js +4 -0
  26. package/dist/esm-node/{logger.js → cli/logger.js} +1 -1
  27. package/dist/esm-node/cli/ssrPlugin.js +7 -23
  28. package/dist/esm-node/cli/utils.js +0 -4
  29. package/dist/esm-node/constant.js +1 -37
  30. package/dist/esm-node/runtime/createRemoteSSRComponent.js +175 -0
  31. package/dist/esm-node/runtime/index.js +2 -10
  32. package/dist/esm-node/ssr-runtime/index.js +1 -0
  33. package/dist/esm-node/ssr-runtime/{devPlugin.js → plugin.js} +2 -5
  34. package/dist/types/cli/constant.d.ts +1 -0
  35. package/dist/types/cli/index.d.ts +0 -1
  36. package/dist/types/cli/utils.d.ts +0 -1
  37. package/dist/types/constant.d.ts +0 -23
  38. package/dist/types/runtime/createRemoteSSRComponent.d.ts +19 -0
  39. package/dist/types/runtime/index.d.ts +2 -6
  40. package/dist/types/ssr-runtime/index.d.ts +1 -0
  41. package/dist/types/ssr-runtime/plugin.d.ts +2 -0
  42. package/package.json +17 -41
  43. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +0 -98
  44. package/dist/cjs/cli/server/data-fetch-server-plugin.js +0 -192
  45. package/dist/cjs/runtime/AwaitDataFetch.js +0 -144
  46. package/dist/cjs/runtime/createRemoteComponent.js +0 -327
  47. package/dist/cjs/ssr-runtime/downgrade.js +0 -108
  48. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -128
  49. package/dist/cjs/utils/dataFetch.js +0 -211
  50. package/dist/cjs/utils/index.js +0 -54
  51. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +0 -74
  52. package/dist/esm/cli/server/data-fetch-server-plugin.js +0 -240
  53. package/dist/esm/interfaces/global.js +0 -0
  54. package/dist/esm/runtime/AwaitDataFetch.js +0 -131
  55. package/dist/esm/runtime/createRemoteComponent.js +0 -417
  56. package/dist/esm/runtime/wrapNoSSR.js +0 -12
  57. package/dist/esm/ssr-runtime/downgrade.js +0 -143
  58. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -168
  59. package/dist/esm/utils/dataFetch.js +0 -237
  60. package/dist/esm/utils/index.js +0 -28
  61. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +0 -68
  62. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +0 -162
  63. package/dist/esm-node/interfaces/global.js +0 -0
  64. package/dist/esm-node/runtime/AwaitDataFetch.js +0 -109
  65. package/dist/esm-node/runtime/createRemoteComponent.js +0 -291
  66. package/dist/esm-node/runtime/wrapNoSSR.js +0 -11
  67. package/dist/esm-node/ssr-runtime/downgrade.js +0 -82
  68. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +0 -94
  69. package/dist/esm-node/utils/dataFetch.js +0 -166
  70. package/dist/esm-node/utils/index.js +0 -27
  71. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +0 -3
  72. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +0 -3
  73. package/dist/types/interfaces/global.d.ts +0 -27
  74. package/dist/types/runtime/AwaitDataFetch.d.ts +0 -19
  75. package/dist/types/runtime/createRemoteComponent.d.ts +0 -26
  76. package/dist/types/runtime/wrapNoSSR.d.ts +0 -9
  77. package/dist/types/ssr-runtime/devPlugin.d.ts +0 -2
  78. package/dist/types/ssr-runtime/downgrade.d.ts +0 -4
  79. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +0 -2
  80. package/dist/types/utils/dataFetch.d.ts +0 -26
  81. package/dist/types/utils/index.d.ts +0 -15
  82. /package/dist/types/{logger.d.ts → cli/logger.d.ts} +0 -0
@@ -1,109 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { Suspense, useRef } from "react";
3
- import logger from "../logger";
4
- import { DATA_FETCH_ERROR_PREFIX, LOAD_REMOTE_ERROR_PREFIX, ERROR_TYPE, DATA_FETCH_FUNCTION } from "../constant";
5
- import { getDataFetchIdWithErrorMsgs, wrapDataFetchId } from "../utils";
6
- function isPromise(obj) {
7
- return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
8
- }
9
- const AWAIT_ERROR_PREFIX = "<Await /> caught the following error during render: ";
10
- const transformError = (err) => {
11
- const errMsg = err instanceof Error ? err.message : err;
12
- const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, "");
13
- const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);
14
- if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {
15
- return {
16
- error: new Error(originalMsg.replace(DATA_FETCH_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")),
17
- errorType: ERROR_TYPE.DATA_FETCH,
18
- dataFetchMapKey
19
- };
20
- }
21
- if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {
22
- return {
23
- error: new Error(originalMsg.replace(LOAD_REMOTE_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")),
24
- errorType: ERROR_TYPE.LOAD_REMOTE,
25
- dataFetchMapKey
26
- };
27
- }
28
- return {
29
- error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), "")),
30
- errorType: ERROR_TYPE.UNKNOWN,
31
- dataFetchMapKey
32
- };
33
- };
34
- const DefaultLoading = /* @__PURE__ */ _jsx(_Fragment, {});
35
- const DefaultErrorElement = (_data) => /* @__PURE__ */ _jsx("div", {
36
- children: "Error"
37
- });
38
- function AwaitDataFetch({ resolve, loading = DefaultLoading, errorElement = DefaultErrorElement, children, params }) {
39
- const dataRef = useRef();
40
- const data = dataRef.current || resolve;
41
- const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;
42
- return /* @__PURE__ */ _jsx(AwaitSuspense, {
43
- params,
44
- loading,
45
- errorElement,
46
- // @ts-ignore
47
- resolve: getData,
48
- children
49
- });
50
- }
51
- function AwaitSuspense({ resolve, children, loading = DefaultLoading, errorElement = DefaultErrorElement }) {
52
- return /* @__PURE__ */ _jsx(Suspense, {
53
- fallback: loading,
54
- children: /* @__PURE__ */ _jsx(ResolveAwait, {
55
- resolve,
56
- errorElement,
57
- children
58
- })
59
- });
60
- }
61
- function ResolveAwait({ children, resolve, errorElement, params }) {
62
- const data = resolve();
63
- logger.debug("resolve data: ", data);
64
- if (typeof data === "string" && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {
65
- const transformedError = transformError(data);
66
- return /* @__PURE__ */ _jsx(_Fragment, {
67
- children: typeof errorElement === "function" ? /* @__PURE__ */ _jsxs(_Fragment, {
68
- children: [
69
- globalThis.FEDERATION_SSR && /* @__PURE__ */ _jsx("script", {
70
- suppressHydrationWarning: true,
71
- dangerouslySetInnerHTML: {
72
- __html: String.raw`
73
- globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || []
74
- globalThis['${DATA_FETCH_FUNCTION}'].push([${transformedError.dataFetchMapKey ? `'${transformedError.dataFetchMapKey}'` : ""},${params ? JSON.stringify(params) : null},true]);`
75
- }
76
- }),
77
- errorElement(transformedError)
78
- ]
79
- }) : errorElement
80
- });
81
- }
82
- const toRender = typeof children === "function" ? children(data) : children;
83
- return /* @__PURE__ */ _jsx(_Fragment, {
84
- children: toRender
85
- });
86
- }
87
- const fetchData = (promise, ref) => {
88
- let data;
89
- let status = "pending";
90
- const suspender = promise.then((res) => {
91
- status = "success";
92
- data = res;
93
- ref.current = res;
94
- }).catch((e) => {
95
- status = "success";
96
- console.warn(e);
97
- data = AWAIT_ERROR_PREFIX + e;
98
- });
99
- return () => {
100
- if (status === "pending") {
101
- throw suspender;
102
- }
103
- return data;
104
- };
105
- };
106
- export {
107
- AwaitDataFetch,
108
- transformError
109
- };
@@ -1,291 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import React, { useEffect, useState } from "react";
3
- import logger from "../logger";
4
- import { getInstance } from "@module-federation/enhanced/runtime";
5
- import { AwaitDataFetch, transformError } from "./AwaitDataFetch";
6
- import { fetchData, getDataFetchItem, getDataFetchMapKey } from "../utils/dataFetch";
7
- import { getDataFetchInfo, getLoadedRemoteInfos, setDataFetchItemLoadedStatus, wrapDataFetchId } from "../utils";
8
- import { DATA_FETCH_ERROR_PREFIX, DATA_FETCH_FUNCTION, FS_HREF, LOAD_REMOTE_ERROR_PREFIX, MF_DATA_FETCH_TYPE } from "../constant";
9
- function getTargetModuleInfo(id) {
10
- const instance = getInstance();
11
- if (!instance) {
12
- return;
13
- }
14
- const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
15
- if (!loadedRemoteInfo) {
16
- return;
17
- }
18
- const snapshot = loadedRemoteInfo.snapshot;
19
- if (!snapshot) {
20
- return;
21
- }
22
- const publicPath = "publicPath" in snapshot ? snapshot.publicPath : "getPublicPath" in snapshot ? new Function(snapshot.getPublicPath)() : "";
23
- if (!publicPath) {
24
- return;
25
- }
26
- const modules = "modules" in snapshot ? snapshot.modules : [];
27
- const targetModule = modules.find((m) => m.modulePath === loadedRemoteInfo.expose);
28
- if (!targetModule) {
29
- return;
30
- }
31
- const remoteEntry = "remoteEntry" in snapshot ? snapshot.remoteEntry : "";
32
- if (!remoteEntry) {
33
- return;
34
- }
35
- return {
36
- module: targetModule,
37
- publicPath,
38
- remoteEntry
39
- };
40
- }
41
- function collectSSRAssets(options) {
42
- const { id, injectLink = true, injectScript = false } = typeof options === "string" ? {
43
- id: options
44
- } : options;
45
- const links = [];
46
- const scripts = [];
47
- const instance = getInstance();
48
- if (!instance || !injectLink && !injectScript) {
49
- return [
50
- ...scripts,
51
- ...links
52
- ];
53
- }
54
- const moduleAndPublicPath = getTargetModuleInfo(id);
55
- if (!moduleAndPublicPath) {
56
- return [
57
- ...scripts,
58
- ...links
59
- ];
60
- }
61
- const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
62
- if (injectLink) {
63
- [
64
- ...targetModule.assets.css.sync,
65
- ...targetModule.assets.css.async
66
- ].sort().forEach((file, index) => {
67
- links.push(/* @__PURE__ */ _jsx("link", {
68
- href: `${publicPath}${file}`,
69
- rel: "stylesheet",
70
- type: "text/css"
71
- }, `${file.split(".")[0]}_${index}`));
72
- });
73
- }
74
- if (injectScript) {
75
- scripts.push(/* @__PURE__ */ _jsx("script", {
76
- async: true,
77
- src: `${publicPath}${remoteEntry}`,
78
- crossOrigin: "anonymous"
79
- }, remoteEntry.split(".")[0]));
80
- [
81
- ...targetModule.assets.js.sync
82
- ].sort().forEach((file, index) => {
83
- scripts.push(/* @__PURE__ */ _jsx("script", {
84
- async: true,
85
- src: `${publicPath}${file}`,
86
- crossOrigin: "anonymous"
87
- }, `${file.split(".")[0]}_${index}`));
88
- });
89
- }
90
- return [
91
- ...scripts,
92
- ...links
93
- ];
94
- }
95
- function getServerNeedRemoteInfo(loadedRemoteInfo, id, noSSR) {
96
- if (noSSR || typeof window !== "undefined" && window.location.href !== window[FS_HREF]) {
97
- var _dataFetchItem_;
98
- if (!(loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.version)) {
99
- throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} version is empty`);
100
- }
101
- const { snapshot } = loadedRemoteInfo;
102
- if (!snapshot) {
103
- throw new Error(`${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} snapshot is empty`);
104
- }
105
- const dataFetchItem = getDataFetchItem(id);
106
- const isFetchServer = (dataFetchItem === null || dataFetchItem === void 0 ? void 0 : (_dataFetchItem_ = dataFetchItem[0]) === null || _dataFetchItem_ === void 0 ? void 0 : _dataFetchItem_[1]) === MF_DATA_FETCH_TYPE.FETCH_SERVER;
107
- if (isFetchServer && (!("ssrPublicPath" in snapshot) || !snapshot.ssrPublicPath)) {
108
- throw new Error(`ssrPublicPath is required while fetching ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data in SSR project!`);
109
- }
110
- if (isFetchServer && (!("ssrRemoteEntry" in snapshot) || !snapshot.ssrRemoteEntry)) {
111
- throw new Error(`ssrRemoteEntry is required while loading ${loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.name} data loader in SSR project!`);
112
- }
113
- return {
114
- name: loadedRemoteInfo.name,
115
- version: loadedRemoteInfo.version,
116
- ssrPublicPath: "ssrPublicPath" in snapshot ? snapshot.ssrPublicPath || "" : "",
117
- ssrRemoteEntry: "ssrRemoteEntry" in snapshot ? snapshot.ssrRemoteEntry || "" : "",
118
- globalName: loadedRemoteInfo.entryGlobalName
119
- };
120
- }
121
- return;
122
- }
123
- function createRemoteComponent(options) {
124
- const exportName = (options === null || options === void 0 ? void 0 : options.export) || "default";
125
- const callLoader = async () => {
126
- logger.debug("callLoader start", Date.now());
127
- const m = await options.loader();
128
- logger.debug("callLoader end", Date.now());
129
- if (!m) {
130
- throw new Error("load remote failed");
131
- }
132
- return m;
133
- };
134
- const getData = async (noSSR) => {
135
- let loadedRemoteInfo;
136
- let moduleId;
137
- const instance = getInstance();
138
- try {
139
- const m = await callLoader();
140
- moduleId = m && m[Symbol.for("mf_module_id")];
141
- if (!moduleId) {
142
- throw new Error("moduleId is empty");
143
- }
144
- loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
145
- if (!loadedRemoteInfo) {
146
- throw new Error(`can not find loaded remote('${moduleId}') info!`);
147
- }
148
- } catch (e) {
149
- const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
150
- logger.debug(e);
151
- throw new Error(errMsg);
152
- }
153
- let dataFetchMapKey;
154
- try {
155
- dataFetchMapKey = getDataFetchMapKey(getDataFetchInfo({
156
- name: loadedRemoteInfo.name,
157
- alias: loadedRemoteInfo.alias,
158
- id: moduleId,
159
- remoteSnapshot: loadedRemoteInfo.snapshot
160
- }), {
161
- name: instance.name,
162
- version: instance === null || instance === void 0 ? void 0 : instance.options.version
163
- });
164
- logger.debug("getData dataFetchMapKey: ", dataFetchMapKey);
165
- if (!dataFetchMapKey) {
166
- return;
167
- }
168
- const data = await fetchData(dataFetchMapKey, {
169
- ...options.dataFetchParams,
170
- isDowngrade: false
171
- }, getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR));
172
- setDataFetchItemLoadedStatus(dataFetchMapKey);
173
- logger.debug("get data res: \n", data);
174
- return data;
175
- } catch (err) {
176
- const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
177
- logger.debug(errMsg);
178
- throw new Error(errMsg);
179
- }
180
- };
181
- const LazyComponent = /* @__PURE__ */ React.lazy(async () => {
182
- const m = await callLoader();
183
- const moduleId = m && m[Symbol.for("mf_module_id")];
184
- const instance = getInstance();
185
- const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
186
- loadedRemoteInfo === null || loadedRemoteInfo === void 0 ? void 0 : loadedRemoteInfo.snapshot;
187
- const dataFetchMapKey = loadedRemoteInfo ? getDataFetchMapKey(getDataFetchInfo({
188
- name: loadedRemoteInfo.name,
189
- alias: loadedRemoteInfo.alias,
190
- id: moduleId,
191
- remoteSnapshot: loadedRemoteInfo.snapshot
192
- }), {
193
- name: instance.name,
194
- version: instance === null || instance === void 0 ? void 0 : instance.options.version
195
- }) : void 0;
196
- logger.debug("LazyComponent dataFetchMapKey: ", dataFetchMapKey);
197
- const assets = collectSSRAssets({
198
- id: moduleId
199
- });
200
- const Com = m[exportName];
201
- if (exportName in m && typeof Com === "function") {
202
- return {
203
- default: (props) => /* @__PURE__ */ _jsxs(_Fragment, {
204
- children: [
205
- globalThis.FEDERATION_SSR && dataFetchMapKey && /* @__PURE__ */ _jsx("script", {
206
- suppressHydrationWarning: true,
207
- dangerouslySetInnerHTML: {
208
- __html: String.raw`
209
- globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
210
- globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
211
- `
212
- }
213
- }),
214
- globalThis.FEDERATION_SSR && assets,
215
- /* @__PURE__ */ _jsx(Com, {
216
- ...props
217
- })
218
- ]
219
- })
220
- };
221
- } else {
222
- throw Error(`Make sure that ${moduleId} has the correct export when export is ${String(exportName)}`);
223
- }
224
- });
225
- return (props) => {
226
- const { key, ...args } = props;
227
- if (globalThis.FEDERATION_SSR && !options.noSSR) {
228
- const { key: key2, ...args2 } = props;
229
- return /* @__PURE__ */ _jsx(AwaitDataFetch, {
230
- resolve: getData(options.noSSR),
231
- loading: options.loading,
232
- errorElement: options.fallback,
233
- children: (data) => /* @__PURE__ */ _jsx(LazyComponent, {
234
- ...args2,
235
- mfData: data
236
- })
237
- });
238
- } else {
239
- const [data, setData] = useState(null);
240
- const [loading, setLoading] = useState(true);
241
- const [error, setError] = useState(null);
242
- useEffect(() => {
243
- let isMounted = true;
244
- const fetchDataAsync = async () => {
245
- try {
246
- setLoading(true);
247
- const result = await getData(options.noSSR);
248
- if (isMounted) {
249
- setData(result);
250
- }
251
- } catch (e) {
252
- if (isMounted) {
253
- setError(transformError(e));
254
- }
255
- } finally {
256
- if (isMounted) {
257
- setLoading(false);
258
- }
259
- }
260
- };
261
- fetchDataAsync();
262
- return () => {
263
- isMounted = false;
264
- };
265
- }, []);
266
- if (loading) {
267
- return /* @__PURE__ */ _jsx(_Fragment, {
268
- children: options.loading
269
- });
270
- }
271
- if (error) {
272
- return /* @__PURE__ */ _jsx(_Fragment, {
273
- children: typeof options.fallback === "function" ? options.fallback(error) : options.fallback
274
- });
275
- }
276
- return /* @__PURE__ */ _jsx(LazyComponent, {
277
- ...args,
278
- mfData: data
279
- });
280
- }
281
- };
282
- }
283
- function createRemoteSSRComponent(options) {
284
- logger.warn("createRemoteSSRComponent is deprecated, please use createRemoteComponent instead!");
285
- return createRemoteComponent(options);
286
- }
287
- export {
288
- collectSSRAssets,
289
- createRemoteComponent,
290
- createRemoteSSRComponent
291
- };
@@ -1,11 +0,0 @@
1
- function wrapNoSSR(createComponentFn) {
2
- return (options) => {
3
- return createComponentFn({
4
- ...options,
5
- noSSR: true
6
- });
7
- };
8
- }
9
- export {
10
- wrapNoSSR
11
- };
@@ -1,82 +0,0 @@
1
- import { DATA_FETCH_QUERY, DOWNGRADE_KEY } from "../constant";
2
- import { MF_DATA_FETCH_STATUS, MF_DATA_FETCH_TYPE } from "../constant";
3
- import { getDataFetchMap } from "../utils";
4
- function getDowngradeTag() {
5
- return globalThis[DOWNGRADE_KEY];
6
- }
7
- function callAllDowngrade() {
8
- const dataFetchMap = getDataFetchMap();
9
- if (!dataFetchMap) {
10
- return;
11
- }
12
- Object.keys(dataFetchMap).forEach((key) => {
13
- callDowngrade(key);
14
- });
15
- }
16
- async function callDowngrade(id, params, remoteInfo) {
17
- const dataFetchMap = getDataFetchMap();
18
- if (!dataFetchMap) {
19
- return;
20
- }
21
- const mfDataFetch = dataFetchMap[id];
22
- if ((mfDataFetch === null || mfDataFetch === void 0 ? void 0 : mfDataFetch[2]) === MF_DATA_FETCH_STATUS.AWAIT) {
23
- mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADING;
24
- let promise, res, rej;
25
- if (mfDataFetch[1]) {
26
- promise = mfDataFetch[1][0];
27
- res = mfDataFetch[1][1];
28
- rej = mfDataFetch[1][2];
29
- } else {
30
- promise = new Promise((resolve, reject) => {
31
- res = resolve;
32
- rej = reject;
33
- });
34
- mfDataFetch[1] = [
35
- promise,
36
- res,
37
- rej
38
- ];
39
- }
40
- const dataFetchType = mfDataFetch[0][1];
41
- if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_CLIENT) {
42
- try {
43
- mfDataFetch[0][0]().then((getDataFetchFn) => {
44
- return getDataFetchFn({
45
- ...params,
46
- isDowngrade: true
47
- }).then((data) => {
48
- mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;
49
- res(data);
50
- });
51
- });
52
- } catch (e) {
53
- mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;
54
- rej(e);
55
- }
56
- } else if (dataFetchType === MF_DATA_FETCH_TYPE.FETCH_SERVER) {
57
- try {
58
- const currentUrl = new URL(window.location.href);
59
- currentUrl.searchParams.set(DATA_FETCH_QUERY, encodeURIComponent(id));
60
- if (params) {
61
- currentUrl.searchParams.set("params", encodeURIComponent(JSON.stringify(params)));
62
- }
63
- if (remoteInfo) {
64
- currentUrl.searchParams.set("remoteInfo", encodeURIComponent(JSON.stringify(remoteInfo)));
65
- }
66
- const fetchUrl = currentUrl.toString();
67
- const data = await fetch(fetchUrl).then((res2) => res2.json());
68
- mfDataFetch[2] = MF_DATA_FETCH_STATUS.LOADED;
69
- res(data);
70
- } catch (e) {
71
- mfDataFetch[2] = MF_DATA_FETCH_STATUS.ERROR;
72
- rej(e);
73
- }
74
- }
75
- return promise;
76
- }
77
- }
78
- export {
79
- callAllDowngrade,
80
- callDowngrade,
81
- getDowngradeTag
82
- };
@@ -1,94 +0,0 @@
1
- import { DATA_FETCH_FUNCTION, DOWNGRADE_KEY, FS_HREF, MF_DATA_FETCH_STATUS, MF_DATA_FETCH_TYPE } from "../constant";
2
- import logger from "../logger";
3
- import { getDataFetchMap, getDataFetchItem, initDataFetchMap } from "../utils";
4
- import { callAllDowngrade, callDowngrade, getDowngradeTag } from "./downgrade";
5
- const injectDataFetchFunctionPlugin = () => ({
6
- name: "@module-federation/inject-data-fetch-function-plugin",
7
- setup: (api) => {
8
- api.onBeforeRender(async () => {
9
- var _globalThis, _DATA_FETCH_FUNCTION;
10
- globalThis.FEDERATION_SSR = true;
11
- if (typeof window === "undefined") {
12
- return;
13
- }
14
- const dataFetchFunction = async function(options) {
15
- const [id, data, downgrade] = options;
16
- logger.debug("==========call data fetch function!");
17
- if (data) {
18
- if (!id) {
19
- throw new Error("id is required!");
20
- }
21
- if (!getDataFetchMap()) {
22
- initDataFetchMap();
23
- }
24
- const dataFetchItem = getDataFetchItem(id);
25
- if (dataFetchItem) {
26
- var _dataFetchItem__, _dataFetchItem_;
27
- (_dataFetchItem_ = dataFetchItem[1]) === null || _dataFetchItem_ === void 0 ? void 0 : (_dataFetchItem__ = _dataFetchItem_[1]) === null || _dataFetchItem__ === void 0 ? void 0 : _dataFetchItem__.call(_dataFetchItem_, data);
28
- dataFetchItem[2] = MF_DATA_FETCH_STATUS.LOADED;
29
- return;
30
- }
31
- if (!dataFetchItem) {
32
- const dataFetchMap = getDataFetchMap();
33
- let res;
34
- let rej;
35
- const p = new Promise((resolve, reject) => {
36
- res = resolve;
37
- rej = reject;
38
- });
39
- dataFetchMap[id] = [
40
- [
41
- async () => async () => {
42
- return "";
43
- },
44
- MF_DATA_FETCH_TYPE.FETCH_SERVER
45
- ],
46
- [
47
- p,
48
- res,
49
- rej
50
- ],
51
- MF_DATA_FETCH_STATUS.LOADED
52
- ];
53
- res(data);
54
- return;
55
- }
56
- }
57
- if (downgrade) {
58
- const mfDowngrade2 = getDowngradeTag();
59
- if (!mfDowngrade2) {
60
- globalThis[DOWNGRADE_KEY] = id ? [
61
- id
62
- ] : true;
63
- } else if (Array.isArray(mfDowngrade2) && id && !mfDowngrade2.includes(id)) {
64
- mfDowngrade2.push(id);
65
- }
66
- }
67
- const mfDowngrade = getDowngradeTag();
68
- if (typeof mfDowngrade === "boolean") {
69
- return callAllDowngrade();
70
- }
71
- if (Array.isArray(mfDowngrade)) {
72
- if (!id) {
73
- globalThis[DOWNGRADE_KEY] = true;
74
- return callAllDowngrade();
75
- }
76
- if (!mfDowngrade.includes(id)) {
77
- mfDowngrade.push(id);
78
- }
79
- return callDowngrade(id);
80
- }
81
- };
82
- globalThis[FS_HREF] = window.location.href;
83
- (_globalThis = globalThis)[_DATA_FETCH_FUNCTION = DATA_FETCH_FUNCTION] || (_globalThis[_DATA_FETCH_FUNCTION] = []);
84
- const dataFetch = globalThis[DATA_FETCH_FUNCTION];
85
- await Promise.all(dataFetch.map(async (options) => {
86
- await dataFetchFunction(options);
87
- }));
88
- dataFetch.push = dataFetchFunction;
89
- });
90
- }
91
- });
92
- export {
93
- injectDataFetchFunctionPlugin
94
- };