@module-federation/bridge-react 0.0.0-next-20250707074728 → 0.0.0-next-20250708033956

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 (62) hide show
  1. package/CHANGELOG.md +8 -4
  2. package/__tests__/bridge.spec.tsx +7 -7
  3. package/dist/{bridge-base-P6pEjY1q.js → bridge-base-BoshEggF.mjs} +1 -1
  4. package/dist/{bridge-base-BBH982Tz.cjs → bridge-base-UGCwcMnG.js} +1 -1
  5. package/dist/data-fetch-runtime-plugin.cjs.js +73 -0
  6. package/dist/data-fetch-runtime-plugin.d.ts +6 -0
  7. package/dist/data-fetch-runtime-plugin.es.js +74 -0
  8. package/dist/data-fetch-server-middleware.cjs.js +163 -0
  9. package/dist/data-fetch-server-middleware.d.ts +6 -0
  10. package/dist/data-fetch-server-middleware.es.js +164 -0
  11. package/dist/data-fetch-utils.cjs.js +1273 -0
  12. package/dist/data-fetch-utils.d.ts +77 -0
  13. package/dist/data-fetch-utils.es.js +1275 -0
  14. package/dist/index-C0fDZB5b.js +45 -0
  15. package/dist/index-CqxytsLY.mjs +46 -0
  16. package/dist/index.cjs.js +461 -9
  17. package/dist/index.d.ts +143 -0
  18. package/dist/index.es.js +464 -11
  19. package/dist/index.esm-BCeUd-x9.mjs +418 -0
  20. package/dist/index.esm-j_1sIRzg.js +417 -0
  21. package/dist/inject-data-fetch-CAvi-gSf.js +79 -0
  22. package/dist/inject-data-fetch-errCdqBS.mjs +80 -0
  23. package/dist/lazy-utils.cjs.js +24 -0
  24. package/dist/lazy-utils.d.ts +140 -0
  25. package/dist/lazy-utils.es.js +24 -0
  26. package/dist/plugin.d.ts +4 -4
  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.cjs.js +1 -1
  32. package/dist/router.es.js +1 -1
  33. package/dist/utils-Bk8hGjjF.mjs +2016 -0
  34. package/dist/utils-iEVlDmyk.js +2015 -0
  35. package/dist/v18.cjs.js +1 -1
  36. package/dist/v18.es.js +1 -1
  37. package/dist/v19.cjs.js +1 -1
  38. package/dist/v19.es.js +1 -1
  39. package/package.json +45 -5
  40. package/src/index.ts +30 -1
  41. package/src/lazy/AwaitDataFetch.tsx +215 -0
  42. package/src/lazy/constant.ts +30 -0
  43. package/src/lazy/createLazyComponent.tsx +404 -0
  44. package/src/lazy/data-fetch/cache.ts +296 -0
  45. package/src/lazy/data-fetch/call-data-fetch.ts +13 -0
  46. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +196 -0
  47. package/src/lazy/data-fetch/index.ts +15 -0
  48. package/src/lazy/data-fetch/inject-data-fetch.ts +109 -0
  49. package/src/lazy/data-fetch/prefetch.ts +102 -0
  50. package/src/lazy/data-fetch/runtime-plugin.ts +116 -0
  51. package/src/lazy/index.ts +31 -0
  52. package/src/lazy/logger.ts +6 -0
  53. package/src/lazy/types.ts +75 -0
  54. package/src/lazy/utils.ts +372 -0
  55. package/src/lazy/wrapNoSSR.tsx +10 -0
  56. package/src/provider/plugin.ts +4 -4
  57. package/src/remote/component.tsx +3 -3
  58. package/src/remote/create.tsx +17 -4
  59. package/tsconfig.json +1 -1
  60. package/vite.config.ts +13 -0
  61. package/dist/index-Cv3p6r66.cjs +0 -235
  62. package/dist/index-D4yt7Udv.js +0 -236
@@ -0,0 +1,404 @@
1
+ import React, { ReactNode, useState, useEffect } from 'react';
2
+ import logger from './logger';
3
+ import {
4
+ AwaitDataFetch,
5
+ DelayedLoading,
6
+ transformError,
7
+ } from './AwaitDataFetch';
8
+ import {
9
+ fetchData,
10
+ getDataFetchItem,
11
+ getDataFetchMapKey,
12
+ getDataFetchInfo,
13
+ getLoadedRemoteInfos,
14
+ setDataFetchItemLoadedStatus,
15
+ wrapDataFetchId,
16
+ isServerEnv,
17
+ } from './utils';
18
+ import {
19
+ DATA_FETCH_ERROR_PREFIX,
20
+ DATA_FETCH_FUNCTION,
21
+ FS_HREF,
22
+ LOAD_REMOTE_ERROR_PREFIX,
23
+ MF_DATA_FETCH_TYPE,
24
+ } from './constant';
25
+
26
+ import type { ErrorInfo } from './AwaitDataFetch';
27
+ import type { DataFetchParams, NoSSRRemoteInfo } from './types';
28
+ import type { FederationHost, getInstance } from '@module-federation/runtime';
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
+ cacheData?: boolean;
47
+ };
48
+
49
+ type ReactKey = { key?: React.Key | null };
50
+
51
+ function getTargetModuleInfo(id: string, instance?: FederationHost) {
52
+ if (!instance) {
53
+ return;
54
+ }
55
+ const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
56
+ if (!loadedRemoteInfo) {
57
+ return;
58
+ }
59
+ const snapshot = loadedRemoteInfo.snapshot;
60
+ if (!snapshot) {
61
+ return;
62
+ }
63
+ const publicPath =
64
+ 'publicPath' in snapshot
65
+ ? snapshot.publicPath
66
+ : 'getPublicPath' in snapshot
67
+ ? new Function(snapshot.getPublicPath)()
68
+ : '';
69
+ if (!publicPath) {
70
+ return;
71
+ }
72
+ const modules = 'modules' in snapshot ? snapshot.modules : [];
73
+ const targetModule = modules.find(
74
+ (m) => m.modulePath === loadedRemoteInfo.expose,
75
+ );
76
+ if (!targetModule) {
77
+ return;
78
+ }
79
+
80
+ const remoteEntry = 'remoteEntry' in snapshot ? snapshot.remoteEntry : '';
81
+ if (!remoteEntry) {
82
+ return;
83
+ }
84
+ return {
85
+ module: targetModule,
86
+ publicPath,
87
+ remoteEntry,
88
+ };
89
+ }
90
+
91
+ export function collectSSRAssets(options: IProps) {
92
+ const {
93
+ id,
94
+ injectLink = true,
95
+ injectScript = false,
96
+ } = typeof options === 'string' ? { id: options } : options;
97
+ const links: React.ReactNode[] = [];
98
+ const scripts: React.ReactNode[] = [];
99
+ const instance = options.instance;
100
+ if (!instance || (!injectLink && !injectScript)) {
101
+ return [...scripts, ...links];
102
+ }
103
+
104
+ const moduleAndPublicPath = getTargetModuleInfo(id, instance);
105
+ if (!moduleAndPublicPath) {
106
+ return [...scripts, ...links];
107
+ }
108
+ const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
109
+ if (injectLink) {
110
+ [...targetModule.assets.css.sync, ...targetModule.assets.css.async]
111
+ .sort()
112
+ .forEach((file, index) => {
113
+ links.push(
114
+ <link
115
+ key={`${file.split('.')[0]}_${index}`}
116
+ href={`${publicPath}${file}`}
117
+ rel="stylesheet"
118
+ type="text/css"
119
+ />,
120
+ );
121
+ });
122
+ }
123
+
124
+ if (injectScript) {
125
+ scripts.push(
126
+ <script
127
+ async={true}
128
+ key={remoteEntry.split('.')[0]}
129
+ src={`${publicPath}${remoteEntry}`}
130
+ crossOrigin="anonymous"
131
+ />,
132
+ );
133
+ [...targetModule.assets.js.sync].sort().forEach((file, index) => {
134
+ scripts.push(
135
+ <script
136
+ key={`${file.split('.')[0]}_${index}`}
137
+ async={true}
138
+ src={`${publicPath}${file}`}
139
+ crossOrigin="anonymous"
140
+ />,
141
+ );
142
+ });
143
+ }
144
+
145
+ return [...scripts, ...links];
146
+ }
147
+
148
+ function getServerNeedRemoteInfo(
149
+ loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>,
150
+ id: string,
151
+ noSSR?: boolean,
152
+ ): NoSSRRemoteInfo | undefined {
153
+ if (
154
+ noSSR ||
155
+ (typeof window !== 'undefined' && window.location.href !== window[FS_HREF])
156
+ ) {
157
+ if (!loadedRemoteInfo?.version) {
158
+ throw new Error(`${loadedRemoteInfo?.name} version is empty`);
159
+ }
160
+ const { snapshot } = loadedRemoteInfo;
161
+ if (!snapshot) {
162
+ throw new Error(`${loadedRemoteInfo?.name} snapshot is empty`);
163
+ }
164
+ const dataFetchItem = getDataFetchItem(id);
165
+ const isFetchServer =
166
+ dataFetchItem?.[0]?.[1] === MF_DATA_FETCH_TYPE.FETCH_SERVER;
167
+
168
+ if (
169
+ isFetchServer &&
170
+ (!('ssrPublicPath' in snapshot) || !snapshot.ssrPublicPath)
171
+ ) {
172
+ throw new Error(
173
+ `ssrPublicPath is required while fetching ${loadedRemoteInfo?.name} data in SSR project!`,
174
+ );
175
+ }
176
+
177
+ if (
178
+ isFetchServer &&
179
+ (!('ssrRemoteEntry' in snapshot) || !snapshot.ssrRemoteEntry)
180
+ ) {
181
+ throw new Error(
182
+ `ssrRemoteEntry is required while loading ${loadedRemoteInfo?.name} data loader in SSR project!`,
183
+ );
184
+ }
185
+
186
+ return {
187
+ name: loadedRemoteInfo.name,
188
+ version: loadedRemoteInfo.version,
189
+ ssrPublicPath:
190
+ 'ssrPublicPath' in snapshot ? snapshot.ssrPublicPath || '' : '',
191
+ ssrRemoteEntry:
192
+ 'ssrRemoteEntry' in snapshot ? snapshot.ssrRemoteEntry || '' : '',
193
+ globalName: loadedRemoteInfo.entryGlobalName,
194
+ };
195
+ }
196
+ return undefined;
197
+ }
198
+
199
+ export function createLazyComponent<T, E extends keyof T>(
200
+ options: CreateLazyComponentOptions<T, E>,
201
+ ) {
202
+ const { instance, cacheData } = options;
203
+ if (!instance) {
204
+ throw new Error('instance is required for createLazyComponent!');
205
+ }
206
+ let dataCache: unknown = null;
207
+
208
+ type ComponentType = T[E] extends (...args: any) => any
209
+ ? Parameters<T[E]>[0] extends undefined
210
+ ? ReactKey
211
+ : Parameters<T[E]>[0] & ReactKey
212
+ : ReactKey;
213
+ const exportName = options?.export || 'default';
214
+
215
+ const callLoader = async () => {
216
+ logger.debug('callLoader start', Date.now());
217
+ const m = (await options.loader()) as Record<string, React.FC> &
218
+ Record<symbol, string>;
219
+ logger.debug('callLoader end', Date.now());
220
+ if (!m) {
221
+ throw new Error('load remote failed');
222
+ }
223
+ return m;
224
+ };
225
+
226
+ const getData = async (noSSR?: boolean) => {
227
+ let loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>;
228
+ let moduleId: string;
229
+ try {
230
+ const m = await callLoader();
231
+ moduleId = m && m[Symbol.for('mf_module_id')];
232
+ if (!moduleId) {
233
+ throw new Error('moduleId is empty');
234
+ }
235
+ loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
236
+ if (!loadedRemoteInfo) {
237
+ throw new Error(`can not find loaded remote('${moduleId}') info!`);
238
+ }
239
+ } catch (e) {
240
+ const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
241
+ logger.debug(e);
242
+ throw new Error(errMsg);
243
+ }
244
+ let dataFetchMapKey: string | undefined;
245
+ try {
246
+ dataFetchMapKey = getDataFetchMapKey(
247
+ getDataFetchInfo({
248
+ name: loadedRemoteInfo.name,
249
+ alias: loadedRemoteInfo.alias,
250
+ id: moduleId,
251
+ remoteSnapshot: loadedRemoteInfo.snapshot,
252
+ }),
253
+ { name: instance.name, version: instance.options.version },
254
+ );
255
+ logger.debug('getData dataFetchMapKey: ', dataFetchMapKey);
256
+ if (!dataFetchMapKey) {
257
+ return;
258
+ }
259
+ const data = await fetchData(
260
+ dataFetchMapKey,
261
+ {
262
+ ...options.dataFetchParams,
263
+ isDowngrade: false,
264
+ },
265
+ getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR),
266
+ );
267
+ setDataFetchItemLoadedStatus(dataFetchMapKey);
268
+ logger.debug('get data res: \n', data);
269
+ dataCache = data;
270
+ return data;
271
+ } catch (err) {
272
+ const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
273
+ logger.debug(errMsg);
274
+ throw new Error(errMsg);
275
+ }
276
+ };
277
+
278
+ const LazyComponent = React.lazy(async () => {
279
+ const m = await callLoader();
280
+ const moduleId = m && m[Symbol.for('mf_module_id')];
281
+ const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
282
+ loadedRemoteInfo?.snapshot;
283
+ const dataFetchMapKey = loadedRemoteInfo
284
+ ? getDataFetchMapKey(
285
+ getDataFetchInfo({
286
+ name: loadedRemoteInfo.name,
287
+ alias: loadedRemoteInfo.alias,
288
+ id: moduleId,
289
+ remoteSnapshot: loadedRemoteInfo.snapshot,
290
+ }),
291
+ { name: instance.name, version: instance?.options.version },
292
+ )
293
+ : undefined;
294
+ logger.debug('LazyComponent dataFetchMapKey: ', dataFetchMapKey);
295
+
296
+ const assets = collectSSRAssets({
297
+ id: moduleId,
298
+ instance,
299
+ });
300
+
301
+ const Com = m[exportName] as React.FC<ComponentType>;
302
+ if (exportName in m && typeof Com === 'function') {
303
+ return {
304
+ default: (props: Omit<ComponentType, 'key'> & { mfData?: unknown }) => (
305
+ <>
306
+ {globalThis.FEDERATION_SSR && dataFetchMapKey && (
307
+ <script
308
+ suppressHydrationWarning
309
+ dangerouslySetInnerHTML={{
310
+ __html: String.raw`
311
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
312
+ globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
313
+ `,
314
+ }}
315
+ ></script>
316
+ )}
317
+ {globalThis.FEDERATION_SSR && assets}
318
+ <Com {...props} />
319
+ </>
320
+ ),
321
+ };
322
+ // eslint-disable-next-line max-lines
323
+ } else {
324
+ throw Error(
325
+ `Make sure that ${moduleId} has the correct export when export is ${String(
326
+ exportName,
327
+ )}`,
328
+ );
329
+ }
330
+ });
331
+
332
+ return (props: ComponentType) => {
333
+ const { key, ...args } = props;
334
+ if (cacheData && dataCache) {
335
+ // @ts-expect-error ignore
336
+ return <LazyComponent {...args} mfData={dataCache} />;
337
+ }
338
+ if (!options.noSSR) {
339
+ return (
340
+ <AwaitDataFetch
341
+ resolve={getData(options.noSSR)}
342
+ loading={options.loading}
343
+ delayLoading={options.delayLoading}
344
+ errorElement={options.fallback}
345
+ >
346
+ {/* @ts-expect-error ignore */}
347
+ {(data) => <LazyComponent {...args} mfData={data} />}
348
+ </AwaitDataFetch>
349
+ );
350
+ } else {
351
+ // Client-side rendering logic
352
+ const [data, setData] = useState<unknown>(null);
353
+ const [loading, setLoading] = useState<boolean>(true);
354
+ const [error, setError] = useState<ErrorInfo | null>(null);
355
+
356
+ useEffect(() => {
357
+ let isMounted = true;
358
+ const fetchDataAsync = async () => {
359
+ try {
360
+ setLoading(true);
361
+ const result = await getData(options.noSSR);
362
+ if (isMounted) {
363
+ setData(result);
364
+ }
365
+ } catch (e) {
366
+ if (isMounted) {
367
+ setError(transformError(e as Error));
368
+ }
369
+ } finally {
370
+ if (isMounted) {
371
+ setLoading(false);
372
+ }
373
+ }
374
+ };
375
+
376
+ fetchDataAsync();
377
+
378
+ return () => {
379
+ isMounted = false;
380
+ };
381
+ }, []);
382
+
383
+ if (loading) {
384
+ return (
385
+ <DelayedLoading delayLoading={options.delayLoading}>
386
+ {options.loading}
387
+ </DelayedLoading>
388
+ );
389
+ }
390
+
391
+ if (error) {
392
+ return (
393
+ <>
394
+ {typeof options.fallback === 'function'
395
+ ? options.fallback(error)
396
+ : options.fallback}
397
+ </>
398
+ );
399
+ }
400
+ // @ts-expect-error ignore
401
+ return <LazyComponent {...args} mfData={data} />;
402
+ }
403
+ };
404
+ }
@@ -0,0 +1,296 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import { getDataFetchCache } from '../utils';
3
+
4
+ import type {
5
+ CacheConfig,
6
+ CacheItem,
7
+ DataFetch,
8
+ DataFetchParams,
9
+ } from '../types';
10
+
11
+ export const CacheSize = {
12
+ KB: 1024,
13
+ MB: 1024 * 1024,
14
+ GB: 1024 * 1024 * 1024,
15
+ } as const;
16
+
17
+ export const CacheTime = {
18
+ SECOND: 1000,
19
+ MINUTE: 60 * 1000,
20
+ HOUR: 60 * 60 * 1000,
21
+ DAY: 24 * 60 * 60 * 1000,
22
+ WEEK: 7 * 24 * 60 * 60 * 1000,
23
+ MONTH: 30 * 24 * 60 * 60 * 1000,
24
+ } as const;
25
+
26
+ export type CacheStatus = 'hit' | 'stale' | 'miss';
27
+
28
+ export interface CacheStatsInfo {
29
+ status: CacheStatus;
30
+ key: string | symbol;
31
+ params: DataFetchParams;
32
+ result: any;
33
+ }
34
+
35
+ interface CacheOptions {
36
+ tag?: string | string[];
37
+ maxAge?: number;
38
+ revalidate?: number;
39
+ getKey?: <Args extends any[]>(...args: Args) => string;
40
+ customKey?: <Args extends any[]>(options: {
41
+ params: Args;
42
+ fn: (...args: Args) => any;
43
+ generatedKey: string;
44
+ }) => string | symbol;
45
+ onCache?: (info: CacheStatsInfo) => boolean;
46
+ }
47
+
48
+ function getTagKeyMap() {
49
+ const dataFetchCache = getDataFetchCache();
50
+ if (!dataFetchCache || !dataFetchCache.tagKeyMap) {
51
+ const tagKeyMap = new Map<string, Set<string>>();
52
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
53
+ globalThis.__MF_DATA_FETCH_CACHE__.tagKeyMap = tagKeyMap;
54
+ return tagKeyMap;
55
+ }
56
+ return dataFetchCache.tagKeyMap;
57
+ }
58
+
59
+ function addTagKeyRelation(tag: string, key: string) {
60
+ const tagKeyMap = getTagKeyMap();
61
+ let keys = tagKeyMap.get(tag);
62
+ if (!keys) {
63
+ keys = new Set();
64
+ tagKeyMap.set(tag, keys);
65
+ }
66
+ keys.add(key);
67
+ }
68
+
69
+ function getCacheConfig() {
70
+ const dataFetchCache = getDataFetchCache();
71
+ if (!dataFetchCache || !dataFetchCache.cacheConfig) {
72
+ const cacheConfig: CacheConfig = {
73
+ maxSize: CacheSize.GB,
74
+ };
75
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
76
+ globalThis.__MF_DATA_FETCH_CACHE__.cacheConfig = cacheConfig;
77
+ return cacheConfig;
78
+ }
79
+ return dataFetchCache.cacheConfig;
80
+ }
81
+
82
+ export function configureCache(config: CacheConfig): void {
83
+ const cacheConfig = getCacheConfig();
84
+ Object.assign(cacheConfig, config);
85
+ }
86
+
87
+ function getLRUCache() {
88
+ const dataFetchCache = getDataFetchCache();
89
+ const cacheConfig = getCacheConfig();
90
+
91
+ if (!dataFetchCache || !dataFetchCache.cacheStore) {
92
+ const cacheStore = new LRUCache<string, Map<string, CacheItem<any>>>({
93
+ maxSize: cacheConfig.maxSize ?? CacheSize.GB,
94
+ sizeCalculation: (value: Map<string, CacheItem<any>>): number => {
95
+ if (!value.size) {
96
+ return 1;
97
+ }
98
+
99
+ let size = 0;
100
+ for (const [k, item] of value.entries()) {
101
+ size += k.length * 2;
102
+ size += estimateObjectSize(item.data);
103
+ size += 8;
104
+ }
105
+ return size;
106
+ },
107
+ updateAgeOnGet: true,
108
+ updateAgeOnHas: true,
109
+ });
110
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
111
+ globalThis.__MF_DATA_FETCH_CACHE__.cacheStore = cacheStore;
112
+ return cacheStore;
113
+ }
114
+
115
+ return dataFetchCache.cacheStore;
116
+ }
117
+
118
+ function estimateObjectSize(data: unknown): number {
119
+ const type = typeof data;
120
+
121
+ if (type === 'number') return 8;
122
+ if (type === 'boolean') return 4;
123
+ if (type === 'string') return Math.max((data as string).length * 2, 1);
124
+ if (data === null || data === undefined) return 1;
125
+
126
+ if (ArrayBuffer.isView(data)) {
127
+ return Math.max(data.byteLength, 1);
128
+ }
129
+
130
+ if (Array.isArray(data)) {
131
+ return Math.max(
132
+ data.reduce((acc, item) => acc + estimateObjectSize(item), 0),
133
+ 1,
134
+ );
135
+ }
136
+
137
+ if (data instanceof Map || data instanceof Set) {
138
+ return 1024;
139
+ }
140
+
141
+ if (data instanceof Date) {
142
+ return 8;
143
+ }
144
+
145
+ if (type === 'object') {
146
+ return Math.max(
147
+ Object.entries(data).reduce(
148
+ (acc, [key, value]) => acc + key.length * 2 + estimateObjectSize(value),
149
+ 0,
150
+ ),
151
+ 1,
152
+ );
153
+ }
154
+
155
+ return 1;
156
+ }
157
+
158
+ export function generateKey(dataFetchOptions: DataFetchParams): string {
159
+ return JSON.stringify(dataFetchOptions, (_, value) => {
160
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
161
+ return Object.keys(value)
162
+ .sort()
163
+ .reduce((result: Record<string, unknown>, key) => {
164
+ result[key] = value[key];
165
+ return result;
166
+ }, {});
167
+ }
168
+ return value;
169
+ });
170
+ }
171
+
172
+ export function cache<T>(
173
+ fn: DataFetch<T>,
174
+ options?: CacheOptions,
175
+ ): DataFetch<T> {
176
+ const {
177
+ tag = 'default',
178
+ maxAge = CacheTime.MINUTE * 5,
179
+ revalidate = 0,
180
+ onCache,
181
+ getKey,
182
+ } = options || {};
183
+
184
+ const tags = Array.isArray(tag) ? tag : [tag];
185
+
186
+ return async (dataFetchOptions) => {
187
+ // if downgrade, skip cache
188
+ if (dataFetchOptions.isDowngrade || !dataFetchOptions._id) {
189
+ return fn(dataFetchOptions);
190
+ }
191
+ const store = getLRUCache();
192
+
193
+ const now = Date.now();
194
+ const storeKey = dataFetchOptions._id;
195
+ const cacheKey = getKey
196
+ ? getKey(dataFetchOptions)
197
+ : generateKey(dataFetchOptions);
198
+
199
+ tags.forEach((t) => addTagKeyRelation(t, cacheKey));
200
+
201
+ let cacheStore = store.get(cacheKey);
202
+ if (!cacheStore) {
203
+ cacheStore = new Map();
204
+ }
205
+
206
+ const cached = cacheStore.get(storeKey);
207
+ if (cached) {
208
+ const age = now - cached.timestamp;
209
+
210
+ if (age < maxAge) {
211
+ if (onCache) {
212
+ const useCache = onCache({
213
+ status: 'hit',
214
+ key: cacheKey,
215
+ params: dataFetchOptions,
216
+ result: cached.data,
217
+ });
218
+ if (!useCache) {
219
+ return fn(dataFetchOptions);
220
+ }
221
+ }
222
+ return cached.data;
223
+ }
224
+
225
+ if (revalidate > 0 && age < maxAge + revalidate) {
226
+ if (onCache) {
227
+ onCache({
228
+ status: 'stale',
229
+ key: cacheKey,
230
+ params: dataFetchOptions,
231
+ result: cached.data,
232
+ });
233
+ }
234
+
235
+ if (!cached.isRevalidating) {
236
+ cached.isRevalidating = true;
237
+ Promise.resolve().then(async () => {
238
+ try {
239
+ const newData = await fn(dataFetchOptions);
240
+ cacheStore!.set(storeKey, {
241
+ data: newData,
242
+ timestamp: Date.now(),
243
+ isRevalidating: false,
244
+ });
245
+
246
+ store.set(cacheKey, cacheStore!);
247
+ } catch (error) {
248
+ cached.isRevalidating = false;
249
+ console.error('Background revalidation failed:', error);
250
+ }
251
+ });
252
+ }
253
+ return cached.data;
254
+ }
255
+ }
256
+
257
+ const data = await fn(dataFetchOptions);
258
+ cacheStore.set(storeKey, {
259
+ data,
260
+ timestamp: now,
261
+ isRevalidating: false,
262
+ });
263
+ store.set(cacheKey, cacheStore);
264
+
265
+ if (onCache) {
266
+ onCache({
267
+ status: 'miss',
268
+ key: cacheKey,
269
+ params: dataFetchOptions,
270
+ result: data,
271
+ });
272
+ }
273
+
274
+ return data;
275
+ };
276
+ }
277
+
278
+ export function revalidateTag(tag: string): void {
279
+ const tagKeyMap = getTagKeyMap();
280
+ const keys = tagKeyMap.get(tag);
281
+ const lruCache = getLRUCache();
282
+ if (keys) {
283
+ keys.forEach((key) => {
284
+ lruCache?.delete(key);
285
+ });
286
+ }
287
+ }
288
+
289
+ export function clearStore(): void {
290
+ const lruCache = getLRUCache();
291
+ const tagKeyMap = getTagKeyMap();
292
+
293
+ lruCache?.clear();
294
+ delete globalThis.__MF_DATA_FETCH_CACHE__?.cacheStore;
295
+ tagKeyMap.clear();
296
+ }
@@ -0,0 +1,13 @@
1
+ import { DATA_FETCH_FUNCTION } from '../constant';
2
+ import { dataFetchFunction } from './inject-data-fetch';
3
+
4
+ export async function callDataFetch() {
5
+ const dataFetch = globalThis[DATA_FETCH_FUNCTION];
6
+ if (dataFetch) {
7
+ await Promise.all(
8
+ dataFetch.map(async (options) => {
9
+ await dataFetchFunction(options);
10
+ }),
11
+ );
12
+ }
13
+ }