@module-federation/rsbuild-plugin 0.0.0-feat-support-bridge-react-router-v7-20251015102312

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present Bytedance, Inc. and its affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,72 @@
1
+ # @module-federation/rsbuild-plugin
2
+
3
+ ## Example
4
+
5
+ ```
6
+ npm install @module-federation/rsbuild-plugin -D
7
+ ```
8
+
9
+ ```
10
+ npm install @module-federation/enhanced
11
+ ```
12
+
13
+ ### Rsbuild App
14
+ ``` js
15
+ import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
16
+ import { defineConfig } from '@rsbuild/core';
17
+ import { pluginReact } from '@rsbuild/plugin-react';
18
+
19
+ export default defineConfig({
20
+ server: {
21
+ port: 2000,
22
+ },
23
+ plugins: [
24
+ pluginReact(),
25
+ pluginModuleFederation({
26
+ name: 'federation_consumer',
27
+ remotes: {
28
+ remote1: 'remote1@http://localhost:2001/mf-manifest.json',
29
+ },
30
+ shared: ['react', 'react-dom'],
31
+ }),
32
+ ],
33
+ });
34
+ ```
35
+
36
+ ### Rslib Module
37
+ ``` js
38
+ import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
39
+ import { defineConfig } from '@rslib/core';
40
+
41
+ export default defineConfig({
42
+ lib: [
43
+ // ...
44
+ {
45
+ format: 'mf',
46
+ output: {
47
+ distPath: {
48
+ root: './dist/mf',
49
+ },
50
+ assetPrefix: 'http://localhost:3001/mf',
51
+ },
52
+ plugins: [
53
+ // ...
54
+ pluginModuleFederation({
55
+ name: 'rslib_provider',
56
+ exposes: {
57
+ '.': './src/index.tsx',
58
+ },
59
+ shared: {
60
+ react: {
61
+ singleton: true,
62
+ },
63
+ 'react-dom': {
64
+ singleton: true,
65
+ },
66
+ },
67
+ }),
68
+ ],
69
+ },
70
+ ],
71
+ });
72
+ ```
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present Bytedance, Inc. and its affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,28 @@
1
+ import { ModuleFederationPlugin, PLUGIN_NAME } from '@module-federation/enhanced/rspack';
2
+ import { SSR_DIR } from '../utils';
3
+ import type { moduleFederationPlugin } from '@module-federation/sdk';
4
+ import type { RsbuildPlugin, Rspack } from '@rsbuild/core';
5
+ type ModuleFederationOptions = moduleFederationPlugin.ModuleFederationPluginOptions;
6
+ type RSBUILD_PLUGIN_OPTIONS = {
7
+ ssr?: boolean;
8
+ ssrDir?: string;
9
+ environment?: string;
10
+ };
11
+ type ExposedAPIType = {
12
+ options: {
13
+ nodePlugin?: ModuleFederationPlugin;
14
+ browserPlugin?: ModuleFederationPlugin;
15
+ rspressSSGPlugin?: ModuleFederationPlugin;
16
+ distOutputDir?: string;
17
+ };
18
+ isSSRConfig: typeof isSSRConfig;
19
+ isRspressSSGConfig: typeof isRspressSSGConfig;
20
+ };
21
+ export type { ModuleFederationOptions, ExposedAPIType };
22
+ declare const RSBUILD_PLUGIN_MODULE_FEDERATION_NAME = "rsbuild:module-federation-enhanced";
23
+ export { RSBUILD_PLUGIN_MODULE_FEDERATION_NAME, PLUGIN_NAME, SSR_DIR };
24
+ export declare function isMFFormat(bundlerConfig: Rspack.Configuration): boolean;
25
+ declare const isSSRConfig: (bundlerConfigName?: string) => boolean;
26
+ declare const isRspressSSGConfig: (bundlerConfigName?: string) => bundlerConfigName is "node";
27
+ export declare const pluginModuleFederation: (moduleFederationOptions: ModuleFederationOptions, rsbuildOptions?: RSBUILD_PLUGIN_OPTIONS) => RsbuildPlugin;
28
+ export { createModuleFederationConfig } from '@module-federation/sdk';
@@ -0,0 +1,9 @@
1
+ export declare const DEFAULT_ASSET_PREFIX = "/";
2
+ export declare const DATA_FETCH_IDENTIFIER = "data";
3
+ export declare const DATA_FETCH_CLIENT_SUFFIX = ".client";
4
+ export declare const CALL_NAME_MAP: {
5
+ RSPRESS: string;
6
+ RSLIB: string;
7
+ };
8
+ export declare const RSPRESS_BUNDLER_CONFIG_NAME = "node";
9
+ export declare const RSPRESS_SSR_DIR = "ssr";
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ CALL_NAME_MAP: ()=>CALL_NAME_MAP,
28
+ DATA_FETCH_CLIENT_SUFFIX: ()=>DATA_FETCH_CLIENT_SUFFIX,
29
+ DATA_FETCH_IDENTIFIER: ()=>DATA_FETCH_IDENTIFIER,
30
+ DEFAULT_ASSET_PREFIX: ()=>DEFAULT_ASSET_PREFIX,
31
+ RSPRESS_BUNDLER_CONFIG_NAME: ()=>RSPRESS_BUNDLER_CONFIG_NAME,
32
+ RSPRESS_SSR_DIR: ()=>RSPRESS_SSR_DIR
33
+ });
34
+ const DEFAULT_ASSET_PREFIX = '/';
35
+ const DATA_FETCH_IDENTIFIER = 'data';
36
+ const DATA_FETCH_CLIENT_SUFFIX = '.client';
37
+ const CALL_NAME_MAP = {
38
+ RSPRESS: 'rspress',
39
+ RSLIB: 'rslib'
40
+ };
41
+ const RSPRESS_BUNDLER_CONFIG_NAME = 'node';
42
+ const RSPRESS_SSR_DIR = 'ssr';
43
+ exports.CALL_NAME_MAP = __webpack_exports__.CALL_NAME_MAP;
44
+ exports.DATA_FETCH_CLIENT_SUFFIX = __webpack_exports__.DATA_FETCH_CLIENT_SUFFIX;
45
+ exports.DATA_FETCH_IDENTIFIER = __webpack_exports__.DATA_FETCH_IDENTIFIER;
46
+ exports.DEFAULT_ASSET_PREFIX = __webpack_exports__.DEFAULT_ASSET_PREFIX;
47
+ exports.RSPRESS_BUNDLER_CONFIG_NAME = __webpack_exports__.RSPRESS_BUNDLER_CONFIG_NAME;
48
+ exports.RSPRESS_SSR_DIR = __webpack_exports__.RSPRESS_SSR_DIR;
49
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
50
+ "CALL_NAME_MAP",
51
+ "DATA_FETCH_CLIENT_SUFFIX",
52
+ "DATA_FETCH_IDENTIFIER",
53
+ "DEFAULT_ASSET_PREFIX",
54
+ "RSPRESS_BUNDLER_CONFIG_NAME",
55
+ "RSPRESS_SSR_DIR"
56
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
57
+ Object.defineProperty(exports, '__esModule', {
58
+ value: true
59
+ });
@@ -0,0 +1,10 @@
1
+ const DEFAULT_ASSET_PREFIX = '/';
2
+ const DATA_FETCH_IDENTIFIER = 'data';
3
+ const DATA_FETCH_CLIENT_SUFFIX = '.client';
4
+ const CALL_NAME_MAP = {
5
+ RSPRESS: 'rspress',
6
+ RSLIB: 'rslib'
7
+ };
8
+ const RSPRESS_BUNDLER_CONFIG_NAME = 'node';
9
+ const RSPRESS_SSR_DIR = 'ssr';
10
+ export { CALL_NAME_MAP, DATA_FETCH_CLIENT_SUFFIX, DATA_FETCH_IDENTIFIER, DEFAULT_ASSET_PREFIX, RSPRESS_BUNDLER_CONFIG_NAME, RSPRESS_SSR_DIR };
package/dist/index.js ADDED
@@ -0,0 +1,436 @@
1
+ "use strict";
2
+ const __rslib_import_meta_url__ = /*#__PURE__*/ function() {
3
+ return 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
4
+ }();
5
+ var __webpack_require__ = {};
6
+ (()=>{
7
+ __webpack_require__.n = (module)=>{
8
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
9
+ __webpack_require__.d(getter, {
10
+ a: getter
11
+ });
12
+ return getter;
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.d = (exports1, definition)=>{
17
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
18
+ enumerable: true,
19
+ get: definition[key]
20
+ });
21
+ };
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
25
+ })();
26
+ (()=>{
27
+ __webpack_require__.r = (exports1)=>{
28
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
29
+ value: 'Module'
30
+ });
31
+ Object.defineProperty(exports1, '__esModule', {
32
+ value: true
33
+ });
34
+ };
35
+ })();
36
+ var __webpack_exports__ = {};
37
+ __webpack_require__.r(__webpack_exports__);
38
+ __webpack_require__.d(__webpack_exports__, {
39
+ pluginModuleFederation: ()=>pluginModuleFederation,
40
+ RSBUILD_PLUGIN_MODULE_FEDERATION_NAME: ()=>RSBUILD_PLUGIN_MODULE_FEDERATION_NAME,
41
+ PLUGIN_NAME: ()=>rspack_namespaceObject.PLUGIN_NAME,
42
+ SSR_DIR: ()=>SSR_DIR,
43
+ isMFFormat: ()=>isMFFormat,
44
+ createModuleFederationConfig: ()=>sdk_namespaceObject.createModuleFederationConfig
45
+ });
46
+ const enhanced_namespaceObject = require("@module-federation/enhanced");
47
+ const rspack_namespaceObject = require("@module-federation/enhanced/rspack");
48
+ const sdk_namespaceObject = require("@module-federation/sdk");
49
+ var package_namespaceObject = JSON.parse('{"UU":"@module-federation/rsbuild-plugin"}');
50
+ const logger = (0, sdk_namespaceObject.createLogger)('[ Module Federation Rsbuild Plugin ]');
51
+ const src_logger = logger;
52
+ const external_util_namespaceObject = require("util");
53
+ var external_util_default = /*#__PURE__*/ __webpack_require__.n(external_util_namespaceObject);
54
+ const SPLIT_CHUNK_MAP = {
55
+ REACT: 'react',
56
+ ROUTER: 'router',
57
+ LODASH: 'lib-lodash',
58
+ ANTD: 'lib-antd',
59
+ ARCO: 'lib-arco',
60
+ SEMI: 'lib-semi',
61
+ AXIOS: 'lib-axios'
62
+ };
63
+ const SHARED_SPLIT_CHUNK_MAP = {
64
+ react: SPLIT_CHUNK_MAP.REACT,
65
+ 'react-dom': SPLIT_CHUNK_MAP.REACT,
66
+ 'react-router': SPLIT_CHUNK_MAP.ROUTER,
67
+ 'react-router-dom': SPLIT_CHUNK_MAP.ROUTER,
68
+ '@remix-run/router': SPLIT_CHUNK_MAP.ROUTER,
69
+ lodash: SPLIT_CHUNK_MAP.LODASH,
70
+ 'lodash-es': SPLIT_CHUNK_MAP.LODASH,
71
+ antd: SPLIT_CHUNK_MAP.ANTD,
72
+ '@arco-design/web-react': SPLIT_CHUNK_MAP.ARCO,
73
+ '@douyinfe/semi-ui': SPLIT_CHUNK_MAP.SEMI,
74
+ axios: SPLIT_CHUNK_MAP.AXIOS
75
+ };
76
+ function autoDeleteSplitChunkCacheGroups(mfConfig, splitChunks) {
77
+ if (!mfConfig.shared) return;
78
+ if (!splitChunks || !(null == splitChunks ? void 0 : splitChunks.cacheGroups)) return;
79
+ const arrayShared = Array.isArray(mfConfig.shared) ? mfConfig.shared : Object.keys(mfConfig.shared);
80
+ for (const shared of arrayShared){
81
+ const splitChunkKey = SHARED_SPLIT_CHUNK_MAP[shared];
82
+ if (splitChunkKey) {
83
+ if (splitChunks.cacheGroups[splitChunkKey]) delete splitChunks.cacheGroups[splitChunkKey];
84
+ }
85
+ }
86
+ return splitChunks;
87
+ }
88
+ const external_fs_extra_namespaceObject = require("fs-extra");
89
+ var external_fs_extra_default = /*#__PURE__*/ __webpack_require__.n(external_fs_extra_namespaceObject);
90
+ const external_path_namespaceObject = require("path");
91
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
92
+ const DATA_FETCH_CLIENT_SUFFIX = '.client';
93
+ const CALL_NAME_MAP = {
94
+ RSPRESS: 'rspress',
95
+ RSLIB: 'rslib'
96
+ };
97
+ const addDataFetchExpose = (exposes, key, filepath, suffix = '')=>{
98
+ if (!external_fs_extra_default().existsSync(filepath)) return false;
99
+ const dataFetchKey = '.' === key ? `./data${suffix}` : `${key}.data${suffix}`;
100
+ if (exposes[dataFetchKey] && exposes[dataFetchKey] !== filepath) throw new Error(`data fetch key ${dataFetchKey} already exists, please modify this expose key, do not end with 'data' or '${DATA_FETCH_CLIENT_SUFFIX}'`);
101
+ exposes[dataFetchKey] = filepath;
102
+ return dataFetchKey;
103
+ };
104
+ const addExcludeDtsSuffix = (filepath)=>`${filepath}?exclude-mf-dts=true`;
105
+ function addDataFetchExposes(exposes, isServer) {
106
+ if ('object' != typeof exposes || Array.isArray(exposes)) return;
107
+ if (0 === Object.keys(exposes).length) return;
108
+ const tempDataFetchFilepath = external_path_default().resolve(process.cwd(), `node_modules/${sdk_namespaceObject.TEMP_DIR}/data-fetch-fallback.ts`);
109
+ const content = "export const fetchData=()=>{throw new Error('should not be called')};";
110
+ external_fs_extra_default().ensureDirSync(external_path_default().dirname(tempDataFetchFilepath));
111
+ external_fs_extra_default().writeFileSync(tempDataFetchFilepath, content);
112
+ Object.keys(exposes).forEach((key)=>{
113
+ const expose = exposes[key];
114
+ if ('string' != typeof expose) return;
115
+ const absPath = external_path_default().resolve(process.cwd(), expose);
116
+ const dataFetchPath = `${absPath.replace(external_path_default().extname(absPath), '')}.data.ts`;
117
+ const dataFetchClientPath = `${absPath.replace(external_path_default().extname(absPath), '')}.data.client.ts`;
118
+ const dateFetchClientKey = addDataFetchExpose(exposes, key, dataFetchClientPath, DATA_FETCH_CLIENT_SUFFIX);
119
+ if (!isServer && dateFetchClientKey) {
120
+ exposes[dateFetchClientKey.replace(DATA_FETCH_CLIENT_SUFFIX, '')] = addExcludeDtsSuffix(tempDataFetchFilepath);
121
+ return;
122
+ }
123
+ const dataFetchKey = addDataFetchExpose(exposes, key, dataFetchPath);
124
+ if (dataFetchKey && external_fs_extra_default().existsSync(dataFetchClientPath)) exposes[`${dataFetchKey}${DATA_FETCH_CLIENT_SUFFIX}`] = addExcludeDtsSuffix(tempDataFetchFilepath);
125
+ });
126
+ }
127
+ function mergeStats(browserStats, nodeStats) {
128
+ const ssrRemoteEntry = nodeStats.metaData.remoteEntry;
129
+ browserStats.metaData.ssrRemoteEntry = ssrRemoteEntry;
130
+ if ('publicPath' in browserStats.metaData) browserStats.metaData.ssrPublicPath = nodeStats.metaData.publicPath;
131
+ return browserStats;
132
+ }
133
+ function mergeManifest(browserManifest, nodeManifest) {
134
+ const ssrRemoteEntry = nodeManifest.metaData.remoteEntry;
135
+ browserManifest.metaData.ssrRemoteEntry = ssrRemoteEntry;
136
+ if ('publicPath' in browserManifest.metaData) browserManifest.metaData.ssrPublicPath = nodeManifest.metaData.publicPath;
137
+ return browserManifest;
138
+ }
139
+ function mergeStatsAndManifest(nodePlugin, browserPlugin) {
140
+ const nodeResourceInfo = nodePlugin.statsResourceInfo;
141
+ const browserResourceInfo = browserPlugin.statsResourceInfo;
142
+ if (!browserResourceInfo || !nodeResourceInfo || !browserResourceInfo.stats || !nodeResourceInfo.stats || !browserResourceInfo.manifest || !nodeResourceInfo.manifest) throw new Error('can not get browserResourceInfo or nodeResourceInfo');
143
+ const mergedStats = mergeStats(browserResourceInfo.stats.stats, nodeResourceInfo.stats.stats);
144
+ const mergedManifest = mergeManifest(browserResourceInfo.manifest.manifest, nodeResourceInfo.manifest.manifest);
145
+ return {
146
+ mergedStats: mergedStats,
147
+ mergedStatsFilePath: browserResourceInfo.stats.filename,
148
+ mergedManifest: mergedManifest,
149
+ mergedManifestFilePath: browserResourceInfo.manifest.filename
150
+ };
151
+ }
152
+ function updateStatsAndManifest(nodePlugin, browserPlugin, outputDir) {
153
+ const { mergedStats, mergedStatsFilePath, mergedManifest, mergedManifestFilePath } = mergeStatsAndManifest(nodePlugin, browserPlugin);
154
+ external_fs_extra_default().writeFileSync(external_path_default().resolve(outputDir, mergedStatsFilePath), JSON.stringify(mergedStats, null, 2));
155
+ external_fs_extra_default().writeFileSync(external_path_default().resolve(outputDir, mergedManifestFilePath), JSON.stringify(mergedManifest, null, 2));
156
+ }
157
+ const external_node_module_namespaceObject = require("node:module");
158
+ const ssr_require = (0, external_node_module_namespaceObject.createRequire)(__rslib_import_meta_url__);
159
+ const resolve = ssr_require.resolve;
160
+ const SSR_DIR = 'ssr';
161
+ const SSR_ENV_NAME = 'mf-ssr';
162
+ function setSSREnv() {
163
+ process.env['MF_DISABLE_EMIT_STATS'] = 'true';
164
+ process.env['MF_SSR_PRJ'] = 'true';
165
+ }
166
+ const isDev = ()=>'development' === process.env['NODE_ENV'];
167
+ function patchSSRRspackConfig(config, mfConfig, ssrDir, callerName, resetEntry = true, modifyPublicPath = true) {
168
+ var _config_output;
169
+ config.output ||= {};
170
+ if (modifyPublicPath) {
171
+ var _config_output1;
172
+ if ('string' != typeof (null == (_config_output1 = config.output) ? void 0 : _config_output1.publicPath)) throw new Error('publicPath must be string!');
173
+ const publicPath = config.output.publicPath;
174
+ if ('auto' === publicPath) throw new Error('publicPath can not be "auto"!');
175
+ const publicPathWithSSRDir = `${publicPath}${ssrDir}/`;
176
+ config.output.publicPath = publicPathWithSSRDir;
177
+ }
178
+ if (callerName === CALL_NAME_MAP.RSPRESS && resetEntry) config.entry = 'data:application/node;base64,';
179
+ config.target = 'async-node';
180
+ const UniverseEntryChunkTrackerPlugin = ssr_require('@module-federation/node/universe-entry-chunk-tracker-plugin').default;
181
+ config.plugins ||= [];
182
+ isDev() && config.plugins.push(new UniverseEntryChunkTrackerPlugin());
183
+ const uniqueName = mfConfig.name || (null == (_config_output = config.output) ? void 0 : _config_output.uniqueName);
184
+ const chunkFileName = config.output.chunkFilename;
185
+ if ('string' == typeof chunkFileName && uniqueName && !chunkFileName.includes(uniqueName)) {
186
+ const suffix = `${(0, sdk_namespaceObject.encodeName)(uniqueName)}-[contenthash].js`;
187
+ config.output.chunkFilename = chunkFileName.replace('.js', suffix);
188
+ }
189
+ return config;
190
+ }
191
+ function createSSRREnvConfig(envConfig, mfConfig, ssrDir, rsbuildConfig, callerName) {
192
+ var _ssrEnvConfig_output, _ssrEnvConfig_output_distPath, _ssrEnvConfig_output1, _rsbuildConfig_output_distPath, _rsbuildConfig_output;
193
+ const ssrEnvConfig = {
194
+ ...envConfig,
195
+ tools: {
196
+ rspack: (config, { environment })=>{
197
+ if (environment.name !== SSR_ENV_NAME) return;
198
+ patchSSRRspackConfig(config, mfConfig, ssrDir, callerName);
199
+ }
200
+ }
201
+ };
202
+ ssrEnvConfig.output = {
203
+ ...ssrEnvConfig.output,
204
+ target: 'node',
205
+ distPath: {
206
+ ...null == (_ssrEnvConfig_output = ssrEnvConfig.output) ? void 0 : _ssrEnvConfig_output.distPath,
207
+ root: external_path_default().join((null == (_ssrEnvConfig_output1 = ssrEnvConfig.output) ? void 0 : null == (_ssrEnvConfig_output_distPath = _ssrEnvConfig_output1.distPath) ? void 0 : _ssrEnvConfig_output_distPath.root) || (null == (_rsbuildConfig_output = rsbuildConfig.output) ? void 0 : null == (_rsbuildConfig_output_distPath = _rsbuildConfig_output.distPath) ? void 0 : _rsbuildConfig_output_distPath.root) || '', ssrDir)
208
+ },
209
+ emitAssets: true
210
+ };
211
+ return ssrEnvConfig;
212
+ }
213
+ function createSSRMFConfig(mfConfig) {
214
+ var _mfConfig_library;
215
+ const ssrMFConfig = {
216
+ ...mfConfig,
217
+ exposes: {
218
+ ...mfConfig.exposes
219
+ },
220
+ library: {
221
+ ...mfConfig.library,
222
+ name: mfConfig.name,
223
+ type: (null == (_mfConfig_library = mfConfig.library) ? void 0 : _mfConfig_library.type) ?? 'commonjs-module'
224
+ },
225
+ dts: false,
226
+ dev: false,
227
+ runtimePlugins: [
228
+ ...mfConfig.runtimePlugins || []
229
+ ]
230
+ };
231
+ ssrMFConfig.runtimePlugins.push(resolve('@module-federation/node/runtimePlugin'));
232
+ if (isDev()) ssrMFConfig.runtimePlugins.push(resolve('@module-federation/node/record-dynamic-remote-entry-hash-plugin'));
233
+ return ssrMFConfig;
234
+ }
235
+ function isRegExp(target) {
236
+ return external_util_default().types.isRegExp(target);
237
+ }
238
+ const RSBUILD_PLUGIN_MODULE_FEDERATION_NAME = 'rsbuild:module-federation-enhanced';
239
+ const RSBUILD_PLUGIN_NAME = '@module-federation/rsbuild-plugin';
240
+ const LIB_FORMAT = [
241
+ 'umd',
242
+ 'modern-module'
243
+ ];
244
+ const DEFAULT_MF_ENVIRONMENT_NAME = 'mf';
245
+ function isStoryBook(rsbuildConfig) {
246
+ var _rsbuildConfig_plugins;
247
+ if (null == (_rsbuildConfig_plugins = rsbuildConfig.plugins) ? void 0 : _rsbuildConfig_plugins.find((p)=>p && 'name' in p && 'module-federation-storybook-plugin' === p.name)) return true;
248
+ return false;
249
+ }
250
+ function isMFFormat(bundlerConfig) {
251
+ var _bundlerConfig_output;
252
+ const library = null == (_bundlerConfig_output = bundlerConfig.output) ? void 0 : _bundlerConfig_output.library;
253
+ if (bundlerConfig.name === SSR_ENV_NAME) return true;
254
+ return !('object' == typeof library && !Array.isArray(library) && 'type' in library && (LIB_FORMAT.includes(library.type) || /commonjs/.test(library.type)));
255
+ }
256
+ const isSSRConfig = (bundlerConfigName)=>Boolean(bundlerConfigName === SSR_ENV_NAME);
257
+ const isRspressSSGConfig = (bundlerConfigName)=>"node" === bundlerConfigName;
258
+ const pluginModuleFederation = (moduleFederationOptions, rsbuildOptions)=>({
259
+ name: RSBUILD_PLUGIN_MODULE_FEDERATION_NAME,
260
+ setup: (api)=>{
261
+ const { ssr, ssrDir = SSR_DIR, environment = DEFAULT_MF_ENVIRONMENT_NAME } = rsbuildOptions || {};
262
+ const { callerName } = api.context;
263
+ const originalRsbuildConfig = api.getRsbuildConfig();
264
+ if (!callerName) throw new Error('`callerName` is undefined. Please ensure the @rsbuild/core version is higher than 1.3.21 .');
265
+ const isRslib = callerName === CALL_NAME_MAP.RSLIB;
266
+ const isRspress = callerName === CALL_NAME_MAP.RSPRESS;
267
+ const isSSR = Boolean(ssr);
268
+ if (isSSR && !isStoryBook(originalRsbuildConfig)) {
269
+ var _rsbuildConfig_environments;
270
+ if (!isRslib && !isRspress) throw new Error("'ssr' option is only supported in rslib.");
271
+ const rsbuildConfig = api.getRsbuildConfig();
272
+ if (!(null == (_rsbuildConfig_environments = rsbuildConfig.environments) ? void 0 : _rsbuildConfig_environments[environment]) || Object.keys(rsbuildConfig.environments).some((key)=>key.startsWith(environment) && key !== environment)) throw new Error(`Please set ${RSBUILD_PLUGIN_NAME} as global plugin in rslib.config.ts if you set 'ssr:true' .`);
273
+ setSSREnv();
274
+ }
275
+ const sharedOptions = (0, enhanced_namespaceObject.parseOptions)(moduleFederationOptions.shared || [], (item, key)=>{
276
+ if ('string' != typeof item) throw new Error('Unexpected array in shared');
277
+ const config = item !== key && (0, sdk_namespaceObject.isRequiredVersion)(item) ? {
278
+ import: key,
279
+ requiredVersion: item
280
+ } : {
281
+ import: item
282
+ };
283
+ return config;
284
+ }, (item, key)=>item);
285
+ const shared = sharedOptions.map((shared)=>shared[0].endsWith('/') ? shared[0].slice(0, -1) : shared[0]);
286
+ api.modifyRsbuildConfig((config)=>{
287
+ if (isStoryBook(config)) return;
288
+ if (moduleFederationOptions.exposes) {
289
+ var _userConfig_server, _config_server, _config_dev_client, _originalConfig_dev, _config_server1;
290
+ config.dev ||= {};
291
+ config.server ||= {};
292
+ const userConfig = api.getRsbuildConfig('original');
293
+ config.server.headers ||= {};
294
+ if (!config.server.headers['Access-Control-Allow-Origin'] && !('object' == typeof (null == (_userConfig_server = userConfig.server) ? void 0 : _userConfig_server.cors) && userConfig.server.cors.origin)) {
295
+ const corsWarnMsgs = [
296
+ 'Detect that CORS options are not set, mf Rsbuild plugin will add default cors header: server.headers["Access-Control-Allow-Headers"] = "*". It is recommended to specify an allowlist of trusted origins in "server.cors" instead.',
297
+ 'View https://module-federation.io/guide/troubleshooting/other.html#cors-warn for more details.'
298
+ ];
299
+ isRslib || isRspress || src_logger.warn(corsWarnMsgs.join('\n'));
300
+ config.server.headers['Access-Control-Allow-Origin'] = '*';
301
+ }
302
+ if ((null == (_config_server = config.server) ? void 0 : _config_server.port) && !(null == (_config_dev_client = config.dev.client) ? void 0 : _config_dev_client.port)) {
303
+ config.dev.client ||= {};
304
+ config.dev.client.port = config.server.port;
305
+ }
306
+ const originalConfig = api.getRsbuildConfig('original');
307
+ if ((null == (_originalConfig_dev = originalConfig.dev) ? void 0 : _originalConfig_dev.assetPrefix) === void 0 && config.dev.assetPrefix === (null == (_config_server1 = config.server) ? void 0 : _config_server1.base)) config.dev.assetPrefix = true;
308
+ }
309
+ if (isSSR) {
310
+ var _config_environments, _config_environments1;
311
+ if (null == (_config_environments = config.environments) ? void 0 : _config_environments[SSR_ENV_NAME]) throw new Error(`'${SSR_ENV_NAME}' environment is already defined. Please use another name.`);
312
+ config.environments[SSR_ENV_NAME] = createSSRREnvConfig(null == (_config_environments1 = config.environments) ? void 0 : _config_environments1[environment], moduleFederationOptions, ssrDir, config, callerName);
313
+ }
314
+ });
315
+ api.modifyEnvironmentConfig((config)=>{
316
+ config.source.include = [
317
+ ...config.source.include || [],
318
+ /@module-federation[\\/]/
319
+ ];
320
+ return config;
321
+ });
322
+ const generateMergedStatsAndManifestOptions = {
323
+ options: {
324
+ nodePlugin: void 0,
325
+ browserPlugin: void 0,
326
+ distOutputDir: void 0
327
+ },
328
+ isSSRConfig,
329
+ isRspressSSGConfig
330
+ };
331
+ api.expose(RSBUILD_PLUGIN_MODULE_FEDERATION_NAME, generateMergedStatsAndManifestOptions);
332
+ api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
333
+ if (!bundlerConfigs) throw new Error('Can not get bundlerConfigs!');
334
+ bundlerConfigs.forEach((bundlerConfig)=>{
335
+ if (!isMFFormat(bundlerConfig) && !isRspress) return;
336
+ if (isStoryBook(originalRsbuildConfig)) bundlerConfig.output.uniqueName = `${moduleFederationOptions.name}-storybook-host`;
337
+ else {
338
+ var _bundlerConfig_optimization, _bundlerConfig_optimization1, _bundlerConfig_output, _bundlerConfig_output1;
339
+ autoDeleteSplitChunkCacheGroups(moduleFederationOptions, null == bundlerConfig ? void 0 : null == (_bundlerConfig_optimization = bundlerConfig.optimization) ? void 0 : _bundlerConfig_optimization.splitChunks);
340
+ addDataFetchExposes(moduleFederationOptions.exposes, isSSRConfig(bundlerConfig.name));
341
+ null == (_bundlerConfig_optimization1 = bundlerConfig.optimization) || delete _bundlerConfig_optimization1.runtimeChunk;
342
+ const externals = bundlerConfig.externals;
343
+ if (Array.isArray(externals)) {
344
+ const sharedModules = new Set();
345
+ bundlerConfig.externals = externals.filter((ext)=>{
346
+ let sharedModule;
347
+ if (isRegExp(ext)) {
348
+ const match = shared.some((dep)=>{
349
+ if (ext.test(dep) || ext.test(package_namespaceObject.UU)) {
350
+ sharedModule = dep;
351
+ return true;
352
+ }
353
+ return false;
354
+ });
355
+ match && sharedModule && sharedModules.add(sharedModule);
356
+ return !match;
357
+ }
358
+ if ('string' == typeof ext) {
359
+ if (ext === package_namespaceObject.UU) return false;
360
+ const match = shared.some((dep)=>{
361
+ if (dep === ext) sharedModule = dep;
362
+ return dep === ext;
363
+ });
364
+ if (match) {
365
+ sharedModule && sharedModules.add(sharedModule);
366
+ return false;
367
+ }
368
+ }
369
+ return true;
370
+ });
371
+ if (sharedModules.size > 0) for (const sharedModule of sharedModules)src_logger.log(`${sharedModule} is removed from externals because it is a shared module.`);
372
+ }
373
+ if (!(null == (_bundlerConfig_output = bundlerConfig.output) ? void 0 : _bundlerConfig_output.chunkLoadingGlobal) && !isSSRConfig(bundlerConfig.name) && !isRspressSSGConfig(bundlerConfig.name)) {
374
+ bundlerConfig.output.chunkLoading = 'jsonp';
375
+ bundlerConfig.output.chunkLoadingGlobal = `chunk_${moduleFederationOptions.name}`;
376
+ }
377
+ if (!(null == (_bundlerConfig_output1 = bundlerConfig.output) ? void 0 : _bundlerConfig_output1.uniqueName)) bundlerConfig.output.uniqueName = moduleFederationOptions.name;
378
+ if (!bundlerConfig.plugins.find((p)=>p && p.name === rspack_namespaceObject.PLUGIN_NAME)) {
379
+ var _bundlerConfig_output2;
380
+ if (isSSRConfig(bundlerConfig.name)) {
381
+ generateMergedStatsAndManifestOptions.options.nodePlugin = new rspack_namespaceObject.ModuleFederationPlugin(createSSRMFConfig(moduleFederationOptions));
382
+ bundlerConfig.plugins.push(generateMergedStatsAndManifestOptions.options.nodePlugin);
383
+ return;
384
+ }
385
+ if (isRspressSSGConfig(bundlerConfig.name)) {
386
+ const mfConfig = {
387
+ ...createSSRMFConfig(moduleFederationOptions),
388
+ exposes: {},
389
+ manifest: false,
390
+ library: void 0
391
+ };
392
+ patchSSRRspackConfig(bundlerConfig, mfConfig, "ssr", callerName, false, false);
393
+ bundlerConfig.output ||= {};
394
+ bundlerConfig.output.publicPath = '/';
395
+ bundlerConfig.output.asyncChunks = void 0;
396
+ generateMergedStatsAndManifestOptions.options.rspressSSGPlugin = new rspack_namespaceObject.ModuleFederationPlugin(mfConfig);
397
+ bundlerConfig.plugins.push(generateMergedStatsAndManifestOptions.options.rspressSSGPlugin);
398
+ return;
399
+ }
400
+ generateMergedStatsAndManifestOptions.options.browserPlugin = new rspack_namespaceObject.ModuleFederationPlugin(moduleFederationOptions);
401
+ generateMergedStatsAndManifestOptions.options.distOutputDir = (null == (_bundlerConfig_output2 = bundlerConfig.output) ? void 0 : _bundlerConfig_output2.path) || '';
402
+ bundlerConfig.plugins.push(generateMergedStatsAndManifestOptions.options.browserPlugin);
403
+ }
404
+ }
405
+ });
406
+ });
407
+ const generateMergedStatsAndManifest = ()=>{
408
+ const { nodePlugin, browserPlugin, distOutputDir } = generateMergedStatsAndManifestOptions.options;
409
+ if (!nodePlugin || !browserPlugin || !distOutputDir) return;
410
+ updateStatsAndManifest(nodePlugin, browserPlugin, distOutputDir);
411
+ };
412
+ api.onDevCompileDone(()=>{
413
+ generateMergedStatsAndManifest();
414
+ });
415
+ api.onAfterBuild(()=>{
416
+ generateMergedStatsAndManifest();
417
+ });
418
+ }
419
+ });
420
+ exports.PLUGIN_NAME = __webpack_exports__.PLUGIN_NAME;
421
+ exports.RSBUILD_PLUGIN_MODULE_FEDERATION_NAME = __webpack_exports__.RSBUILD_PLUGIN_MODULE_FEDERATION_NAME;
422
+ exports.SSR_DIR = __webpack_exports__.SSR_DIR;
423
+ exports.createModuleFederationConfig = __webpack_exports__.createModuleFederationConfig;
424
+ exports.isMFFormat = __webpack_exports__.isMFFormat;
425
+ exports.pluginModuleFederation = __webpack_exports__.pluginModuleFederation;
426
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
427
+ "PLUGIN_NAME",
428
+ "RSBUILD_PLUGIN_MODULE_FEDERATION_NAME",
429
+ "SSR_DIR",
430
+ "createModuleFederationConfig",
431
+ "isMFFormat",
432
+ "pluginModuleFederation"
433
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
434
+ Object.defineProperty(exports, '__esModule', {
435
+ value: true
436
+ });