@module-federation/data-prefetch 1.0.16 → 2.0.0

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 (114) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -1
  3. package/dist/LICENSE +21 -0
  4. package/dist/babel.cjs.cjs +54 -0
  5. package/dist/babel.cjs.cjs.map +1 -0
  6. package/dist/babel.cjs.d.ts +2 -0
  7. package/dist/babel.d.ts +2 -0
  8. package/dist/babel.esm.js +52 -0
  9. package/dist/babel.esm.js.map +1 -0
  10. package/dist/cli.cjs.cjs +156 -0
  11. package/dist/cli.cjs.cjs.map +1 -0
  12. package/dist/cli.cjs.d.ts +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.esm.js +153 -0
  15. package/dist/cli.esm.js.map +1 -0
  16. package/dist/constant.cjs.cjs +6 -0
  17. package/dist/constant.cjs.cjs.map +1 -0
  18. package/dist/constant.esm.js +4 -0
  19. package/dist/constant.esm.js.map +1 -0
  20. package/dist/index.cjs.cjs +10 -0
  21. package/dist/index.cjs.cjs.map +1 -0
  22. package/dist/index.cjs.d.ts +1 -0
  23. package/dist/index.cjs2.cjs +8 -0
  24. package/dist/index.cjs2.cjs.map +1 -0
  25. package/dist/index.d.ts +1 -5
  26. package/dist/index.esm.js +3 -0
  27. package/dist/index.esm.js.map +1 -0
  28. package/dist/index.esm2.js +6 -0
  29. package/dist/index.esm2.js.map +1 -0
  30. package/dist/plugin.cjs.cjs +158 -0
  31. package/dist/plugin.cjs.cjs.map +1 -0
  32. package/dist/plugin.cjs.d.ts +2 -0
  33. package/dist/plugin.d.ts +2 -5
  34. package/dist/plugin.esm.js +153 -0
  35. package/dist/plugin.esm.js.map +1 -0
  36. package/dist/prefetch.cjs.cjs +182 -0
  37. package/dist/prefetch.cjs.cjs.map +1 -0
  38. package/dist/prefetch.esm.js +179 -0
  39. package/dist/prefetch.esm.js.map +1 -0
  40. package/dist/react.cjs.cjs +76 -0
  41. package/dist/react.cjs.cjs.map +1 -0
  42. package/dist/react.cjs.d.ts +1 -0
  43. package/dist/react.d.ts +1 -0
  44. package/dist/react.esm.js +74 -0
  45. package/dist/react.esm.js.map +1 -0
  46. package/dist/runtime-utils.cjs.cjs +29 -0
  47. package/dist/runtime-utils.cjs.cjs.map +1 -0
  48. package/dist/runtime-utils.esm.js +24 -0
  49. package/dist/runtime-utils.esm.js.map +1 -0
  50. package/dist/{cli → src/cli}/babel.d.ts +2 -4
  51. package/dist/{cli → src/cli}/index.d.ts +5 -8
  52. package/dist/src/common/constant.d.ts +1 -0
  53. package/dist/src/common/node-utils.d.ts +2 -0
  54. package/dist/src/common/runtime-utils.d.ts +5 -0
  55. package/dist/src/constant.d.ts +1 -0
  56. package/dist/src/logger/index.d.ts +2 -0
  57. package/dist/src/plugin.d.ts +3 -0
  58. package/dist/{prefetch-4e9646e4.d.ts → src/prefetch.d.ts} +14 -17
  59. package/dist/src/react/hooks.d.ts +11 -0
  60. package/dist/src/react/utils.d.ts +1 -0
  61. package/dist/src/universal/index.d.ts +2 -0
  62. package/dist/universal.cjs.cjs +30 -0
  63. package/dist/universal.cjs.cjs.map +1 -0
  64. package/dist/universal.cjs.d.ts +1 -0
  65. package/dist/universal.d.ts +1 -0
  66. package/dist/universal.esm.js +28 -0
  67. package/dist/universal.esm.js.map +1 -0
  68. package/package.json +49 -39
  69. package/CHANGELOG.md +0 -9
  70. package/__tests__/babel.spec.ts +0 -75
  71. package/__tests__/prefetch.spec.ts +0 -138
  72. package/__tests__/react.spec.ts +0 -119
  73. package/dist/cli/babel.js +0 -84
  74. package/dist/cli/index.js +0 -205
  75. package/dist/esm/chunk-AJPO2B2T.js +0 -30
  76. package/dist/esm/chunk-EZUCZHGV.js +0 -11
  77. package/dist/esm/chunk-ISLXMAIA.js +0 -155
  78. package/dist/esm/chunk-KI4QGPIS.js +0 -32
  79. package/dist/esm/chunk-TTJJJ2WZ.js +0 -7
  80. package/dist/esm/chunk-VVZ6XIM6.js +0 -166
  81. package/dist/esm/cli/babel.js +0 -57
  82. package/dist/esm/cli/index.js +0 -178
  83. package/dist/esm/index.js +0 -13
  84. package/dist/esm/plugin.js +0 -12
  85. package/dist/esm/react/index.js +0 -94
  86. package/dist/esm/shared/index.js +0 -27
  87. package/dist/esm/universal/index.js +0 -9
  88. package/dist/index.js +0 -350
  89. package/dist/plugin.js +0 -346
  90. package/dist/react/index.d.ts +0 -16
  91. package/dist/react/index.js +0 -286
  92. package/dist/shared/index.d.ts +0 -5
  93. package/dist/shared/index.js +0 -48
  94. package/dist/universal/index.d.ts +0 -8
  95. package/dist/universal/index.js +0 -204
  96. package/jest.config.js +0 -29
  97. package/project.json +0 -21
  98. package/src/cli/babel.ts +0 -94
  99. package/src/cli/index.ts +0 -171
  100. package/src/common/constant.ts +0 -1
  101. package/src/common/node-utils.ts +0 -24
  102. package/src/common/runtime-utils.ts +0 -34
  103. package/src/logger/index.ts +0 -3
  104. package/src/plugin.ts +0 -191
  105. package/src/prefetch.ts +0 -207
  106. package/src/react/hooks.ts +0 -95
  107. package/src/react/utils.ts +0 -11
  108. package/src/shared/index.ts +0 -26
  109. package/src/universal/index.ts +0 -27
  110. package/tsconfig.json +0 -27
  111. package/tsup.config.ts +0 -35
  112. /package/{src/common/index.ts → dist/src/common/index.d.ts} +0 -0
  113. /package/{src/index.ts → dist/src/index.d.ts} +0 -0
  114. /package/{src/react/index.ts → dist/src/react/index.d.ts} +0 -0
@@ -1,178 +0,0 @@
1
- import {
2
- getPrefetchId
3
- } from "../chunk-AJPO2B2T.js";
4
- import {
5
- __require
6
- } from "../chunk-EZUCZHGV.js";
7
-
8
- // src/cli/index.ts
9
- import path2 from "path";
10
- import fs2 from "fs-extra";
11
- import {
12
- encodeName,
13
- MFPrefetchCommon
14
- } from "@module-federation/sdk";
15
- import { normalizeWebpackPath } from "@module-federation/sdk/normalize-webpack-path";
16
-
17
- // src/common/constant.ts
18
- var TEMP_DIR = ".mf";
19
-
20
- // src/common/node-utils.ts
21
- import path from "path";
22
- import fs from "fs-extra";
23
- var fileExistsWithCaseSync = (filepath) => {
24
- const dir = path.dirname(filepath);
25
- if (filepath === "/" || filepath === ".") {
26
- return true;
27
- }
28
- const filenames = fs.readdirSync(dir);
29
- if (filenames.indexOf(path.basename(filepath)) === -1) {
30
- return false;
31
- }
32
- return fileExistsWithCaseSync(dir);
33
- };
34
- var fixPrefetchPath = (exposePath) => {
35
- const pathExt = [".js", ".ts"];
36
- const extReg = /\.(ts|js|tsx|jsx)$/;
37
- if (extReg.test(exposePath)) {
38
- return pathExt.map((ext) => exposePath.replace(extReg, `.prefetch${ext}`));
39
- } else {
40
- return pathExt.map((ext) => exposePath + `.prefetch${ext}`);
41
- }
42
- };
43
-
44
- // src/cli/index.ts
45
- var { RuntimeGlobals, Template } = __require(normalizeWebpackPath("webpack"));
46
- function getFederationGlobalScope(runtimeGlobals) {
47
- return `${runtimeGlobals.require || "__webpack_require__"}.federation`;
48
- }
49
- var PrefetchPlugin = class {
50
- constructor(options) {
51
- this.options = options;
52
- this._reWriteExports = "";
53
- }
54
- apply(compiler) {
55
- var _a, _b;
56
- const { name, exposes } = this.options;
57
- if (!exposes) {
58
- return;
59
- }
60
- if (!compiler.options.context) {
61
- throw new Error("compiler.options.context is not defined");
62
- }
63
- const { runtimePlugins } = this.options;
64
- if (!Array.isArray(runtimePlugins)) {
65
- this.options.runtimePlugins = [];
66
- }
67
- const runtimePath = path2.resolve(__dirname, "../esm/plugin.js");
68
- const sharedPath = path2.resolve(__dirname, "../esm/shared/index.js");
69
- if (!((_a = this.options.runtimePlugins) == null ? void 0 : _a.includes(runtimePath))) {
70
- this.options.runtimePlugins.push(runtimePath);
71
- }
72
- if (!((_b = this.options.runtimePlugins) == null ? void 0 : _b.includes(sharedPath))) {
73
- this.options.runtimePlugins.push(sharedPath);
74
- }
75
- const encodedName = encodeName(name);
76
- const asyncEntryPath = path2.resolve(
77
- compiler.options.context,
78
- `node_modules/${TEMP_DIR}/${encodedName}/bootstrap.js`
79
- );
80
- if (fs2.existsSync(asyncEntryPath)) {
81
- fs2.unlinkSync(asyncEntryPath);
82
- }
83
- if (!this.options.dataPrefetch) {
84
- return;
85
- }
86
- const prefetchs = [];
87
- const exposeAlias = Object.keys(exposes);
88
- exposeAlias.forEach((alias) => {
89
- let exposePath;
90
- const exposeValue = exposes[alias];
91
- if (typeof exposeValue === "string") {
92
- exposePath = exposeValue;
93
- } else {
94
- exposePath = exposeValue.import[0];
95
- }
96
- const targetPaths = fixPrefetchPath(exposePath);
97
- for (const pathItem of targetPaths) {
98
- const absolutePath = path2.resolve(compiler.options.context, pathItem);
99
- if (fileExistsWithCaseSync(absolutePath)) {
100
- prefetchs.push(pathItem);
101
- const absoluteAlias = alias.replace(".", "");
102
- this._reWriteExports += `export * as ${getPrefetchId(
103
- `${name}${absoluteAlias}`
104
- )} from '${absolutePath}';
105
- `;
106
- break;
107
- }
108
- }
109
- });
110
- if (!this._reWriteExports) {
111
- return;
112
- }
113
- const tempDirRealPath = path2.resolve(
114
- compiler.options.context,
115
- "node_modules",
116
- TEMP_DIR
117
- );
118
- if (!fs2.existsSync(tempDirRealPath)) {
119
- fs2.mkdirSync(tempDirRealPath);
120
- }
121
- if (!fs2.existsSync(`${tempDirRealPath}/${encodedName}`)) {
122
- fs2.mkdirSync(`${tempDirRealPath}/${encodedName}`);
123
- }
124
- fs2.writeFileSync(asyncEntryPath, this._reWriteExports);
125
- new compiler.webpack.DefinePlugin({
126
- FederationDataPrefetch: JSON.stringify(asyncEntryPath)
127
- }).apply(compiler);
128
- }
129
- static addRuntime(compiler, options) {
130
- const encodedName = encodeName(options.name);
131
- if (!compiler.options.context) {
132
- throw new Error("compiler.options.context is not defined");
133
- }
134
- const prefetchEntry = path2.resolve(
135
- compiler.options.context,
136
- `node_modules/.mf/${encodedName}/bootstrap.js`
137
- );
138
- const federationGlobal = getFederationGlobalScope(
139
- RuntimeGlobals || {}
140
- );
141
- return Template.asString([
142
- fs2.existsSync(prefetchEntry) ? Template.indent([
143
- "function injectPrefetch() {",
144
- `globalThis.__FEDERATION__ = globalThis.__FEDERATION__ || {};`,
145
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}'] = globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}'] || {`,
146
- `entryLoading: {},`,
147
- `instance: new Map(),`,
148
- `__PREFETCH_EXPORTS__: {},`,
149
- `};`,
150
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}'] = globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}'] || {};`,
151
- `globalThis.__FEDERATION__['${MFPrefetchCommon.globalKey}']['${MFPrefetchCommon.exportsKey}']['${options.name}'] = import('${prefetchEntry}');`,
152
- "}",
153
- `${federationGlobal}.prefetch = injectPrefetch`
154
- ]) : "",
155
- Template.indent([
156
- `if(!${federationGlobal}.isMFRemote && ${federationGlobal}.prefetch){`,
157
- `${federationGlobal}.prefetch()`,
158
- "}"
159
- ])
160
- ]);
161
- }
162
- static setRemoteIdentifier() {
163
- const federationGlobal = getFederationGlobalScope(
164
- RuntimeGlobals || {}
165
- );
166
- return Template.indent([`${federationGlobal}.isMFRemote = true;`]);
167
- }
168
- static removeRemoteIdentifier() {
169
- const federationGlobal = getFederationGlobalScope(
170
- RuntimeGlobals || {}
171
- );
172
- return Template.indent([`${federationGlobal}.isMFRemote = false;`]);
173
- }
174
- };
175
- export {
176
- PrefetchPlugin,
177
- getFederationGlobalScope
178
- };
package/dist/esm/index.js DELETED
@@ -1,13 +0,0 @@
1
- import {
2
- prefetchPlugin
3
- } from "./chunk-VVZ6XIM6.js";
4
- import "./chunk-TTJJJ2WZ.js";
5
- import {
6
- MFDataPrefetch
7
- } from "./chunk-ISLXMAIA.js";
8
- import "./chunk-AJPO2B2T.js";
9
- import "./chunk-EZUCZHGV.js";
10
- export {
11
- MFDataPrefetch,
12
- prefetchPlugin
13
- };
@@ -1,12 +0,0 @@
1
- import {
2
- plugin_default,
3
- prefetchPlugin
4
- } from "./chunk-VVZ6XIM6.js";
5
- import "./chunk-TTJJJ2WZ.js";
6
- import "./chunk-ISLXMAIA.js";
7
- import "./chunk-AJPO2B2T.js";
8
- import "./chunk-EZUCZHGV.js";
9
- export {
10
- plugin_default as default,
11
- prefetchPlugin
12
- };
@@ -1,94 +0,0 @@
1
- import {
2
- prefetch
3
- } from "../chunk-KI4QGPIS.js";
4
- import {
5
- logger_default
6
- } from "../chunk-TTJJJ2WZ.js";
7
- import {
8
- MFDataPrefetch
9
- } from "../chunk-ISLXMAIA.js";
10
- import {
11
- getScope
12
- } from "../chunk-AJPO2B2T.js";
13
- import "../chunk-EZUCZHGV.js";
14
-
15
- // src/react/hooks.ts
16
- import { useEffect as useEffect2, useState } from "react";
17
-
18
- // src/react/utils.ts
19
- import { useEffect, useRef } from "react";
20
- var useFirstMounted = () => {
21
- const ref = useRef(true);
22
- useEffect(() => {
23
- ref.current = false;
24
- }, []);
25
- return ref.current;
26
- };
27
-
28
- // src/react/hooks.ts
29
- var usePrefetch = (options) => {
30
- const isFirstMounted = useFirstMounted();
31
- if (isFirstMounted) {
32
- const startTiming = performance.now();
33
- logger_default.info(
34
- `2. Start Get Prefetch Data: ${options.id} - ${options.functionId || "default"} - ${startTiming}`
35
- );
36
- }
37
- const { id, functionId, deferId } = options;
38
- const prefetchInfo = {
39
- id,
40
- functionId
41
- };
42
- const mfScope = getScope();
43
- let state;
44
- const prefetchResult = prefetch(options);
45
- if (deferId) {
46
- if (prefetchResult instanceof Promise) {
47
- state = prefetchResult.then(
48
- (deferredData) => deferredData.data[deferId]
49
- );
50
- } else {
51
- state = prefetchResult.data[deferId];
52
- }
53
- } else {
54
- state = prefetchResult;
55
- }
56
- const [prefetchState, setPrefetchState] = useState(
57
- state
58
- );
59
- const prefetchInstance = MFDataPrefetch.getInstance(mfScope);
60
- useEffect2(() => {
61
- const useEffectTiming = performance.now();
62
- logger_default.info(
63
- `3. Start Execute UseEffect: ${options.id} - ${options.functionId || "default"} - ${useEffectTiming}`
64
- );
65
- return () => {
66
- prefetchInstance == null ? void 0 : prefetchInstance.markOutdate(prefetchInfo, true);
67
- };
68
- }, []);
69
- const refreshExecutor = (refetchParams) => {
70
- const refetchOptions = {
71
- ...options
72
- };
73
- if (refetchParams) {
74
- refetchOptions.refetchParams = refetchParams;
75
- }
76
- prefetchInstance == null ? void 0 : prefetchInstance.markOutdate(prefetchInfo, true);
77
- const newVal = prefetch(refetchOptions);
78
- let newState;
79
- if (deferId) {
80
- if (newVal instanceof Promise) {
81
- newState = newVal.then((deferredData) => deferredData.data[deferId]);
82
- } else {
83
- newState = newVal.data[deferId];
84
- }
85
- } else {
86
- newState = newVal;
87
- }
88
- setPrefetchState(newState);
89
- };
90
- return [prefetchState, refreshExecutor];
91
- };
92
- export {
93
- usePrefetch
94
- };
@@ -1,27 +0,0 @@
1
- import "../chunk-EZUCZHGV.js";
2
-
3
- // src/shared/index.ts
4
- var sharedStrategy = () => ({
5
- name: "shared-strategy",
6
- beforeInit(args) {
7
- const { userOptions } = args;
8
- const shared = userOptions.shared;
9
- if (shared) {
10
- Object.keys(shared).forEach((sharedKey) => {
11
- const sharedConfigs = shared[sharedKey];
12
- const arraySharedConfigs = Array.isArray(sharedConfigs) ? sharedConfigs : [sharedConfigs];
13
- arraySharedConfigs.forEach((s) => {
14
- s.strategy = "loaded-first";
15
- });
16
- });
17
- console.warn(
18
- `[Module Federation Data Prefetch]: Your shared strategy is set to 'loaded-first', this is a necessary condition for data prefetch`
19
- );
20
- }
21
- return args;
22
- }
23
- });
24
- var shared_default = sharedStrategy;
25
- export {
26
- shared_default as default
27
- };
@@ -1,9 +0,0 @@
1
- import {
2
- prefetch
3
- } from "../chunk-KI4QGPIS.js";
4
- import "../chunk-ISLXMAIA.js";
5
- import "../chunk-AJPO2B2T.js";
6
- import "../chunk-EZUCZHGV.js";
7
- export {
8
- prefetch
9
- };
package/dist/index.js DELETED
@@ -1,350 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- MFDataPrefetch: () => MFDataPrefetch,
24
- prefetchPlugin: () => prefetchPlugin
25
- });
26
- module.exports = __toCommonJS(src_exports);
27
-
28
- // src/prefetch.ts
29
- var import_runtime2 = require("@module-federation/runtime");
30
- var import_sdk2 = require("@module-federation/sdk");
31
-
32
- // src/common/runtime-utils.ts
33
- var import_runtime = require("@module-federation/runtime");
34
- var import_sdk = require("@module-federation/sdk");
35
- var getPrefetchId = (id) => (0, import_sdk.encodeName)(`${id}/${import_sdk.MFPrefetchCommon.identifier}`);
36
- var compatGetPrefetchId = (id) => (0, import_sdk.encodeName)(`${id}/VmokPrefetch`);
37
- var getSignalFromManifest = (remoteSnapshot) => {
38
- if (!remoteSnapshot) {
39
- return false;
40
- }
41
- if (!("prefetchEntry" in remoteSnapshot) && !("prefetchInterface" in remoteSnapshot)) {
42
- return false;
43
- }
44
- if (!remoteSnapshot.prefetchEntry && !remoteSnapshot.prefetchInterface) {
45
- return false;
46
- }
47
- return true;
48
- };
49
-
50
- // src/prefetch.ts
51
- globalThis.__FEDERATION__ ?? (globalThis.__FEDERATION__ = {});
52
- var _a;
53
- (_a = globalThis.__FEDERATION__).__PREFETCH__ ?? (_a.__PREFETCH__ = {
54
- entryLoading: {},
55
- instance: /* @__PURE__ */ new Map(),
56
- __PREFETCH_EXPORTS__: {}
57
- });
58
- var MFDataPrefetch = class {
59
- constructor(options) {
60
- this.prefetchMemory = /* @__PURE__ */ new Map();
61
- this.recordOutdate = {};
62
- this._exports = {};
63
- this._options = options;
64
- this.global.instance.set(options.name, this);
65
- }
66
- get global() {
67
- return globalThis.__FEDERATION__.__PREFETCH__;
68
- }
69
- static getInstance(id) {
70
- return globalThis.__FEDERATION__.__PREFETCH__.instance.get(id);
71
- }
72
- async loadEntry(entry) {
73
- const { name, remoteSnapshot, remote, origin } = this._options;
74
- if (entry) {
75
- const { buildVersion, globalName } = remoteSnapshot;
76
- const uniqueKey = globalName || `${name}:${buildVersion}`;
77
- if (!this.global.entryLoading[uniqueKey]) {
78
- this.global.entryLoading[uniqueKey] = (0, import_sdk2.loadScript)(entry, {});
79
- }
80
- return this.global.entryLoading[uniqueKey];
81
- } else {
82
- const remoteInfo = (0, import_runtime2.getRemoteInfo)(remote);
83
- const module2 = origin.moduleCache.get(remoteInfo.name);
84
- return (0, import_runtime2.getRemoteEntry)({
85
- origin,
86
- remoteInfo,
87
- remoteEntryExports: module2 ? module2.remoteEntryExports : void 0
88
- });
89
- }
90
- }
91
- getProjectExports() {
92
- var _a2;
93
- if (Object.keys(this._exports).length > 0) {
94
- return this._exports;
95
- }
96
- const { name } = this._options;
97
- const exportsPromise = (_a2 = globalThis.__FEDERATION__.__PREFETCH__.__PREFETCH_EXPORTS__) == null ? void 0 : _a2[name];
98
- const resolve = exportsPromise.then(
99
- (exports = {}) => {
100
- const memory = {};
101
- Object.keys(exports).forEach((key) => {
102
- memory[key] = {};
103
- const exportVal = exports[key];
104
- Object.keys(exportVal).reduce(
105
- (memo, current) => {
106
- if (current.toLocaleLowerCase().endsWith("prefetch") || current.toLocaleLowerCase() === "default") {
107
- memo[current] = exportVal[current];
108
- }
109
- return memo;
110
- },
111
- memory[key]
112
- );
113
- });
114
- this.memorizeExports(memory);
115
- }
116
- );
117
- return resolve;
118
- }
119
- memorizeExports(exports) {
120
- this._exports = exports;
121
- }
122
- getExposeExports(id) {
123
- const prefetchId = getPrefetchId(id);
124
- const compatId = compatGetPrefetchId(id);
125
- const prefetchExports = this._exports[prefetchId] || this._exports[compatId];
126
- return prefetchExports || {};
127
- }
128
- prefetch(prefetchOptions) {
129
- const { id, functionId = "default", refetchParams } = prefetchOptions;
130
- let prefetchResult;
131
- const prefetchId = getPrefetchId(id);
132
- const compatId = compatGetPrefetchId(id);
133
- const memorizeId = id + functionId;
134
- const memory = this.prefetchMemory.get(memorizeId);
135
- if (!this.checkOutdate(prefetchOptions) && memory) {
136
- return memory;
137
- }
138
- const prefetchExports = this._exports[prefetchId] || this._exports[compatId];
139
- if (!prefetchExports) {
140
- return;
141
- }
142
- const executePrefetch = prefetchExports[functionId];
143
- if (typeof executePrefetch === "function") {
144
- if (refetchParams) {
145
- prefetchResult = executePrefetch(refetchParams);
146
- } else {
147
- prefetchResult = executePrefetch();
148
- }
149
- } else {
150
- throw new Error(
151
- `[Module Federation Data Prefetch]: No prefetch function called ${functionId} export in prefetch file`
152
- );
153
- }
154
- this.memorize(memorizeId, prefetchResult);
155
- return prefetchResult;
156
- }
157
- memorize(id, value) {
158
- this.prefetchMemory.set(id, value);
159
- }
160
- markOutdate(markOptions, isOutdate) {
161
- const { id, functionId = "default" } = markOptions;
162
- if (!this.recordOutdate[id]) {
163
- this.recordOutdate[id] = {};
164
- }
165
- this.recordOutdate[id][functionId] = isOutdate;
166
- }
167
- checkOutdate(outdateOptions) {
168
- const { id, functionId = "default", cacheStrategy } = outdateOptions;
169
- if (typeof cacheStrategy === "function") {
170
- return cacheStrategy();
171
- }
172
- if (!this.recordOutdate[id]) {
173
- this.recordOutdate[id] = {};
174
- }
175
- if (this.recordOutdate[id][functionId]) {
176
- this.markOutdate(
177
- {
178
- id,
179
- functionId
180
- },
181
- false
182
- );
183
- return true;
184
- } else {
185
- return false;
186
- }
187
- }
188
- };
189
-
190
- // src/plugin.ts
191
- var import_sdk4 = require("@module-federation/sdk");
192
-
193
- // src/logger/index.ts
194
- var import_sdk3 = require("@module-federation/sdk");
195
- var logger_default = new import_sdk3.Logger("[Module Federation Data Prefetch]");
196
-
197
- // src/plugin.ts
198
- var loadingArray = [];
199
- var strategy = "loaded-first";
200
- var sharedFlag = strategy;
201
- var prefetchPlugin = () => ({
202
- name: "data-prefetch-runtime-plugin",
203
- initContainer(options) {
204
- const { remoteSnapshot, remoteInfo, id, origin } = options;
205
- const snapshot = remoteSnapshot;
206
- const { name } = remoteInfo;
207
- const prefetchOptions = {
208
- name,
209
- remote: remoteInfo,
210
- origin,
211
- remoteSnapshot: snapshot
212
- };
213
- const signal = getSignalFromManifest(snapshot);
214
- if (!signal) {
215
- return options;
216
- }
217
- if (sharedFlag !== strategy) {
218
- throw new Error(
219
- `[Module Federation Data Prefetch]: If you want to use data prefetch, the shared strategy must be 'loaded-first'`
220
- );
221
- }
222
- const instance = MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
223
- let prefetchUrl;
224
- if (snapshot.prefetchEntry) {
225
- prefetchUrl = (0, import_sdk4.getResourceUrl)(snapshot, snapshot.prefetchEntry);
226
- }
227
- const exist = loadingArray.find((loading) => loading.id === id);
228
- if (exist) {
229
- return options;
230
- }
231
- const promise = instance.loadEntry(prefetchUrl).then(async () => {
232
- const projectExports = instance.getProjectExports();
233
- if (projectExports instanceof Promise) {
234
- await projectExports;
235
- }
236
- return Promise.resolve().then(() => {
237
- const exports = instance.getExposeExports(id);
238
- logger_default.info(
239
- `1. Start Prefetch initContainer: ${id} - ${performance.now()}`
240
- );
241
- const result = Object.keys(exports).map((k) => {
242
- const value = instance.prefetch({
243
- id,
244
- functionId: k
245
- });
246
- const functionId = k;
247
- return {
248
- value,
249
- functionId
250
- };
251
- });
252
- return result;
253
- });
254
- });
255
- loadingArray.push({
256
- id,
257
- promise
258
- });
259
- return options;
260
- },
261
- afterResolve(options) {
262
- const { remoteSnapshot, remoteInfo, id, origin } = options;
263
- const snapshot = remoteSnapshot;
264
- const { name } = remoteInfo;
265
- const prefetchOptions = {
266
- name,
267
- remote: remoteInfo,
268
- origin,
269
- remoteSnapshot: snapshot
270
- };
271
- const signal = getSignalFromManifest(snapshot);
272
- if (!signal) {
273
- return options;
274
- }
275
- const inited = loadingArray.some((info) => info.id === id);
276
- if (!inited) {
277
- return options;
278
- }
279
- if (sharedFlag !== strategy) {
280
- throw new Error(
281
- `[Module Federation Data Prefetch]: If you want to use data prefetch, the shared strategy must be 'loaded-first'`
282
- );
283
- }
284
- const instance = MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
285
- let prefetchUrl;
286
- if (snapshot.prefetchEntry) {
287
- prefetchUrl = (0, import_sdk4.getResourceUrl)(snapshot, snapshot.prefetchEntry);
288
- }
289
- const index = loadingArray.findIndex((loading) => loading.id === id);
290
- if (index !== -1) {
291
- loadingArray.splice(index, 1);
292
- }
293
- const promise = instance.loadEntry(prefetchUrl).then(async () => {
294
- const projectExports = instance.getProjectExports();
295
- if (projectExports instanceof Promise) {
296
- await projectExports;
297
- }
298
- return Promise.resolve().then(() => {
299
- const exports = instance.getExposeExports(id);
300
- logger_default.info(
301
- `1. Start Prefetch afterResolve: ${id} - ${performance.now()}`
302
- );
303
- const result = Object.keys(exports).map((k) => {
304
- const value = instance.prefetch({
305
- id,
306
- functionId: k
307
- });
308
- const functionId = k;
309
- return {
310
- value,
311
- functionId
312
- };
313
- });
314
- return result;
315
- });
316
- });
317
- loadingArray.push({
318
- id,
319
- promise
320
- });
321
- return options;
322
- },
323
- async onLoad(options) {
324
- var _a2;
325
- const { remote, id } = options;
326
- const { name } = remote;
327
- const promise = (_a2 = loadingArray.find((loading) => loading.id === id)) == null ? void 0 : _a2.promise;
328
- if (promise) {
329
- const prefetch = await promise;
330
- const prefetchValue = prefetch.map((result) => result.value);
331
- await Promise.all(prefetchValue);
332
- const instance = MFDataPrefetch.getInstance(name);
333
- prefetch.forEach((result) => {
334
- const { value, functionId } = result;
335
- instance.memorize(id + functionId, value);
336
- });
337
- }
338
- return options;
339
- },
340
- beforeLoadShare(options) {
341
- const shareInfo = options.shareInfo;
342
- sharedFlag = (shareInfo == null ? void 0 : shareInfo.strategy) || sharedFlag;
343
- return options;
344
- }
345
- });
346
- // Annotate the CommonJS export names for ESM import in node:
347
- 0 && (module.exports = {
348
- MFDataPrefetch,
349
- prefetchPlugin
350
- });