@module-federation/data-prefetch 0.0.0-next-20241230094715 → 0.0.0-next-20250103032148

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.
package/src/prefetch.ts DELETED
@@ -1,211 +0,0 @@
1
- import {
2
- FederationHost,
3
- getRemoteEntry,
4
- getRemoteInfo,
5
- } from '@module-federation/runtime';
6
- import {
7
- loadScript,
8
- ModuleInfo,
9
- ProviderModuleInfo,
10
- } from '@module-federation/sdk';
11
- import { Remote } from '@module-federation/runtime/types';
12
-
13
- import { getPrefetchId, compatGetPrefetchId } from './common/runtime-utils';
14
-
15
- declare module '@module-federation/runtime' {
16
- export interface Federation {
17
- __PREFETCH__: {
18
- entryLoading: Record<string, undefined | Promise<void>>;
19
- instance: Map<string, MFDataPrefetch>;
20
- __PREFETCH_EXPORTS__: Record<string, () => Promise<Record<string, any>>>;
21
- };
22
- }
23
- }
24
-
25
- type PrefetchExports = Record<string, any>;
26
-
27
- export interface DataPrefetchOptions {
28
- name: string;
29
- remote?: Remote;
30
- origin?: FederationHost;
31
- remoteSnapshot?: ModuleInfo;
32
- }
33
-
34
- export interface prefetchOptions {
35
- id: string;
36
- functionId?: string;
37
- cacheStrategy?: () => boolean;
38
- refetchParams?: any;
39
- }
40
-
41
- // @ts-ignore init global variable for test
42
- globalThis.__FEDERATION__ ??= {};
43
- globalThis.__FEDERATION__.__PREFETCH__ ??= {
44
- entryLoading: {},
45
- instance: new Map(),
46
- __PREFETCH_EXPORTS__: {},
47
- };
48
- export class MFDataPrefetch {
49
- public prefetchMemory: Map<string, Promise<any>>;
50
- public recordOutdate: Record<string, Record<string, boolean>>;
51
- private _exports: Record<string, any>;
52
- private _options: DataPrefetchOptions;
53
-
54
- constructor(options: DataPrefetchOptions) {
55
- this.prefetchMemory = new Map();
56
- this.recordOutdate = {};
57
- this._exports = {};
58
- this._options = options;
59
- this.global.instance.set(options.name, this);
60
- }
61
-
62
- get global(): Record<string, any> {
63
- return globalThis.__FEDERATION__.__PREFETCH__;
64
- }
65
-
66
- static getInstance(id: string): MFDataPrefetch | undefined {
67
- return globalThis.__FEDERATION__.__PREFETCH__.instance.get(id);
68
- }
69
-
70
- async loadEntry(entry: string | undefined): Promise<any> {
71
- const { name, remoteSnapshot, remote, origin } = this._options;
72
-
73
- if (entry) {
74
- const { buildVersion, globalName } = remoteSnapshot as ProviderModuleInfo;
75
- const uniqueKey = globalName || `${name}:${buildVersion}`;
76
-
77
- if (!this.global.entryLoading[uniqueKey]) {
78
- this.global.entryLoading[uniqueKey] = loadScript(entry, {});
79
- }
80
- return this.global.entryLoading[uniqueKey];
81
- } else {
82
- const remoteInfo = getRemoteInfo(remote as Remote);
83
- const module = origin!.moduleCache.get(remoteInfo.name);
84
- return getRemoteEntry({
85
- origin: origin!,
86
- remoteInfo,
87
- remoteEntryExports: module ? module.remoteEntryExports : undefined,
88
- });
89
- }
90
- }
91
-
92
- getProjectExports() {
93
- if (Object.keys(this._exports).length > 0) {
94
- return this._exports;
95
- }
96
- const { name } = this._options;
97
- const exportsPromiseFn =
98
- globalThis.__FEDERATION__.__PREFETCH__.__PREFETCH_EXPORTS__?.[name];
99
- const exportsPromise =
100
- typeof exportsPromiseFn === 'function'
101
- ? exportsPromiseFn()
102
- : exportsPromiseFn;
103
- const resolve = exportsPromise.then(
104
- (exports: Record<string, Record<string, any>> = {}) => {
105
- // Match prefetch based on the function name suffix so that other capabilities can be expanded later.
106
- // Not all functions should be directly identified as prefetch functions
107
- const memory: Record<string, Record<string, any>> = {};
108
- Object.keys(exports).forEach((key) => {
109
- memory[key] = {};
110
- const exportVal = exports[key];
111
- Object.keys(exportVal).reduce(
112
- (memo: Record<string, any>, current: string) => {
113
- if (
114
- current.toLocaleLowerCase().endsWith('prefetch') ||
115
- current.toLocaleLowerCase() === 'default'
116
- ) {
117
- memo[current] = exportVal[current];
118
- }
119
- return memo;
120
- },
121
- memory[key],
122
- );
123
- });
124
- this.memorizeExports(memory);
125
- },
126
- );
127
- return resolve;
128
- }
129
-
130
- memorizeExports(exports: Record<string, any>): void {
131
- this._exports = exports;
132
- }
133
-
134
- getExposeExports(id: string): PrefetchExports {
135
- const prefetchId = getPrefetchId(id);
136
- const compatId = compatGetPrefetchId(id);
137
- const prefetchExports =
138
- this._exports[prefetchId] || (this._exports[compatId] as PrefetchExports);
139
- return prefetchExports || {};
140
- }
141
-
142
- prefetch(prefetchOptions: prefetchOptions): any {
143
- const { id, functionId = 'default', refetchParams } = prefetchOptions;
144
- let prefetchResult;
145
- const prefetchId = getPrefetchId(id);
146
- const compatId = compatGetPrefetchId(id);
147
- const memorizeId = id + functionId;
148
- const memory = this.prefetchMemory.get(memorizeId);
149
- if (!this.checkOutdate(prefetchOptions) && memory) {
150
- return memory;
151
- }
152
-
153
- const prefetchExports =
154
- this._exports[prefetchId] || (this._exports[compatId] as PrefetchExports);
155
- if (!prefetchExports) {
156
- return;
157
- }
158
- const executePrefetch = prefetchExports[functionId];
159
- if (typeof executePrefetch === 'function') {
160
- if (refetchParams) {
161
- prefetchResult = executePrefetch(refetchParams);
162
- } else {
163
- prefetchResult = executePrefetch();
164
- }
165
- } else {
166
- throw new Error(
167
- `[Module Federation Data Prefetch]: No prefetch function called ${functionId} export in prefetch file`,
168
- );
169
- }
170
- this.memorize(memorizeId, prefetchResult);
171
- return prefetchResult;
172
- }
173
-
174
- memorize(id: string, value: any): void {
175
- this.prefetchMemory.set(id, value);
176
- }
177
-
178
- markOutdate(
179
- markOptions: Omit<prefetchOptions, 'cacheStrategy'>,
180
- isOutdate: boolean,
181
- ): void {
182
- const { id, functionId = 'default' } = markOptions;
183
- if (!this.recordOutdate[id]) {
184
- this.recordOutdate[id] = {};
185
- }
186
- this.recordOutdate[id][functionId] = isOutdate;
187
- }
188
-
189
- checkOutdate(outdateOptions: prefetchOptions): boolean {
190
- const { id, functionId = 'default', cacheStrategy } = outdateOptions;
191
- if (typeof cacheStrategy === 'function') {
192
- return cacheStrategy();
193
- }
194
-
195
- if (!this.recordOutdate[id]) {
196
- this.recordOutdate[id] = {};
197
- }
198
- if (this.recordOutdate[id][functionId]) {
199
- this.markOutdate(
200
- {
201
- id,
202
- functionId,
203
- },
204
- false,
205
- );
206
- return true;
207
- } else {
208
- return false;
209
- }
210
- }
211
- }
@@ -1,95 +0,0 @@
1
- import { useEffect, useState } from 'react';
2
- import type { defer } from 'react-router';
3
-
4
- import logger from '../logger';
5
- import { MFDataPrefetch, type prefetchOptions } from '../prefetch';
6
- import { prefetch } from '../universal';
7
- import { getScope } from '../common/runtime-utils';
8
- import { useFirstMounted } from './utils';
9
-
10
- type refetchParams = any;
11
- type DeferredData = ReturnType<typeof defer>;
12
- type prefetchReturnType<T> = [
13
- Promise<T>,
14
- (refetchParams?: refetchParams) => void,
15
- ];
16
-
17
- type UsePrefetchOptions = prefetchOptions & {
18
- deferId?: string;
19
- };
20
-
21
- export const usePrefetch = <T>(
22
- options: UsePrefetchOptions,
23
- ): prefetchReturnType<T> => {
24
- const isFirstMounted = useFirstMounted();
25
- if (isFirstMounted) {
26
- const startTiming = performance.now();
27
- logger.info(
28
- `2. Start Get Prefetch Data: ${options.id} - ${
29
- options.functionId || 'default'
30
- } - ${startTiming}`,
31
- );
32
- }
33
- const { id, functionId, deferId } = options;
34
- const prefetchInfo = {
35
- id,
36
- functionId,
37
- };
38
- const mfScope = getScope();
39
-
40
- let state;
41
- const prefetchResult = prefetch(options);
42
- if (deferId) {
43
- if (prefetchResult instanceof Promise) {
44
- state = (prefetchResult as Promise<DeferredData>).then(
45
- (deferredData) => deferredData.data[deferId],
46
- );
47
- } else {
48
- state = (prefetchResult as DeferredData).data[deferId];
49
- }
50
- } else {
51
- state = prefetchResult;
52
- }
53
- const [prefetchState, setPrefetchState] = useState<Promise<T>>(
54
- state as Promise<T>,
55
- );
56
- const prefetchInstance = MFDataPrefetch.getInstance(mfScope);
57
-
58
- useEffect(() => {
59
- const useEffectTiming = performance.now();
60
- logger.info(
61
- `3. Start Execute UseEffect: ${options.id} - ${
62
- options.functionId || 'default'
63
- } - ${useEffectTiming}`,
64
- );
65
-
66
- return () => {
67
- prefetchInstance?.markOutdate(prefetchInfo, true);
68
- };
69
- }, []);
70
-
71
- const refreshExecutor = (refetchParams?: refetchParams) => {
72
- const refetchOptions = {
73
- ...options,
74
- };
75
- if (refetchParams) {
76
- refetchOptions.refetchParams = refetchParams;
77
- }
78
- prefetchInstance?.markOutdate(prefetchInfo, true);
79
- const newVal = prefetch(refetchOptions) as Promise<DeferredData>;
80
- let newState;
81
- if (deferId) {
82
- if (newVal instanceof Promise) {
83
- newState = newVal.then((deferredData) => deferredData.data[deferId]);
84
- } else {
85
- newState = (newVal as DeferredData).data[deferId];
86
- }
87
- } else {
88
- newState = newVal;
89
- }
90
-
91
- setPrefetchState(newState as Promise<T>);
92
- };
93
-
94
- return [prefetchState, refreshExecutor];
95
- };
@@ -1 +0,0 @@
1
- export * from './hooks';
@@ -1,11 +0,0 @@
1
- import { useEffect, useRef } from 'react';
2
-
3
- export const useFirstMounted = (): boolean => {
4
- const ref = useRef(true);
5
-
6
- useEffect(() => {
7
- ref.current = false;
8
- }, []);
9
-
10
- return ref.current;
11
- };
@@ -1,27 +0,0 @@
1
- import { MFDataPrefetch, type prefetchOptions } from '../prefetch';
2
- import { getScope } from '../common/runtime-utils';
3
-
4
- export function prefetch(options: prefetchOptions): Promise<any> {
5
- const { id, functionId = 'default' } = options;
6
- const mfScope = getScope();
7
-
8
- const prefetchInstance =
9
- MFDataPrefetch.getInstance(mfScope) ||
10
- new MFDataPrefetch({
11
- name: mfScope,
12
- });
13
-
14
- const res = prefetchInstance.getProjectExports();
15
- if (res instanceof Promise) {
16
- const promise = res.then(() => {
17
- const result = prefetchInstance!.prefetch(options);
18
- prefetchInstance.memorize(id + functionId, result);
19
- return result;
20
- });
21
- return promise;
22
- } else {
23
- const result = prefetchInstance!.prefetch(options);
24
- prefetchInstance.memorize(id + functionId, result);
25
- return result;
26
- }
27
- }
package/tsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "baseUrl": ".",
4
- "rootDir": "./",
5
- "outDir": "dist",
6
- "sourceMap": false,
7
- "module": "commonjs",
8
- "target": "ES2015",
9
- "skipLibCheck": true,
10
- "moduleResolution": "node",
11
- "allowJs": false,
12
- "strict": true,
13
- "types": ["jest", "node"],
14
- "experimentalDecorators": true,
15
- "resolveJsonModule": true,
16
- "allowSyntheticDefaultImports": true,
17
- "esModuleInterop": true,
18
- "removeComments": true,
19
- "declaration": true,
20
- "paths": {
21
- "@/*": ["./*"],
22
- "@src/*": ["./src/*"]
23
- }
24
- },
25
- "include": ["src", "../../global.d.ts", "__tests__/**/*"],
26
- "exclude": ["node_modules/**/*", "../node_modules"]
27
- }
package/tsconfig.lib.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "../../dist/out-tsc",
5
- "declaration": true,
6
- "types": ["node"]
7
- },
8
- "include": ["src/**/*.ts"],
9
- "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
10
- }