@module-federation/modern-js 0.0.0-next-20240913081127 → 0.0.0-next-20240913095223

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 (99) hide show
  1. package/dist/cjs/cli/dataLoader/ast/constant.js +49 -0
  2. package/dist/cjs/cli/dataLoader/ast/generateRoutes.js +141 -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 +143 -0
  6. package/dist/cjs/cli/dataLoader/patchMFConfig.js +140 -0
  7. package/dist/cjs/cli/dataLoader/plugin.js +204 -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 +84 -0
  13. package/dist/cjs/cli/server/fetchRemoteFullRoutesMap.js +69 -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 +32 -2
  18. package/dist/cjs/interfaces/route.js +16 -0
  19. package/dist/cjs/runtime/dataLoader/plugin-inject-assets.js +94 -0
  20. package/dist/cjs/runtime/dataLoader/plugin.js +74 -0
  21. package/dist/cjs/runtime/dataLoader/utils.js +106 -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 +9 -22
  25. package/dist/esm/cli/dataLoader/ast/constant.js +18 -0
  26. package/dist/esm/cli/dataLoader/ast/generateRoutes.js +108 -0
  27. package/dist/esm/cli/dataLoader/ast/index.js +4 -0
  28. package/dist/esm/cli/dataLoader/clearMFCache.js +34 -0
  29. package/dist/esm/cli/dataLoader/generateRouteFile.js +293 -0
  30. package/dist/esm/cli/dataLoader/patchMFConfig.js +106 -0
  31. package/dist/esm/cli/dataLoader/plugin.js +232 -0
  32. package/dist/esm/cli/index.js +6 -2
  33. package/dist/esm/cli/mfRuntimePlugins/{inject-node-fetch.js → node-fetch.js} +3 -3
  34. package/dist/esm/cli/mfRuntimePlugins/node.js +13 -0
  35. package/dist/esm/cli/server/dataLoaderPlugin.js +107 -0
  36. package/dist/esm/cli/server/fetchRemoteFullRoutesMap.js +88 -0
  37. package/dist/esm/cli/ssrPlugin.js +6 -3
  38. package/dist/esm/cli/utils.js +13 -8
  39. package/dist/esm/cli/utils.spec.js +5 -6
  40. package/dist/esm/constant.js +21 -1
  41. package/dist/esm/interfaces/route.js +0 -0
  42. package/dist/esm/runtime/dataLoader/plugin-inject-assets.js +73 -0
  43. package/dist/esm/runtime/dataLoader/plugin.js +94 -0
  44. package/dist/esm/runtime/dataLoader/utils.js +77 -0
  45. package/dist/esm/runtime/index.js +3 -1
  46. package/dist/esm/runtime/withMFRouteId.js +7 -0
  47. package/dist/esm/ssr-runtime/plugin.js +10 -26
  48. package/dist/esm-node/cli/dataLoader/ast/constant.js +18 -0
  49. package/dist/esm-node/cli/dataLoader/ast/generateRoutes.js +107 -0
  50. package/dist/esm-node/cli/dataLoader/ast/index.js +4 -0
  51. package/dist/esm-node/cli/dataLoader/clearMFCache.js +33 -0
  52. package/dist/esm-node/cli/dataLoader/generateRouteFile.js +108 -0
  53. package/dist/esm-node/cli/dataLoader/patchMFConfig.js +106 -0
  54. package/dist/esm-node/cli/dataLoader/plugin.js +169 -0
  55. package/dist/esm-node/cli/index.js +5 -1
  56. package/dist/esm-node/cli/mfRuntimePlugins/{inject-node-fetch.js → node-fetch.js} +3 -3
  57. package/dist/esm-node/cli/mfRuntimePlugins/node.js +11 -0
  58. package/dist/esm-node/cli/mfRuntimePlugins/resolve-entry-ipv4.js +40 -38
  59. package/dist/esm-node/cli/server/dataLoaderPlugin.js +64 -0
  60. package/dist/esm-node/cli/server/fetchRemoteFullRoutesMap.js +44 -0
  61. package/dist/esm-node/cli/ssrPlugin.js +5 -2
  62. package/dist/esm-node/cli/utils.js +9 -5
  63. package/dist/esm-node/cli/utils.spec.js +5 -6
  64. package/dist/esm-node/constant.js +21 -1
  65. package/dist/esm-node/interfaces/route.js +0 -0
  66. package/dist/esm-node/runtime/dataLoader/plugin-inject-assets.js +70 -0
  67. package/dist/esm-node/runtime/dataLoader/plugin.js +50 -0
  68. package/dist/esm-node/runtime/dataLoader/utils.js +77 -0
  69. package/dist/esm-node/runtime/index.js +3 -1
  70. package/dist/esm-node/runtime/withMFRouteId.js +7 -0
  71. package/dist/esm-node/ssr-runtime/plugin.js +9 -22
  72. package/dist/types/cli/dataLoader/ast/constant.d.ts +8 -0
  73. package/dist/types/cli/dataLoader/ast/generateRoutes.d.ts +5 -0
  74. package/dist/types/cli/dataLoader/ast/index.d.ts +1 -0
  75. package/dist/types/cli/dataLoader/clearMFCache.d.ts +1 -0
  76. package/dist/types/cli/dataLoader/generateRouteFile.d.ts +7 -0
  77. package/dist/types/cli/dataLoader/patchMFConfig.d.ts +10 -0
  78. package/dist/types/cli/dataLoader/plugin.d.ts +6 -0
  79. package/dist/types/cli/mfRuntimePlugins/node.d.ts +3 -0
  80. package/dist/types/cli/server/dataLoaderPlugin.d.ts +10 -0
  81. package/dist/types/cli/server/fetchRemoteFullRoutesMap.d.ts +10 -0
  82. package/dist/types/cli/utils.d.ts +2 -0
  83. package/dist/types/constant.d.ts +10 -0
  84. package/dist/types/interfaces/route.d.ts +12 -0
  85. package/dist/types/runtime/dataLoader/plugin-inject-assets.d.ts +4 -0
  86. package/dist/types/runtime/dataLoader/plugin.d.ts +4 -0
  87. package/dist/types/runtime/dataLoader/utils.d.ts +22 -0
  88. package/dist/types/runtime/index.d.ts +1 -0
  89. package/dist/types/runtime/withMFRouteId.d.ts +1 -0
  90. package/dist/types/ssr-runtime/plugin.d.ts +3 -1
  91. package/dist/types/types/index.d.ts +9 -0
  92. package/package.json +48 -11
  93. package/dist/esm/cli/constant.js +0 -4
  94. package/dist/esm/cli/mfRuntimePlugins/shared-strategy.js +0 -25
  95. package/dist/esm-node/cli/constant.js +0 -4
  96. package/dist/esm-node/cli/mfRuntimePlugins/shared-strategy.js +0 -23
  97. package/dist/types/cli/constant.d.ts +0 -1
  98. package/dist/types/cli/mfRuntimePlugins/shared-strategy.d.ts +0 -3
  99. /package/dist/types/cli/mfRuntimePlugins/{inject-node-fetch.d.ts → node-fetch.d.ts} +0 -0
@@ -1,27 +1,25 @@
1
1
  import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
2
- import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
3
2
  import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
4
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
5
- import hoistNonReactStatics from "hoist-non-react-statics";
6
- import { SSRLiveReload } from "./SSRLiveReload";
7
- var mfSSRPlugin = function() {
3
+ console.log("mfSSRPlugin trigger");
4
+ var mfSSRPlugin = function(param) {
5
+ var metaName = param.metaName;
8
6
  return {
9
7
  name: "@module-federation/modern-js",
8
+ pre: [
9
+ "@".concat(metaName, "/plugin-router")
10
+ ],
10
11
  setup: function() {
11
12
  return {
12
- init: function init(param, next) {
13
- var context = param.context;
13
+ beforeRender: function beforeRender() {
14
14
  return _async_to_generator(function() {
15
15
  var nodeUtils, shouldUpdate;
16
16
  return _ts_generator(this, function(_state) {
17
17
  switch (_state.label) {
18
18
  case 0:
19
+ console.log("live reload beforeRender");
19
20
  if (typeof window !== "undefined") {
20
21
  return [
21
- 2,
22
- next({
23
- context
24
- })
22
+ 2
25
23
  ];
26
24
  }
27
25
  globalThis.shouldUpdate = false;
@@ -53,25 +51,11 @@ var mfSSRPlugin = function() {
53
51
  _state.label = 4;
54
52
  case 4:
55
53
  return [
56
- 2,
57
- next({
58
- context
59
- })
54
+ 2
60
55
  ];
61
56
  }
62
57
  });
63
58
  })();
64
- },
65
- wrapRoot: function wrapRoot(App) {
66
- var AppWrapper = function(props) {
67
- return /* @__PURE__ */ _jsxs(_Fragment, {
68
- children: [
69
- /* @__PURE__ */ _jsx(SSRLiveReload, {}),
70
- /* @__PURE__ */ _jsx(App, _object_spread({}, props))
71
- ]
72
- });
73
- };
74
- return hoistNonReactStatics(AppWrapper, App);
75
59
  }
76
60
  };
77
61
  }
@@ -0,0 +1,18 @@
1
+ const IS_ROOT = "isRoot";
2
+ const ID = "id";
3
+ const COMPONENT = "component";
4
+ const LAZY_COMPONENT = "lazyImport";
5
+ const SHOULD_REVALIDATE = "shouldRevalidate";
6
+ const PRIVATE_COMPONENT = "_component";
7
+ const ELEMENT = "element";
8
+ const LOADER = "loader";
9
+ export {
10
+ COMPONENT,
11
+ ELEMENT,
12
+ ID,
13
+ IS_ROOT,
14
+ LAZY_COMPONENT,
15
+ LOADER,
16
+ PRIVATE_COMPONENT,
17
+ SHOULD_REVALIDATE
18
+ };
@@ -0,0 +1,107 @@
1
+ import fs from "fs";
2
+ import traverse from "@babel/traverse";
3
+ import * as babelParser from "@babel/parser";
4
+ import generate from "@babel/generator";
5
+ import * as t from "@babel/types";
6
+ function findTargetKeyNode(nodeProperties, key) {
7
+ return nodeProperties.find((p) => t.isObjectProperty(p) && t.isStringLiteral(p.key) && p.key.value === key);
8
+ }
9
+ function generateRoutes({ sourceCode, filePath }) {
10
+ const ast = babelParser.parse(sourceCode, {
11
+ sourceType: "module"
12
+ });
13
+ const lazyComponentDeclarations = [];
14
+ const componentDeclarations = [];
15
+ let componentId = 0;
16
+ traverse(ast, {
17
+ // ImportDeclaration(path) {
18
+ // const source = path.node.source.value;
19
+ // const routeIdMatch = source.match(/routeId=([^&]+)/);
20
+ // if (routeIdMatch) {
21
+ // const originalRouteId = routeIdMatch[1];
22
+ // const newRouteId = `${prefix}${originalRouteId}`;
23
+ // const newSource = source.replace(
24
+ // /routeId=[^&]+/,
25
+ // `routeId=${newRouteId}`,
26
+ // );
27
+ // path.node.source = t.stringLiteral(newSource);
28
+ // }
29
+ // },
30
+ ObjectExpression(path) {
31
+ let componentName = "";
32
+ let lazyComponentName = "";
33
+ if (!Array.isArray(path.node.properties)) {
34
+ return;
35
+ }
36
+ const idNode = findTargetKeyNode(path.node.properties, "id");
37
+ if (idNode && t.isObjectProperty(idNode) && t.isStringLiteral(idNode.value)) {
38
+ }
39
+ const isRootNode = findTargetKeyNode(path.node.properties, "isRoot");
40
+ if (isRootNode && t.isObjectProperty(isRootNode) && t.isBooleanLiteral(isRootNode.value)) {
41
+ isRootNode.value.value = false;
42
+ }
43
+ if (!isRootNode) {
44
+ const lazyComponentNode = findTargetKeyNode(path.node.properties, "lazyImport");
45
+ if (lazyComponentNode && t.isObjectProperty(lazyComponentNode) && t.isArrowFunctionExpression(lazyComponentNode.value)) {
46
+ lazyComponentName = `LazyComponent_${componentId}`;
47
+ const lazyDeclaration = t.variableDeclaration("const", [
48
+ t.variableDeclarator(t.identifier(lazyComponentName), lazyComponentNode.value)
49
+ ]);
50
+ lazyComponentNode.value = t.identifier(lazyComponentName);
51
+ const componentNode2 = findTargetKeyNode(path.node.properties, "component");
52
+ if (componentNode2 && t.isObjectProperty(componentNode2) && t.isCallExpression(componentNode2.value) && t.isIdentifier(componentNode2.value.callee)) {
53
+ componentNode2.value = t.callExpression(t.identifier("lazy"), [
54
+ t.identifier(lazyComponentName)
55
+ ]);
56
+ }
57
+ lazyComponentDeclarations.push(lazyDeclaration);
58
+ }
59
+ }
60
+ const componentNode = findTargetKeyNode(path.node.properties, "component");
61
+ if (componentNode && t.isObjectProperty(componentNode) && t.isCallExpression(componentNode.value) && t.isIdentifier(componentNode.value.callee)) {
62
+ componentName = `Component_${componentId}`;
63
+ const componentDeclaration = t.variableDeclaration("const", [
64
+ t.variableDeclarator(t.identifier(componentName), lazyComponentName ? t.callExpression(t.identifier("lazy"), [
65
+ t.identifier(lazyComponentName)
66
+ ]) : componentNode.value)
67
+ ]);
68
+ componentDeclarations.push(componentDeclaration);
69
+ componentNode.value = t.identifier(componentName);
70
+ }
71
+ if (lazyComponentName || componentName) {
72
+ componentId++;
73
+ if (componentName) {
74
+ const upperFirstName = componentName.slice(0, 1).toUpperCase() + componentName.slice(1);
75
+ const jsxElement = t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier(upperFirstName), [], true), null, [], true);
76
+ path.node.properties.push(t.objectProperty(t.identifier("element"), jsxElement));
77
+ }
78
+ }
79
+ }
80
+ });
81
+ traverse(ast, {
82
+ Program(path) {
83
+ const lastImportIndex = path.get("body").reduce((lastIndex, p, index) => {
84
+ if (t.isImportDeclaration(p.node)) {
85
+ lastIndex = index;
86
+ }
87
+ return lastIndex;
88
+ }, -1);
89
+ if (lastImportIndex >= 0) {
90
+ const lastImport = path.get(`body.${lastImportIndex}`);
91
+ [
92
+ ...componentDeclarations,
93
+ ...lazyComponentDeclarations
94
+ ].forEach((declaration) => {
95
+ if ("insertAfter" in lastImport) {
96
+ lastImport.insertAfter(declaration);
97
+ }
98
+ });
99
+ }
100
+ }
101
+ });
102
+ const { code } = generate(ast);
103
+ fs.writeFileSync(filePath, code);
104
+ }
105
+ export {
106
+ generateRoutes
107
+ };
@@ -0,0 +1,4 @@
1
+ import { generateRoutes } from "./generateRoutes";
2
+ export {
3
+ generateRoutes
4
+ };
@@ -0,0 +1,33 @@
1
+ function clearMFCache() {
2
+ if (!globalThis.__FEDERATION__) {
3
+ console.log("clearMFCache no globalThis.__FEDERATION__");
4
+ return;
5
+ }
6
+ globalThis.__FEDERATION__.__INSTANCES__.map((i) => {
7
+ i.moduleCache.forEach((mc) => {
8
+ if (mc.remoteInfo && mc.remoteInfo.entryGlobalName) {
9
+ delete globalThis[mc.remoteInfo.entryGlobalName];
10
+ }
11
+ });
12
+ i.moduleCache.clear();
13
+ if (globalThis[i.name]) {
14
+ delete globalThis[i.name];
15
+ }
16
+ });
17
+ Object.keys(globalThis.__FEDERATION__).forEach((key) => {
18
+ if (Array.isArray(globalThis.__FEDERATION__[key])) {
19
+ globalThis.__FEDERATION__[key] = [];
20
+ } else if (key === "__PRELOADED_MAP__") {
21
+ globalThis.__FEDERATION__[key] = /* @__PURE__ */ new Map();
22
+ } else if (typeof globalThis.__FEDERATION__[key] === "object") {
23
+ globalThis.__FEDERATION__[key] = {};
24
+ }
25
+ });
26
+ if (globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__) {
27
+ globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__ = {};
28
+ }
29
+ globalThis.FORCE_MF_REFRESH = true;
30
+ }
31
+ export {
32
+ clearMFCache
33
+ };
@@ -0,0 +1,108 @@
1
+ import { fs, normalizeToPosixPath } from "@modern-js/utils";
2
+ import path from "path";
3
+ import { MF_JSON } from "../../constant";
4
+ import { getRemoteLayoutId } from "../../runtime/dataLoader/utils";
5
+ const ROUTES = "routes";
6
+ function calcPathName(filePath, rootDir, entry) {
7
+ const relativePath = path.relative(rootDir, filePath);
8
+ const conditionalReg = /^\[(.*)\]$/;
9
+ const splitPaths = relativePath.split("/").reduce((sum, cur) => {
10
+ if (cur.includes(".")) {
11
+ const split = cur.split(".").map((i) => {
12
+ const match = i.match(conditionalReg);
13
+ if (match) {
14
+ return `:${match[1]}`;
15
+ }
16
+ return i.startsWith("__") ? "" : i;
17
+ });
18
+ sum.push(...split);
19
+ } else {
20
+ const match = cur.match(conditionalReg);
21
+ if (match) {
22
+ sum.push(`:${match[1]}`);
23
+ } else {
24
+ if (!cur.startsWith("__")) {
25
+ sum.push(cur);
26
+ }
27
+ }
28
+ }
29
+ return sum;
30
+ }, []);
31
+ return path.join(entry, splitPaths.filter((p) => !!p).join("/"));
32
+ }
33
+ async function generateRouteFile(options) {
34
+ const { appDirectory } = options;
35
+ const entries = [];
36
+ const remotePathMap = {};
37
+ const srcPath = `${appDirectory}/src`;
38
+ const traverse = async (filepath, rootDir, entry) => {
39
+ if (!await fs.pathExists(filepath)) {
40
+ return null;
41
+ }
42
+ const isDirectory = (await fs.stat(filepath)).isDirectory();
43
+ if (!isDirectory) {
44
+ return null;
45
+ }
46
+ const items = await fs.readdir(filepath);
47
+ const mfJson = items.find((i) => i === MF_JSON);
48
+ if (mfJson) {
49
+ const mfJsonContent = await fs.readJSON(normalizeToPosixPath(path.join(filepath, mfJson)));
50
+ const { remoteName } = mfJsonContent;
51
+ const remoteLayoutId = getRemoteLayoutId(remoteName);
52
+ const writeFile = async (id, type, pathname) => {
53
+ const generatedFilePath = normalizeToPosixPath(path.join(filepath, `${type}.tsx`));
54
+ const content = [
55
+ "// Do not edit this file. It is a auto generated.",
56
+ `// It will render ${remoteName}'s ${type}.`,
57
+ `// The ${type} pathname is: ${pathname}`,
58
+ `// The ${type} route id is: ${id}`
59
+ ];
60
+ await fs.writeFile(generatedFilePath, content.join("\n"));
61
+ };
62
+ if (remoteLayoutId) {
63
+ const pathname = calcPathName(filepath, rootDir, entry);
64
+ writeFile(remoteLayoutId, "layout", pathname);
65
+ remotePathMap[pathname] = remoteName;
66
+ }
67
+ return;
68
+ }
69
+ await Promise.all(items.map(async (item) => {
70
+ await traverse(normalizeToPosixPath(path.join(filepath, item)), rootDir, entry);
71
+ }));
72
+ };
73
+ const traverseRoutes = async (dir, level = 1) => {
74
+ if (level > 3) {
75
+ return;
76
+ }
77
+ const isDirectory = (await fs.stat(dir)).isDirectory();
78
+ if (!isDirectory) {
79
+ return;
80
+ }
81
+ const items = await fs.readdir(dir);
82
+ if (items.find((i) => i === ROUTES)) {
83
+ const entry = path.relative(srcPath, dir);
84
+ entries.push(entry);
85
+ const rootDir = `${dir}/${ROUTES}`;
86
+ await traverse(rootDir, rootDir, entry);
87
+ } else {
88
+ await Promise.all(items.map(async (item) => {
89
+ await traverseRoutes(path.join(dir, item), level++);
90
+ }));
91
+ }
92
+ };
93
+ await traverseRoutes(srcPath);
94
+ const normalizedEntries = entries.map((entry) => {
95
+ if (entry === "") {
96
+ return "main";
97
+ }
98
+ return entry;
99
+ });
100
+ return {
101
+ entries: normalizedEntries,
102
+ remotePathMap
103
+ };
104
+ }
105
+ export {
106
+ calcPathName,
107
+ generateRouteFile
108
+ };
@@ -0,0 +1,106 @@
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
+ if (mfConfig.remotes && mfConfig.exposes) {
56
+ throw new Error(`dataLoader only support for pure provider/consumer!`);
57
+ }
58
+ const { entryMap } = generateExtraExposeFiles(options);
59
+ const addExposeByEntry = (entry, routesPath, routeServerLoaderPath, clientRouteServerLoaderPath) => {
60
+ if (!mfConfig.exposes) {
61
+ mfConfig.exposes = {};
62
+ }
63
+ const routesKey = `./${entry}/${MF_ROUTES}`;
64
+ if (!mfConfig.exposes[routesKey]) {
65
+ mfConfig.exposes[routesKey] = routesPath;
66
+ }
67
+ const routeServerLoaderKey = `./${entry}/${MODERN_JS_ROUTE_SERVER_LOADER}`;
68
+ if (!mfConfig.exposes[routeServerLoaderKey]) {
69
+ if (isServer) {
70
+ mfConfig.exposes[routeServerLoaderKey] = routeServerLoaderPath;
71
+ } else {
72
+ mfConfig.exposes[routeServerLoaderKey] = clientRouteServerLoaderPath;
73
+ }
74
+ }
75
+ };
76
+ Object.keys(entryMap).forEach((entry) => {
77
+ const { routesPath, routeServerLoaderPath, clientRouteServerLoaderPath } = entryMap[entry];
78
+ addExposeByEntry(entry, routesPath, routeServerLoaderPath, clientRouteServerLoaderPath);
79
+ });
80
+ }
81
+ function addShared(options) {
82
+ const { metaName, mfConfig } = options;
83
+ const alias = `@${metaName}/runtime/router`;
84
+ if (!mfConfig.shared) {
85
+ mfConfig.shared = {
86
+ [alias]: {
87
+ singleton: true
88
+ }
89
+ };
90
+ } else {
91
+ if (!Array.isArray(mfConfig.shared)) {
92
+ mfConfig.shared[alias] = {
93
+ singleton: true
94
+ };
95
+ } else {
96
+ mfConfig.shared.push(alias);
97
+ }
98
+ }
99
+ }
100
+ function patchMFConfig(options) {
101
+ addShared(options);
102
+ addExpose(options);
103
+ }
104
+ export {
105
+ patchMFConfig
106
+ };
@@ -0,0 +1,169 @@
1
+ import { transformName2Prefix } from "../../runtime/dataLoader/utils";
2
+ import { DEFAULT_ENTRY } from "../../constant";
3
+ import { META_NAME } from "../../constant";
4
+ import { generateRoutes } from "./ast";
5
+ import { generateRouteFile } from "./generateRouteFile";
6
+ import { patchMFConfig } from "./patchMFConfig";
7
+ import { clearMFCache } from "./clearMFCache";
8
+ import path from "path";
9
+ function _transformRuntimeOptions(buildOptions) {
10
+ const remotes = buildOptions.remotes || {};
11
+ const runtimeRemotes = Object.entries(remotes).map((remote) => {
12
+ const [alias, nameAndEntry] = remote;
13
+ const [name, entry] = nameAndEntry.split("@");
14
+ return {
15
+ name,
16
+ entry,
17
+ alias
18
+ };
19
+ });
20
+ return {
21
+ name: buildOptions.name,
22
+ remotes: runtimeRemotes
23
+ };
24
+ }
25
+ const moduleFederationDataLoaderPlugin = (enable, internalOptions, userConfig) => ({
26
+ name: "@modern-js/plugin-module-federation-data-loader",
27
+ pre: [
28
+ "@modern-js/plugin-module-federation-config"
29
+ ],
30
+ post: [
31
+ "@modern-js/plugin-router",
32
+ "@modern-js/plugin-module-federation"
33
+ ],
34
+ setup: async ({ useAppContext }) => {
35
+ if (!enable) {
36
+ return;
37
+ }
38
+ const { serverPlugin = "@module-federation/modern-js/data-loader-server", transformRuntimeOptions } = userConfig;
39
+ const appContext = useAppContext();
40
+ const name = internalOptions.csrConfig.name;
41
+ const { metaName = META_NAME } = internalOptions;
42
+ const internalDirectory = appContext.internalDirectory.replace(META_NAME, metaName || META_NAME);
43
+ const transformRuntimeFn = transformRuntimeOptions || _transformRuntimeOptions;
44
+ const partialSSRRemotes = [];
45
+ const entries = /* @__PURE__ */ new Set();
46
+ let remotePathMap = {};
47
+ const ssrByRouteIdsMap = {};
48
+ const serverPluginOptions = {
49
+ runtimeOptions: transformRuntimeFn(internalOptions.csrConfig),
50
+ partialSSRRemotes,
51
+ ssrByRouteIdsMap
52
+ };
53
+ const csrConfig = internalOptions.csrConfig;
54
+ if (typeof csrConfig.remotes === "object" && Object.keys(csrConfig.remotes).length) {
55
+ const { entries: scanEntries, remotePathMap: scanRemotePathMap } = await generateRouteFile({
56
+ appDirectory: appContext.appDirectory
57
+ });
58
+ scanEntries.forEach((e) => entries.add(e));
59
+ remotePathMap = scanRemotePathMap;
60
+ } else {
61
+ entries.add(DEFAULT_ENTRY);
62
+ }
63
+ return {
64
+ _internalRuntimePlugins: ({ entrypoint, plugins }) => {
65
+ plugins.push({
66
+ name: "ssrDataLoader",
67
+ path: "@module-federation/modern-js/data-loader",
68
+ config: {
69
+ metaName
70
+ }
71
+ });
72
+ plugins.push({
73
+ name: "ssrDataLoaderInjectAssets",
74
+ path: "@module-federation/modern-js/data-loader-inject-assets",
75
+ config: {
76
+ metaName
77
+ }
78
+ });
79
+ return {
80
+ entrypoint,
81
+ plugins
82
+ };
83
+ },
84
+ _internalServerPlugins({ plugins }) {
85
+ plugins.push({
86
+ name: serverPlugin,
87
+ options: serverPluginOptions
88
+ });
89
+ return {
90
+ plugins
91
+ };
92
+ },
93
+ async modifyFileSystemRoutes(options) {
94
+ const { routes, entrypoint } = options;
95
+ const { entryName } = entrypoint;
96
+ const prefix = transformName2Prefix(internalOptions.csrConfig.name);
97
+ const modifyRouteIds = (route, pathName) => {
98
+ const currentPathName = route.path ? path.join(pathName, route.path) : pathName;
99
+ if (route.id) {
100
+ var _route_children;
101
+ const originalId = route.id;
102
+ route.originalId = originalId;
103
+ const remoteName = remotePathMap[currentPathName];
104
+ if (remoteName) {
105
+ const remoteIdPrefix = transformName2Prefix(remoteName);
106
+ const isLayout = Boolean(route.children);
107
+ const newId = `${remoteIdPrefix}${isLayout ? "layout" : "page"}`;
108
+ ssrByRouteIdsMap[originalId] = newId;
109
+ route.id = newId;
110
+ if (!partialSSRRemotes.includes(remoteName)) {
111
+ partialSSRRemotes.push(remoteName);
112
+ }
113
+ } else {
114
+ route.id = `${prefix}${route.id}`;
115
+ }
116
+ (_route_children = route.children) === null || _route_children === void 0 ? void 0 : _route_children.forEach((r) => {
117
+ modifyRouteIds(r, currentPathName);
118
+ });
119
+ }
120
+ };
121
+ routes.forEach((route) => {
122
+ modifyRouteIds(route, entryName);
123
+ });
124
+ return options;
125
+ },
126
+ config: async () => {
127
+ return {
128
+ tools: {
129
+ // bundlerChain can not keep target order
130
+ rspack(_config, { isServer }) {
131
+ patchMFConfig({
132
+ mfConfig: isServer ? internalOptions.ssrConfig : internalOptions.csrConfig,
133
+ metaName,
134
+ isServer,
135
+ internalDirectory,
136
+ entries
137
+ });
138
+ },
139
+ // bundlerChain can not keep target order
140
+ webpack(_config, { isServer }) {
141
+ patchMFConfig({
142
+ mfConfig: isServer ? internalOptions.ssrConfig : internalOptions.csrConfig,
143
+ metaName,
144
+ isServer,
145
+ internalDirectory,
146
+ entries
147
+ });
148
+ }
149
+ },
150
+ source: {
151
+ define: {
152
+ MODERN_ROUTER_ID_PREFIX: JSON.stringify(transformName2Prefix(name))
153
+ }
154
+ }
155
+ };
156
+ },
157
+ async afterDev() {
158
+ clearMFCache();
159
+ console.log("afterDev", globalThis.__VMOK__);
160
+ }
161
+ };
162
+ }
163
+ });
164
+ var plugin_default = moduleFederationDataLoaderPlugin;
165
+ export {
166
+ plugin_default as default,
167
+ generateRoutes,
168
+ moduleFederationDataLoaderPlugin
169
+ };
@@ -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
+ };