@module-federation/data-prefetch 0.0.0-next-20241231075249 → 0.0.0-next-20250106035038

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,216 +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
- import type { Federation } from '@module-federation/runtime';
13
- import { getPrefetchId, compatGetPrefetchId } from './common/runtime-utils';
14
-
15
- // Define an interface that extends Federation to include __PREFETCH__
16
- interface FederationWithPrefetch extends 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
- type PrefetchExports = Record<string, any>;
25
-
26
- export interface DataPrefetchOptions {
27
- name: string;
28
- remote?: Remote;
29
- origin?: FederationHost;
30
- remoteSnapshot?: ModuleInfo;
31
- }
32
-
33
- export interface prefetchOptions {
34
- id: string;
35
- functionId?: string;
36
- cacheStrategy?: () => boolean;
37
- refetchParams?: any;
38
- }
39
-
40
- // @ts-ignore init global variable for test
41
- globalThis.__FEDERATION__ ??= {};
42
- (
43
- globalThis.__FEDERATION__ as unknown as FederationWithPrefetch
44
- ).__PREFETCH__ ??= {
45
- entryLoading: {},
46
- instance: new Map(),
47
- __PREFETCH_EXPORTS__: {},
48
- } as FederationWithPrefetch['__PREFETCH__'];
49
- export class MFDataPrefetch {
50
- public prefetchMemory: Map<string, Promise<any>>;
51
- public recordOutdate: Record<string, Record<string, boolean>>;
52
- private _exports: Record<string, any>;
53
- private _options: DataPrefetchOptions;
54
-
55
- constructor(options: DataPrefetchOptions) {
56
- this.prefetchMemory = new Map();
57
- this.recordOutdate = {};
58
- this._exports = {};
59
- this._options = options;
60
- this.global.instance.set(options.name, this);
61
- }
62
-
63
- get global(): FederationWithPrefetch['__PREFETCH__'] {
64
- return (globalThis.__FEDERATION__ as unknown as FederationWithPrefetch)
65
- .__PREFETCH__;
66
- }
67
-
68
- static getInstance(id: string): MFDataPrefetch | undefined {
69
- return (
70
- globalThis.__FEDERATION__ as unknown as FederationWithPrefetch
71
- ).__PREFETCH__.instance.get(id);
72
- }
73
-
74
- async loadEntry(entry: string | undefined): Promise<any> {
75
- const { name, remoteSnapshot, remote, origin } = this._options;
76
-
77
- if (entry) {
78
- const { buildVersion, globalName } = remoteSnapshot as ProviderModuleInfo;
79
- const uniqueKey = globalName || `${name}:${buildVersion}`;
80
-
81
- if (!this.global.entryLoading[uniqueKey]) {
82
- this.global.entryLoading[uniqueKey] = loadScript(entry, {});
83
- }
84
- return this.global.entryLoading[uniqueKey];
85
- } else {
86
- const remoteInfo = getRemoteInfo(remote as Remote);
87
- const module = origin!.moduleCache.get(remoteInfo.name);
88
- return getRemoteEntry({
89
- origin: origin!,
90
- remoteInfo,
91
- remoteEntryExports: module ? module.remoteEntryExports : undefined,
92
- });
93
- }
94
- }
95
-
96
- getProjectExports() {
97
- if (Object.keys(this._exports).length > 0) {
98
- return this._exports;
99
- }
100
- const { name } = this._options;
101
- const exportsPromiseFn = (
102
- globalThis.__FEDERATION__ as unknown as FederationWithPrefetch
103
- ).__PREFETCH__.__PREFETCH_EXPORTS__?.[name];
104
- const exportsPromise =
105
- typeof exportsPromiseFn === 'function'
106
- ? exportsPromiseFn()
107
- : exportsPromiseFn;
108
- const resolve = exportsPromise.then(
109
- (exports: Record<string, Record<string, any>> = {}) => {
110
- // Match prefetch based on the function name suffix so that other capabilities can be expanded later.
111
- // Not all functions should be directly identified as prefetch functions
112
- const memory: Record<string, Record<string, any>> = {};
113
- Object.keys(exports).forEach((key) => {
114
- memory[key] = {};
115
- const exportVal = exports[key];
116
- Object.keys(exportVal).reduce(
117
- (memo: Record<string, any>, current: string) => {
118
- if (
119
- current.toLocaleLowerCase().endsWith('prefetch') ||
120
- current.toLocaleLowerCase() === 'default'
121
- ) {
122
- memo[current] = exportVal[current];
123
- }
124
- return memo;
125
- },
126
- memory[key],
127
- );
128
- });
129
- this.memorizeExports(memory);
130
- },
131
- );
132
- return resolve;
133
- }
134
-
135
- memorizeExports(exports: Record<string, any>): void {
136
- this._exports = exports;
137
- }
138
-
139
- getExposeExports(id: string): PrefetchExports {
140
- const prefetchId = getPrefetchId(id);
141
- const compatId = compatGetPrefetchId(id);
142
- const prefetchExports =
143
- this._exports[prefetchId] || (this._exports[compatId] as PrefetchExports);
144
- return prefetchExports || {};
145
- }
146
-
147
- prefetch(prefetchOptions: prefetchOptions): any {
148
- const { id, functionId = 'default', refetchParams } = prefetchOptions;
149
- let prefetchResult;
150
- const prefetchId = getPrefetchId(id);
151
- const compatId = compatGetPrefetchId(id);
152
- const memorizeId = id + functionId;
153
- const memory = this.prefetchMemory.get(memorizeId);
154
- if (!this.checkOutdate(prefetchOptions) && memory) {
155
- return memory;
156
- }
157
-
158
- const prefetchExports =
159
- this._exports[prefetchId] || (this._exports[compatId] as PrefetchExports);
160
- if (!prefetchExports) {
161
- return;
162
- }
163
- const executePrefetch = prefetchExports[functionId];
164
- if (typeof executePrefetch === 'function') {
165
- if (refetchParams) {
166
- prefetchResult = executePrefetch(refetchParams);
167
- } else {
168
- prefetchResult = executePrefetch();
169
- }
170
- } else {
171
- throw new Error(
172
- `[Module Federation Data Prefetch]: No prefetch function called ${functionId} export in prefetch file`,
173
- );
174
- }
175
- this.memorize(memorizeId, prefetchResult);
176
- return prefetchResult;
177
- }
178
-
179
- memorize(id: string, value: any): void {
180
- this.prefetchMemory.set(id, value);
181
- }
182
-
183
- markOutdate(
184
- markOptions: Omit<prefetchOptions, 'cacheStrategy'>,
185
- isOutdate: boolean,
186
- ): void {
187
- const { id, functionId = 'default' } = markOptions;
188
- if (!this.recordOutdate[id]) {
189
- this.recordOutdate[id] = {};
190
- }
191
- this.recordOutdate[id][functionId] = isOutdate;
192
- }
193
-
194
- checkOutdate(outdateOptions: prefetchOptions): boolean {
195
- const { id, functionId = 'default', cacheStrategy } = outdateOptions;
196
- if (typeof cacheStrategy === 'function') {
197
- return cacheStrategy();
198
- }
199
-
200
- if (!this.recordOutdate[id]) {
201
- this.recordOutdate[id] = {};
202
- }
203
- if (this.recordOutdate[id][functionId]) {
204
- this.markOutdate(
205
- {
206
- id,
207
- functionId,
208
- },
209
- false,
210
- );
211
- return true;
212
- } else {
213
- return false;
214
- }
215
- }
216
- }
@@ -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
- }