@module-federation/modern-js 0.0.0-next-20250522124810 → 0.0.0-next-20250522130707

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 (106) hide show
  1. package/dist/LICENSE +21 -0
  2. package/dist/cjs/cli/configPlugin.js +390 -0
  3. package/dist/cjs/cli/configPlugin.spec.js +114 -0
  4. package/dist/cjs/cli/index.js +85 -0
  5. package/dist/cjs/cli/manifest.js +75 -0
  6. package/dist/cjs/cli/mfRuntimePlugins/auto-fetch-data.js +98 -0
  7. package/dist/cjs/cli/mfRuntimePlugins/inject-node-fetch.js +44 -0
  8. package/dist/cjs/cli/mfRuntimePlugins/resolve-entry-ipv4.js +82 -0
  9. package/dist/cjs/cli/mfRuntimePlugins/shared-strategy.js +43 -0
  10. package/dist/cjs/cli/server/data-fetch-server-plugin.js +184 -0
  11. package/dist/cjs/cli/ssrPlugin.js +222 -0
  12. package/dist/cjs/cli/utils.js +90 -0
  13. package/dist/cjs/constant.js +78 -0
  14. package/dist/cjs/interfaces/bundler.js +16 -0
  15. package/dist/cjs/interfaces/global.js +16 -0
  16. package/dist/cjs/logger.js +27 -0
  17. package/dist/cjs/runtime/AwaitDataFetch.js +144 -0
  18. package/dist/cjs/runtime/createRemoteComponent.js +327 -0
  19. package/dist/cjs/runtime/index.js +47 -0
  20. package/dist/cjs/runtime/wrapNoSSR.js +35 -0
  21. package/dist/cjs/ssr-runtime/SSRLiveReload.js +43 -0
  22. package/dist/cjs/ssr-runtime/devPlugin.js +71 -0
  23. package/dist/cjs/ssr-runtime/downgrade.js +108 -0
  24. package/dist/cjs/ssr-runtime/injectDataFetchFunctionPlugin.js +129 -0
  25. package/dist/cjs/types/index.js +16 -0
  26. package/dist/cjs/utils/dataFetch.js +200 -0
  27. package/dist/cjs/utils/index.js +54 -0
  28. package/dist/esm/cli/configPlugin.js +399 -0
  29. package/dist/esm/cli/configPlugin.spec.js +110 -0
  30. package/dist/esm/cli/index.js +79 -0
  31. package/dist/esm/cli/manifest.js +41 -0
  32. package/dist/esm/cli/mfRuntimePlugins/auto-fetch-data.js +74 -0
  33. package/dist/esm/cli/mfRuntimePlugins/inject-node-fetch.js +16 -0
  34. package/dist/esm/cli/mfRuntimePlugins/resolve-entry-ipv4.js +74 -0
  35. package/dist/esm/cli/mfRuntimePlugins/shared-strategy.js +25 -0
  36. package/dist/esm/cli/server/data-fetch-server-plugin.js +237 -0
  37. package/dist/esm/cli/ssrPlugin.js +204 -0
  38. package/dist/esm/cli/utils.js +53 -0
  39. package/dist/esm/constant.js +42 -0
  40. package/dist/esm/interfaces/bundler.js +0 -0
  41. package/dist/esm/interfaces/global.js +0 -0
  42. package/dist/esm/logger.js +7 -0
  43. package/dist/esm/runtime/AwaitDataFetch.js +131 -0
  44. package/dist/esm/runtime/createRemoteComponent.js +417 -0
  45. package/dist/esm/runtime/index.js +20 -0
  46. package/dist/esm/runtime/wrapNoSSR.js +12 -0
  47. package/dist/esm/ssr-runtime/SSRLiveReload.js +26 -0
  48. package/dist/esm/ssr-runtime/devPlugin.js +73 -0
  49. package/dist/esm/ssr-runtime/downgrade.js +141 -0
  50. package/dist/esm/ssr-runtime/injectDataFetchFunctionPlugin.js +171 -0
  51. package/dist/esm/types/index.js +0 -0
  52. package/dist/esm/utils/dataFetch.js +227 -0
  53. package/dist/esm/utils/index.js +28 -0
  54. package/dist/esm-node/cli/configPlugin.js +349 -0
  55. package/dist/esm-node/cli/configPlugin.spec.js +91 -0
  56. package/dist/esm-node/cli/index.js +60 -0
  57. package/dist/esm-node/cli/manifest.js +41 -0
  58. package/dist/esm-node/cli/mfRuntimePlugins/auto-fetch-data.js +68 -0
  59. package/dist/esm-node/cli/mfRuntimePlugins/inject-node-fetch.js +14 -0
  60. package/dist/esm-node/cli/mfRuntimePlugins/resolve-entry-ipv4.js +62 -0
  61. package/dist/esm-node/cli/mfRuntimePlugins/shared-strategy.js +23 -0
  62. package/dist/esm-node/cli/server/data-fetch-server-plugin.js +154 -0
  63. package/dist/esm-node/cli/ssrPlugin.js +186 -0
  64. package/dist/esm-node/cli/utils.js +53 -0
  65. package/dist/esm-node/constant.js +42 -0
  66. package/dist/esm-node/interfaces/bundler.js +0 -0
  67. package/dist/esm-node/interfaces/global.js +0 -0
  68. package/dist/esm-node/logger.js +7 -0
  69. package/dist/esm-node/runtime/AwaitDataFetch.js +109 -0
  70. package/dist/esm-node/runtime/createRemoteComponent.js +291 -0
  71. package/dist/esm-node/runtime/index.js +20 -0
  72. package/dist/esm-node/runtime/wrapNoSSR.js +11 -0
  73. package/dist/esm-node/ssr-runtime/SSRLiveReload.js +19 -0
  74. package/dist/esm-node/ssr-runtime/devPlugin.js +37 -0
  75. package/dist/esm-node/ssr-runtime/downgrade.js +82 -0
  76. package/dist/esm-node/ssr-runtime/injectDataFetchFunctionPlugin.js +95 -0
  77. package/dist/esm-node/types/index.js +0 -0
  78. package/dist/esm-node/utils/dataFetch.js +156 -0
  79. package/dist/esm-node/utils/index.js +27 -0
  80. package/dist/types/cli/configPlugin.d.ts +21 -0
  81. package/dist/types/cli/configPlugin.spec.d.ts +1 -0
  82. package/dist/types/cli/index.d.ts +6 -0
  83. package/dist/types/cli/manifest.d.ts +2 -0
  84. package/dist/types/cli/mfRuntimePlugins/auto-fetch-data.d.ts +3 -0
  85. package/dist/types/cli/mfRuntimePlugins/inject-node-fetch.d.ts +3 -0
  86. package/dist/types/cli/mfRuntimePlugins/resolve-entry-ipv4.d.ts +3 -0
  87. package/dist/types/cli/mfRuntimePlugins/shared-strategy.d.ts +3 -0
  88. package/dist/types/cli/server/data-fetch-server-plugin.d.ts +3 -0
  89. package/dist/types/cli/ssrPlugin.d.ts +6 -0
  90. package/dist/types/cli/utils.d.ts +6 -0
  91. package/dist/types/constant.d.ts +25 -0
  92. package/dist/types/interfaces/bundler.d.ts +18 -0
  93. package/dist/types/interfaces/global.d.ts +27 -0
  94. package/dist/types/logger.d.ts +2 -0
  95. package/dist/types/runtime/AwaitDataFetch.d.ts +19 -0
  96. package/dist/types/runtime/createRemoteComponent.d.ts +26 -0
  97. package/dist/types/runtime/index.d.ts +9 -0
  98. package/dist/types/runtime/wrapNoSSR.d.ts +9 -0
  99. package/dist/types/ssr-runtime/SSRLiveReload.d.ts +1 -0
  100. package/dist/types/ssr-runtime/devPlugin.d.ts +2 -0
  101. package/dist/types/ssr-runtime/downgrade.d.ts +4 -0
  102. package/dist/types/ssr-runtime/injectDataFetchFunctionPlugin.d.ts +2 -0
  103. package/dist/types/types/index.d.ts +22 -0
  104. package/dist/types/utils/dataFetch.d.ts +25 -0
  105. package/dist/types/utils/index.d.ts +15 -0
  106. package/package.json +8 -8
@@ -0,0 +1,23 @@
1
+ const sharedStrategy = () => ({
2
+ name: "shared-strategy-plugin",
3
+ beforeInit(args) {
4
+ const { userOptions } = args;
5
+ const shared = userOptions.shared;
6
+ if (shared) {
7
+ Object.keys(shared).forEach((sharedKey) => {
8
+ const sharedConfigs = shared[sharedKey];
9
+ const arraySharedConfigs = Array.isArray(sharedConfigs) ? sharedConfigs : [
10
+ sharedConfigs
11
+ ];
12
+ arraySharedConfigs.forEach((s) => {
13
+ s.strategy = "loaded-first";
14
+ });
15
+ });
16
+ }
17
+ return args;
18
+ }
19
+ });
20
+ var shared_strategy_default = sharedStrategy;
21
+ export {
22
+ shared_strategy_default as default
23
+ };
@@ -0,0 +1,154 @@
1
+ import { DATA_FETCH_QUERY } from "../../constant";
2
+ import logger from "../../logger";
3
+ import { getDataFetchMap } from "../../utils";
4
+ import { fetchData, initDataFetchMap, loadDataFetchModule } from "../../utils/dataFetch";
5
+ import { SEPARATOR } from "@module-federation/sdk";
6
+ function wrapSetTimeout(targetPromise, delay = 2e4, id) {
7
+ if (targetPromise && typeof targetPromise.then === "function") {
8
+ return new Promise((resolve, reject) => {
9
+ const timeoutId = setTimeout(() => {
10
+ logger.warn(`Data fetch for ID ${id} timed out after 20 seconds.`);
11
+ reject(new Error(`Data fetch for ID ${id} timed out after 20 seconds`));
12
+ }, delay);
13
+ targetPromise.then((value) => {
14
+ clearTimeout(timeoutId);
15
+ resolve(value);
16
+ }).catch((err) => {
17
+ clearTimeout(timeoutId);
18
+ reject(err);
19
+ });
20
+ });
21
+ }
22
+ }
23
+ function addProtocol(url) {
24
+ if (url.startsWith("//")) {
25
+ return "https:" + url;
26
+ }
27
+ return url;
28
+ }
29
+ const getDecodeQuery = (url, name) => {
30
+ const res = url.searchParams.get(name);
31
+ if (!res) {
32
+ return null;
33
+ }
34
+ return decodeURIComponent(res);
35
+ };
36
+ const middleware = async (ctx, next) => {
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
+ console.error(e);
49
+ return next();
50
+ }
51
+ if (!dataFetchId) {
52
+ return next();
53
+ }
54
+ logger.debug("dataFetchId: ", dataFetchId);
55
+ try {
56
+ var _dataFetchMap_dataFetchId;
57
+ const dataFetchMap = getDataFetchMap();
58
+ if (!dataFetchMap) {
59
+ initDataFetchMap();
60
+ }
61
+ const fetchDataPromise = (_dataFetchMap_dataFetchId = dataFetchMap[dataFetchId]) === null || _dataFetchMap_dataFetchId === void 0 ? void 0 : _dataFetchMap_dataFetchId[1];
62
+ if (fetchDataPromise) {
63
+ const targetPromise = fetchDataPromise[0];
64
+ const wrappedPromise = wrapSetTimeout(targetPromise, 2e4, dataFetchId);
65
+ if (wrappedPromise) {
66
+ const res = await wrappedPromise;
67
+ return ctx.json(res);
68
+ }
69
+ logger.error(`Expected a Promise from fetchDataPromise[0] for dataFetchId ${dataFetchId}, but received:`, targetPromise, "Will try call new dataFetch again...");
70
+ }
71
+ if (remoteInfo) {
72
+ try {
73
+ const hostInstance2 = globalThis.__FEDERATION__.__INSTANCES__[0];
74
+ const remoteEntry = `${addProtocol(remoteInfo.ssrPublicPath) + remoteInfo.ssrRemoteEntry}`;
75
+ if (!hostInstance2) {
76
+ throw new Error("host instance not found!");
77
+ }
78
+ const remote = hostInstance2.options.remotes.find((remote2) => remote2.name === remoteInfo.name);
79
+ logger.debug("find remote: ", JSON.stringify(remote));
80
+ if (!remote) {
81
+ hostInstance2.registerRemotes([
82
+ {
83
+ name: remoteInfo.name,
84
+ entry: remoteEntry,
85
+ entryGlobalName: remoteInfo.globalName
86
+ }
87
+ ]);
88
+ } else {
89
+ const { hostGlobalSnapshot, remoteSnapshot } = hostInstance2.snapshotHandler.getGlobalRemoteInfo(remoteInfo);
90
+ logger.debug("find hostGlobalSnapshot: ", JSON.stringify(hostGlobalSnapshot));
91
+ logger.debug("find remoteSnapshot: ", JSON.stringify(remoteSnapshot));
92
+ if (!hostGlobalSnapshot || !remoteSnapshot) {
93
+ if ("version" in remote) {
94
+ delete remote.version;
95
+ }
96
+ remote.entry = remoteEntry;
97
+ remote.entryGlobalName = remoteInfo.globalName;
98
+ }
99
+ }
100
+ } catch (e) {
101
+ ctx.status(500);
102
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
103
+ ${e}`);
104
+ }
105
+ }
106
+ const dataFetchItem = dataFetchMap[dataFetchId];
107
+ if (dataFetchItem) {
108
+ const callFetchDataPromise = fetchData(dataFetchId, {
109
+ ...params,
110
+ isDowngrade: true
111
+ });
112
+ const wrappedPromise = wrapSetTimeout(callFetchDataPromise, 2e4, dataFetchId);
113
+ if (wrappedPromise) {
114
+ const res = await wrappedPromise;
115
+ return ctx.json(res);
116
+ }
117
+ return next();
118
+ }
119
+ const remoteId = dataFetchId.split(SEPARATOR)[0];
120
+ const hostInstance = globalThis.__FEDERATION__.__INSTANCES__[0];
121
+ if (!hostInstance) {
122
+ throw new Error("host instance not found!");
123
+ }
124
+ const dataFetchFn = await loadDataFetchModule(hostInstance, remoteId);
125
+ const data = await dataFetchFn({
126
+ ...params,
127
+ isDowngrade: !remoteInfo
128
+ });
129
+ return ctx.json(data);
130
+ } catch (e) {
131
+ console.log("data fetch error:");
132
+ console.error(e);
133
+ ctx.status(500);
134
+ return ctx.text(`failed to fetch ${remoteInfo.name} data, error:
135
+ ${e}`);
136
+ }
137
+ };
138
+ const dataFetchServePlugin = () => ({
139
+ name: "mf-data-fetch-server-plugin",
140
+ setup: (api) => {
141
+ api.onPrepare(() => {
142
+ const { middlewares } = api.getServerContext();
143
+ middlewares.push({
144
+ name: "module-federation-serve-manifest",
145
+ // @ts-ignore type error
146
+ handler: middleware
147
+ });
148
+ });
149
+ }
150
+ });
151
+ var data_fetch_server_plugin_default = dataFetchServePlugin;
152
+ export {
153
+ data_fetch_server_plugin_default as default
154
+ };
@@ -0,0 +1,186 @@
1
+ import path from "path";
2
+ import { fs } from "@modern-js/utils";
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 { updateStatsAndManifest } from "./manifest";
7
+ import logger from "../logger";
8
+ import { isDev } from "./utils";
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
+ plugins.push({
80
+ name: "injectDataFetchFunction",
81
+ path: "@module-federation/modern-js/ssr-inject-data-fetch-function-plugin",
82
+ config: {}
83
+ });
84
+ if (!isDev()) {
85
+ return {
86
+ entrypoint,
87
+ plugins
88
+ };
89
+ }
90
+ plugins.push({
91
+ name: "mfSSRDev",
92
+ path: "@module-federation/modern-js/ssr-dev-plugin",
93
+ config: {}
94
+ });
95
+ return {
96
+ entrypoint,
97
+ plugins
98
+ };
99
+ });
100
+ api.modifyBundlerChain((chain) => {
101
+ const target = chain.get("target");
102
+ if (skipByTarget(target)) {
103
+ return;
104
+ }
105
+ const bundlerType = api.getAppContext().bundlerType === "rspack" ? "rspack" : "webpack";
106
+ const MFPlugin = bundlerType === "webpack" ? ModuleFederationPlugin : RspackModuleFederationPlugin;
107
+ const isWeb = isWebTarget(target);
108
+ if (!isWeb) {
109
+ if (!chain.plugins.has(CHAIN_MF_PLUGIN_ID)) {
110
+ chain.plugin(CHAIN_MF_PLUGIN_ID).use(MFPlugin, [
111
+ pluginOptions.ssrConfig
112
+ ]).init((Plugin, args) => {
113
+ pluginOptions.nodePlugin = new Plugin(args[0]);
114
+ return pluginOptions.nodePlugin;
115
+ });
116
+ }
117
+ }
118
+ if (!isWeb) {
119
+ chain.target("async-node");
120
+ if (isDev()) {
121
+ chain.plugin("UniverseEntryChunkTrackerPlugin").use(UniverseEntryChunkTrackerPlugin);
122
+ }
123
+ const userSSRConfig = pluginOptions.userConfig.ssr ? typeof pluginOptions.userConfig.ssr === "object" ? pluginOptions.userConfig.ssr : {} : {};
124
+ const publicPath = chain.output.get("publicPath");
125
+ if (userSSRConfig.distOutputDir && publicPath) {
126
+ chain.output.publicPath(`${publicPath}${userSSRConfig.distOutputDir}/`);
127
+ }
128
+ }
129
+ if (isDev() && isWeb) {
130
+ chain.externals({
131
+ "@module-federation/node/utils": "NOT_USED_IN_BROWSER"
132
+ });
133
+ }
134
+ });
135
+ api.config(() => {
136
+ return {
137
+ builderPlugins: [
138
+ mfSSRRsbuildPlugin(pluginOptions)
139
+ ],
140
+ tools: {
141
+ devServer: {
142
+ before: [
143
+ (req, res, next) => {
144
+ if (!enableSSR) {
145
+ next();
146
+ return;
147
+ }
148
+ try {
149
+ var _req_url, _req_url1;
150
+ 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"))) {
151
+ const filepath = path.join(process.cwd(), `dist${req.url}`);
152
+ fs.statSync(filepath);
153
+ res.setHeader("Access-Control-Allow-Origin", "*");
154
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
155
+ res.setHeader("Access-Control-Allow-Headers", "*");
156
+ fs.createReadStream(filepath).pipe(res);
157
+ } else {
158
+ next();
159
+ }
160
+ } catch (err) {
161
+ logger.debug(err);
162
+ next();
163
+ }
164
+ }
165
+ ]
166
+ }
167
+ }
168
+ };
169
+ });
170
+ api.onAfterBuild(() => {
171
+ const { nodePlugin, browserPlugin, distOutputDir } = pluginOptions;
172
+ updateStatsAndManifest(nodePlugin, browserPlugin, distOutputDir);
173
+ });
174
+ api.onDevCompileDone(() => {
175
+ const { nodePlugin, browserPlugin, distOutputDir } = pluginOptions;
176
+ updateStatsAndManifest(nodePlugin, browserPlugin, distOutputDir);
177
+ });
178
+ }
179
+ });
180
+ var ssrPlugin_default = moduleFederationSSRPlugin;
181
+ export {
182
+ CHAIN_MF_PLUGIN_ID,
183
+ ssrPlugin_default as default,
184
+ moduleFederationSSRPlugin,
185
+ setEnv
186
+ };
@@ -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,42 @@
1
+ const LOCALHOST = "localhost";
2
+ const PLUGIN_IDENTIFIER = "[ Modern.js Module Federation ]";
3
+ const DATA_FETCH_QUERY = "x-mf-data-fetch";
4
+ const DATA_FETCH_ERROR_PREFIX = "caught the following error during dataFetch: ";
5
+ const LOAD_REMOTE_ERROR_PREFIX = "caught the following error during loadRemote: ";
6
+ const DOWNGRADE_KEY = "_mfSSRDowngrade";
7
+ const DATA_FETCH_MAP_KEY = "__MF_DATA_FETCH_MAP__";
8
+ const DATA_FETCH_FUNCTION = "_mfDataFetch";
9
+ const FS_HREF = "_mfFSHref";
10
+ const ERROR_TYPE = {
11
+ DATA_FETCH: 1,
12
+ LOAD_REMOTE: 2,
13
+ UNKNOWN: 3
14
+ };
15
+ const WRAP_DATA_FETCH_ID_IDENTIFIER = "wrap_dfip_identifier";
16
+ var MF_DATA_FETCH_TYPE;
17
+ (function(MF_DATA_FETCH_TYPE2) {
18
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_SERVER"] = 1] = "FETCH_SERVER";
19
+ MF_DATA_FETCH_TYPE2[MF_DATA_FETCH_TYPE2["FETCH_CLIENT"] = 2] = "FETCH_CLIENT";
20
+ })(MF_DATA_FETCH_TYPE || (MF_DATA_FETCH_TYPE = {}));
21
+ var MF_DATA_FETCH_STATUS;
22
+ (function(MF_DATA_FETCH_STATUS2) {
23
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADED"] = 1] = "LOADED";
24
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["LOADING"] = 2] = "LOADING";
25
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["AWAIT"] = 0] = "AWAIT";
26
+ MF_DATA_FETCH_STATUS2[MF_DATA_FETCH_STATUS2["ERROR"] = 3] = "ERROR";
27
+ })(MF_DATA_FETCH_STATUS || (MF_DATA_FETCH_STATUS = {}));
28
+ export {
29
+ DATA_FETCH_ERROR_PREFIX,
30
+ DATA_FETCH_FUNCTION,
31
+ DATA_FETCH_MAP_KEY,
32
+ DATA_FETCH_QUERY,
33
+ DOWNGRADE_KEY,
34
+ ERROR_TYPE,
35
+ FS_HREF,
36
+ LOAD_REMOTE_ERROR_PREFIX,
37
+ LOCALHOST,
38
+ MF_DATA_FETCH_STATUS,
39
+ MF_DATA_FETCH_TYPE,
40
+ PLUGIN_IDENTIFIER,
41
+ WRAP_DATA_FETCH_ID_IDENTIFIER
42
+ };
File without changes
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,109 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Suspense, useRef } from "react";
3
+ import logger from "../logger";
4
+ import { DATA_FETCH_ERROR_PREFIX, LOAD_REMOTE_ERROR_PREFIX, ERROR_TYPE, DATA_FETCH_FUNCTION } from "../constant";
5
+ import { getDataFetchIdWithErrorMsgs, wrapDataFetchId } from "../utils";
6
+ function isPromise(obj) {
7
+ return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
8
+ }
9
+ const AWAIT_ERROR_PREFIX = "<Await /> caught the following error during render: ";
10
+ const transformError = (err) => {
11
+ const errMsg = err instanceof Error ? err.message : err;
12
+ const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, "");
13
+ const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);
14
+ if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {
15
+ return {
16
+ error: new Error(originalMsg.replace(DATA_FETCH_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")),
17
+ errorType: ERROR_TYPE.DATA_FETCH,
18
+ dataFetchMapKey
19
+ };
20
+ }
21
+ if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {
22
+ return {
23
+ error: new Error(originalMsg.replace(LOAD_REMOTE_ERROR_PREFIX, "").replace(wrapDataFetchId(dataFetchMapKey), "")),
24
+ errorType: ERROR_TYPE.LOAD_REMOTE,
25
+ dataFetchMapKey
26
+ };
27
+ }
28
+ return {
29
+ error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), "")),
30
+ errorType: ERROR_TYPE.UNKNOWN,
31
+ dataFetchMapKey
32
+ };
33
+ };
34
+ const DefaultLoading = /* @__PURE__ */ _jsx(_Fragment, {});
35
+ const DefaultErrorElement = (_data) => /* @__PURE__ */ _jsx("div", {
36
+ children: "Error"
37
+ });
38
+ function AwaitDataFetch({ resolve, loading = DefaultLoading, errorElement = DefaultErrorElement, children, params }) {
39
+ const dataRef = useRef();
40
+ const data = dataRef.current || resolve;
41
+ const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;
42
+ return /* @__PURE__ */ _jsx(AwaitSuspense, {
43
+ params,
44
+ loading,
45
+ errorElement,
46
+ // @ts-ignore
47
+ resolve: getData,
48
+ children
49
+ });
50
+ }
51
+ function AwaitSuspense({ resolve, children, loading = DefaultLoading, errorElement = DefaultErrorElement }) {
52
+ return /* @__PURE__ */ _jsx(Suspense, {
53
+ fallback: loading,
54
+ children: /* @__PURE__ */ _jsx(ResolveAwait, {
55
+ resolve,
56
+ errorElement,
57
+ children
58
+ })
59
+ });
60
+ }
61
+ function ResolveAwait({ children, resolve, errorElement, params }) {
62
+ const data = resolve();
63
+ logger.debug("resolve data: ", data);
64
+ if (typeof data === "string" && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {
65
+ const transformedError = transformError(data);
66
+ return /* @__PURE__ */ _jsx(_Fragment, {
67
+ children: typeof errorElement === "function" ? /* @__PURE__ */ _jsxs(_Fragment, {
68
+ children: [
69
+ globalThis.FEDERATION_SSR && /* @__PURE__ */ _jsx("script", {
70
+ suppressHydrationWarning: true,
71
+ dangerouslySetInnerHTML: {
72
+ __html: String.raw`
73
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || []
74
+ globalThis['${DATA_FETCH_FUNCTION}'].push([${transformedError.dataFetchMapKey ? `'${transformedError.dataFetchMapKey}'` : ""},${params ? JSON.stringify(params) : null},true]);`
75
+ }
76
+ }),
77
+ errorElement(transformedError)
78
+ ]
79
+ }) : errorElement
80
+ });
81
+ }
82
+ const toRender = typeof children === "function" ? children(data) : children;
83
+ return /* @__PURE__ */ _jsx(_Fragment, {
84
+ children: toRender
85
+ });
86
+ }
87
+ const fetchData = (promise, ref) => {
88
+ let data;
89
+ let status = "pending";
90
+ const suspender = promise.then((res) => {
91
+ status = "success";
92
+ data = res;
93
+ ref.current = res;
94
+ }).catch((e) => {
95
+ status = "success";
96
+ console.warn(e);
97
+ data = AWAIT_ERROR_PREFIX + e;
98
+ });
99
+ return () => {
100
+ if (status === "pending") {
101
+ throw suspender;
102
+ }
103
+ return data;
104
+ };
105
+ };
106
+ export {
107
+ AwaitDataFetch,
108
+ transformError
109
+ };