@module-federation/bridge-react 0.0.0-feat-support-bridge-react-router-v7-20251015102312

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 (100) hide show
  1. package/CHANGELOG.md +670 -0
  2. package/LICENSE +21 -0
  3. package/README.md +131 -0
  4. package/__tests__/bridge.spec.tsx +160 -0
  5. package/__tests__/createLazyComponent.spec.tsx +209 -0
  6. package/__tests__/prefetch.spec.ts +156 -0
  7. package/__tests__/router.spec.tsx +82 -0
  8. package/__tests__/setupTests.ts +8 -0
  9. package/__tests__/util.ts +36 -0
  10. package/dist/bridge-base-29j7dZKh.mjs +201 -0
  11. package/dist/bridge-base-CTNdBioh.js +216 -0
  12. package/dist/data-fetch-server-middleware.cjs.js +163 -0
  13. package/dist/data-fetch-server-middleware.d.ts +15 -0
  14. package/dist/data-fetch-server-middleware.es.js +164 -0
  15. package/dist/data-fetch-utils.cjs.js +24 -0
  16. package/dist/data-fetch-utils.d.ts +81 -0
  17. package/dist/data-fetch-utils.es.js +26 -0
  18. package/dist/index-Dm-M9ouh.mjs +46 -0
  19. package/dist/index-DqCpgmgH.js +45 -0
  20. package/dist/index.cjs.js +293 -0
  21. package/dist/index.d.ts +274 -0
  22. package/dist/index.es.js +276 -0
  23. package/dist/index.esm-CzoIcLts.js +459 -0
  24. package/dist/index.esm-JLwyxgUK.mjs +460 -0
  25. package/dist/lazy-load-component-plugin-B4fdMQTL.js +521 -0
  26. package/dist/lazy-load-component-plugin-ijw36GA0.mjs +522 -0
  27. package/dist/lazy-load-component-plugin.cjs.js +6 -0
  28. package/dist/lazy-load-component-plugin.d.ts +16 -0
  29. package/dist/lazy-load-component-plugin.es.js +6 -0
  30. package/dist/lazy-utils.cjs.js +24 -0
  31. package/dist/lazy-utils.d.ts +149 -0
  32. package/dist/lazy-utils.es.js +24 -0
  33. package/dist/plugin.cjs.js +14 -0
  34. package/dist/plugin.d.ts +22 -0
  35. package/dist/plugin.es.js +14 -0
  36. package/dist/prefetch-Bgm31z9s.js +1272 -0
  37. package/dist/prefetch-DjeoxOeZ.mjs +1273 -0
  38. package/dist/router-v5.cjs.js +55 -0
  39. package/dist/router-v5.d.ts +18 -0
  40. package/dist/router-v5.es.js +32 -0
  41. package/dist/router-v6.cjs.js +84 -0
  42. package/dist/router-v6.d.ts +20 -0
  43. package/dist/router-v6.es.js +61 -0
  44. package/dist/router-v7.cjs.js +83 -0
  45. package/dist/router-v7.d.ts +20 -0
  46. package/dist/router-v7.es.js +61 -0
  47. package/dist/router.cjs.js +82 -0
  48. package/dist/router.d.ts +20 -0
  49. package/dist/router.es.js +60 -0
  50. package/dist/utils-0HFFqmd4.js +2015 -0
  51. package/dist/utils-BTpxHmva.mjs +2016 -0
  52. package/dist/v18.cjs.js +15 -0
  53. package/dist/v18.d.ts +114 -0
  54. package/dist/v18.es.js +15 -0
  55. package/dist/v19.cjs.js +15 -0
  56. package/dist/v19.d.ts +115 -0
  57. package/dist/v19.es.js +15 -0
  58. package/jest.config.ts +21 -0
  59. package/package.json +144 -0
  60. package/project.json +23 -0
  61. package/src/index.ts +45 -0
  62. package/src/lazy/AwaitDataFetch.tsx +215 -0
  63. package/src/lazy/constant.ts +30 -0
  64. package/src/lazy/createLazyComponent.tsx +411 -0
  65. package/src/lazy/data-fetch/cache.ts +291 -0
  66. package/src/lazy/data-fetch/call-data-fetch.ts +13 -0
  67. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +196 -0
  68. package/src/lazy/data-fetch/index.ts +16 -0
  69. package/src/lazy/data-fetch/inject-data-fetch.ts +109 -0
  70. package/src/lazy/data-fetch/prefetch.ts +112 -0
  71. package/src/lazy/data-fetch/runtime-plugin.ts +115 -0
  72. package/src/lazy/index.ts +35 -0
  73. package/src/lazy/logger.ts +6 -0
  74. package/src/lazy/types.ts +75 -0
  75. package/src/lazy/utils.ts +372 -0
  76. package/src/lazy/wrapNoSSR.tsx +10 -0
  77. package/src/modern-app-env.d.ts +2 -0
  78. package/src/plugins/lazy-load-component-plugin.spec.ts +21 -0
  79. package/src/plugins/lazy-load-component-plugin.ts +57 -0
  80. package/src/provider/context.tsx +4 -0
  81. package/src/provider/plugin.ts +22 -0
  82. package/src/provider/versions/bridge-base.tsx +127 -0
  83. package/src/provider/versions/legacy.ts +87 -0
  84. package/src/provider/versions/v18.ts +47 -0
  85. package/src/provider/versions/v19.ts +48 -0
  86. package/src/remote/component.tsx +211 -0
  87. package/src/remote/create.tsx +103 -0
  88. package/src/router/default.tsx +73 -0
  89. package/src/router/v5.tsx +43 -0
  90. package/src/router/v6.tsx +74 -0
  91. package/src/router/v7.tsx +75 -0
  92. package/src/types.ts +147 -0
  93. package/src/utils/index.ts +44 -0
  94. package/src/v18.ts +9 -0
  95. package/src/v19.ts +9 -0
  96. package/tsconfig.json +42 -0
  97. package/tsconfig.node.json +11 -0
  98. package/tsconfig.spec.json +26 -0
  99. package/vite.config.ts +106 -0
  100. package/vitest.config.ts +27 -0
@@ -0,0 +1,215 @@
1
+ import React, {
2
+ MutableRefObject,
3
+ ReactNode,
4
+ Suspense,
5
+ useRef,
6
+ useState,
7
+ } from 'react';
8
+ import logger from './logger';
9
+ import {
10
+ DATA_FETCH_ERROR_PREFIX,
11
+ LOAD_REMOTE_ERROR_PREFIX,
12
+ ERROR_TYPE,
13
+ DATA_FETCH_FUNCTION,
14
+ } from './constant';
15
+
16
+ import { getDataFetchIdWithErrorMsgs, wrapDataFetchId } from './utils';
17
+ import type { DataFetchParams } from './types';
18
+
19
+ function isPromise<T>(obj: any): obj is PromiseLike<T> {
20
+ return (
21
+ !!obj &&
22
+ (typeof obj === 'object' || typeof obj === 'function') &&
23
+ typeof obj.then === 'function'
24
+ );
25
+ }
26
+ const AWAIT_ERROR_PREFIX =
27
+ '<Await /> caught the following error during render: ';
28
+
29
+ export type ErrorInfo = {
30
+ error: Error;
31
+ errorType: number;
32
+ dataFetchMapKey?: string;
33
+ };
34
+
35
+ export const transformError = (err: string | Error): ErrorInfo => {
36
+ const errMsg = err instanceof Error ? err.message : err;
37
+ const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, '');
38
+ const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);
39
+ if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {
40
+ return {
41
+ error: new Error(
42
+ originalMsg
43
+ .replace(DATA_FETCH_ERROR_PREFIX, '')
44
+ .replace(wrapDataFetchId(dataFetchMapKey), ''),
45
+ ),
46
+ errorType: ERROR_TYPE.DATA_FETCH,
47
+ dataFetchMapKey,
48
+ };
49
+ }
50
+ if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {
51
+ return {
52
+ error: new Error(
53
+ originalMsg
54
+ .replace(LOAD_REMOTE_ERROR_PREFIX, '')
55
+ .replace(wrapDataFetchId(dataFetchMapKey), ''),
56
+ ),
57
+ errorType: ERROR_TYPE.LOAD_REMOTE,
58
+ dataFetchMapKey,
59
+ };
60
+ }
61
+
62
+ return {
63
+ error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), '')),
64
+ errorType: ERROR_TYPE.UNKNOWN,
65
+ dataFetchMapKey,
66
+ };
67
+ };
68
+
69
+ export interface AwaitProps<T> {
70
+ resolve: T | Promise<T>;
71
+ loading?: ReactNode;
72
+ delayLoading?: number;
73
+ errorElement?: ReactNode | ((errorInfo: ErrorInfo) => ReactNode);
74
+ children: (data: T) => ReactNode;
75
+ params?: DataFetchParams;
76
+ }
77
+
78
+ export interface AwaitErrorHandlerProps<T = any>
79
+ extends Omit<AwaitProps<T>, 'resolve'> {
80
+ resolve: () => T | string;
81
+ }
82
+
83
+ const DefaultLoading = <></>;
84
+ const DefaultErrorElement = (_data: any) => <div>Error</div>;
85
+
86
+ export function AwaitDataFetch<T>({
87
+ resolve,
88
+ loading = DefaultLoading,
89
+ errorElement = DefaultErrorElement,
90
+ children,
91
+ params,
92
+ delayLoading,
93
+ }: AwaitProps<T>) {
94
+ const dataRef = useRef<T>();
95
+ const data = dataRef.current || resolve;
96
+ const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;
97
+
98
+ return (
99
+ <AwaitSuspense
100
+ params={params}
101
+ loading={loading}
102
+ errorElement={errorElement}
103
+ delayLoading={delayLoading}
104
+ // @ts-expect-error
105
+ resolve={getData}
106
+ >
107
+ {children}
108
+ </AwaitSuspense>
109
+ );
110
+ }
111
+
112
+ export const DelayedLoading = ({
113
+ delayLoading,
114
+ children,
115
+ }: {
116
+ delayLoading?: number;
117
+ children: ReactNode;
118
+ }) => {
119
+ const [show, setShow] = useState(false);
120
+ const timerSet = useRef(false);
121
+
122
+ if (!delayLoading) {
123
+ return children;
124
+ }
125
+
126
+ if (typeof window !== 'undefined' && !show && !timerSet.current) {
127
+ timerSet.current = true;
128
+ setTimeout(() => {
129
+ setShow(true);
130
+ }, delayLoading);
131
+ }
132
+
133
+ return show ? children : null;
134
+ };
135
+
136
+ function AwaitSuspense<T>({
137
+ resolve,
138
+ children,
139
+ loading = DefaultLoading,
140
+ errorElement = DefaultErrorElement,
141
+ delayLoading,
142
+ }: AwaitErrorHandlerProps<T>) {
143
+ return (
144
+ <Suspense
145
+ fallback={
146
+ <DelayedLoading delayLoading={delayLoading}>{loading}</DelayedLoading>
147
+ }
148
+ >
149
+ <ResolveAwait resolve={resolve} errorElement={errorElement}>
150
+ {children}
151
+ </ResolveAwait>
152
+ </Suspense>
153
+ );
154
+ }
155
+
156
+ function ResolveAwait<T>({
157
+ children,
158
+ resolve,
159
+ errorElement,
160
+ params,
161
+ }: AwaitErrorHandlerProps<T>) {
162
+ const data = resolve();
163
+ logger.debug('resolve data: ', data);
164
+ if (typeof data === 'string' && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {
165
+ const transformedError = transformError(data);
166
+ return (
167
+ <>
168
+ {typeof errorElement === 'function' ? (
169
+ <>
170
+ {globalThis.FEDERATION_SSR && (
171
+ <script
172
+ suppressHydrationWarning
173
+ // eslint-disable-next-line react/no-danger
174
+ dangerouslySetInnerHTML={{
175
+ __html: String.raw`
176
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || []
177
+ globalThis['${DATA_FETCH_FUNCTION}'].push([${transformedError.dataFetchMapKey ? `'${transformedError.dataFetchMapKey}'` : ''},${params ? JSON.stringify(params) : null},true]);`,
178
+ }}
179
+ ></script>
180
+ )}
181
+ {errorElement(transformedError)}
182
+ </>
183
+ ) : (
184
+ errorElement
185
+ )}
186
+ </>
187
+ );
188
+ }
189
+ const toRender =
190
+ typeof children === 'function' ? children(data as T) : children;
191
+ return <>{toRender}</>;
192
+ }
193
+
194
+ // return string when promise is rejected
195
+ const fetchData = <T,>(promise: Promise<T>, ref: MutableRefObject<T>) => {
196
+ let data: T | string;
197
+ let status: 'pending' | 'success' = 'pending';
198
+ const suspender = promise
199
+ .then((res) => {
200
+ status = 'success';
201
+ data = res;
202
+ ref.current = res;
203
+ })
204
+ .catch((e) => {
205
+ status = 'success';
206
+ console.warn(e);
207
+ data = AWAIT_ERROR_PREFIX + e;
208
+ });
209
+ return () => {
210
+ if (status === 'pending') {
211
+ throw suspender;
212
+ }
213
+ return data;
214
+ };
215
+ };
@@ -0,0 +1,30 @@
1
+ export const PLUGIN_IDENTIFIER = '[ Module Federation React ]';
2
+ export const DOWNGRADE_KEY = '_mfSSRDowngrade';
3
+ export const DATA_FETCH_MAP_KEY = '__MF_DATA_FETCH_MAP__';
4
+ export const DATA_FETCH_FUNCTION = '_mfDataFetch';
5
+ export const FS_HREF = '_mfFSHref';
6
+ export const ERROR_TYPE = {
7
+ DATA_FETCH: 1,
8
+ LOAD_REMOTE: 2,
9
+ UNKNOWN: 3,
10
+ };
11
+ export const WRAP_DATA_FETCH_ID_IDENTIFIER = 'wrap_dfip_identifier';
12
+ export const enum MF_DATA_FETCH_TYPE {
13
+ FETCH_SERVER = 1,
14
+ FETCH_CLIENT = 2,
15
+ }
16
+
17
+ export const enum MF_DATA_FETCH_STATUS {
18
+ LOADED = 1,
19
+ LOADING = 2,
20
+ AWAIT = 0,
21
+ ERROR = 3,
22
+ }
23
+
24
+ export const DATA_FETCH_IDENTIFIER = 'data';
25
+ export const DATA_FETCH_CLIENT_SUFFIX = '.client';
26
+ export const DATA_FETCH_QUERY = 'x-mf-data-fetch';
27
+ export const DATA_FETCH_ERROR_PREFIX =
28
+ 'caught the following error during dataFetch: ';
29
+ export const LOAD_REMOTE_ERROR_PREFIX =
30
+ 'caught the following error during loadRemote: ';
@@ -0,0 +1,411 @@
1
+ import type { ModuleFederation, getInstance } from '@module-federation/runtime';
2
+ import type { BasicProviderModuleInfo } from '@module-federation/sdk';
3
+ import React, { ReactNode, useState, useEffect } from 'react';
4
+ import type { ErrorInfo } from './AwaitDataFetch';
5
+ import type { DataFetchParams, NoSSRRemoteInfo } from './types';
6
+
7
+ import logger from './logger';
8
+ import {
9
+ AwaitDataFetch,
10
+ DelayedLoading,
11
+ transformError,
12
+ } from './AwaitDataFetch';
13
+ import {
14
+ fetchData,
15
+ getDataFetchItem,
16
+ getDataFetchMapKey,
17
+ getDataFetchInfo,
18
+ getLoadedRemoteInfos,
19
+ setDataFetchItemLoadedStatus,
20
+ wrapDataFetchId,
21
+ } from './utils';
22
+ import {
23
+ DATA_FETCH_ERROR_PREFIX,
24
+ DATA_FETCH_FUNCTION,
25
+ FS_HREF,
26
+ LOAD_REMOTE_ERROR_PREFIX,
27
+ MF_DATA_FETCH_TYPE,
28
+ } from './constant';
29
+
30
+ export type IProps = {
31
+ id: string;
32
+ instance: ReturnType<typeof getInstance>;
33
+ injectScript?: boolean;
34
+ injectLink?: boolean;
35
+ };
36
+
37
+ export type CreateLazyComponentOptions<T, E extends keyof T> = {
38
+ loader: () => Promise<T>;
39
+ instance: ReturnType<typeof getInstance>;
40
+ loading: React.ReactNode;
41
+ delayLoading?: number;
42
+ fallback: ReactNode | ((errorInfo: ErrorInfo) => ReactNode);
43
+ export?: E;
44
+ dataFetchParams?: DataFetchParams;
45
+ noSSR?: boolean;
46
+ injectScript?: boolean;
47
+ injectLink?: boolean;
48
+ };
49
+
50
+ type ReactKey = { key?: React.Key | null };
51
+
52
+ function getTargetModuleInfo(
53
+ id: string,
54
+ instance?: ModuleFederation,
55
+ ):
56
+ | {
57
+ module: BasicProviderModuleInfo['modules'][0];
58
+ publicPath: string;
59
+ remoteEntry: string;
60
+ }
61
+ | undefined {
62
+ if (!instance) {
63
+ return;
64
+ }
65
+ const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
66
+ if (!loadedRemoteInfo) {
67
+ return;
68
+ }
69
+ const { snapshot } = loadedRemoteInfo;
70
+ if (!snapshot) {
71
+ return;
72
+ }
73
+ const publicPath: string =
74
+ 'publicPath' in snapshot
75
+ ? snapshot.publicPath
76
+ : 'getPublicPath' in snapshot
77
+ ? new Function(snapshot.getPublicPath)()
78
+ : '';
79
+ if (!publicPath) {
80
+ return;
81
+ }
82
+ const modules = 'modules' in snapshot ? snapshot.modules : [];
83
+ const targetModule = modules.find(
84
+ (m) => m.modulePath === loadedRemoteInfo.expose,
85
+ );
86
+ if (!targetModule) {
87
+ return;
88
+ }
89
+
90
+ const remoteEntry = 'remoteEntry' in snapshot ? snapshot.remoteEntry : '';
91
+ if (!remoteEntry) {
92
+ return;
93
+ }
94
+ return {
95
+ module: targetModule,
96
+ publicPath,
97
+ remoteEntry,
98
+ };
99
+ }
100
+
101
+ export function collectSSRAssets(options: IProps) {
102
+ const {
103
+ id,
104
+ injectLink = true,
105
+ injectScript = false,
106
+ } = typeof options === 'string' ? { id: options } : options;
107
+ const links: React.ReactNode[] = [];
108
+ const scripts: React.ReactNode[] = [];
109
+ const instance = options.instance;
110
+ if (!instance || (!injectLink && !injectScript)) {
111
+ return [...scripts, ...links];
112
+ }
113
+
114
+ const moduleAndPublicPath = getTargetModuleInfo(id, instance);
115
+ if (!moduleAndPublicPath) {
116
+ return [...scripts, ...links];
117
+ }
118
+ const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
119
+ if (injectLink) {
120
+ [...targetModule.assets.css.sync, ...targetModule.assets.css.async]
121
+ .sort()
122
+ .forEach((file, index) => {
123
+ links.push(
124
+ <link
125
+ key={`${file.split('.')[0]}_${index}`}
126
+ href={`${publicPath}${file}`}
127
+ rel="stylesheet"
128
+ type="text/css"
129
+ />,
130
+ );
131
+ });
132
+ }
133
+
134
+ if (injectScript) {
135
+ scripts.push(
136
+ <script
137
+ async={true}
138
+ key={remoteEntry.split('.')[0]}
139
+ src={`${publicPath}${remoteEntry}`}
140
+ crossOrigin="anonymous"
141
+ />,
142
+ );
143
+ [...targetModule.assets.js.sync].sort().forEach((file, index) => {
144
+ scripts.push(
145
+ <script
146
+ key={`${file.split('.')[0]}_${index}`}
147
+ async={true}
148
+ src={`${publicPath}${file}`}
149
+ crossOrigin="anonymous"
150
+ />,
151
+ );
152
+ });
153
+ }
154
+
155
+ return [...scripts, ...links];
156
+ }
157
+
158
+ function getServerNeedRemoteInfo(
159
+ loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>,
160
+ id: string,
161
+ noSSR?: boolean,
162
+ ): NoSSRRemoteInfo | undefined {
163
+ if (
164
+ noSSR ||
165
+ (typeof window !== 'undefined' && window.location.href !== window[FS_HREF])
166
+ ) {
167
+ if (!loadedRemoteInfo?.version) {
168
+ throw new Error(`${loadedRemoteInfo?.name} version is empty`);
169
+ }
170
+ const { snapshot } = loadedRemoteInfo;
171
+ if (!snapshot) {
172
+ throw new Error(`${loadedRemoteInfo?.name} snapshot is empty`);
173
+ }
174
+ const dataFetchItem = getDataFetchItem(id);
175
+ const isFetchServer =
176
+ dataFetchItem?.[0]?.[1] === MF_DATA_FETCH_TYPE.FETCH_SERVER;
177
+
178
+ if (
179
+ isFetchServer &&
180
+ (!('ssrPublicPath' in snapshot) || !snapshot.ssrPublicPath)
181
+ ) {
182
+ throw new Error(
183
+ `ssrPublicPath is required while fetching ${loadedRemoteInfo?.name} data in SSR project!`,
184
+ );
185
+ }
186
+
187
+ if (
188
+ isFetchServer &&
189
+ (!('ssrRemoteEntry' in snapshot) || !snapshot.ssrRemoteEntry)
190
+ ) {
191
+ throw new Error(
192
+ `ssrRemoteEntry is required while loading ${loadedRemoteInfo?.name} data loader in SSR project!`,
193
+ );
194
+ }
195
+
196
+ return {
197
+ name: loadedRemoteInfo.name,
198
+ version: loadedRemoteInfo.version,
199
+ ssrPublicPath:
200
+ 'ssrPublicPath' in snapshot ? snapshot.ssrPublicPath || '' : '',
201
+ ssrRemoteEntry:
202
+ 'ssrRemoteEntry' in snapshot ? snapshot.ssrRemoteEntry || '' : '',
203
+ globalName: loadedRemoteInfo.entryGlobalName,
204
+ };
205
+ }
206
+ return undefined;
207
+ }
208
+
209
+ export function createLazyComponent<T, E extends keyof T>(
210
+ options: CreateLazyComponentOptions<T, E>,
211
+ ) {
212
+ const { instance, injectScript, injectLink } = options;
213
+ if (!instance) {
214
+ throw new Error('instance is required for createLazyComponent!');
215
+ }
216
+
217
+ type ComponentType = T[E] extends (...args: any) => any
218
+ ? Parameters<T[E]>[0] extends undefined
219
+ ? ReactKey
220
+ : Parameters<T[E]>[0] & ReactKey
221
+ : ReactKey;
222
+ const exportName = options?.export || 'default';
223
+
224
+ const callLoader = async () => {
225
+ logger.debug('callLoader start', Date.now());
226
+ const m = (await options.loader()) as Record<string, React.FC> &
227
+ Record<symbol, string>;
228
+ logger.debug('callLoader end', Date.now());
229
+ if (!m) {
230
+ throw new Error('load remote failed');
231
+ }
232
+ return m;
233
+ };
234
+
235
+ const getData = async (noSSR?: boolean) => {
236
+ let loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>;
237
+ let moduleId: string;
238
+ try {
239
+ const m = await callLoader();
240
+ moduleId = m && m[Symbol.for('mf_module_id')];
241
+ if (!moduleId) {
242
+ throw new Error('moduleId is empty');
243
+ }
244
+ loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
245
+ if (!loadedRemoteInfo) {
246
+ throw new Error(`can not find loaded remote('${moduleId}') info!`);
247
+ }
248
+ } catch (e) {
249
+ const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
250
+ logger.debug(e);
251
+ throw new Error(errMsg);
252
+ }
253
+ let dataFetchMapKey: string | undefined;
254
+ try {
255
+ dataFetchMapKey = getDataFetchMapKey(
256
+ getDataFetchInfo({
257
+ name: loadedRemoteInfo.name,
258
+ alias: loadedRemoteInfo.alias,
259
+ id: moduleId,
260
+ remoteSnapshot: loadedRemoteInfo.snapshot,
261
+ }),
262
+ { name: instance.name, version: instance.options.version },
263
+ );
264
+ logger.debug('getData dataFetchMapKey: ', dataFetchMapKey);
265
+ if (!dataFetchMapKey) {
266
+ return;
267
+ }
268
+ const data = await fetchData(
269
+ dataFetchMapKey,
270
+ {
271
+ ...options.dataFetchParams,
272
+ isDowngrade: false,
273
+ },
274
+ getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR),
275
+ );
276
+ setDataFetchItemLoadedStatus(dataFetchMapKey);
277
+ logger.debug('get data res: \n', data);
278
+ return data;
279
+ } catch (err) {
280
+ const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
281
+ logger.debug(errMsg);
282
+ throw new Error(errMsg);
283
+ }
284
+ };
285
+
286
+ const LazyComponent = React.lazy(async () => {
287
+ const m = await callLoader();
288
+ const moduleId = m && m[Symbol.for('mf_module_id')];
289
+ const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
290
+ loadedRemoteInfo?.snapshot;
291
+ const dataFetchMapKey = loadedRemoteInfo
292
+ ? getDataFetchMapKey(
293
+ getDataFetchInfo({
294
+ name: loadedRemoteInfo.name,
295
+ alias: loadedRemoteInfo.alias,
296
+ id: moduleId,
297
+ remoteSnapshot: loadedRemoteInfo.snapshot,
298
+ }),
299
+ { name: instance.name, version: instance?.options.version },
300
+ )
301
+ : undefined;
302
+ logger.debug('LazyComponent dataFetchMapKey: ', dataFetchMapKey);
303
+
304
+ const assets = collectSSRAssets({
305
+ id: moduleId,
306
+ instance,
307
+ injectLink,
308
+ injectScript,
309
+ });
310
+
311
+ const Com = m[exportName] as React.FC<ComponentType>;
312
+ if (exportName in m && typeof Com === 'function') {
313
+ return {
314
+ default: (props: Omit<ComponentType, 'key'> & { mfData?: unknown }) => (
315
+ <>
316
+ {globalThis.FEDERATION_SSR && dataFetchMapKey && (
317
+ <script
318
+ suppressHydrationWarning
319
+ dangerouslySetInnerHTML={{
320
+ __html: String.raw`
321
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
322
+ globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
323
+ `,
324
+ }}
325
+ ></script>
326
+ )}
327
+ {globalThis.FEDERATION_SSR && assets}
328
+ <Com {...props} />
329
+ </>
330
+ ),
331
+ };
332
+ // eslint-disable-next-line max-lines
333
+ } else {
334
+ throw Error(
335
+ `Make sure that ${moduleId} has the correct export when export is ${String(
336
+ exportName,
337
+ )}`,
338
+ );
339
+ }
340
+ });
341
+
342
+ return (props: ComponentType) => {
343
+ const { key, ...args } = props;
344
+
345
+ if (!options.noSSR) {
346
+ return (
347
+ <AwaitDataFetch
348
+ resolve={getData(options.noSSR)}
349
+ loading={options.loading}
350
+ delayLoading={options.delayLoading}
351
+ errorElement={options.fallback}
352
+ >
353
+ {/* @ts-expect-error ignore */}
354
+ {(data) => <LazyComponent {...args} mfData={data} />}
355
+ </AwaitDataFetch>
356
+ );
357
+ } else {
358
+ // Client-side rendering logic
359
+ const [data, setData] = useState<unknown>(null);
360
+ const [loading, setLoading] = useState<boolean>(true);
361
+ const [error, setError] = useState<ErrorInfo | null>(null);
362
+
363
+ useEffect(() => {
364
+ let isMounted = true;
365
+ const fetchDataAsync = async () => {
366
+ try {
367
+ setLoading(true);
368
+ const result = await getData(options.noSSR);
369
+ if (isMounted) {
370
+ setData(result);
371
+ }
372
+ } catch (e) {
373
+ if (isMounted) {
374
+ setError(transformError(e as Error));
375
+ }
376
+ } finally {
377
+ if (isMounted) {
378
+ setLoading(false);
379
+ }
380
+ }
381
+ };
382
+
383
+ fetchDataAsync();
384
+
385
+ return () => {
386
+ isMounted = false;
387
+ };
388
+ }, []);
389
+
390
+ if (loading) {
391
+ return (
392
+ <DelayedLoading delayLoading={options.delayLoading}>
393
+ {options.loading}
394
+ </DelayedLoading>
395
+ );
396
+ }
397
+
398
+ if (error) {
399
+ return (
400
+ <>
401
+ {typeof options.fallback === 'function'
402
+ ? options.fallback(error)
403
+ : options.fallback}
404
+ </>
405
+ );
406
+ }
407
+ // @ts-expect-error ignore
408
+ return <LazyComponent {...args} mfData={data} />;
409
+ }
410
+ };
411
+ }