@module-federation/modern-js 0.0.0-next-20250613163655 → 0.0.0-next-20250616091910

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 (90) hide show
  1. package/dist/LICENSE +21 -0
  2. package/dist/cjs/cli/configPlugin.js +381 -0
  3. package/dist/cjs/cli/configPlugin.spec.js +114 -0
  4. package/dist/cjs/cli/index.js +95 -0
  5. package/dist/cjs/cli/mfRuntimePlugins/inject-node-fetch.js +44 -0
  6. package/dist/cjs/cli/mfRuntimePlugins/resolve-entry-ipv4.js +82 -0
  7. package/dist/cjs/cli/mfRuntimePlugins/shared-strategy.js +43 -0
  8. package/dist/cjs/cli/server/data-fetch-server-plugin.js +188 -0
  9. package/dist/cjs/cli/ssrPlugin.js +236 -0
  10. package/dist/cjs/cli/utils.js +90 -0
  11. package/dist/cjs/constant.js +31 -0
  12. package/dist/cjs/interfaces/bundler.js +16 -0
  13. package/dist/cjs/logger.js +27 -0
  14. package/dist/cjs/runtime/index.js +33 -0
  15. package/dist/cjs/server/fileCache.js +84 -0
  16. package/dist/cjs/server/fileCache.spec.js +28 -0
  17. package/dist/cjs/server/index.js +58 -0
  18. package/dist/cjs/server/staticMiddleware.js +77 -0
  19. package/dist/cjs/server/staticMiddleware.spec.js +185 -0
  20. package/dist/cjs/ssr-runtime/SSRLiveReload.js +43 -0
  21. package/dist/cjs/ssr-runtime/devPlugin.js +71 -0
  22. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +41 -0
  23. package/dist/cjs/types/index.js +16 -0
  24. package/dist/esm/cli/configPlugin.js +388 -0
  25. package/dist/esm/cli/configPlugin.spec.js +110 -0
  26. package/dist/esm/cli/index.js +90 -0
  27. package/dist/esm/cli/mfRuntimePlugins/inject-node-fetch.js +16 -0
  28. package/dist/esm/cli/mfRuntimePlugins/resolve-entry-ipv4.js +74 -0
  29. package/dist/esm/cli/mfRuntimePlugins/shared-strategy.js +25 -0
  30. package/dist/esm/cli/server/data-fetch-server-plugin.js +236 -0
  31. package/dist/esm/cli/ssrPlugin.js +219 -0
  32. package/dist/esm/cli/utils.js +53 -0
  33. package/dist/esm/constant.js +6 -0
  34. package/dist/esm/interfaces/bundler.js +0 -0
  35. package/dist/esm/logger.js +7 -0
  36. package/dist/esm/runtime/index.js +6 -0
  37. package/dist/esm/server/fileCache.js +98 -0
  38. package/dist/esm/server/fileCache.spec.js +50 -0
  39. package/dist/esm/server/index.js +36 -0
  40. package/dist/esm/server/staticMiddleware.js +81 -0
  41. package/dist/esm/server/staticMiddleware.spec.js +328 -0
  42. package/dist/esm/ssr-runtime/SSRLiveReload.js +26 -0
  43. package/dist/esm/ssr-runtime/devPlugin.js +73 -0
  44. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +35 -0
  45. package/dist/esm/types/index.js +0 -0
  46. package/dist/esm-node/cli/configPlugin.js +340 -0
  47. package/dist/esm-node/cli/configPlugin.spec.js +91 -0
  48. package/dist/esm-node/cli/index.js +70 -0
  49. package/dist/esm-node/cli/mfRuntimePlugins/inject-node-fetch.js +14 -0
  50. package/dist/esm-node/cli/mfRuntimePlugins/resolve-entry-ipv4.js +62 -0
  51. package/dist/esm-node/cli/mfRuntimePlugins/shared-strategy.js +23 -0
  52. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +158 -0
  53. package/dist/esm-node/cli/ssrPlugin.js +200 -0
  54. package/dist/esm-node/cli/utils.js +53 -0
  55. package/dist/esm-node/constant.js +6 -0
  56. package/dist/esm-node/interfaces/bundler.js +0 -0
  57. package/dist/esm-node/logger.js +7 -0
  58. package/dist/esm-node/runtime/index.js +6 -0
  59. package/dist/esm-node/server/fileCache.js +49 -0
  60. package/dist/esm-node/server/fileCache.spec.js +27 -0
  61. package/dist/esm-node/server/index.js +34 -0
  62. package/dist/esm-node/server/staticMiddleware.js +43 -0
  63. package/dist/esm-node/server/staticMiddleware.spec.js +162 -0
  64. package/dist/esm-node/ssr-runtime/SSRLiveReload.js +19 -0
  65. package/dist/esm-node/ssr-runtime/devPlugin.js +37 -0
  66. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +17 -0
  67. package/dist/esm-node/types/index.js +0 -0
  68. package/dist/types/cli/configPlugin.d.ts +21 -0
  69. package/dist/types/cli/configPlugin.spec.d.ts +1 -0
  70. package/dist/types/cli/index.d.ts +6 -0
  71. package/dist/types/cli/mfRuntimePlugins/inject-node-fetch.d.ts +3 -0
  72. package/dist/types/cli/mfRuntimePlugins/resolve-entry-ipv4.d.ts +3 -0
  73. package/dist/types/cli/mfRuntimePlugins/shared-strategy.d.ts +3 -0
  74. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +3 -0
  75. package/dist/types/cli/ssrPlugin.d.ts +6 -0
  76. package/dist/types/cli/utils.d.ts +6 -0
  77. package/dist/types/constant.d.ts +2 -0
  78. package/dist/types/interfaces/bundler.d.ts +18 -0
  79. package/dist/types/logger.d.ts +2 -0
  80. package/dist/types/runtime/index.d.ts +3 -0
  81. package/dist/types/server/fileCache.d.ts +14 -0
  82. package/dist/types/server/fileCache.spec.d.ts +1 -0
  83. package/dist/types/server/index.d.ts +4 -0
  84. package/dist/types/server/staticMiddleware.d.ts +6 -0
  85. package/dist/types/server/staticMiddleware.spec.d.ts +1 -0
  86. package/dist/types/ssr-runtime/SSRLiveReload.d.ts +1 -0
  87. package/dist/types/ssr-runtime/devPlugin.d.ts +2 -0
  88. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +4 -0
  89. package/dist/types/types/index.d.ts +24 -0
  90. package/package.json +9 -16
@@ -0,0 +1,158 @@
1
+ import { DATA_FETCH_QUERY, MF_DATA_FETCH_STATUS } from "@module-federation/bridge-react/data-fetch-constant";
2
+ import { getDataFetchMap, fetchData, initDataFetchMap, loadDataFetchModule } from "@module-federation/bridge-react/data-fetch-utils";
3
+ import { SEPARATOR, MANIFEST_EXT } from "@module-federation/sdk";
4
+ import logger from "../../logger";
5
+ function wrapSetTimeout(targetPromise, delay = 2e4, id) {
6
+ if (targetPromise && typeof targetPromise.then === "function") {
7
+ return new Promise((resolve, reject) => {
8
+ const timeoutId = setTimeout(() => {
9
+ logger.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
10
+ reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
11
+ }, delay);
12
+ targetPromise.then((value) => {
13
+ clearTimeout(timeoutId);
14
+ resolve(value);
15
+ }).catch((err) => {
16
+ clearTimeout(timeoutId);
17
+ reject(err);
18
+ });
19
+ });
20
+ }
21
+ }
22
+ function addProtocol(url) {
23
+ if (url.startsWith("//")) {
24
+ return "https:" + url;
25
+ }
26
+ return url;
27
+ }
28
+ const getDecodeQuery = (url, name) => {
29
+ const res = url.searchParams.get(name);
30
+ if (!res) {
31
+ return null;
32
+ }
33
+ return decodeURIComponent(res);
34
+ };
35
+ const middleware = async (ctx, next) => {
36
+ var _globalThis___FEDERATION__;
37
+ let url;
38
+ let dataFetchId;
39
+ let params;
40
+ let remoteInfo;
41
+ try {
42
+ url = new URL(ctx.req.url);
43
+ dataFetchId = getDecodeQuery(url, DATA_FETCH_QUERY);
44
+ params = JSON.parse(getDecodeQuery(url, "params") || "{}");
45
+ const remoteInfoQuery = getDecodeQuery(url, "remoteInfo");
46
+ remoteInfo = remoteInfoQuery ? JSON.parse(remoteInfoQuery) : null;
47
+ } catch (e) {
48
+ logger.error("fetch data from server, error: ", e);
49
+ return next();
50
+ }
51
+ if (!dataFetchId) {
52
+ return next();
53
+ }
54
+ logger.log("fetch data from server, dataFetchId: ", dataFetchId);
55
+ logger.debug("fetch data from server, moduleInfo: ", (_globalThis___FEDERATION__ = globalThis.__FEDERATION__) === null || _globalThis___FEDERATION__ === void 0 ? void 0 : _globalThis___FEDERATION__.moduleInfo);
56
+ try {
57
+ var _dataFetchMap_dataFetchId, _dataFetchMap_dataFetchId1;
58
+ const dataFetchMap = getDataFetchMap();
59
+ if (!dataFetchMap) {
60
+ initDataFetchMap();
61
+ }
62
+ const fetchDataPromise = (_dataFetchMap_dataFetchId = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId === void 0 ? void 0 : _dataFetchMap_dataFetchId[1];
63
+ logger.debug("fetch data from server, fetchDataPromise: ", fetchDataPromise);
64
+ if (fetchDataPromise && ((_dataFetchMap_dataFetchId1 = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId1 === void 0 ? void 0 : _dataFetchMap_dataFetchId1[2]) !== MF_DATA_FETCH_STATUS.ERROR) {
65
+ const targetPromise = fetchDataPromise[0];
66
+ const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
67
+ if (wrappedPromise) {
68
+ const res = await wrappedPromise;
69
+ logger.log("fetch data from server, fetchDataPromise res: ", res);
70
+ return ctx.json(res);
71
+ }
72
+ logger.error(`Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`, targetPromise, "Will try call new dataFetch again...");
73
+ }
74
+ if (remoteInfo) {
75
+ try {
76
+ const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
77
+ const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
78
+ if (!hostInstance2) {
79
+ throw new Error("host instance not found!");
80
+ }
81
+ const remote = hostInstance2.options.remotes.find((remote2) => remote2.name === remoteInfo.name);
82
+ logger.debug("find remote: ", JSON.stringify(remote));
83
+ if (!remote) {
84
+ hostInstance2.registerRemotes([
85
+ {
86
+ name: remoteInfo.name,
87
+ entry: remoteEntry,
88
+ entryGlobalName: remoteInfo.globalName
89
+ }
90
+ ]);
91
+ } else if (!("entry" in remote) || !remote.entry.includes(MANIFEST_EXT)) {
92
+ const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
93
+ logger.debug("find hostGlobalSnapshot: ", JSON.stringify(hostGlobalSnapshot));
94
+ logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
95
+ if (!hostGlobalSnapshot || !remoteSnapshot) {
96
+ if ("version" in remote) {
97
+ delete remote.version;
98
+ }
99
+ remote.entry = remoteEntry;
100
+ remote.entryGlobalName = remoteInfo.globalName;
101
+ }
102
+ }
103
+ } catch (e) {
104
+ ctx.status(500);
105
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
106
+ ${e}`);
107
+ }
108
+ }
109
+ const dataFetchItem = dataFetchMap[dataFetchId];
110
+ logger.debug("fetch data from server, dataFetchItem: ", dataFetchItem);
111
+ if (dataFetchItem) {
112
+ const callFetchDataPromise = fetchData(dataFetchId, {
113
+ ...params,
114
+ isDowngrade: !remoteInfo
115
+ });
116
+ const wrappedPromise = wrapSetTimeout(callFetchDataPromise, 2e4, dataFetchId);
117
+ if (wrappedPromise) {
118
+ const res = await wrappedPromise;
119
+ logger.log("fetch data from server, dataFetchItem res: ", res);
120
+ return ctx.json(res);
121
+ }
122
+ }
123
+ const remoteId = dataFetchId.split(SEPARATOR)[0];
124
+ const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
125
+ if (!hostInstance) {
126
+ throw new Error("host instance not found!");
127
+ }
128
+ const dataFetchFn = await loadDataFetchModule(hostInstance, remoteId);
129
+ const data = await dataFetchFn({
130
+ ...params,
131
+ isDowngrade: !remoteInfo
132
+ });
133
+ logger.log("fetch data from server, loadDataFetchModule res: ", data);
134
+ return ctx.json(data);
135
+ } catch (e) {
136
+ logger.error("server plugin data fetch error: ", e);
137
+ ctx.status(500);
138
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
139
+ ${e}`);
140
+ }
141
+ };
142
+ const dataFetchServePlugin = () => ({
143
+ name: "mf-data-fetch-server-plugin",
144
+ setup: (api) => {
145
+ api.onPrepare(() => {
146
+ const { middlewares } = api.getServerContext();
147
+ middlewares.push({
148
+ name: "module-federation-serve-manifest",
149
+ // @ts-ignore type error
150
+ handler: middleware
151
+ });
152
+ });
153
+ }
154
+ });
155
+ var data_fetch_server_plugin_default = dataFetchServePlugin;
156
+ export {
157
+ data_fetch_server_plugin_default as default
158
+ };
@@ -0,0 +1,200 @@
1
+ import path from "path";
2
+ import fs from "fs-extra";
3
+ import { ModuleFederationPlugin } from "@module-federation/enhanced/webpack";
4
+ import { ModuleFederationPlugin as RspackModuleFederationPlugin } from "@module-federation/enhanced/rspack";
5
+ import UniverseEntryChunkTrackerPlugin from "@module-federation/node/universe-entry-chunk-tracker-plugin";
6
+ import logger from "../logger";
7
+ import { isDev } from "./utils";
8
+ import { updateStatsAndManifest } from "@module-federation/rsbuild-plugin/manifest";
9
+ import { isWebTarget, skipByTarget } from "./utils";
10
+ function setEnv() {
11
+ process.env["MF_DISABLE_EMIT_STATS"] = "true";
12
+ process.env["MF_SSR_PRJ"] = "true";
13
+ }
14
+ const CHAIN_MF_PLUGIN_ID = "plugin-module-federation-server";
15
+ const mfSSRRsbuildPlugin = (pluginOptions) => {
16
+ return {
17
+ name: "@modern-js/plugin-mf-post-config",
18
+ pre: [
19
+ "@modern-js/builder-plugin-ssr"
20
+ ],
21
+ setup(api) {
22
+ if (pluginOptions.csrConfig.getPublicPath) {
23
+ return;
24
+ }
25
+ let csrOutputPath = "";
26
+ let ssrOutputPath = "";
27
+ let ssrEnv = "";
28
+ api.modifyEnvironmentConfig((config, { name }) => {
29
+ const target = config.output.target;
30
+ if (skipByTarget(target)) {
31
+ return config;
32
+ }
33
+ if (isWebTarget(target)) {
34
+ csrOutputPath = config.output.distPath.root;
35
+ } else {
36
+ ssrOutputPath = config.output.distPath.root;
37
+ ssrEnv = name;
38
+ }
39
+ return config;
40
+ });
41
+ const modifySSRPublicPath = (config, utils) => {
42
+ if (ssrEnv !== utils.environment.name) {
43
+ return config;
44
+ }
45
+ const userSSRConfig = pluginOptions.userConfig.ssr ? typeof pluginOptions.userConfig.ssr === "object" ? pluginOptions.userConfig.ssr : {} : {};
46
+ if (userSSRConfig.distOutputDir) {
47
+ return;
48
+ }
49
+ config.output.publicPath = `${config.output.publicPath}${path.relative(csrOutputPath, ssrOutputPath)}/`;
50
+ return config;
51
+ };
52
+ api.modifyWebpackConfig((config, utils) => {
53
+ modifySSRPublicPath(config, utils);
54
+ return config;
55
+ });
56
+ api.modifyRspackConfig((config, utils) => {
57
+ modifySSRPublicPath(config, utils);
58
+ return config;
59
+ });
60
+ }
61
+ };
62
+ };
63
+ const moduleFederationSSRPlugin = (pluginOptions) => ({
64
+ name: "@modern-js/plugin-module-federation-ssr",
65
+ pre: [
66
+ "@modern-js/plugin-module-federation-config",
67
+ "@modern-js/plugin-module-federation"
68
+ ],
69
+ setup: async (api) => {
70
+ var _pluginOptions_userConfig, _modernjsConfig_server;
71
+ const modernjsConfig = api.getConfig();
72
+ var _pluginOptions_userConfig_ssr;
73
+ const enableSSR = (_pluginOptions_userConfig_ssr = (_pluginOptions_userConfig = pluginOptions.userConfig) === null || _pluginOptions_userConfig === void 0 ? void 0 : _pluginOptions_userConfig.ssr) !== null && _pluginOptions_userConfig_ssr !== void 0 ? _pluginOptions_userConfig_ssr : Boolean(modernjsConfig === null || modernjsConfig === void 0 ? void 0 : (_modernjsConfig_server = modernjsConfig.server) === null || _modernjsConfig_server === void 0 ? void 0 : _modernjsConfig_server.ssr);
74
+ if (!enableSSR) {
75
+ return;
76
+ }
77
+ setEnv();
78
+ api._internalRuntimePlugins(({ entrypoint, plugins }) => {
79
+ const { fetchServerQuery } = pluginOptions;
80
+ plugins.push({
81
+ name: "injectDataFetchFunction",
82
+ path: "@module-federation/modern-js/ssr-inject-data-fetch-function-plugin",
83
+ config: {
84
+ fetchServerQuery
85
+ }
86
+ });
87
+ if (!isDev()) {
88
+ return {
89
+ entrypoint,
90
+ plugins
91
+ };
92
+ }
93
+ plugins.push({
94
+ name: "mfSSRDev",
95
+ path: "@module-federation/modern-js/ssr-dev-plugin",
96
+ config: {}
97
+ });
98
+ return {
99
+ entrypoint,
100
+ plugins
101
+ };
102
+ });
103
+ if (pluginOptions.ssrConfig.remotes) {
104
+ api._internalServerPlugins(({ plugins }) => {
105
+ plugins.push({
106
+ name: "@module-federation/modern-js/data-fetch-server-plugin",
107
+ options: {}
108
+ });
109
+ return {
110
+ plugins
111
+ };
112
+ });
113
+ }
114
+ api.modifyBundlerChain((chain) => {
115
+ const target = chain.get("target");
116
+ if (skipByTarget(target)) {
117
+ return;
118
+ }
119
+ const bundlerType = api.getAppContext().bundlerType === "rspack" ? "rspack" : "webpack";
120
+ const MFPlugin = bundlerType === "webpack" ? ModuleFederationPlugin : RspackModuleFederationPlugin;
121
+ const isWeb = isWebTarget(target);
122
+ if (!isWeb) {
123
+ if (!chain.plugins.has(CHAIN_MF_PLUGIN_ID)) {
124
+ chain.plugin(CHAIN_MF_PLUGIN_ID).use(MFPlugin, [
125
+ pluginOptions.ssrConfig
126
+ ]).init((Plugin, args) => {
127
+ pluginOptions.nodePlugin = new Plugin(args[0]);
128
+ return pluginOptions.nodePlugin;
129
+ });
130
+ }
131
+ }
132
+ if (!isWeb) {
133
+ chain.target("async-node");
134
+ if (isDev()) {
135
+ chain.plugin("UniverseEntryChunkTrackerPlugin").use(UniverseEntryChunkTrackerPlugin);
136
+ }
137
+ const userSSRConfig = pluginOptions.userConfig.ssr ? typeof pluginOptions.userConfig.ssr === "object" ? pluginOptions.userConfig.ssr : {} : {};
138
+ const publicPath = chain.output.get("publicPath");
139
+ if (userSSRConfig.distOutputDir && publicPath) {
140
+ chain.output.publicPath(`${publicPath}${userSSRConfig.distOutputDir}/`);
141
+ }
142
+ }
143
+ if (isDev() && isWeb) {
144
+ chain.externals({
145
+ "@module-federation/node/utils": "NOT_USED_IN_BROWSER"
146
+ });
147
+ }
148
+ });
149
+ api.config(() => {
150
+ return {
151
+ builderPlugins: [
152
+ mfSSRRsbuildPlugin(pluginOptions)
153
+ ],
154
+ tools: {
155
+ devServer: {
156
+ before: [
157
+ (req, res, next) => {
158
+ if (!enableSSR) {
159
+ next();
160
+ return;
161
+ }
162
+ try {
163
+ var _req_url, _req_url1;
164
+ if (((_req_url = req.url) === null || _req_url === void 0 ? void 0 : _req_url.includes(".json")) && !((_req_url1 = req.url) === null || _req_url1 === void 0 ? void 0 : _req_url1.includes("hot-update"))) {
165
+ const filepath = path.join(process.cwd(), `dist${req.url}`);
166
+ fs.statSync(filepath);
167
+ res.setHeader("Access-Control-Allow-Origin", "*");
168
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
169
+ res.setHeader("Access-Control-Allow-Headers", "*");
170
+ fs.createReadStream(filepath).pipe(res);
171
+ } else {
172
+ next();
173
+ }
174
+ } catch (err) {
175
+ logger.debug(err);
176
+ next();
177
+ }
178
+ }
179
+ ]
180
+ }
181
+ }
182
+ };
183
+ });
184
+ api.onAfterBuild(() => {
185
+ const { nodePlugin, browserPlugin, distOutputDir } = pluginOptions;
186
+ updateStatsAndManifest(nodePlugin, browserPlugin, distOutputDir);
187
+ });
188
+ api.onDevCompileDone(() => {
189
+ const { nodePlugin, browserPlugin, distOutputDir } = pluginOptions;
190
+ updateStatsAndManifest(nodePlugin, browserPlugin, distOutputDir);
191
+ });
192
+ }
193
+ });
194
+ var ssrPlugin_default = moduleFederationSSRPlugin;
195
+ export {
196
+ CHAIN_MF_PLUGIN_ID,
197
+ ssrPlugin_default as default,
198
+ moduleFederationSSRPlugin,
199
+ setEnv
200
+ };
@@ -0,0 +1,53 @@
1
+ import os from "os";
2
+ const localIpv4 = "127.0.0.1";
3
+ const getIpv4Interfaces = () => {
4
+ try {
5
+ const interfaces = os.networkInterfaces();
6
+ const ipv4Interfaces = [];
7
+ Object.values(interfaces).forEach((detail) => {
8
+ detail === null || detail === void 0 ? void 0 : detail.forEach((detail2) => {
9
+ const familyV4Value = typeof detail2.family === "string" ? "IPv4" : 4;
10
+ if (detail2.family === familyV4Value && detail2.address !== localIpv4) {
11
+ ipv4Interfaces.push(detail2);
12
+ }
13
+ });
14
+ });
15
+ return ipv4Interfaces;
16
+ } catch (_err) {
17
+ return [];
18
+ }
19
+ };
20
+ const getIPV4 = () => {
21
+ const ipv4Interfaces = getIpv4Interfaces();
22
+ const ipv4Interface = ipv4Interfaces[0] || {
23
+ address: localIpv4
24
+ };
25
+ return ipv4Interface.address;
26
+ };
27
+ const isWebTarget = (target) => {
28
+ const WEB_TARGET = "web";
29
+ if (Array.isArray(target)) {
30
+ return target.includes(WEB_TARGET);
31
+ } else if (typeof target === "string") {
32
+ return target === WEB_TARGET;
33
+ }
34
+ return false;
35
+ };
36
+ const skipByTarget = (target) => {
37
+ const IGNORE_TARGET = "webworker";
38
+ if (Array.isArray(target)) {
39
+ return target.includes(IGNORE_TARGET);
40
+ } else if (typeof target === "string") {
41
+ return target === IGNORE_TARGET;
42
+ }
43
+ return false;
44
+ };
45
+ function isDev() {
46
+ return process.env.NODE_ENV === "development";
47
+ }
48
+ export {
49
+ getIPV4,
50
+ isDev,
51
+ isWebTarget,
52
+ skipByTarget
53
+ };
@@ -0,0 +1,6 @@
1
+ const LOCALHOST = "localhost";
2
+ const PLUGIN_IDENTIFIER = "[ Modern.js Module Federation ]";
3
+ export {
4
+ LOCALHOST,
5
+ PLUGIN_IDENTIFIER
6
+ };
File without changes
@@ -0,0 +1,7 @@
1
+ import { createLogger } from "@module-federation/sdk";
2
+ import { PLUGIN_IDENTIFIER } from "./constant";
3
+ const logger = createLogger(PLUGIN_IDENTIFIER);
4
+ var logger_default = logger;
5
+ export {
6
+ logger_default as default
7
+ };
@@ -0,0 +1,6 @@
1
+ export * from "@module-federation/enhanced/runtime";
2
+ import { kit, ERROR_TYPE } from "@module-federation/bridge-react";
3
+ export {
4
+ ERROR_TYPE,
5
+ kit
6
+ };
@@ -0,0 +1,49 @@
1
+ import fs from "fs-extra";
2
+ import { LRUCache } from "lru-cache";
3
+ class FileCache {
4
+ /**
5
+ * Check if file exists and return file info
6
+ * @param filepath Path to the file
7
+ * @returns FileResult or null if file doesn't exist
8
+ */
9
+ async getFile(filepath) {
10
+ if (!await fs.pathExists(filepath)) {
11
+ return null;
12
+ }
13
+ try {
14
+ const stat = await fs.lstat(filepath);
15
+ const currentModified = stat.mtimeMs;
16
+ const cachedEntry = this.cache.get(filepath);
17
+ if (cachedEntry && currentModified <= cachedEntry.lastModified) {
18
+ return {
19
+ content: cachedEntry.content,
20
+ lastModified: cachedEntry.lastModified
21
+ };
22
+ }
23
+ const content = await fs.readFile(filepath, "utf-8");
24
+ const newEntry = {
25
+ content,
26
+ lastModified: currentModified
27
+ };
28
+ this.cache.set(filepath, newEntry, {
29
+ size: stat.size || content.length
30
+ });
31
+ return {
32
+ content,
33
+ lastModified: currentModified
34
+ };
35
+ } catch (err) {
36
+ return null;
37
+ }
38
+ }
39
+ constructor() {
40
+ this.cache = new LRUCache({
41
+ maxSize: 200 * 1024 * 1024
42
+ });
43
+ }
44
+ }
45
+ const fileCache = new FileCache();
46
+ export {
47
+ FileCache,
48
+ fileCache
49
+ };
@@ -0,0 +1,27 @@
1
+ import { it, expect, describe, vi, beforeAll } from "vitest";
2
+ import { FileCache } from "./fileCache";
3
+ beforeAll(() => {
4
+ vi.mock("fs-extra", () => ({
5
+ default: {
6
+ pathExists: () => {
7
+ return true;
8
+ },
9
+ lstat: () => {
10
+ return {
11
+ mtimeMs: Date.now(),
12
+ size: 4
13
+ };
14
+ },
15
+ readFile: () => {
16
+ return "test";
17
+ }
18
+ }
19
+ }));
20
+ });
21
+ describe("modern serve static file cache", async () => {
22
+ it("should cache file", async () => {
23
+ const cache = new FileCache();
24
+ const result = await cache.getFile("test.txt");
25
+ expect(result === null || result === void 0 ? void 0 : result.content).toBe("test");
26
+ });
27
+ });
@@ -0,0 +1,34 @@
1
+ import { createStaticMiddleware } from "./staticMiddleware";
2
+ const staticServePlugin = () => ({
3
+ name: "@modern-js/module-federation/server",
4
+ setup: (api) => {
5
+ api.onPrepare(() => {
6
+ var _config_output, _config_server;
7
+ console.log(process.env.NODE_ENV);
8
+ if (process.env.NODE_ENV === "development") {
9
+ return;
10
+ }
11
+ const { middlewares } = api.getServerContext();
12
+ const config = api.getServerConfig();
13
+ const assetPrefix = ((_config_output = config.output) === null || _config_output === void 0 ? void 0 : _config_output.assetPrefix) || "";
14
+ if (!((_config_server = config.server) === null || _config_server === void 0 ? void 0 : _config_server.ssr)) {
15
+ return;
16
+ }
17
+ const context = api.getServerContext();
18
+ const pwd = context.distDirectory;
19
+ const serverStaticMiddleware = createStaticMiddleware({
20
+ assetPrefix,
21
+ pwd
22
+ });
23
+ middlewares.push({
24
+ name: "module-federation-serve-manifest",
25
+ handler: serverStaticMiddleware
26
+ });
27
+ });
28
+ }
29
+ });
30
+ var server_default = staticServePlugin;
31
+ export {
32
+ server_default as default,
33
+ staticServePlugin
34
+ };
@@ -0,0 +1,43 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ import { fileCache } from "./fileCache";
4
+ const bundlesAssetPrefix = "/bundles";
5
+ const removeHost = (url) => {
6
+ try {
7
+ const hasProtocol = url.includes("://");
8
+ const hasDomain = hasProtocol || url.startsWith("//");
9
+ const pathname = hasDomain ? new URL(hasProtocol ? url : `http:${url}`).pathname : url;
10
+ return pathname;
11
+ } catch (e) {
12
+ return url;
13
+ }
14
+ };
15
+ const createStaticMiddleware = (options) => {
16
+ const { assetPrefix, pwd } = options;
17
+ return async (c, next) => {
18
+ const pathname = c.req.path;
19
+ if (path.extname(pathname) !== ".js") {
20
+ return next();
21
+ }
22
+ const prefixWithoutHost = removeHost(assetPrefix);
23
+ const prefixWithBundle = path.join(prefixWithoutHost, bundlesAssetPrefix);
24
+ if (!pathname.startsWith(prefixWithBundle)) {
25
+ return next();
26
+ }
27
+ const pathnameWithoutPrefix = pathname.replace(prefixWithBundle, "");
28
+ const filepath = path.join(pwd, bundlesAssetPrefix, pathnameWithoutPrefix);
29
+ if (!await fs.pathExists(filepath)) {
30
+ return next();
31
+ }
32
+ const fileResult = await fileCache.getFile(filepath);
33
+ if (!fileResult) {
34
+ return next();
35
+ }
36
+ c.header("Content-Type", "application/javascript");
37
+ c.header("Content-Length", String(fileResult.content.length));
38
+ return c.body(fileResult.content, 200);
39
+ };
40
+ };
41
+ export {
42
+ createStaticMiddleware
43
+ };