@module-federation/data-prefetch 0.0.0-next-20240617071542 → 0.0.0-next-20240702090143

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/plugin.ts ADDED
@@ -0,0 +1,210 @@
1
+ import { Module } from '@module-federation/runtime';
2
+ import type {
3
+ FederationRuntimePlugin,
4
+ RemoteInfo,
5
+ } from '@module-federation/runtime/types';
6
+ import { ModuleInfo, getResourceUrl } from '@module-federation/sdk';
7
+
8
+ import { getSignalFromManifest } from './common/runtime-utils';
9
+ import { MFDataPrefetch } from './prefetch';
10
+ import logger from './logger';
11
+
12
+ type depsPreloadArg = Omit<PreloadRemoteArgs, 'depsRemote'>;
13
+
14
+ interface PreloadRemoteArgs {
15
+ nameOrAlias: string;
16
+ exposes?: Array<string>;
17
+ resourceCategory?: 'all' | 'sync';
18
+ share?: boolean;
19
+ depsRemote?: boolean | Array<depsPreloadArg>;
20
+ filter?: (assetUrl: string) => boolean;
21
+ prefetchInterface?: boolean;
22
+ }
23
+
24
+ interface Loading {
25
+ id: string;
26
+ promise: Promise<
27
+ Array<{
28
+ value: any;
29
+ functionId: string;
30
+ }>
31
+ >;
32
+ }
33
+ const loadingArray: Array<Loading> = [];
34
+ const strategy = 'loaded-first';
35
+ let sharedFlag = strategy;
36
+ // eslint-disable-next-line max-lines-per-function
37
+ export const prefetchPlugin = (): FederationRuntimePlugin => ({
38
+ name: 'data-prefetch-runtime-plugin',
39
+ initContainer(options) {
40
+ const { remoteSnapshot, remoteInfo, id, origin } = options;
41
+ const snapshot = remoteSnapshot as ModuleInfo;
42
+ const { name } = remoteInfo;
43
+
44
+ const prefetchOptions = {
45
+ name,
46
+ remote: remoteInfo,
47
+ origin,
48
+ remoteSnapshot: snapshot,
49
+ };
50
+ const signal = getSignalFromManifest(snapshot);
51
+ if (!signal) {
52
+ return options;
53
+ }
54
+ if (sharedFlag !== strategy) {
55
+ throw new Error(
56
+ `[Module Federation Data Prefetch]: If you want to use data prefetch, the shared strategy must be 'loaded-first'`,
57
+ );
58
+ }
59
+
60
+ const instance =
61
+ MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
62
+
63
+ let prefetchUrl;
64
+ // @ts-expect-error
65
+ if (snapshot.prefetchEntry) {
66
+ // @ts-expect-error
67
+ prefetchUrl = getResourceUrl(snapshot, snapshot.prefetchEntry as string);
68
+ }
69
+
70
+ const exist = loadingArray.find((loading) => loading.id === id);
71
+ if (exist) {
72
+ return options;
73
+ }
74
+ // @ts-ignore
75
+ const promise = instance.loadEntry(prefetchUrl).then(async () => {
76
+ const projectExports = instance!.getProjectExports();
77
+ if (projectExports instanceof Promise) {
78
+ await projectExports;
79
+ }
80
+ return Promise.resolve().then(() => {
81
+ const exports = instance!.getExposeExports(id);
82
+ logger.info(`1. Start Prefetch: ${id} - ${performance.now()}`);
83
+ const result = Object.keys(exports).map((k) => {
84
+ const value = instance!.prefetch({
85
+ id,
86
+ functionId: k,
87
+ });
88
+ const functionId = k;
89
+
90
+ return {
91
+ value,
92
+ functionId,
93
+ };
94
+ });
95
+ return result;
96
+ });
97
+ });
98
+
99
+ loadingArray.push({
100
+ id,
101
+ promise,
102
+ });
103
+ return options;
104
+ },
105
+
106
+ async onLoad(options) {
107
+ const { remote, id } = options;
108
+ const { name } = remote;
109
+ const promise = loadingArray.find((loading) => loading.id === id)?.promise;
110
+
111
+ if (promise) {
112
+ const prefetch = await promise;
113
+ const prefetchValue = prefetch.map((result) => result.value);
114
+ await Promise.all(prefetchValue);
115
+ const instance = MFDataPrefetch.getInstance(name);
116
+
117
+ prefetch.forEach((result: { value: any; functionId: string }) => {
118
+ const { value, functionId } = result;
119
+ instance!.memorize(id + functionId, value);
120
+ });
121
+ }
122
+ return options;
123
+ },
124
+
125
+ handlePreloadModule(options) {
126
+ const { remoteSnapshot, name, id, preloadConfig, origin, remote } = options;
127
+ const snapshot = remoteSnapshot as ModuleInfo;
128
+
129
+ const signal = getSignalFromManifest(snapshot);
130
+ if (!signal) {
131
+ return options;
132
+ }
133
+
134
+ const prefetchOptions = {
135
+ name,
136
+ origin,
137
+ remote,
138
+ remoteSnapshot: snapshot,
139
+ };
140
+ const instance =
141
+ MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
142
+
143
+ let prefetchUrl;
144
+ // @ts-expect-error
145
+ if (snapshot.prefetchEntry) {
146
+ // @ts-expect-error
147
+ prefetchUrl = getResourceUrl(snapshot, snapshot.prefetchEntry);
148
+ }
149
+
150
+ if (!preloadConfig.prefetchInterface) {
151
+ // @ts-ignore
152
+ instance.loadEntry(prefetchUrl);
153
+ return options;
154
+ }
155
+
156
+ const promise = instance.loadEntry(prefetchUrl).then(async () => {
157
+ let module = origin.moduleCache.get(remote.name);
158
+ const moduleOptions = {
159
+ host: origin,
160
+ remoteInfo: remote as RemoteInfo,
161
+ };
162
+ if (!module) {
163
+ module = new Module(moduleOptions);
164
+ origin.moduleCache.set(remote.name, module);
165
+ }
166
+ const idPart = id.split('/');
167
+ let expose = idPart[idPart.length - 1];
168
+ if (expose !== '.') {
169
+ expose = `./${expose}`;
170
+ }
171
+ await module.get(id, expose, {}, remoteSnapshot);
172
+
173
+ const projectExports = instance!.getProjectExports();
174
+ if (projectExports instanceof Promise) {
175
+ await projectExports;
176
+ }
177
+ const exports = instance!.getExposeExports(id);
178
+ logger.info(
179
+ `1. PreloadRemote Start Prefetch: ${id} - ${performance.now()}`,
180
+ );
181
+ const result = Object.keys(exports).map((k) => {
182
+ const value = instance!.prefetch({
183
+ id,
184
+ functionId: k,
185
+ });
186
+ const functionId = k;
187
+
188
+ return {
189
+ value,
190
+ functionId,
191
+ };
192
+ });
193
+ return result;
194
+ });
195
+
196
+ loadingArray.push({
197
+ id,
198
+ promise,
199
+ });
200
+ return options;
201
+ },
202
+
203
+ beforeLoadShare(options) {
204
+ const shareInfo = options.shareInfo;
205
+ sharedFlag = shareInfo?.strategy || sharedFlag;
206
+ return options;
207
+ },
208
+ });
209
+
210
+ export default prefetchPlugin;
@@ -0,0 +1,210 @@
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 } 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
+ remoteInfo,
86
+ remoteEntryExports: module ? module.remoteEntryExports : undefined,
87
+ createScriptHook: (url: string) => {
88
+ const res = origin!.loaderHook.lifecycle.createScript.emit({
89
+ url,
90
+ });
91
+ if (res instanceof HTMLScriptElement) {
92
+ return res;
93
+ }
94
+ return;
95
+ },
96
+ });
97
+ }
98
+ }
99
+
100
+ getProjectExports() {
101
+ if (Object.keys(this._exports).length > 0) {
102
+ return this._exports;
103
+ }
104
+ const { name } = this._options;
105
+ const exportsPromise =
106
+ globalThis.__FEDERATION__.__PREFETCH__.__PREFETCH_EXPORTS__?.[name];
107
+ const resolve = exportsPromise.then(
108
+ (exports: Record<string, Record<string, any>> = {}) => {
109
+ // 根据函数名后缀匹配 prefetch,以便后续拓展其他能力,不应直接将所有函数都识别为 prefetch 函数
110
+ const memory: Record<string, Record<string, any>> = {};
111
+ Object.keys(exports).forEach((key) => {
112
+ memory[key] = {};
113
+ const exportVal = exports[key];
114
+ Object.keys(exportVal).reduce(
115
+ (memo: Record<string, any>, current: string) => {
116
+ if (
117
+ current.toLocaleLowerCase().endsWith('prefetch') ||
118
+ current.toLocaleLowerCase() === 'default'
119
+ ) {
120
+ memo[current] = exportVal[current];
121
+ }
122
+ return memo;
123
+ },
124
+ memory[key],
125
+ );
126
+ });
127
+ this.memorizeExports(memory);
128
+ },
129
+ );
130
+ return resolve;
131
+ }
132
+
133
+ memorizeExports(exports: Record<string, any>): void {
134
+ this._exports = exports;
135
+ }
136
+
137
+ getExposeExports(id: string): PrefetchExports {
138
+ const prefetchId = getPrefetchId(id);
139
+ const prefetchExports = this._exports[prefetchId] as PrefetchExports;
140
+ return prefetchExports || {};
141
+ }
142
+
143
+ prefetch(prefetchOptions: prefetchOptions): any {
144
+ const { id, functionId = 'default', refetchParams } = prefetchOptions;
145
+ let prefetchResult;
146
+ const prefetchId = getPrefetchId(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 = this._exports[prefetchId] as PrefetchExports;
154
+ if (!prefetchExports) {
155
+ return;
156
+ }
157
+ const executePrefetch = prefetchExports[functionId];
158
+ if (typeof executePrefetch === 'function') {
159
+ if (refetchParams) {
160
+ prefetchResult = executePrefetch(refetchParams);
161
+ } else {
162
+ prefetchResult = executePrefetch();
163
+ }
164
+ } else {
165
+ throw new Error(
166
+ `[Module Federation Data Prefetch]: No prefetch function called ${functionId} export in prefetch file`,
167
+ );
168
+ }
169
+ this.memorize(memorizeId, prefetchResult);
170
+ return prefetchResult;
171
+ }
172
+
173
+ memorize(id: string, value: any): void {
174
+ this.prefetchMemory.set(id, value);
175
+ }
176
+
177
+ markOutdate(
178
+ markOptions: Omit<prefetchOptions, 'cacheStrategy'>,
179
+ isOutdate: boolean,
180
+ ): void {
181
+ const { id, functionId = 'default' } = markOptions;
182
+ if (!this.recordOutdate[id]) {
183
+ this.recordOutdate[id] = {};
184
+ }
185
+ this.recordOutdate[id][functionId] = isOutdate;
186
+ }
187
+
188
+ checkOutdate(outdateOptions: prefetchOptions): boolean {
189
+ const { id, functionId = 'default', cacheStrategy } = outdateOptions;
190
+ if (typeof cacheStrategy === 'function') {
191
+ return cacheStrategy();
192
+ }
193
+
194
+ if (!this.recordOutdate[id]) {
195
+ this.recordOutdate[id] = {};
196
+ }
197
+ if (this.recordOutdate[id][functionId]) {
198
+ this.markOutdate(
199
+ {
200
+ id,
201
+ functionId,
202
+ },
203
+ false,
204
+ );
205
+ return true;
206
+ } else {
207
+ return false;
208
+ }
209
+ }
210
+ }
@@ -0,0 +1,95 @@
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(id);
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
+ };
@@ -0,0 +1 @@
1
+ export * from './hooks';
@@ -0,0 +1,11 @@
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
+ };
@@ -0,0 +1,26 @@
1
+ import type { FederationRuntimePlugin } from '@module-federation/runtime';
2
+
3
+ const sharedStrategy: () => FederationRuntimePlugin = () => ({
4
+ name: 'shared-strategy',
5
+ beforeInit(args) {
6
+ const { userOptions } = args;
7
+ const shared = userOptions.shared;
8
+ if (shared) {
9
+ Object.keys(shared).forEach((sharedKey) => {
10
+ const sharedConfigs = shared[sharedKey];
11
+ const arraySharedConfigs = Array.isArray(sharedConfigs)
12
+ ? sharedConfigs
13
+ : [sharedConfigs];
14
+ arraySharedConfigs.forEach((s) => {
15
+ s.strategy = 'loaded-first';
16
+ });
17
+ });
18
+ console.warn(
19
+ `[Module Federation Data Prefetch]: Your shared strategy is set to 'loaded-first', this is a necessary condition for data prefetch`,
20
+ );
21
+ }
22
+ return args;
23
+ },
24
+ });
25
+
26
+ export default sharedStrategy;
@@ -0,0 +1,27 @@
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 } = options;
6
+ const mfScope = getScope(id);
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/tsup.config.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { replace } from 'esbuild-plugin-replace';
2
+ import minimist from 'minimist';
3
+ import type { Options } from 'tsup';
4
+
5
+ import pkg from './package.json';
6
+
7
+ const args = minimist(process.argv.slice(2));
8
+ const watch = process.env.WATCH;
9
+ const sourceMap = args.sourcemap || args.s;
10
+
11
+ export const tsup: Options = {
12
+ entry: [
13
+ 'src/index.ts',
14
+ 'src/react/index.ts',
15
+ 'src/cli/index.ts',
16
+ 'src/cli/babel.ts',
17
+ 'src/universal/index.ts',
18
+ 'src/plugin.ts',
19
+ 'src/shared/index.ts',
20
+ ],
21
+ sourcemap: sourceMap,
22
+ clean: true,
23
+ dts: true,
24
+ watch: watch ? 'src/' : false,
25
+ format: ['esm', 'cjs'],
26
+ legacyOutput: true,
27
+ esbuildPlugins: [
28
+ replace({
29
+ __VERSION__: `'${pkg.version}'`,
30
+ __DEV__:
31
+ '(typeof process !== "undefined" && process.env && process.env.NODE_ENV ? (process.env.NODE_ENV !== "production") : false)',
32
+ __TEST__: 'false',
33
+ }),
34
+ ],
35
+ };