@module-federation/modern-js 0.0.0-next-20241010084324 → 0.0.0-next-20241011105718

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 (103) hide show
  1. package/dist/cjs/cli/dataLoader/ast/constant.js +49 -0
  2. package/dist/cjs/cli/dataLoader/ast/generateRoutes.js +143 -0
  3. package/dist/cjs/cli/{constant.js → dataLoader/ast/index.js} +6 -6
  4. package/dist/cjs/cli/dataLoader/clearMFCache.js +57 -0
  5. package/dist/cjs/cli/dataLoader/generateRouteFile.js +148 -0
  6. package/dist/cjs/cli/dataLoader/patchMFConfig.js +137 -0
  7. package/dist/cjs/cli/dataLoader/plugin.js +219 -0
  8. package/dist/cjs/cli/index.js +5 -1
  9. package/dist/cjs/cli/mfRuntimePlugins/{inject-node-fetch.js → node-fetch.js} +6 -6
  10. package/dist/cjs/cli/mfRuntimePlugins/node.js +41 -0
  11. package/dist/cjs/cli/mfRuntimePlugins/resolve-entry-ipv4.js +40 -38
  12. package/dist/cjs/cli/server/dataLoaderPlugin.js +81 -0
  13. package/dist/cjs/cli/server/fetchRemoteFullRoutesMap.js +72 -0
  14. package/dist/cjs/cli/ssrPlugin.js +5 -2
  15. package/dist/cjs/cli/utils.js +11 -6
  16. package/dist/cjs/cli/utils.spec.js +5 -6
  17. package/dist/cjs/constant.js +35 -2
  18. package/dist/cjs/interfaces/route.js +16 -0
  19. package/dist/cjs/runtime/dataLoader/plugin-inject-assets.js +92 -0
  20. package/dist/cjs/runtime/dataLoader/plugin.js +75 -0
  21. package/dist/cjs/runtime/dataLoader/utils.js +115 -0
  22. package/dist/cjs/runtime/index.js +4 -1
  23. package/dist/cjs/{cli/mfRuntimePlugins/shared-strategy.js → runtime/withMFRouteId.js} +11 -23
  24. package/dist/cjs/ssr-runtime/plugin.js +7 -8
  25. package/dist/cjs/types/modern.js +16 -0
  26. package/dist/esm/cli/dataLoader/ast/constant.js +18 -0
  27. package/dist/esm/cli/dataLoader/ast/generateRoutes.js +110 -0
  28. package/dist/esm/cli/dataLoader/ast/index.js +4 -0
  29. package/dist/esm/cli/dataLoader/clearMFCache.js +34 -0
  30. package/dist/esm/cli/dataLoader/generateRouteFile.js +308 -0
  31. package/dist/esm/cli/dataLoader/patchMFConfig.js +103 -0
  32. package/dist/esm/cli/dataLoader/plugin.js +341 -0
  33. package/dist/esm/cli/index.js +6 -2
  34. package/dist/esm/cli/mfRuntimePlugins/{inject-node-fetch.js → node-fetch.js} +3 -3
  35. package/dist/esm/cli/mfRuntimePlugins/node.js +13 -0
  36. package/dist/esm/cli/server/dataLoaderPlugin.js +104 -0
  37. package/dist/esm/cli/server/fetchRemoteFullRoutesMap.js +93 -0
  38. package/dist/esm/cli/ssrPlugin.js +6 -3
  39. package/dist/esm/cli/utils.js +13 -8
  40. package/dist/esm/cli/utils.spec.js +5 -6
  41. package/dist/esm/constant.js +23 -1
  42. package/dist/esm/interfaces/route.js +0 -0
  43. package/dist/esm/runtime/dataLoader/plugin-inject-assets.js +71 -0
  44. package/dist/esm/runtime/dataLoader/plugin.js +97 -0
  45. package/dist/esm/runtime/dataLoader/utils.js +86 -0
  46. package/dist/esm/runtime/index.js +3 -1
  47. package/dist/esm/runtime/withMFRouteId.js +7 -0
  48. package/dist/esm/ssr-runtime/plugin.js +8 -11
  49. package/dist/esm/types/modern.js +0 -0
  50. package/dist/esm-node/cli/dataLoader/ast/constant.js +18 -0
  51. package/dist/esm-node/cli/dataLoader/ast/generateRoutes.js +109 -0
  52. package/dist/esm-node/cli/dataLoader/ast/index.js +4 -0
  53. package/dist/esm-node/cli/dataLoader/clearMFCache.js +33 -0
  54. package/dist/esm-node/cli/dataLoader/generateRouteFile.js +113 -0
  55. package/dist/esm-node/cli/dataLoader/patchMFConfig.js +103 -0
  56. package/dist/esm-node/cli/dataLoader/plugin.js +184 -0
  57. package/dist/esm-node/cli/index.js +5 -1
  58. package/dist/esm-node/cli/mfRuntimePlugins/{inject-node-fetch.js → node-fetch.js} +3 -3
  59. package/dist/esm-node/cli/mfRuntimePlugins/node.js +11 -0
  60. package/dist/esm-node/cli/mfRuntimePlugins/resolve-entry-ipv4.js +40 -38
  61. package/dist/esm-node/cli/server/dataLoaderPlugin.js +61 -0
  62. package/dist/esm-node/cli/server/fetchRemoteFullRoutesMap.js +47 -0
  63. package/dist/esm-node/cli/ssrPlugin.js +5 -2
  64. package/dist/esm-node/cli/utils.js +9 -5
  65. package/dist/esm-node/cli/utils.spec.js +5 -6
  66. package/dist/esm-node/constant.js +23 -1
  67. package/dist/esm-node/interfaces/route.js +0 -0
  68. package/dist/esm-node/runtime/dataLoader/plugin-inject-assets.js +68 -0
  69. package/dist/esm-node/runtime/dataLoader/plugin.js +51 -0
  70. package/dist/esm-node/runtime/dataLoader/utils.js +86 -0
  71. package/dist/esm-node/runtime/index.js +3 -1
  72. package/dist/esm-node/runtime/withMFRouteId.js +7 -0
  73. package/dist/esm-node/ssr-runtime/plugin.js +7 -8
  74. package/dist/esm-node/types/modern.js +0 -0
  75. package/dist/types/cli/dataLoader/ast/constant.d.ts +8 -0
  76. package/dist/types/cli/dataLoader/ast/generateRoutes.d.ts +5 -0
  77. package/dist/types/cli/dataLoader/ast/index.d.ts +1 -0
  78. package/dist/types/cli/dataLoader/clearMFCache.d.ts +1 -0
  79. package/dist/types/cli/dataLoader/generateRouteFile.d.ts +10 -0
  80. package/dist/types/cli/dataLoader/patchMFConfig.d.ts +10 -0
  81. package/dist/types/cli/dataLoader/plugin.d.ts +6 -0
  82. package/dist/types/cli/mfRuntimePlugins/node.d.ts +3 -0
  83. package/dist/types/cli/server/dataLoaderPlugin.d.ts +10 -0
  84. package/dist/types/cli/server/fetchRemoteFullRoutesMap.d.ts +11 -0
  85. package/dist/types/cli/utils.d.ts +2 -0
  86. package/dist/types/constant.d.ts +11 -0
  87. package/dist/types/interfaces/route.d.ts +12 -0
  88. package/dist/types/runtime/dataLoader/plugin-inject-assets.d.ts +4 -0
  89. package/dist/types/runtime/dataLoader/plugin.d.ts +5 -0
  90. package/dist/types/runtime/dataLoader/utils.d.ts +22 -0
  91. package/dist/types/runtime/index.d.ts +1 -0
  92. package/dist/types/runtime/withMFRouteId.d.ts +1 -0
  93. package/dist/types/ssr-runtime/plugin.d.ts +3 -1
  94. package/dist/types/types/index.d.ts +8 -0
  95. package/dist/types/types/modern.d.ts +12 -0
  96. package/package.json +48 -11
  97. package/dist/esm/cli/constant.js +0 -4
  98. package/dist/esm/cli/mfRuntimePlugins/shared-strategy.js +0 -25
  99. package/dist/esm-node/cli/constant.js +0 -4
  100. package/dist/esm-node/cli/mfRuntimePlugins/shared-strategy.js +0 -23
  101. package/dist/types/cli/constant.d.ts +0 -1
  102. package/dist/types/cli/mfRuntimePlugins/shared-strategy.d.ts +0 -3
  103. /package/dist/types/cli/mfRuntimePlugins/{inject-node-fetch.d.ts → node-fetch.d.ts} +0 -0
@@ -0,0 +1,113 @@
1
+ import { fs, normalizeToPosixPath } from "@modern-js/utils";
2
+ import path from "path";
3
+ import os from "os";
4
+ import { MF_JSON, ROUTE_ID } from "../../constant";
5
+ import { getRemoteLayoutId } from "../../runtime/dataLoader/utils";
6
+ const ROUTES = "routes";
7
+ function calcPathName(filePath, rootDir, entry) {
8
+ const relativePath = path.relative(rootDir, filePath);
9
+ const conditionalReg = /^\[(.*)\]$/;
10
+ const splitPaths = relativePath.split("/").reduce((sum, cur) => {
11
+ if (cur.includes(".")) {
12
+ const split = cur.split(".").map((i) => {
13
+ const match = i.match(conditionalReg);
14
+ if (match) {
15
+ return `:${match[1]}`;
16
+ }
17
+ return i.startsWith("__") ? "" : i;
18
+ });
19
+ sum.push(...split);
20
+ } else {
21
+ const match = cur.match(conditionalReg);
22
+ if (match) {
23
+ sum.push(`:${match[1]}`);
24
+ } else {
25
+ if (!cur.startsWith("__")) {
26
+ sum.push(cur);
27
+ }
28
+ }
29
+ }
30
+ return sum;
31
+ }, []);
32
+ return path.join(entry, splitPaths.filter((p) => !!p).join("/"));
33
+ }
34
+ async function generateRouteFile(options) {
35
+ const { appDirectory } = options;
36
+ const entries = [];
37
+ const remotePathMap = {};
38
+ const srcPath = `${appDirectory}/src`;
39
+ const traverse = async (filepath, rootDir, entry) => {
40
+ if (!await fs.pathExists(filepath)) {
41
+ return null;
42
+ }
43
+ const isDirectory = (await fs.stat(filepath)).isDirectory();
44
+ if (!isDirectory) {
45
+ return null;
46
+ }
47
+ const items = await fs.readdir(filepath);
48
+ const mfJson = items.find((i) => i === MF_JSON);
49
+ if (mfJson) {
50
+ const mfJsonContent = await fs.readJSON(normalizeToPosixPath(path.join(filepath, mfJson)));
51
+ const { remoteName } = mfJsonContent;
52
+ const remoteLayoutId = getRemoteLayoutId(remoteName);
53
+ const writeFile = async (id, type, pathname) => {
54
+ const generatedFilePath = normalizeToPosixPath(path.join(filepath, `${type}.tsx`));
55
+ const content = [
56
+ "// Do not edit this file. It is a auto generated.",
57
+ `// It will render ${remoteName}'s ${type}.`,
58
+ `// The ${type} pathname is: ${pathname}`,
59
+ `// The ${type} route id is: ${ROUTE_ID}`
60
+ ];
61
+ await fs.writeFile(generatedFilePath, content.join(os.EOL));
62
+ return generatedFilePath;
63
+ };
64
+ if (remoteLayoutId) {
65
+ const pathname = calcPathName(filepath, rootDir, entry);
66
+ const filePath = await writeFile(remoteLayoutId, "layout", pathname);
67
+ remotePathMap[pathname] = {
68
+ name: remoteName,
69
+ path: filePath
70
+ };
71
+ }
72
+ return;
73
+ }
74
+ await Promise.all(items.map(async (item) => {
75
+ await traverse(normalizeToPosixPath(path.join(filepath, item)), rootDir, entry);
76
+ }));
77
+ };
78
+ const traverseRoutes = async (dir, level = 1) => {
79
+ if (level > 3) {
80
+ return;
81
+ }
82
+ const isDirectory = (await fs.stat(dir)).isDirectory();
83
+ if (!isDirectory) {
84
+ return;
85
+ }
86
+ const items = await fs.readdir(dir);
87
+ if (items.find((i) => i === ROUTES)) {
88
+ const entry = path.relative(srcPath, dir);
89
+ entries.push(entry);
90
+ const rootDir = `${dir}/${ROUTES}`;
91
+ await traverse(rootDir, rootDir, entry);
92
+ } else {
93
+ await Promise.all(items.map(async (item) => {
94
+ await traverseRoutes(path.join(dir, item), level++);
95
+ }));
96
+ }
97
+ };
98
+ await traverseRoutes(srcPath);
99
+ const normalizedEntries = entries.map((entry) => {
100
+ if (entry === "") {
101
+ return "main";
102
+ }
103
+ return entry;
104
+ });
105
+ return {
106
+ entries: normalizedEntries,
107
+ remotePathMap
108
+ };
109
+ }
110
+ export {
111
+ calcPathName,
112
+ generateRouteFile
113
+ };
@@ -0,0 +1,103 @@
1
+ import path from "path";
2
+ import { fs } from "@modern-js/utils";
3
+ import { MODERN_JS_ROUTE_SERVER_LOADER } from "../../constant";
4
+ import { MF_ROUTES, MODERN_JS_FILE_SYSTEM_ROUTES_FILE_NAME } from "../../constant";
5
+ import { generateRoutes } from "./ast";
6
+ function generateExtraExposeFiles(options) {
7
+ const { internalDirectory, mfConfig, isServer, entries } = options;
8
+ const entryMap = {};
9
+ const outputDir = path.resolve(process.cwd(), "node_modules/.federation/data-loader");
10
+ fs.ensureDirSync(outputDir);
11
+ const addSuffix = (fileName, ext = ".jsx") => {
12
+ if (!isServer) {
13
+ return `${fileName}${ext}`;
14
+ }
15
+ return `${fileName}.server${ext}`;
16
+ };
17
+ const generateEntryRoutes = (entry) => {
18
+ const outputEntryDir = path.resolve(outputDir, entry);
19
+ fs.ensureDirSync(outputEntryDir);
20
+ const sourceDir = path.resolve(internalDirectory, entry);
21
+ const routesFilePath = path.resolve(sourceDir, addSuffix(MODERN_JS_FILE_SYSTEM_ROUTES_FILE_NAME, ".js"));
22
+ const routesFileContent = fs.readFileSync(routesFilePath, "utf-8");
23
+ const outputFullRoutesPath = path.resolve(outputEntryDir, addSuffix(MF_ROUTES));
24
+ generateRoutes({
25
+ sourceCode: routesFileContent,
26
+ filePath: outputFullRoutesPath
27
+ });
28
+ const routeServerLoaderPath = path.resolve(sourceDir, `${MODERN_JS_ROUTE_SERVER_LOADER}.js`);
29
+ const outputRouteServerLoaderPath = path.resolve(outputEntryDir, `${MODERN_JS_ROUTE_SERVER_LOADER}.js`);
30
+ const clientRouteServerLoaderPath = outputRouteServerLoaderPath.replace(MODERN_JS_ROUTE_SERVER_LOADER, `${MODERN_JS_ROUTE_SERVER_LOADER}-client`);
31
+ if (isServer) {
32
+ const routeServerLoaderContent = fs.readFileSync(routeServerLoaderPath, "utf-8");
33
+ generateRoutes({
34
+ sourceCode: routeServerLoaderContent,
35
+ filePath: outputRouteServerLoaderPath
36
+ });
37
+ } else {
38
+ fs.writeFileSync(clientRouteServerLoaderPath, `export const routes = []`);
39
+ }
40
+ entryMap[entry] = {
41
+ routesPath: outputFullRoutesPath,
42
+ routeServerLoaderPath: outputRouteServerLoaderPath,
43
+ clientRouteServerLoaderPath
44
+ };
45
+ };
46
+ entries.forEach((entry) => {
47
+ generateEntryRoutes(entry);
48
+ });
49
+ return {
50
+ entryMap
51
+ };
52
+ }
53
+ function addExpose(options) {
54
+ const { mfConfig, isServer } = options;
55
+ const { entryMap } = generateExtraExposeFiles(options);
56
+ const addExposeByEntry = (entry, routesPath, routeServerLoaderPath, clientRouteServerLoaderPath) => {
57
+ if (!mfConfig.exposes) {
58
+ mfConfig.exposes = {};
59
+ }
60
+ const routesKey = `./${entry}/${MF_ROUTES}`;
61
+ if (!mfConfig.exposes[routesKey]) {
62
+ mfConfig.exposes[routesKey] = routesPath;
63
+ }
64
+ const routeServerLoaderKey = `./${entry}/${MODERN_JS_ROUTE_SERVER_LOADER}`;
65
+ if (!mfConfig.exposes[routeServerLoaderKey]) {
66
+ if (isServer) {
67
+ mfConfig.exposes[routeServerLoaderKey] = routeServerLoaderPath;
68
+ } else {
69
+ mfConfig.exposes[routeServerLoaderKey] = clientRouteServerLoaderPath;
70
+ }
71
+ }
72
+ };
73
+ Object.keys(entryMap).forEach((entry) => {
74
+ const { routesPath, routeServerLoaderPath, clientRouteServerLoaderPath } = entryMap[entry];
75
+ addExposeByEntry(entry, routesPath, routeServerLoaderPath, clientRouteServerLoaderPath);
76
+ });
77
+ }
78
+ function addShared(options) {
79
+ const { metaName, mfConfig } = options;
80
+ const alias = `@${metaName}/runtime/router`;
81
+ if (!mfConfig.shared) {
82
+ mfConfig.shared = {
83
+ [alias]: {
84
+ singleton: true
85
+ }
86
+ };
87
+ } else {
88
+ if (!Array.isArray(mfConfig.shared)) {
89
+ mfConfig.shared[alias] = {
90
+ singleton: true
91
+ };
92
+ } else {
93
+ mfConfig.shared.push(alias);
94
+ }
95
+ }
96
+ }
97
+ function patchMFConfig(options) {
98
+ addShared(options);
99
+ addExpose(options);
100
+ }
101
+ export {
102
+ patchMFConfig
103
+ };
@@ -0,0 +1,184 @@
1
+ import { fs } from "@modern-js/utils";
2
+ import { transformName2Prefix } from "../../runtime/dataLoader/utils";
3
+ import { DEFAULT_ENTRY, ROUTE_ID } from "../../constant";
4
+ import { META_NAME } from "../../constant";
5
+ import { generateRoutes } from "./ast";
6
+ import { generateRouteFile } from "./generateRouteFile";
7
+ import { patchMFConfig } from "./patchMFConfig";
8
+ import { clearMFCache } from "./clearMFCache";
9
+ import path from "path";
10
+ function _transformRuntimeOptions(buildOptions) {
11
+ const remotes = buildOptions.remotes || {};
12
+ const runtimeRemotes = Object.entries(remotes).map((remote) => {
13
+ const [alias, nameAndEntry] = remote;
14
+ const [name, entry] = nameAndEntry.split("@");
15
+ return {
16
+ name,
17
+ entry,
18
+ alias
19
+ };
20
+ });
21
+ return {
22
+ name: buildOptions.name,
23
+ remotes: runtimeRemotes
24
+ };
25
+ }
26
+ const moduleFederationDataLoaderPlugin = (enable, internalOptions, userConfig) => ({
27
+ name: "@modern-js/plugin-module-federation-data-loader",
28
+ pre: [
29
+ "@modern-js/plugin-module-federation-config"
30
+ ],
31
+ post: [
32
+ "@modern-js/plugin-router",
33
+ "@modern-js/plugin-module-federation"
34
+ ],
35
+ setup: async ({ useAppContext }) => {
36
+ if (!enable) {
37
+ return;
38
+ }
39
+ const { serverPlugin = "@module-federation/modern-js/data-loader-server", transformRuntimeOptions } = userConfig;
40
+ const appContext = useAppContext();
41
+ const name = internalOptions.csrConfig.name;
42
+ const { metaName = META_NAME } = internalOptions;
43
+ const internalDirectory = appContext.internalDirectory.replace(META_NAME, metaName || META_NAME);
44
+ const transformRuntimeFn = transformRuntimeOptions || _transformRuntimeOptions;
45
+ const entries = /* @__PURE__ */ new Set();
46
+ let remotePathMap = {};
47
+ const ssrByRouteIdsMap = {};
48
+ const csrConfig = internalOptions.csrConfig;
49
+ if (typeof csrConfig.remotes === "object" && Object.keys(csrConfig.remotes).length) {
50
+ const { entries: scanEntries, remotePathMap: scanRemotePathMap } = await generateRouteFile({
51
+ appDirectory: appContext.appDirectory
52
+ });
53
+ scanEntries.forEach((e) => entries.add(e));
54
+ remotePathMap = scanRemotePathMap;
55
+ } else {
56
+ entries.add(DEFAULT_ENTRY);
57
+ }
58
+ const dataLoaderRemotes = [
59
+ ...new Set(Object.values(remotePathMap).map((i) => i.name))
60
+ ];
61
+ const serverPluginOptions = {
62
+ runtimeOptions: transformRuntimeFn(internalOptions.csrConfig),
63
+ dataLoaderRemotes,
64
+ ssrByRouteIdsMap
65
+ };
66
+ const hasDataLoaderRemotes = () => Boolean(serverPluginOptions.dataLoaderRemotes.length);
67
+ return {
68
+ _internalRuntimePlugins: ({ entrypoint, plugins }) => {
69
+ if (!hasDataLoaderRemotes()) {
70
+ return {
71
+ entrypoint,
72
+ plugins
73
+ };
74
+ }
75
+ plugins.push({
76
+ name: "ssrDataLoader",
77
+ path: "@module-federation/modern-js/data-loader",
78
+ config: {
79
+ metaName,
80
+ dataLoaderRemotes
81
+ }
82
+ });
83
+ plugins.push({
84
+ name: "ssrDataLoaderInjectAssets",
85
+ path: "@module-federation/modern-js/data-loader-inject-assets",
86
+ config: {
87
+ metaName,
88
+ dataLoaderRemotes
89
+ }
90
+ });
91
+ return {
92
+ entrypoint,
93
+ plugins
94
+ };
95
+ },
96
+ _internalServerPlugins({ plugins }) {
97
+ if (!hasDataLoaderRemotes()) {
98
+ return {
99
+ plugins
100
+ };
101
+ }
102
+ plugins.push({
103
+ name: serverPlugin,
104
+ options: serverPluginOptions
105
+ });
106
+ return {
107
+ plugins
108
+ };
109
+ },
110
+ async modifyFileSystemRoutes(options) {
111
+ const { routes, entrypoint } = options;
112
+ const { entryName } = entrypoint;
113
+ const prefix = transformName2Prefix(internalOptions.csrConfig.name);
114
+ const modifyRouteIds = async (route, pathName) => {
115
+ const currentPathName = route.path ? path.join(pathName, route.path) : pathName;
116
+ if (route.id) {
117
+ const originalId = route.id;
118
+ route.originalId = originalId;
119
+ const remoteInfo = remotePathMap[currentPathName];
120
+ if (remoteInfo) {
121
+ const { path: path2, name: name2 } = remoteInfo;
122
+ const remoteIdPrefix = transformName2Prefix(name2);
123
+ const isLayout = Boolean(route.children);
124
+ const newId = `${remoteIdPrefix}${isLayout ? "layout" : "page"}`;
125
+ ssrByRouteIdsMap[originalId] = newId;
126
+ const content = fs.readFileSync(path2, "utf-8");
127
+ await fs.writeFile(path2, content.replace(ROUTE_ID, originalId));
128
+ route.id = newId;
129
+ } else {
130
+ route.id = `${prefix}${route.id}`;
131
+ }
132
+ route.children && await Promise.all(route.children.map(async (r) => {
133
+ return await modifyRouteIds(r, currentPathName);
134
+ }));
135
+ }
136
+ };
137
+ await Promise.all(routes.map(async (route) => {
138
+ await modifyRouteIds(route, entryName);
139
+ }));
140
+ return options;
141
+ },
142
+ config: async () => {
143
+ return {
144
+ tools: {
145
+ // bundlerChain can not keep target order
146
+ rspack(_config, { isServer }) {
147
+ patchMFConfig({
148
+ mfConfig: isServer ? internalOptions.ssrConfig : internalOptions.csrConfig,
149
+ metaName,
150
+ isServer,
151
+ internalDirectory,
152
+ entries
153
+ });
154
+ },
155
+ // bundlerChain can not keep target order
156
+ webpack(_config, { isServer }) {
157
+ patchMFConfig({
158
+ mfConfig: isServer ? internalOptions.ssrConfig : internalOptions.csrConfig,
159
+ metaName,
160
+ isServer,
161
+ internalDirectory,
162
+ entries
163
+ });
164
+ }
165
+ },
166
+ source: {
167
+ define: {
168
+ MODERN_ROUTER_ID_PREFIX: JSON.stringify(transformName2Prefix(name))
169
+ }
170
+ }
171
+ };
172
+ },
173
+ async afterDev() {
174
+ clearMFCache();
175
+ }
176
+ };
177
+ }
178
+ });
179
+ var plugin_default = moduleFederationDataLoaderPlugin;
180
+ export {
181
+ plugin_default as default,
182
+ generateRoutes,
183
+ moduleFederationDataLoaderPlugin
184
+ };
@@ -2,6 +2,7 @@ import { ModuleFederationPlugin as WebpackModuleFederationPlugin, AsyncBoundaryP
2
2
  import { ModuleFederationPlugin as RspackModuleFederationPlugin } from "@module-federation/enhanced/rspack";
3
3
  import { moduleFederationConfigPlugin } from "./configPlugin";
4
4
  import { moduleFederationSSRPlugin } from "./ssrPlugin";
5
+ import { moduleFederationDataLoaderPlugin } from "./dataLoader/plugin";
5
6
  const moduleFederationPlugin = (userConfig = {}) => {
6
7
  const internalModernPluginOptions = {
7
8
  csrConfig: void 0,
@@ -53,7 +54,10 @@ const moduleFederationPlugin = (userConfig = {}) => {
53
54
  },
54
55
  usePlugins: [
55
56
  moduleFederationConfigPlugin(internalModernPluginOptions),
56
- moduleFederationSSRPlugin(internalModernPluginOptions)
57
+ moduleFederationSSRPlugin(internalModernPluginOptions),
58
+ moduleFederationDataLoaderPlugin(Boolean(userConfig.dataLoader), internalModernPluginOptions, {
59
+ ...typeof userConfig.dataLoader === "boolean" ? {} : userConfig.dataLoader
60
+ })
57
61
  ]
58
62
  };
59
63
  };
@@ -1,6 +1,6 @@
1
1
  import nodeFetch from "node-fetch";
2
2
  const injectNodeFetchPlugin = () => ({
3
- name: "inject-node-fetch-plugin",
3
+ name: "node-fetch-plugin",
4
4
  beforeInit(args) {
5
5
  if (!globalThis.fetch) {
6
6
  globalThis.fetch = nodeFetch;
@@ -8,7 +8,7 @@ const injectNodeFetchPlugin = () => ({
8
8
  return args;
9
9
  }
10
10
  });
11
- var inject_node_fetch_default = injectNodeFetchPlugin;
11
+ var node_fetch_default = injectNodeFetchPlugin;
12
12
  export {
13
- inject_node_fetch_default as default
13
+ node_fetch_default as default
14
14
  };
@@ -0,0 +1,11 @@
1
+ import nodeRuntimePlugin from "@module-federation/node/runtimePlugin";
2
+ const isContainer = typeof __filename === "string" ? __filename.includes("remote") ? true : false : false;
3
+ const pluginName = `node-plugin-${isContainer}`;
4
+ const nodePlugin = () => ({
5
+ name: pluginName,
6
+ beforeInit: nodeRuntimePlugin().beforeInit
7
+ });
8
+ var node_default = nodePlugin;
9
+ export {
10
+ node_default as default
11
+ };
@@ -16,46 +16,48 @@ function replaceObjectLocalhost(key, obj) {
16
16
  function replaceLocalhost(url) {
17
17
  return url.replace(LOCALHOST, ipv4);
18
18
  }
19
- const resolveEntryIpv4Plugin = () => ({
20
- name: "resolve-entry-ipv4",
21
- beforeRegisterRemote(args) {
22
- const { remote } = args;
23
- replaceObjectLocalhost("entry", remote);
24
- return args;
25
- },
26
- async afterResolve(args) {
27
- const { remoteInfo } = args;
28
- replaceObjectLocalhost("entry", remoteInfo);
29
- return args;
30
- },
31
- beforeLoadRemoteSnapshot(args) {
32
- const { moduleInfo } = args;
33
- if ("entry" in moduleInfo) {
34
- replaceObjectLocalhost("entry", moduleInfo);
19
+ const resolveEntryIpv4Plugin = () => {
20
+ return {
21
+ name: "resolve-entry-ipv4",
22
+ beforeRegisterRemote(args) {
23
+ const { remote } = args;
24
+ replaceObjectLocalhost("entry", remote);
25
+ return args;
26
+ },
27
+ async afterResolve(args) {
28
+ const { remoteInfo } = args;
29
+ replaceObjectLocalhost("entry", remoteInfo);
30
+ return args;
31
+ },
32
+ beforeLoadRemoteSnapshot(args) {
33
+ const { moduleInfo } = args;
34
+ if ("entry" in moduleInfo) {
35
+ replaceObjectLocalhost("entry", moduleInfo);
36
+ return args;
37
+ }
38
+ if ("version" in moduleInfo) {
39
+ replaceObjectLocalhost("version", moduleInfo);
40
+ }
41
+ return args;
42
+ },
43
+ loadRemoteSnapshot(args) {
44
+ const { remoteSnapshot } = args;
45
+ if ("publicPath" in remoteSnapshot) {
46
+ replaceObjectLocalhost("publicPath", remoteSnapshot);
47
+ }
48
+ if ("getPublicPath" in remoteSnapshot) {
49
+ replaceObjectLocalhost("getPublicPath", remoteSnapshot);
50
+ }
51
+ if (remoteSnapshot.remotesInfo) {
52
+ Object.keys(remoteSnapshot.remotesInfo).forEach((key) => {
53
+ const remoteInfo = remoteSnapshot.remotesInfo[key];
54
+ replaceObjectLocalhost("matchedVersion", remoteInfo);
55
+ });
56
+ }
35
57
  return args;
36
58
  }
37
- if ("version" in moduleInfo) {
38
- replaceObjectLocalhost("version", moduleInfo);
39
- }
40
- return args;
41
- },
42
- loadRemoteSnapshot(args) {
43
- const { remoteSnapshot } = args;
44
- if ("publicPath" in remoteSnapshot) {
45
- replaceObjectLocalhost("publicPath", remoteSnapshot);
46
- }
47
- if ("getPublicPath" in remoteSnapshot) {
48
- replaceObjectLocalhost("getPublicPath", remoteSnapshot);
49
- }
50
- if (remoteSnapshot.remotesInfo) {
51
- Object.keys(remoteSnapshot.remotesInfo).forEach((key) => {
52
- const remoteInfo = remoteSnapshot.remotesInfo[key];
53
- replaceObjectLocalhost("matchedVersion", remoteInfo);
54
- });
55
- }
56
- return args;
57
- }
58
- });
59
+ };
60
+ };
59
61
  var resolve_entry_ipv4_default = resolveEntryIpv4Plugin;
60
62
  export {
61
63
  resolve_entry_ipv4_default as default
@@ -0,0 +1,61 @@
1
+ import { init } from "@module-federation/enhanced/runtime";
2
+ import { isBrowserEnv } from "@module-federation/sdk";
3
+ import { fetchRemoteFullRoutesMap, getSSRByRouteIds } from "./fetchRemoteFullRoutesMap";
4
+ import { injectRemoteRoutes } from "../../runtime/dataLoader/utils";
5
+ import { MF_ROUTES, DEFAULT_ENTRY, MODERN_JS_ROUTE_SERVER_LOADER } from "../../constant";
6
+ var dataLoaderPlugin_default = ({ runtimeOptions, dataLoaderRemotes, ssrByRouteIdsMap }) => ({
7
+ name: "MFDataLoaderServerPlugin",
8
+ pre: [
9
+ "@modern-js/plugin-inject-resource"
10
+ ],
11
+ setup(api) {
12
+ const { remotes, name } = runtimeOptions;
13
+ let isHandled = false;
14
+ return {
15
+ prepare() {
16
+ const { middlewares } = api.useAppContext();
17
+ middlewares.push({
18
+ name: "MFPatchRouteMiddleWare",
19
+ handler: async (c, next) => {
20
+ const serverManifest = c.get("serverManifest");
21
+ const { loaderBundles, nestedRoutesJson } = serverManifest;
22
+ if (isHandled && !globalThis.FORCE_MF_REFRESH) {
23
+ await next();
24
+ } else {
25
+ var _api_useConfigContext_server;
26
+ const instance = init({
27
+ name,
28
+ remotes
29
+ });
30
+ const remoteFullRoutesMap = await fetchRemoteFullRoutesMap({
31
+ instance,
32
+ remotePath: isBrowserEnv() ? `${DEFAULT_ENTRY}/${MF_ROUTES}` : `${DEFAULT_ENTRY}/${MODERN_JS_ROUTE_SERVER_LOADER}`,
33
+ dataLoaderRemotes
34
+ });
35
+ const originalSSRByRouteIds = (_api_useConfigContext_server = api.useConfigContext().server) === null || _api_useConfigContext_server === void 0 ? void 0 : _api_useConfigContext_server.ssrByRouteIds;
36
+ if (originalSSRByRouteIds && dataLoaderRemotes.length) {
37
+ const remoteSSRByRouteIds = getSSRByRouteIds(dataLoaderRemotes, remoteFullRoutesMap) || [];
38
+ const ssrByRouteIds = /* @__PURE__ */ new Set([
39
+ ...originalSSRByRouteIds,
40
+ ...remoteSSRByRouteIds.map((id) => ssrByRouteIdsMap[id] || id)
41
+ ]);
42
+ api.useConfigContext().server.ssrByRouteIds = Array.from(ssrByRouteIds);
43
+ }
44
+ injectRemoteRoutes(loaderBundles, remoteFullRoutesMap);
45
+ injectRemoteRoutes(nestedRoutesJson, remoteFullRoutesMap);
46
+ isHandled = true;
47
+ globalThis.FORCE_MF_REFRESH = false;
48
+ await next();
49
+ }
50
+ },
51
+ before: [
52
+ "render"
53
+ ]
54
+ });
55
+ }
56
+ };
57
+ }
58
+ });
59
+ export {
60
+ dataLoaderPlugin_default as default
61
+ };
@@ -0,0 +1,47 @@
1
+ async function fetchRemoteFullRoutesMap(options) {
2
+ const { instance, remotePath, dataLoaderRemotes } = options;
3
+ const { remotes } = instance.options;
4
+ const remoteRoutesMap = {};
5
+ if (!remotes.length) {
6
+ return remoteRoutesMap;
7
+ }
8
+ await Promise.all(remotes.map(async (remote) => {
9
+ if (!dataLoaderRemotes.includes(remote.name)) {
10
+ return;
11
+ }
12
+ const remoteId = `${remote.name}/${remotePath}`;
13
+ const { routes } = await instance.loadRemote(remoteId);
14
+ remoteRoutesMap[remote.name] = {
15
+ routes
16
+ };
17
+ }));
18
+ return remoteRoutesMap;
19
+ }
20
+ function getSSRByRouteIds(dataLoaderRemotes, remoteRoutesMap) {
21
+ const remoteProviderRouteIds = /* @__PURE__ */ new Set();
22
+ const collectIds = (route) => {
23
+ remoteProviderRouteIds.add(route.id);
24
+ if (route.children) {
25
+ route.children.forEach((r) => {
26
+ collectIds(r);
27
+ });
28
+ }
29
+ };
30
+ Object.entries(remoteRoutesMap).forEach((item) => {
31
+ const [remoteName, routesObj] = item;
32
+ if (!dataLoaderRemotes.includes(remoteName)) {
33
+ return;
34
+ }
35
+ const { routes } = routesObj;
36
+ routes.forEach((route) => {
37
+ collectIds(route);
38
+ });
39
+ });
40
+ return [
41
+ ...remoteProviderRouteIds
42
+ ];
43
+ }
44
+ export {
45
+ fetchRemoteFullRoutesMap,
46
+ getSSRByRouteIds
47
+ };
@@ -4,7 +4,7 @@ import { ModuleFederationPlugin } from "@module-federation/enhanced/webpack";
4
4
  import { ModuleFederationPlugin as RspackModuleFederationPlugin } from "@module-federation/enhanced/rspack";
5
5
  import UniverseEntryChunkTrackerPlugin from "@module-federation/node/universe-entry-chunk-tracker-plugin";
6
6
  import { updateStatsAndManifest } from "./manifest";
7
- import { isDev } from "./constant";
7
+ import { isDev, META_NAME } from "../constant";
8
8
  function setEnv() {
9
9
  process.env["MF_DISABLE_EMIT_STATS"] = "true";
10
10
  process.env["MF_SSR_PRJ"] = "true";
@@ -18,6 +18,7 @@ const moduleFederationSSRPlugin = (userConfig) => ({
18
18
  setup: async ({ useConfigContext, useAppContext }) => {
19
19
  var _modernjsConfig_server;
20
20
  const modernjsConfig = useConfigContext();
21
+ const { metaName = META_NAME } = userConfig;
21
22
  const enableSSR = Boolean(modernjsConfig === null || modernjsConfig === void 0 ? void 0 : (_modernjsConfig_server = modernjsConfig.server) === null || _modernjsConfig_server === void 0 ? void 0 : _modernjsConfig_server.ssr);
22
23
  if (!enableSSR) {
23
24
  return {};
@@ -34,7 +35,9 @@ const moduleFederationSSRPlugin = (userConfig) => ({
34
35
  plugins.push({
35
36
  name: "mfSSR",
36
37
  path: "@module-federation/modern-js/ssr-runtime",
37
- config: {}
38
+ config: {
39
+ metaName
40
+ }
38
41
  });
39
42
  return {
40
43
  entrypoint,