@module-federation/vite 1.10.0 → 1.11.1

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 (45) hide show
  1. package/README.md +4 -1
  2. package/lib/index.cjs +1819 -1963
  3. package/lib/index.d.cts +131 -0
  4. package/lib/index.d.mts +131 -0
  5. package/lib/index.mjs +1946 -0
  6. package/package.json +29 -18
  7. package/lib/index.d.ts +0 -4
  8. package/lib/index.esm.js +0 -2091
  9. package/lib/index.modern.js +0 -2123
  10. package/lib/index.umd.js +0 -2112
  11. package/lib/plugins/__tests__/pluginCheckAliasConflicts.test.d.ts +0 -1
  12. package/lib/plugins/__tests__/pluginDts.test.d.ts +0 -1
  13. package/lib/plugins/pluginAddEntry.d.ts +0 -10
  14. package/lib/plugins/pluginCheckAliasConflicts.d.ts +0 -9
  15. package/lib/plugins/pluginDevProxyModuleTopLevelAwait.d.ts +0 -2
  16. package/lib/plugins/pluginDts.d.ts +0 -3
  17. package/lib/plugins/pluginMFManifest.d.ts +0 -3
  18. package/lib/plugins/pluginModuleParseEnd.d.ts +0 -10
  19. package/lib/plugins/pluginProxyRemoteEntry.d.ts +0 -2
  20. package/lib/plugins/pluginProxyRemotes.d.ts +0 -3
  21. package/lib/plugins/pluginProxySharedModule_preBuild.d.ts +0 -7
  22. package/lib/utils/PromiseStore.d.ts +0 -16
  23. package/lib/utils/VirtualModule.d.ts +0 -26
  24. package/lib/utils/__tests__/VirtualModule.test.d.ts +0 -1
  25. package/lib/utils/__tests__/cssModuleHelpers.test.d.ts +0 -1
  26. package/lib/utils/__tests__/helpers.d.ts +0 -2
  27. package/lib/utils/__tests__/normalizeModuleFederationOption.test.d.ts +0 -1
  28. package/lib/utils/__tests__/publicPath.test.d.ts +0 -1
  29. package/lib/utils/__tests__/serializeRuntimeOptions.test.d.ts +0 -1
  30. package/lib/utils/aliasToArrayPlugin.d.ts +0 -10
  31. package/lib/utils/cssModuleHelpers.d.ts +0 -75
  32. package/lib/utils/localSharedImportMap_temp.d.ts +0 -2
  33. package/lib/utils/mapCodeToCodeWithSourcemap.d.ts +0 -4
  34. package/lib/utils/normalizeModuleFederationOptions.d.ts +0 -159
  35. package/lib/utils/normalizeOptimizeDeps.d.ts +0 -9
  36. package/lib/utils/packageNameUtils.d.ts +0 -22
  37. package/lib/utils/publicPath.d.ts +0 -9
  38. package/lib/utils/serializeRuntimeOptions.d.ts +0 -10
  39. package/lib/utils/wrapManualChunks.d.ts +0 -1
  40. package/lib/virtualModules/index.d.ts +0 -6
  41. package/lib/virtualModules/virtualExposes.d.ts +0 -2
  42. package/lib/virtualModules/virtualRemoteEntry.d.ts +0 -16
  43. package/lib/virtualModules/virtualRemotes.d.ts +0 -6
  44. package/lib/virtualModules/virtualRuntimeInitStatus.d.ts +0 -3
  45. package/lib/virtualModules/virtualShared_preBuild.d.ts +0 -17
package/lib/index.cjs CHANGED
@@ -1,2115 +1,1971 @@
1
- var defu = require('defu');
2
- var fs = require('fs');
3
- var path = require('pathe');
4
- var MagicString = require('magic-string');
5
- var pluginutils = require('@rollup/pluginutils');
6
- var estreeWalker = require('estree-walker');
7
- var sdk = require('@module-federation/sdk');
8
- var dtsPlugin = require('@module-federation/dts-plugin');
9
- var core = require('@module-federation/dts-plugin/core');
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) {
14
+ __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ }
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
10
27
 
11
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
28
+ //#endregion
29
+ let defu = require("defu");
30
+ defu = __toESM(defu);
31
+ let fs = require("fs");
32
+ fs = __toESM(fs);
33
+ let pathe = require("pathe");
34
+ pathe = __toESM(pathe);
35
+ let magic_string = require("magic-string");
36
+ magic_string = __toESM(magic_string);
37
+ let _rollup_pluginutils = require("@rollup/pluginutils");
38
+ let estree_walker = require("estree-walker");
39
+ let _module_federation_sdk = require("@module-federation/sdk");
40
+ let _module_federation_dts_plugin = require("@module-federation/dts-plugin");
41
+ let _module_federation_dts_plugin_core = require("@module-federation/dts-plugin/core");
42
+ let url = require("url");
12
43
 
13
- function _interopNamespace(e) {
14
- if (e && e.__esModule) return e;
15
- var n = Object.create(null);
16
- if (e) {
17
- Object.keys(e).forEach(function (k) {
18
- if (k !== 'default') {
19
- var d = Object.getOwnPropertyDescriptor(e, k);
20
- Object.defineProperty(n, k, d.get ? d : {
21
- enumerable: true,
22
- get: function () { return e[k]; }
23
- });
24
- }
25
- });
26
- }
27
- n["default"] = e;
28
- return n;
44
+ //#region src/utils/mapCodeToCodeWithSourcemap.ts
45
+ async function mapCodeToCodeWithSourcemap(code) {
46
+ const resolvedCode = await code;
47
+ if (resolvedCode === void 0) return;
48
+ const s = new magic_string.default(resolvedCode);
49
+ return {
50
+ code: s.toString(),
51
+ map: s.generateMap({ hires: true })
52
+ };
29
53
  }
30
54
 
31
- var defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
32
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
33
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
34
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
35
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
36
-
37
- var mapCodeToCodeWithSourcemap = function mapCodeToCodeWithSourcemap(code) {
38
- return Promise.resolve(code).then(function (resolvedCode) {
39
- if (resolvedCode === undefined) {
40
- return;
41
- }
42
- var s = new MagicString__default["default"](resolvedCode);
43
- return {
44
- code: s.toString(),
45
- map: s.generateMap({
46
- hires: true
47
- })
48
- };
49
- });
50
- };
51
-
55
+ //#endregion
56
+ //#region src/plugins/pluginAddEntry.ts
52
57
  function getFirstHtmlEntryFile(entryFiles) {
53
- return entryFiles.find(function (file) {
54
- return file.endsWith('.html');
55
- });
58
+ return entryFiles.find((file) => file.endsWith(".html"));
56
59
  }
57
- var addEntry = function addEntry(_ref) {
58
- var entryName = _ref.entryName,
59
- entryPath = _ref.entryPath,
60
- fileName = _ref.fileName,
61
- _ref$inject = _ref.inject,
62
- inject = _ref$inject === void 0 ? 'entry' : _ref$inject;
63
- var devEntryPath = entryPath.startsWith('virtual:mf') ? '@id/' + entryPath : entryPath;
64
- var entryFiles = [];
65
- var htmlFilePath;
66
- var _command;
67
- var emitFileId;
68
- var viteConfig;
69
- function injectHtml() {
70
- return inject === 'html' && htmlFilePath;
71
- }
72
- function injectEntry() {
73
- return inject === 'entry' || !htmlFilePath;
74
- }
75
- return [{
76
- name: 'add-entry',
77
- apply: 'serve',
78
- config: function config(_config, _ref2) {
79
- var command = _ref2.command;
80
- _command = command;
81
- },
82
- configResolved: function configResolved(config) {
83
- viteConfig = config;
84
- devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, '/').replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/^\//, '');
85
- },
86
- configureServer: function configureServer(server) {
87
- server.middlewares.use(function (req, res, next) {
88
- if (!fileName) {
89
- next();
90
- return;
91
- }
92
- if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, '/'))) {
93
- req.url = devEntryPath;
94
- }
95
- next();
96
- });
97
- },
98
- transformIndexHtml: function transformIndexHtml(c) {
99
- if (!injectHtml()) return;
100
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
101
- },
102
- transform: function transform(code, id) {
103
- if (id.includes('node_modules') || inject !== 'html' || htmlFilePath) {
104
- return;
105
- }
106
- if (id.includes('.svelte-kit') && id.includes('internal.js')) {
107
- var src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/');
108
- return code.replace(/<head>/g, '<head><script type=\\"module\\" src=\\"' + src + '\\"></script>');
109
- }
110
- }
111
- }, {
112
- name: 'add-entry',
113
- enforce: 'post',
114
- configResolved: function configResolved(config) {
115
- viteConfig = config;
116
- var inputOptions = config.build.rollupOptions.input;
117
- if (!inputOptions) {
118
- htmlFilePath = path__namespace.resolve(config.root, 'index.html');
119
- } else if (typeof inputOptions === 'string') {
120
- entryFiles = [inputOptions];
121
- } else if (Array.isArray(inputOptions)) {
122
- entryFiles = inputOptions;
123
- } else if (typeof inputOptions === 'object') {
124
- entryFiles = Object.values(inputOptions);
125
- }
126
- if (entryFiles && entryFiles.length > 0) {
127
- htmlFilePath = getFirstHtmlEntryFile(entryFiles);
128
- }
129
- },
130
- buildStart: function buildStart() {
131
- if (_command === 'serve') return;
132
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
133
- var emitFileOptions = {
134
- name: entryName,
135
- type: 'chunk',
136
- id: entryPath,
137
- preserveSignature: 'strict'
138
- };
139
- if (!hasHash) {
140
- emitFileOptions.fileName = fileName;
141
- }
142
- emitFileId = this.emitFile(emitFileOptions);
143
- if (htmlFilePath && fs__namespace.existsSync(htmlFilePath)) {
144
- var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
145
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
146
- var match;
147
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
148
- entryFiles.push(match[1]);
149
- }
150
- }
151
- },
152
- generateBundle: function generateBundle(options, bundle) {
153
- var _viteConfig$experimen, _viteConfig$experimen2;
154
- if (!injectHtml()) return;
155
- var file = this.getFileName(emitFileId);
156
- var path = (_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl ? (_viteConfig$experimen2 = viteConfig.experimental) == null ? void 0 : _viteConfig$experimen2.renderBuiltUrl(file) : viteConfig.base + file;
157
- var scriptContent = "\n <script type=\"module\" src=\"" + path + "\"></script>\n ";
158
- for (var _fileName in bundle) {
159
- if (_fileName.endsWith('.html')) {
160
- var htmlAsset = bundle[_fileName];
161
- if (htmlAsset.type === 'chunk') return;
162
- var htmlContent = htmlAsset.source.toString() || '';
163
- htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
164
- htmlAsset.source = htmlContent;
165
- }
166
- }
167
- },
168
- transform: function transform(code, id) {
169
- if (injectEntry() && entryFiles.some(function (file) {
170
- return id.endsWith(file);
171
- })) {
172
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
173
- return mapCodeToCodeWithSourcemap(injection + code);
174
- }
175
- }
176
- }];
60
+ const addEntry = ({ entryName, entryPath, fileName, inject = "entry" }) => {
61
+ let devEntryPath = entryPath.startsWith("virtual:mf") ? "@id/" + entryPath : entryPath;
62
+ let entryFiles = [];
63
+ let htmlFilePath;
64
+ let _command;
65
+ let emitFileId;
66
+ let viteConfig;
67
+ function injectHtml() {
68
+ return inject === "html" && htmlFilePath;
69
+ }
70
+ function injectEntry() {
71
+ return inject === "entry" || !htmlFilePath;
72
+ }
73
+ return [{
74
+ name: "add-entry",
75
+ apply: "serve",
76
+ config(config, { command }) {
77
+ _command = command;
78
+ },
79
+ configResolved(config) {
80
+ viteConfig = config;
81
+ devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, "/").replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/^\//, "");
82
+ },
83
+ configureServer(server) {
84
+ server.middlewares.use((req, res, next) => {
85
+ if (!fileName) {
86
+ next();
87
+ return;
88
+ }
89
+ if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/"))) req.url = devEntryPath;
90
+ next();
91
+ });
92
+ },
93
+ transformIndexHtml(c) {
94
+ if (!injectHtml()) return;
95
+ return c.replace("<head>", `<head><script type="module" src=${JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/\\\\?/g, "/"))}><\/script>`);
96
+ },
97
+ transform(code, id) {
98
+ if (id.includes("node_modules") || inject !== "html" || htmlFilePath) return;
99
+ if (id.includes(".svelte-kit") && id.includes("internal.js")) {
100
+ const src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, "$1").replace(/\\\\?/g, "/");
101
+ return code.replace(/<head>/g, "<head><script type=\\\"module\\\" src=\\\"" + src + "\\\"><\/script>");
102
+ }
103
+ }
104
+ }, {
105
+ name: "add-entry",
106
+ enforce: "post",
107
+ configResolved(config) {
108
+ viteConfig = config;
109
+ const inputOptions = config.build.rollupOptions.input;
110
+ if (!inputOptions) htmlFilePath = pathe.resolve(config.root, "index.html");
111
+ else if (typeof inputOptions === "string") entryFiles = [inputOptions];
112
+ else if (Array.isArray(inputOptions)) entryFiles = inputOptions;
113
+ else if (typeof inputOptions === "object") entryFiles = Object.values(inputOptions);
114
+ if (entryFiles && entryFiles.length > 0) htmlFilePath = getFirstHtmlEntryFile(entryFiles);
115
+ },
116
+ buildStart() {
117
+ if (_command === "serve") return;
118
+ const hasHash = fileName?.includes?.("[hash");
119
+ const emitFileOptions = {
120
+ name: entryName,
121
+ type: "chunk",
122
+ id: entryPath,
123
+ preserveSignature: "strict"
124
+ };
125
+ if (!hasHash) emitFileOptions.fileName = fileName;
126
+ emitFileId = this.emitFile(emitFileOptions);
127
+ if (htmlFilePath && fs.existsSync(htmlFilePath)) {
128
+ const htmlContent = fs.readFileSync(htmlFilePath, "utf-8");
129
+ const scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
130
+ let match;
131
+ while ((match = scriptRegex.exec(htmlContent)) !== null) entryFiles.push(match[1]);
132
+ }
133
+ },
134
+ generateBundle(options, bundle) {
135
+ if (!injectHtml()) return;
136
+ const file = this.getFileName(emitFileId);
137
+ const resolvePath = (htmlFileName) => {
138
+ if (!viteConfig.experimental?.renderBuiltUrl) return viteConfig.base + file;
139
+ const result = viteConfig.experimental.renderBuiltUrl(file, {
140
+ hostId: htmlFileName,
141
+ hostType: "html",
142
+ type: "asset",
143
+ ssr: false
144
+ });
145
+ if (typeof result === "string") return result;
146
+ if (result && typeof result === "object") {
147
+ if ("runtime" in result) {
148
+ console.warn("[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. Runtime code cannot be used in <script src=\"\">. Falling back to base path.");
149
+ return viteConfig.base + file;
150
+ }
151
+ if (result.relative) return file;
152
+ }
153
+ return viteConfig.base + file;
154
+ };
155
+ for (const fileName in bundle) if (fileName.endsWith(".html")) {
156
+ let htmlAsset = bundle[fileName];
157
+ if (htmlAsset.type === "chunk") return;
158
+ const scriptContent = `
159
+ <script type="module" src="${resolvePath(fileName)}"><\/script>
160
+ `;
161
+ let htmlContent = htmlAsset.source.toString() || "";
162
+ htmlContent = htmlContent.replace("<head>", `<head>${scriptContent}`);
163
+ htmlAsset.source = htmlContent;
164
+ }
165
+ },
166
+ transform(code, id) {
167
+ if (injectEntry() && entryFiles.some((file) => id.endsWith(file))) return mapCodeToCodeWithSourcemap(`
168
+ import ${JSON.stringify(entryPath)};
169
+ ` + code);
170
+ }
171
+ }];
177
172
  };
178
173
 
179
- function _arrayLikeToArray(r, a) {
180
- (null == a || a > r.length) && (a = r.length);
181
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
182
- return n;
183
- }
184
- function _createForOfIteratorHelperLoose(r, e) {
185
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
186
- if (t) return (t = t.call(r)).next.bind(t);
187
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
188
- t && (r = t);
189
- var o = 0;
190
- return function () {
191
- return o >= r.length ? {
192
- done: !0
193
- } : {
194
- done: !1,
195
- value: r[o++]
196
- };
197
- };
198
- }
199
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
200
- }
201
- function _extends() {
202
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
203
- for (var e = 1; e < arguments.length; e++) {
204
- var t = arguments[e];
205
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
206
- }
207
- return n;
208
- }, _extends.apply(null, arguments);
209
- }
210
- function _unsupportedIterableToArray(r, a) {
211
- if (r) {
212
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
213
- var t = {}.toString.call(r).slice(8, -1);
214
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
215
- }
216
- }
217
-
218
- /**
219
- * Check if user-defined alias conflicts with shared modules
220
- * This should run after aliasToArrayPlugin to ensure alias is an array
221
- */
174
+ //#endregion
175
+ //#region src/plugins/pluginCheckAliasConflicts.ts
176
+ /**
177
+ * Check if user-defined alias conflicts with shared modules
178
+ * This should run after aliasToArrayPlugin to ensure alias is an array
179
+ */
222
180
  function checkAliasConflicts(options) {
223
- var _options$shared = options.shared,
224
- shared = _options$shared === void 0 ? {} : _options$shared;
225
- var sharedKeys = Object.keys(shared);
226
- return {
227
- name: 'check-alias-conflicts',
228
- configResolved: function configResolved(config) {
229
- var _config$resolve;
230
- if (sharedKeys.length === 0) return;
231
- var userAliases = ((_config$resolve = config.resolve) == null ? void 0 : _config$resolve.alias) || [];
232
- var conflicts = [];
233
- for (var _i = 0, _sharedKeys = sharedKeys; _i < _sharedKeys.length; _i++) {
234
- var sharedKey = _sharedKeys[_i];
235
- for (var _iterator = _createForOfIteratorHelperLoose(userAliases), _step; !(_step = _iterator()).done;) {
236
- var aliasEntry = _step.value;
237
- var findPattern = aliasEntry.find;
238
- var replacement = aliasEntry.replacement;
239
- // Skip if replacement is not a string (e.g., customResolver)
240
- if (typeof replacement !== 'string') continue;
241
- // Skip Module Federation internal aliases (used for proxying shared modules)
242
- // These are generated with replacement '$1' and should not trigger warnings
243
- if (replacement === '$1') continue;
244
- // Check if alias pattern matches the shared module
245
- var isMatch = false;
246
- if (typeof findPattern === 'string') {
247
- isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + '/');
248
- } else if (findPattern instanceof RegExp) {
249
- isMatch = findPattern.test(sharedKey);
250
- }
251
- if (isMatch) {
252
- conflicts.push({
253
- sharedModule: sharedKey,
254
- alias: String(findPattern),
255
- target: replacement
256
- });
257
- }
258
- }
259
- }
260
- if (conflicts.length > 0) {
261
- config.logger.warn('\n[Module Federation] Detected alias conflicts with shared modules:');
262
- conflicts.forEach(function (_ref) {
263
- var sharedModule = _ref.sharedModule,
264
- alias = _ref.alias,
265
- target = _ref.target;
266
- config.logger.warn(" - Shared module \"" + sharedModule + "\" is aliased by \"" + alias + "\" to \"" + target + "\"");
267
- });
268
- config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
269
- }
270
- }
271
- };
181
+ const { shared = {} } = options;
182
+ const sharedKeys = Object.keys(shared);
183
+ return {
184
+ name: "check-alias-conflicts",
185
+ configResolved(config) {
186
+ if (sharedKeys.length === 0) return;
187
+ const userAliases = config.resolve?.alias || [];
188
+ const conflicts = [];
189
+ for (const sharedKey of sharedKeys) for (const aliasEntry of userAliases) {
190
+ const findPattern = aliasEntry.find;
191
+ const replacement = aliasEntry.replacement;
192
+ if (typeof replacement !== "string") continue;
193
+ if (replacement === "$1") continue;
194
+ let isMatch = false;
195
+ if (typeof findPattern === "string") isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + "/");
196
+ else if (findPattern instanceof RegExp) isMatch = findPattern.test(sharedKey);
197
+ if (isMatch) conflicts.push({
198
+ sharedModule: sharedKey,
199
+ alias: String(findPattern),
200
+ target: replacement
201
+ });
202
+ }
203
+ if (conflicts.length > 0) {
204
+ config.logger.warn("\n[Module Federation] Detected alias conflicts with shared modules:");
205
+ conflicts.forEach(({ sharedModule, alias, target }) => {
206
+ config.logger.warn(` - Shared module "${sharedModule}" is aliased by "${alias}" to "${target}"`);
207
+ });
208
+ config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
209
+ }
210
+ }
211
+ };
272
212
  }
273
213
 
274
- /**
275
- * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
276
- */
214
+ //#endregion
215
+ //#region src/plugins/pluginDevProxyModuleTopLevelAwait.ts
216
+ /**
217
+ * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
218
+ */
277
219
  function PluginDevProxyModuleTopLevelAwait() {
278
- var filterFunction = pluginutils.createFilter();
279
- var processedFlag = '/* already-processed-by-dev-proxy-module-top-level-await */';
280
- return {
281
- name: 'dev-proxy-module-top-level-await',
282
- apply: 'serve',
283
- transform: function transform(code, id) {
284
- if (code.includes(processedFlag)) {
285
- return null;
286
- }
287
- if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
288
- return null;
289
- }
290
- if (!filterFunction(id)) return null;
291
- var ast;
292
- try {
293
- ast = this.parse(code, {
294
- allowReturnOutsideFunction: true
295
- });
296
- } catch (e) {
297
- throw new Error(id + ": " + e);
298
- }
299
- var magicString = new MagicString__default["default"](code);
300
- estreeWalker.walk(ast, {
301
- enter: function enter(node) {
302
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
303
- var exportSpecifiers = node.specifiers.map(function (specifier) {
304
- return specifier.exported.name;
305
- });
306
- var proxyStatements = exportSpecifiers.map(function (name) {
307
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
308
- }).join('\n');
309
- var exportStatements = exportSpecifiers.map(function (name) {
310
- return "__mfproxy__" + name + " as " + name;
311
- }).join(', ');
312
- var start = node.start;
313
- var end = node.end;
314
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
315
- magicString.overwrite(start, end, replacement);
316
- }
317
- if (node.type === 'ExportDefaultDeclaration') {
318
- var declaration = node.declaration;
319
- var _start = node.start;
320
- var _end = node.end;
321
- var proxyStatement;
322
- var exportStatement = 'default';
323
- if (declaration.type === 'Identifier') {
324
- // example: export default foo;
325
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
326
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
327
- // example: export default someFunction();
328
- var declarationCode = code.slice(declaration.start, declaration.end);
329
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
330
- } else {
331
- // other
332
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
333
- }
334
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
335
- magicString.overwrite(_start, _end, _replacement);
336
- }
337
- }
338
- });
339
- var transformedCode = magicString.toString();
340
- return {
341
- code: processedFlag + "\n" + transformedCode,
342
- map: magicString.generateMap({
343
- hires: true
344
- })
345
- };
346
- }
347
- };
220
+ const filterFunction = (0, _rollup_pluginutils.createFilter)();
221
+ const processedFlag = "/* already-processed-by-dev-proxy-module-top-level-await */";
222
+ return {
223
+ name: "dev-proxy-module-top-level-await",
224
+ apply: "serve",
225
+ transform(code, id) {
226
+ if (code.includes(processedFlag)) return null;
227
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) return null;
228
+ if (!filterFunction(id)) return null;
229
+ let ast;
230
+ try {
231
+ ast = this.parse(code, { allowReturnOutsideFunction: true });
232
+ } catch (e) {
233
+ throw new Error(`${id}: ${e}`);
234
+ }
235
+ const magicString = new magic_string.default(code);
236
+ (0, estree_walker.walk)(ast, { enter(node) {
237
+ if (node.type === "ExportNamedDeclaration" && node.specifiers) {
238
+ const exportSpecifiers = node.specifiers.map((specifier) => specifier.exported.name);
239
+ const proxyStatements = exportSpecifiers.map((name) => `
240
+ const __mfproxy__await${name} = await ${name}();
241
+ const __mfproxy__${name} = () => __mfproxy__await${name};
242
+ `).join("\n");
243
+ const exportStatements = exportSpecifiers.map((name) => `__mfproxy__${name} as ${name}`).join(", ");
244
+ const start = node.start;
245
+ const end = node.end;
246
+ const replacement = `${proxyStatements}\nexport { ${exportStatements} };`;
247
+ magicString.overwrite(start, end, replacement);
248
+ }
249
+ if (node.type === "ExportDefaultDeclaration") {
250
+ const declaration = node.declaration;
251
+ const start = node.start;
252
+ const end = node.end;
253
+ let proxyStatement;
254
+ let exportStatement = "default";
255
+ if (declaration.type === "Identifier") proxyStatement = `
256
+ const __mfproxy__awaitdefault = await ${declaration.name}();
257
+ const __mfproxy__default = __mfproxy__awaitdefault;
258
+ `;
259
+ else if (declaration.type === "CallExpression" || declaration.type === "FunctionDeclaration") proxyStatement = `
260
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
261
+ const __mfproxy__default = __mfproxy__awaitdefault;
262
+ `;
263
+ else proxyStatement = `
264
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
265
+ const __mfproxy__default = __mfproxy__awaitdefault;
266
+ `;
267
+ const replacement = `${proxyStatement}\nexport { __mfproxy__default as ${exportStatement} };`;
268
+ magicString.overwrite(start, end, replacement);
269
+ }
270
+ } });
271
+ return {
272
+ code: `${processedFlag}\n${magicString.toString()}`,
273
+ map: magicString.generateMap({ hires: true })
274
+ };
275
+ }
276
+ };
348
277
  }
349
278
 
350
- function _catch(body, recover) {
351
- try {
352
- var result = body();
353
- } catch (e) {
354
- return recover(e);
355
- }
356
- if (result && result.then) {
357
- return result.then(void 0, recover);
358
- }
359
- return result;
360
- }
361
- var DEFAULT_DEV_OPTIONS = {
362
- disableLiveReload: true,
363
- disableHotTypesReload: false,
364
- disableDynamicRemoteTypeHints: false
279
+ //#endregion
280
+ //#region src/plugins/pluginDts.ts
281
+ const DEFAULT_DEV_OPTIONS = {
282
+ disableLiveReload: true,
283
+ disableHotTypesReload: false,
284
+ disableDynamicRemoteTypeHints: false
365
285
  };
366
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
367
- var getIPv4 = function getIPv4() {
368
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
286
+ const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
287
+ const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
288
+ const forkDevWorkerPath = require.resolve("@module-federation/dts-plugin/dist/fork-dev-worker.js");
289
+ var DevWorker = class {
290
+ constructor(options) {
291
+ this.worker = _module_federation_dts_plugin_core.rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
292
+ this.worker.connect(options);
293
+ }
294
+ update() {
295
+ this.worker.process?.send?.({
296
+ type: _module_federation_dts_plugin_core.rpc.RpcGMCallTypes.CALL,
297
+ id: this.worker.id,
298
+ args: [void 0, "update"]
299
+ });
300
+ }
301
+ exit() {
302
+ this.worker.terminate();
303
+ }
369
304
  };
370
- var forkDevWorkerPath = function () {
371
- // eslint-disable-next-line @typescript-eslint/no-var-requires
372
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
373
- }();
374
- var DevWorker = /*#__PURE__*/function () {
375
- function DevWorker(options) {
376
- this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
377
- this.worker.connect(options);
378
- }
379
- var _proto = DevWorker.prototype;
380
- _proto.update = function update() {
381
- var _this$worker$process;
382
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
383
- type: core.rpc.RpcGMCallTypes.CALL,
384
- id: this.worker.id,
385
- args: [undefined, 'update']
386
- });
387
- };
388
- _proto.exit = function exit() {
389
- this.worker.terminate();
390
- };
391
- return DevWorker;
392
- }();
393
- var normalizeDevOptions = function normalizeDevOptions(dev) {
394
- if (dev === false) {
395
- return false;
396
- }
397
- if (dev === true || typeof dev === 'undefined') {
398
- return _extends({}, DEFAULT_DEV_OPTIONS);
399
- }
400
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
305
+ const normalizeDevOptions = (dev) => {
306
+ if (dev === false) return false;
307
+ if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
308
+ return {
309
+ ...DEFAULT_DEV_OPTIONS,
310
+ ...dev
311
+ };
401
312
  };
402
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
403
- var exposes = {};
404
- Object.entries(options.exposes).forEach(function (_ref) {
405
- var key = _ref[0],
406
- value = _ref[1];
407
- if (typeof value === 'string') {
408
- exposes[key] = value;
409
- return;
410
- }
411
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
412
- if (importValue) {
413
- exposes[key] = importValue;
414
- }
415
- });
416
- var remotes = {};
417
- Object.entries(options.remotes).forEach(function (_ref2) {
418
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
419
- var key = _ref2[0],
420
- remote = _ref2[1];
421
- if (typeof remote === 'string') {
422
- remotes[key] = remote;
423
- return;
424
- }
425
- if (!remote.entry) {
426
- return;
427
- }
428
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
429
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
430
- remotes[key] = entryGlobalName + "@" + remote.entry;
431
- });
432
- return _extends({}, options, {
433
- exposes: exposes,
434
- remotes: remotes
435
- });
313
+ const buildDtsModuleFederationConfig = (options) => {
314
+ const exposes = {};
315
+ Object.entries(options.exposes).forEach(([key, value]) => {
316
+ if (typeof value === "string") {
317
+ exposes[key] = value;
318
+ return;
319
+ }
320
+ const importValue = Array.isArray(value.import) ? value.import[0] : value.import;
321
+ if (importValue) exposes[key] = importValue;
322
+ });
323
+ const remotes = {};
324
+ Object.entries(options.remotes).forEach(([key, remote]) => {
325
+ if (typeof remote === "string") {
326
+ remotes[key] = remote;
327
+ return;
328
+ }
329
+ if (!remote.entry) return;
330
+ remotes[key] = `${remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key}@${remote.entry}`;
331
+ });
332
+ return {
333
+ ...options,
334
+ exposes,
335
+ remotes
336
+ };
436
337
  };
437
- var resolveOutputDir = function resolveOutputDir(config) {
438
- var outDir = config.build.outDir;
439
- if (path__namespace.isAbsolute(outDir)) {
440
- return path__namespace.relative(config.root, outDir);
441
- }
442
- return outDir;
338
+ const resolveOutputDir = (config) => {
339
+ const { outDir } = config.build;
340
+ if (pathe.isAbsolute(outDir)) return pathe.relative(config.root, outDir);
341
+ return outDir;
443
342
  };
444
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
445
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
446
- if (typeof plugin === 'string') {
447
- return plugin === pluginId;
448
- }
449
- return plugin[0] === pluginId;
450
- });
451
- if (!hasPlugin) {
452
- options.runtimePlugins.push(pluginId);
453
- }
343
+ const ensureRuntimePlugin = (options, pluginId) => {
344
+ if (!options.runtimePlugins.some((plugin) => {
345
+ if (typeof plugin === "string") return plugin === pluginId;
346
+ return plugin[0] === pluginId;
347
+ })) options.runtimePlugins.push(pluginId);
454
348
  };
455
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
456
- var defaultGenerateTypes = {
457
- compileInChildProcess: true
458
- };
459
- var defaultConsumeTypes = {
460
- consumeAPITypes: true
461
- };
462
- return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
463
- generateTypes: defaultGenerateTypes,
464
- consumeTypes: defaultConsumeTypes,
465
- extraOptions: {},
466
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
467
- }, 'mfOptions.dts')(dts);
349
+ const normalizeDevDtsOptions = (dts, context) => {
350
+ return (0, _module_federation_sdk.normalizeOptions)((0, _module_federation_dts_plugin.isTSProject)(dts, context), {
351
+ generateTypes: { compileInChildProcess: true },
352
+ consumeTypes: { consumeAPITypes: true },
353
+ extraOptions: {},
354
+ displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
355
+ }, "mfOptions.dts")(dts);
468
356
  };
469
- var logDtsError = function logDtsError(error, dtsOptions) {
470
- if (dtsOptions === false) {
471
- return;
472
- }
473
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
474
- return;
475
- }
476
- console.error(error);
357
+ const logDtsError = (error, dtsOptions) => {
358
+ if (dtsOptions === false) return;
359
+ if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
360
+ console.error(error);
477
361
  };
478
362
  function pluginDts(options) {
479
- if (options.dts === false) {
480
- return [];
481
- }
482
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
483
- var resolvedConfig;
484
- var devWorker;
485
- var normalizedDevOptions;
486
- var hasGeneratedBundle = false;
487
- var devPlugin = {
488
- name: 'module-federation-dts-dev',
489
- apply: 'serve',
490
- config: function config(_config) {
491
- normalizedDevOptions = normalizeDevOptions(options.dev);
492
- if (!normalizedDevOptions) {
493
- return;
494
- }
495
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
496
- return;
497
- }
498
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
499
- var define = _config.define ? _extends({}, _config.define) : {};
500
- if (!('FEDERATION_IPV4' in define)) {
501
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
502
- }
503
- _config.define = define;
504
- },
505
- configResolved: function configResolved(config) {
506
- resolvedConfig = config;
507
- },
508
- configureServer: function configureServer(server) {
509
- if (!normalizedDevOptions || !resolvedConfig) {
510
- return;
511
- }
512
- var devOptions = normalizedDevOptions;
513
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
514
- return;
515
- }
516
- if (!options.name) {
517
- throw new Error('name is required if you want to enable dev server!');
518
- }
519
- var outputDir = resolveOutputDir(resolvedConfig);
520
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
521
- if (typeof normalizedDtsOptions !== 'object') {
522
- return;
523
- }
524
- var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
525
- compileInChildProcess: true
526
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
527
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
528
- implementation: normalizedDtsOptions.implementation,
529
- context: resolvedConfig.root,
530
- outputDir: outputDir,
531
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
532
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
533
- }, normalizedGenerateTypes, {
534
- typesFolder: '.dev-server'
535
- });
536
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
537
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
538
- }
539
- var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
540
- consumeAPITypes: true
541
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
542
- var host = normalizedConsumeTypes === false ? undefined : _extends({
543
- implementation: normalizedDtsOptions.implementation,
544
- context: resolvedConfig.root,
545
- moduleFederationConfig: dtsModuleFederationConfig,
546
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
547
- abortOnError: false
548
- }, normalizedConsumeTypes);
549
- var extraOptions = normalizedDtsOptions.extraOptions || {};
550
- if (!remote && !host && devOptions.disableLiveReload) {
551
- return;
552
- }
553
- var startDevWorker = function startDevWorker() {
554
- try {
555
- var _temp2 = function _temp2() {
556
- var _server$httpServer;
557
- devWorker = new DevWorker({
558
- name: options.name,
559
- remote: remote,
560
- host: host ? _extends({}, host, {
561
- remoteTypeUrls: remoteTypeUrls
562
- }) : undefined,
563
- extraOptions: extraOptions,
564
- disableLiveReload: devOptions.disableLiveReload,
565
- disableHotTypesReload: devOptions.disableHotTypesReload
566
- });
567
- var update = function update() {
568
- var _devWorker;
569
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
570
- };
571
- server.watcher.on('change', update);
572
- server.watcher.on('add', update);
573
- server.watcher.on('unlink', update);
574
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
575
- var _devWorker2;
576
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
577
- server.watcher.off('change', update);
578
- server.watcher.off('add', update);
579
- server.watcher.off('unlink', update);
580
- });
581
- };
582
- var remoteTypeUrls;
583
- var _temp = function () {
584
- if (host) {
585
- return Promise.resolve(new Promise(function (resolve) {
586
- dtsPlugin.consumeTypesAPI({
587
- host: host,
588
- extraOptions: extraOptions,
589
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
590
- }, resolve);
591
- })).then(function (_Promise) {
592
- remoteTypeUrls = _Promise;
593
- });
594
- }
595
- }();
596
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
597
- } catch (e) {
598
- return Promise.reject(e);
599
- }
600
- };
601
- startDevWorker()["catch"](function (error) {
602
- logDtsError(error, normalizedDtsOptions);
603
- });
604
- }
605
- };
606
- var buildPlugin = {
607
- name: 'module-federation-dts-build',
608
- apply: 'build',
609
- configResolved: function configResolved(config) {
610
- resolvedConfig = config;
611
- },
612
- generateBundle: function generateBundle() {
613
- try {
614
- var _temp6 = function _temp6() {
615
- var generateOptions;
616
- try {
617
- generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
618
- context: context,
619
- outputDir: outputDir,
620
- dtsOptions: normalizedDtsOptions,
621
- pluginOptions: dtsModuleFederationConfig
622
- });
623
- } catch (error) {
624
- logDtsError(error, normalizedDtsOptions);
625
- return;
626
- }
627
- if (!generateOptions) {
628
- return;
629
- }
630
- var _temp4 = _catch(function () {
631
- return Promise.resolve(dtsPlugin.generateTypesAPI({
632
- dtsManagerOptions: generateOptions
633
- })).then(function () {});
634
- }, function (error) {
635
- logDtsError(error, normalizedDtsOptions);
636
- });
637
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
638
- };
639
- if (hasGeneratedBundle) {
640
- return Promise.resolve();
641
- }
642
- hasGeneratedBundle = true;
643
- if (!resolvedConfig) {
644
- return Promise.resolve();
645
- }
646
- var normalizedDtsOptions;
647
- try {
648
- normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
649
- } catch (error) {
650
- logDtsError(error, options.dts);
651
- return Promise.resolve();
652
- }
653
- if (typeof normalizedDtsOptions !== 'object') {
654
- return Promise.resolve();
655
- }
656
- var context = resolvedConfig.root;
657
- var outputDir = resolveOutputDir(resolvedConfig);
658
- var consumeOptions;
659
- try {
660
- consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
661
- context: context,
662
- dtsOptions: normalizedDtsOptions,
663
- pluginOptions: dtsModuleFederationConfig
664
- });
665
- } catch (error) {
666
- logDtsError(error, normalizedDtsOptions);
667
- return Promise.resolve();
668
- }
669
- var _temp5 = function (_consumeOptions) {
670
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
671
- var _temp3 = _catch(function () {
672
- return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
673
- }, function (error) {
674
- logDtsError(error, normalizedDtsOptions);
675
- });
676
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
677
- }
678
- }();
679
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
680
- } catch (e) {
681
- return Promise.reject(e);
682
- }
683
- }
684
- };
685
- return [devPlugin, buildPlugin];
363
+ if (options.dts === false) return [];
364
+ const dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
365
+ let resolvedConfig;
366
+ let devWorker;
367
+ let normalizedDevOptions;
368
+ let hasGeneratedBundle = false;
369
+ return [{
370
+ name: "module-federation-dts-dev",
371
+ apply: "serve",
372
+ config(config) {
373
+ normalizedDevOptions = normalizeDevOptions(options.dev);
374
+ if (!normalizedDevOptions) return;
375
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
376
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
377
+ const define = config.define ? { ...config.define } : {};
378
+ if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
379
+ config.define = define;
380
+ },
381
+ configResolved(config) {
382
+ resolvedConfig = config;
383
+ },
384
+ configureServer(server) {
385
+ if (!normalizedDevOptions || !resolvedConfig) return;
386
+ const devOptions = normalizedDevOptions;
387
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
388
+ if (!options.name) throw new Error("name is required if you want to enable dev server!");
389
+ const outputDir = resolveOutputDir(resolvedConfig);
390
+ const normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
391
+ if (typeof normalizedDtsOptions !== "object") return;
392
+ const normalizedGenerateTypes = (0, _module_federation_sdk.normalizeOptions)(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
393
+ const remote = normalizedGenerateTypes === false ? void 0 : {
394
+ implementation: normalizedDtsOptions.implementation,
395
+ context: resolvedConfig.root,
396
+ outputDir,
397
+ moduleFederationConfig: { ...dtsModuleFederationConfig },
398
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
399
+ ...normalizedGenerateTypes,
400
+ typesFolder: ".dev-server"
401
+ };
402
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === "object" && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
403
+ const normalizedConsumeTypes = (0, _module_federation_sdk.normalizeOptions)(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
404
+ const host = normalizedConsumeTypes === false ? void 0 : {
405
+ implementation: normalizedDtsOptions.implementation,
406
+ context: resolvedConfig.root,
407
+ moduleFederationConfig: dtsModuleFederationConfig,
408
+ typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
409
+ abortOnError: false,
410
+ ...normalizedConsumeTypes
411
+ };
412
+ const extraOptions = normalizedDtsOptions.extraOptions || {};
413
+ if (!remote && !host && devOptions.disableLiveReload) return;
414
+ const startDevWorker = async () => {
415
+ let remoteTypeUrls;
416
+ if (host) remoteTypeUrls = await new Promise((resolve) => {
417
+ (0, _module_federation_dts_plugin.consumeTypesAPI)({
418
+ host,
419
+ extraOptions,
420
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
421
+ }, resolve);
422
+ });
423
+ devWorker = new DevWorker({
424
+ name: options.name,
425
+ remote,
426
+ host: host ? {
427
+ ...host,
428
+ remoteTypeUrls
429
+ } : void 0,
430
+ extraOptions,
431
+ disableLiveReload: devOptions.disableLiveReload,
432
+ disableHotTypesReload: devOptions.disableHotTypesReload
433
+ });
434
+ const update = () => devWorker?.update();
435
+ server.watcher.on("change", update);
436
+ server.watcher.on("add", update);
437
+ server.watcher.on("unlink", update);
438
+ server.httpServer?.once("close", () => {
439
+ devWorker?.exit();
440
+ server.watcher.off("change", update);
441
+ server.watcher.off("add", update);
442
+ server.watcher.off("unlink", update);
443
+ });
444
+ };
445
+ startDevWorker().catch((error) => {
446
+ logDtsError(error, normalizedDtsOptions);
447
+ });
448
+ }
449
+ }, {
450
+ name: "module-federation-dts-build",
451
+ apply: "build",
452
+ configResolved(config) {
453
+ resolvedConfig = config;
454
+ },
455
+ async generateBundle() {
456
+ if (hasGeneratedBundle) return;
457
+ hasGeneratedBundle = true;
458
+ if (!resolvedConfig) return;
459
+ let normalizedDtsOptions;
460
+ try {
461
+ normalizedDtsOptions = (0, _module_federation_dts_plugin.normalizeDtsOptions)(dtsModuleFederationConfig, resolvedConfig.root);
462
+ } catch (error) {
463
+ logDtsError(error, options.dts);
464
+ return;
465
+ }
466
+ if (typeof normalizedDtsOptions !== "object") return;
467
+ const context = resolvedConfig.root;
468
+ const outputDir = resolveOutputDir(resolvedConfig);
469
+ let consumeOptions;
470
+ try {
471
+ consumeOptions = (0, _module_federation_dts_plugin.normalizeConsumeTypesOptions)({
472
+ context,
473
+ dtsOptions: normalizedDtsOptions,
474
+ pluginOptions: dtsModuleFederationConfig
475
+ });
476
+ } catch (error) {
477
+ logDtsError(error, normalizedDtsOptions);
478
+ return;
479
+ }
480
+ if (consumeOptions?.host?.typesOnBuild) try {
481
+ await (0, _module_federation_dts_plugin.consumeTypesAPI)(consumeOptions);
482
+ } catch (error) {
483
+ logDtsError(error, normalizedDtsOptions);
484
+ }
485
+ let generateOptions;
486
+ try {
487
+ generateOptions = (0, _module_federation_dts_plugin.normalizeGenerateTypesOptions)({
488
+ context,
489
+ outputDir,
490
+ dtsOptions: normalizedDtsOptions,
491
+ pluginOptions: dtsModuleFederationConfig
492
+ });
493
+ } catch (error) {
494
+ logDtsError(error, normalizedDtsOptions);
495
+ return;
496
+ }
497
+ if (!generateOptions) return;
498
+ try {
499
+ await (0, _module_federation_dts_plugin.generateTypesAPI)({ dtsManagerOptions: generateOptions });
500
+ } catch (error) {
501
+ logDtsError(error, normalizedDtsOptions);
502
+ }
503
+ }
504
+ }];
686
505
  }
687
506
 
507
+ //#endregion
508
+ //#region src/utils/normalizeModuleFederationOptions.ts
688
509
  function normalizeExposesItem(key, item) {
689
- var importPath = '';
690
- if (typeof item === 'string') {
691
- importPath = item;
692
- }
693
- if (typeof item === 'object') {
694
- importPath = item["import"];
695
- }
696
- return {
697
- "import": importPath
698
- };
510
+ let importPath = "";
511
+ if (typeof item === "string") importPath = item;
512
+ if (typeof item === "object") importPath = item.import;
513
+ return { import: importPath };
699
514
  }
700
515
  function normalizeExposes(exposes) {
701
- if (!exposes) return {};
702
- var res = {};
703
- Object.keys(exposes).forEach(function (key) {
704
- res[key] = normalizeExposesItem(key, exposes[key]);
705
- });
706
- return res;
516
+ if (!exposes) return {};
517
+ const res = {};
518
+ Object.keys(exposes).forEach((key) => {
519
+ res[key] = normalizeExposesItem(key, exposes[key]);
520
+ });
521
+ return res;
707
522
  }
708
523
  function normalizeRemotes(remotes) {
709
- if (!remotes) return {};
710
- var result = {};
711
- if (typeof remotes === 'object') {
712
- Object.keys(remotes).forEach(function (key) {
713
- result[key] = normalizeRemoteItem(key, remotes[key]);
714
- });
715
- }
716
- return result;
524
+ if (!remotes) return {};
525
+ const result = {};
526
+ if (typeof remotes === "object") Object.keys(remotes).forEach((key) => {
527
+ result[key] = normalizeRemoteItem(key, remotes[key]);
528
+ });
529
+ return result;
717
530
  }
718
531
  function normalizeRemoteItem(key, remote) {
719
- if (typeof remote === 'string') {
720
- var _remote$split = remote.split('@'),
721
- entryGlobalName = _remote$split[0];
722
- var entry = remote.replace(entryGlobalName + '@', '');
723
- return {
724
- type: 'var',
725
- name: key,
726
- entry: entry,
727
- entryGlobalName: entryGlobalName,
728
- shareScope: 'default'
729
- };
730
- }
731
- return Object.assign({
732
- type: 'var',
733
- name: key,
734
- shareScope: 'default',
735
- entryGlobalName: key
736
- }, remote);
532
+ if (typeof remote === "string") {
533
+ const [entryGlobalName] = remote.split("@");
534
+ return {
535
+ type: "var",
536
+ name: key,
537
+ entry: remote.replace(entryGlobalName + "@", ""),
538
+ entryGlobalName,
539
+ shareScope: "default"
540
+ };
541
+ }
542
+ return Object.assign({
543
+ type: "var",
544
+ name: key,
545
+ shareScope: "default",
546
+ entryGlobalName: key
547
+ }, remote);
737
548
  }
738
549
  function removePathFromNpmPackage(packageString) {
739
- // 匹配npm包名的正则表达式,忽略路径部分
740
- var regex = /^(?:@[^/]+\/)?[^/]+/;
741
- // 使用正则表达式匹配并提取包名
742
- var match = packageString.match(regex);
743
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
744
- return match ? match[0] : packageString;
550
+ const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
551
+ return match ? match[0] : packageString;
745
552
  }
746
- /**
747
- * Tries to find the package.json's version of a shared package
748
- * if `package.json` is not declared in `exports`
749
- * @param {string} sharedName
750
- * @returns {string | undefined}
751
- */
553
+ /**
554
+ * Tries to find the package.json's version of a shared package
555
+ * if `package.json` is not declared in `exports`
556
+ * @param {string} sharedName
557
+ * @returns {string | undefined}
558
+ */
752
559
  function searchPackageVersion(sharedName) {
753
- try {
754
- var sharedPath = require.resolve(sharedName);
755
- var potentialPackageJsonDir = path__namespace.dirname(sharedPath);
756
- var rootDir = path__namespace.parse(potentialPackageJsonDir).root;
757
- while (path__namespace.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
758
- var potentialPackageJsonPath = path__namespace.join(potentialPackageJsonDir, 'package.json');
759
- if (fs__namespace.existsSync(potentialPackageJsonPath)) {
760
- var potentialPackageJson = require(potentialPackageJsonPath);
761
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
762
- return potentialPackageJson.version;
763
- }
764
- }
765
- potentialPackageJsonDir = path__namespace.dirname(potentialPackageJsonDir);
766
- }
767
- } catch (_) {}
768
- return undefined;
560
+ try {
561
+ const sharedPath = require.resolve(sharedName);
562
+ let potentialPackageJsonDir = pathe.dirname(sharedPath);
563
+ const rootDir = pathe.parse(potentialPackageJsonDir).root;
564
+ while (pathe.parse(potentialPackageJsonDir).base !== "node_modules" && potentialPackageJsonDir !== rootDir) {
565
+ const potentialPackageJsonPath = pathe.join(potentialPackageJsonDir, "package.json");
566
+ if (fs.existsSync(potentialPackageJsonPath)) {
567
+ const potentialPackageJson = require(potentialPackageJsonPath);
568
+ if (typeof potentialPackageJson == "object" && potentialPackageJson !== null && typeof potentialPackageJson.version === "string" && potentialPackageJson.name === sharedName) return potentialPackageJson.version;
569
+ }
570
+ potentialPackageJsonDir = pathe.dirname(potentialPackageJsonDir);
571
+ }
572
+ } catch (_) {}
769
573
  }
770
574
  function normalizeShareItem(key, shareItem) {
771
- var version;
772
- try {
773
- try {
774
- version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
775
- } catch (e1) {
776
- try {
777
- var localPath = path__namespace.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
778
- version = require(localPath).version;
779
- } catch (e2) {
780
- version = searchPackageVersion(key);
781
- if (!version) console.error(e1);
782
- }
783
- }
784
- } catch (e) {
785
- console.error("Unexpected error resolving version for " + key + ":", e);
786
- }
787
- if (typeof shareItem === 'string') {
788
- return {
789
- name: shareItem,
790
- version: version,
791
- scope: 'default',
792
- from: '',
793
- shareConfig: {
794
- "import": undefined,
795
- singleton: false,
796
- requiredVersion: version ? "^" + version : '*'
797
- }
798
- };
799
- }
800
- return {
801
- name: key,
802
- from: '',
803
- version: shareItem.version || version,
804
- scope: shareItem.shareScope || 'default',
805
- shareConfig: {
806
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
807
- singleton: shareItem.singleton || false,
808
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
809
- strictVersion: !!shareItem.strictVersion
810
- }
811
- };
575
+ let version;
576
+ try {
577
+ try {
578
+ version = require(pathe.join(removePathFromNpmPackage(key), "package.json")).version;
579
+ } catch (e1) {
580
+ try {
581
+ const localPath = pathe.join(process.cwd(), "node_modules", removePathFromNpmPackage(key), "package.json");
582
+ version = require(localPath).version;
583
+ } catch (e2) {
584
+ version = searchPackageVersion(key);
585
+ if (!version) console.error(e1);
586
+ }
587
+ }
588
+ } catch (e) {
589
+ console.error(`Unexpected error resolving version for ${key}:`, e);
590
+ }
591
+ if (typeof shareItem === "string") return {
592
+ name: shareItem,
593
+ version,
594
+ scope: "default",
595
+ from: "",
596
+ shareConfig: {
597
+ import: void 0,
598
+ singleton: false,
599
+ requiredVersion: version ? `^${version}` : "*"
600
+ }
601
+ };
602
+ return {
603
+ name: key,
604
+ from: "",
605
+ version: shareItem.version || version,
606
+ scope: shareItem.shareScope || "default",
607
+ shareConfig: {
608
+ import: typeof shareItem === "object" ? shareItem.import : void 0,
609
+ singleton: shareItem.singleton || false,
610
+ requiredVersion: shareItem.requiredVersion || (version ? `^${version}` : "*"),
611
+ strictVersion: !!shareItem.strictVersion
612
+ }
613
+ };
812
614
  }
813
615
  function normalizeShared(shared) {
814
- if (!shared) return {};
815
- var result = {};
816
- if (Array.isArray(shared)) {
817
- shared.forEach(function (key) {
818
- result[key] = normalizeShareItem(key, key);
819
- });
820
- return result;
821
- }
822
- if (typeof shared === 'object') {
823
- Object.keys(shared).forEach(function (key) {
824
- result[key] = normalizeShareItem(key, shared[key]);
825
- });
826
- }
827
- return result;
616
+ if (!shared) return {};
617
+ const result = {};
618
+ if (Array.isArray(shared)) {
619
+ shared.forEach((key) => {
620
+ result[key] = normalizeShareItem(key, key);
621
+ });
622
+ return result;
623
+ }
624
+ if (typeof shared === "object") Object.keys(shared).forEach((key) => {
625
+ result[key] = normalizeShareItem(key, shared[key]);
626
+ });
627
+ return result;
828
628
  }
829
629
  function normalizeLibrary(library) {
830
- if (!library) return undefined;
831
- return library;
630
+ if (!library) return void 0;
631
+ return library;
832
632
  }
833
- function normalizeManifest(manifest) {
834
- if (manifest === void 0) {
835
- manifest = false;
836
- }
837
- if (typeof manifest === 'boolean') {
838
- return manifest;
839
- }
840
- return Object.assign({
841
- filePath: '',
842
- disableAssetsAnalyze: false,
843
- fileName: 'mf-manifest.json'
844
- }, manifest);
633
+ function normalizeManifest(manifest = false) {
634
+ if (typeof manifest === "boolean") return manifest;
635
+ return Object.assign({
636
+ filePath: "",
637
+ disableAssetsAnalyze: false,
638
+ fileName: "mf-manifest.json"
639
+ }, manifest);
845
640
  }
846
- var config;
641
+ let config;
847
642
  function getNormalizeModuleFederationOptions() {
848
- return config;
643
+ return config;
849
644
  }
850
645
  function getNormalizeShareItem(key) {
851
- var options = getNormalizeModuleFederationOptions();
852
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
853
- return shareItem;
646
+ const options = getNormalizeModuleFederationOptions();
647
+ return options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
854
648
  }
855
649
  function normalizeModuleFederationOptions(options) {
856
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
857
- throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
858
- }
859
- return config = {
860
- exposes: normalizeExposes(options.exposes),
861
- filename: options.filename || 'remoteEntry-[hash]',
862
- library: normalizeLibrary(options.library),
863
- name: options.name,
864
- // remoteType: options.remoteType,
865
- remotes: normalizeRemotes(options.remotes),
866
- runtime: options.runtime,
867
- shareScope: options.shareScope || 'default',
868
- shared: normalizeShared(options.shared),
869
- runtimePlugins: options.runtimePlugins || [],
870
- implementation: options.implementation || require.resolve('@module-federation/runtime'),
871
- manifest: normalizeManifest(options.manifest),
872
- dev: options.dev,
873
- dts: options.dts,
874
- getPublicPath: options.getPublicPath,
875
- publicPath: options.publicPath,
876
- shareStrategy: options.shareStrategy || 'version-first',
877
- ignoreOrigin: options.ignoreOrigin || false,
878
- virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
879
- hostInitInjectLocation: options.hostInitInjectLocation || 'html',
880
- bundleAllCSS: options.bundleAllCSS || false,
881
- moduleParseTimeout: options.moduleParseTimeout || 10
882
- };
650
+ if (options.virtualModuleDir && options.virtualModuleDir.includes("/")) throw new Error(`Invalid virtualModuleDir: "${options.virtualModuleDir}". The virtualModuleDir option cannot contain slashes (/). Please use a single directory name like '__mf__virtual__your_app_name'.`);
651
+ return config = {
652
+ exposes: normalizeExposes(options.exposes),
653
+ filename: options.filename || "remoteEntry-[hash]",
654
+ library: normalizeLibrary(options.library),
655
+ name: options.name,
656
+ remotes: normalizeRemotes(options.remotes),
657
+ runtime: options.runtime,
658
+ shareScope: options.shareScope || "default",
659
+ shared: normalizeShared(options.shared),
660
+ runtimePlugins: options.runtimePlugins || [],
661
+ implementation: options.implementation || require.resolve("@module-federation/runtime"),
662
+ manifest: normalizeManifest(options.manifest),
663
+ dev: options.dev,
664
+ dts: options.dts,
665
+ getPublicPath: options.getPublicPath,
666
+ publicPath: options.publicPath,
667
+ shareStrategy: options.shareStrategy || "version-first",
668
+ ignoreOrigin: options.ignoreOrigin || false,
669
+ virtualModuleDir: options.virtualModuleDir || "__mf__virtual",
670
+ hostInitInjectLocation: options.hostInitInjectLocation || "html",
671
+ bundleAllCSS: options.bundleAllCSS || false,
672
+ moduleParseTimeout: options.moduleParseTimeout || 10,
673
+ varFilename: options.varFilename,
674
+ target: options.target
675
+ };
883
676
  }
884
677
 
885
- /**
886
- * Escaping rules:
887
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
888
- * @ => 1
889
- * / => 2
890
- * - => 3
891
- * . => 4
892
- */
893
- /**
894
- * Encodes a package name into a valid file name.
895
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
896
- * @returns {string} - The encoded file name.
897
- */
678
+ //#endregion
679
+ //#region src/utils/packageNameUtils.ts
680
+ /**
681
+ * Escaping rules:
682
+ * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
683
+ * @ => 1
684
+ * / => 2
685
+ * - => 3
686
+ * . => 4
687
+ */
688
+ /**
689
+ * Encodes a package name into a valid file name.
690
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
691
+ * @returns {string} - The encoded file name.
692
+ */
898
693
  function packageNameEncode(name) {
899
- if (typeof name !== 'string') throw new Error('A string package name is required');
900
- return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
694
+ if (typeof name !== "string") throw new Error("A string package name is required");
695
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
901
696
  }
902
- /**
903
- * Decodes an encoded file name back to the original package name.
904
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
905
- * @returns {string} - The decoded package name.
906
- */
697
+ /**
698
+ * Decodes an encoded file name back to the original package name.
699
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
700
+ * @returns {string} - The decoded package name.
701
+ */
907
702
  function packageNameDecode(encoded) {
908
- if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
909
- return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
703
+ if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
704
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
910
705
  }
911
706
 
912
- /**
913
- * https://github.com/module-federation/vite/issues/68
914
- */
707
+ //#endregion
708
+ //#region src/utils/localSharedImportMap_temp.ts
709
+ /**
710
+ * https://github.com/module-federation/vite/issues/68
711
+ */
915
712
  function getLocalSharedImportMapPath_temp() {
916
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
917
- name = _getNormalizeModuleFe.name;
918
- return path__default["default"].resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
713
+ const { name } = getNormalizeModuleFederationOptions();
714
+ return pathe.default.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
919
715
  }
920
716
  function writeLocalSharedImportMap_temp(content) {
921
- var localSharedImportMapId = getLocalSharedImportMapPath_temp();
922
- createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
717
+ createFile(getLocalSharedImportMapPath_temp() + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
923
718
  }
924
719
  function createFile(filePath, content) {
925
- var dir = path__default["default"].dirname(filePath);
926
- fs.mkdirSync(dir, {
927
- recursive: true
928
- });
929
- fs.writeFileSync(filePath, content);
720
+ (0, fs.mkdirSync)(pathe.default.dirname(filePath), { recursive: true });
721
+ (0, fs.writeFileSync)(filePath, content);
930
722
  }
931
723
 
932
- /**
933
- * Serializes a JavaScript object into a string of source code that can be evaluated.
934
- * This function is used to create runtime plugin options without relying solely on JSON.stringify,
935
- * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
936
- * It also safely handles circular references.
937
- *
938
- * @param {Record<string, unknown>} options - The options object to serialize.
939
- * @returns {string} The resulting JavaScript source code string.
940
- */
724
+ //#endregion
725
+ //#region src/utils/serializeRuntimeOptions.ts
726
+ /**
727
+ * Serializes a JavaScript object into a string of source code that can be evaluated.
728
+ * This function is used to create runtime plugin options without relying solely on JSON.stringify,
729
+ * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
730
+ * It also safely handles circular references.
731
+ *
732
+ * @param {Record<string, unknown>} options - The options object to serialize.
733
+ * @returns {string} The resulting JavaScript source code string.
734
+ */
941
735
  function serializeRuntimeOptions(options) {
942
- // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
943
- var seenObjects = new WeakSet();
944
- /**
945
- * Recursive inner function to serialize any value into a source code string.
946
- */
947
- function valueToCode(val) {
948
- // 1. Handle primitive values
949
- if (val === null) return 'null';
950
- var type = typeof val;
951
- if (type === 'string') return JSON.stringify(val);
952
- if (type === 'number' || type === 'boolean') return String(val);
953
- if (type === 'undefined') return 'undefined';
954
- // Handle Symbol
955
- if (type === 'symbol') {
956
- var _val$description;
957
- var desc = (_val$description = val.description) != null ? _val$description : '';
958
- return "Symbol(" + JSON.stringify(desc) + ")";
959
- }
960
- // Handle Function (returns the function's source code)
961
- if (type === 'function') return val.toString();
962
- // 2. Handle special built-in objects
963
- if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
964
- if (val instanceof RegExp) {
965
- return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
966
- }
967
- // 3. Check for circular references and mark object as seen
968
- // This applies to objects, arrays, maps, and sets.
969
- if (type === 'object') {
970
- if (seenObjects.has(val)) {
971
- // This object has been seen previously in the recursion path
972
- return "\"__circular__\"";
973
- }
974
- seenObjects.add(val);
975
- }
976
- // 4. Handle Array, Map, Set
977
- if (Array.isArray(val)) {
978
- // Recursively serialize each element
979
- return "[" + val.map(valueToCode).join(', ') + "]";
980
- }
981
- if (val instanceof Map) {
982
- // Serialize Map entries into an array of [key, value] pairs
983
- var entries = Array.from(val.entries()).map(function (_ref) {
984
- var k = _ref[0],
985
- v = _ref[1];
986
- return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
987
- });
988
- return "new Map([" + entries.join(', ') + "])";
989
- }
990
- if (val instanceof Set) {
991
- // Serialize Set values into an array
992
- var items = Array.from(val.values()).map(valueToCode);
993
- return "new Set([" + items.join(', ') + "])";
994
- }
995
- // 5. Handle plain objects (the default object type)
996
- if (type === 'object') {
997
- var properties = [];
998
- // Iterate over the object's own enumerable properties
999
- for (var key in val) {
1000
- if (Object.prototype.hasOwnProperty.call(val, key)) {
1001
- // Wrap the key in JSON.stringify to handle non-identifier keys
1002
- properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
1003
- }
1004
- }
1005
- return "{" + properties.join(', ') + "}";
1006
- }
1007
- // 6. Fallback case (e.g., BigInt, other object types)
1008
- // Coerce to string and then JSON.stringify that string for safety
1009
- return JSON.stringify(String(val));
1010
- }
1011
- // Start serialization for the top-level object
1012
- var topLevelProps = [];
1013
- // Iterate over the properties of the root 'options' object
1014
- for (var key in options) {
1015
- if (Object.prototype.hasOwnProperty.call(options, key)) {
1016
- topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
1017
- }
1018
- }
1019
- return "{" + topLevelProps.join(', ') + "}";
736
+ const seenObjects = /* @__PURE__ */ new WeakSet();
737
+ /**
738
+ * Recursive inner function to serialize any value into a source code string.
739
+ */
740
+ function valueToCode(val) {
741
+ if (val === null) return "null";
742
+ const type = typeof val;
743
+ if (type === "string") return JSON.stringify(val);
744
+ if (type === "number" || type === "boolean") return String(val);
745
+ if (type === "undefined") return "undefined";
746
+ if (type === "symbol") {
747
+ const desc = val.description ?? "";
748
+ return `Symbol(${JSON.stringify(desc)})`;
749
+ }
750
+ if (type === "function") return val.toString();
751
+ if (val instanceof Date) return `new Date(${JSON.stringify(val.toISOString())})`;
752
+ if (val instanceof RegExp) return `new RegExp(${JSON.stringify(val.source)}, ${JSON.stringify(val.flags)})`;
753
+ if (type === "object") {
754
+ if (seenObjects.has(val)) return `"__circular__"`;
755
+ seenObjects.add(val);
756
+ }
757
+ if (Array.isArray(val)) return `[${val.map(valueToCode).join(", ")}]`;
758
+ if (val instanceof Map) return `new Map([${Array.from(val.entries()).map(([k, v]) => `[${valueToCode(k)}, ${valueToCode(v)}]`).join(", ")}])`;
759
+ if (val instanceof Set) return `new Set([${Array.from(val.values()).map(valueToCode).join(", ")}])`;
760
+ if (type === "object") {
761
+ const properties = [];
762
+ for (const key in val) if (Object.prototype.hasOwnProperty.call(val, key)) properties.push(`${JSON.stringify(key)}: ${valueToCode(val[key])}`);
763
+ return `{${properties.join(", ")}}`;
764
+ }
765
+ return JSON.stringify(String(val));
766
+ }
767
+ const topLevelProps = [];
768
+ for (const key in options) if (Object.prototype.hasOwnProperty.call(options, key)) topLevelProps.push(`${JSON.stringify(key)}: ${valueToCode(options[key])}`);
769
+ return `{${topLevelProps.join(", ")}}`;
1020
770
  }
1021
771
 
1022
- // Cache root path
1023
- var rootDir;
1024
- function findNodeModulesDir(root) {
1025
- if (root === void 0) {
1026
- root = process.cwd();
1027
- }
1028
- var currentDir = root;
1029
- while (currentDir !== path.parse(currentDir).root) {
1030
- var nodeModulesPath = path.join(currentDir, 'node_modules');
1031
- if (fs.existsSync(nodeModulesPath)) {
1032
- return nodeModulesPath;
1033
- }
1034
- currentDir = path.dirname(currentDir);
1035
- }
1036
- return '';
772
+ //#endregion
773
+ //#region src/utils/VirtualModule.ts
774
+ let rootDir;
775
+ function findNodeModulesDir(root = process.cwd()) {
776
+ let currentDir = root;
777
+ while (currentDir !== (0, pathe.parse)(currentDir).root) {
778
+ const nodeModulesPath = (0, pathe.join)(currentDir, "node_modules");
779
+ if ((0, fs.existsSync)(nodeModulesPath)) return nodeModulesPath;
780
+ currentDir = (0, pathe.dirname)(currentDir);
781
+ }
782
+ return "";
1037
783
  }
1038
- // Cache nodeModulesDir result to avoid repeated calculations
1039
- var cachedNodeModulesDir;
784
+ let cachedNodeModulesDir;
1040
785
  function getNodeModulesDir() {
1041
- if (!cachedNodeModulesDir) {
1042
- cachedNodeModulesDir = findNodeModulesDir(rootDir);
1043
- }
1044
- return cachedNodeModulesDir;
786
+ if (!cachedNodeModulesDir) cachedNodeModulesDir = findNodeModulesDir(rootDir);
787
+ return cachedNodeModulesDir;
1045
788
  }
1046
789
  function getSuffix(name) {
1047
- var base = path.basename(name);
1048
- var dotIndex = base.lastIndexOf('.');
1049
- if (dotIndex > 0 && dotIndex < base.length - 1) {
1050
- return base.slice(dotIndex);
1051
- }
1052
- return '.js';
790
+ const base = (0, pathe.basename)(name);
791
+ const dotIndex = base.lastIndexOf(".");
792
+ if (dotIndex > 0 && dotIndex < base.length - 1) return base.slice(dotIndex);
793
+ return ".js";
1053
794
  }
1054
- var patternMap = {};
1055
- var cacheMap = {};
1056
- /**
1057
- * Physically generate files as virtual modules under node_modules/__mf__virtual/*
1058
- */
1059
- function assertModuleFound(tag, str) {
1060
- if (str === void 0) {
1061
- str = '';
1062
- }
1063
- var module = VirtualModule.findModule(tag, str);
1064
- if (!module) {
1065
- throw new Error("Module Federation shared module '" + str + "' not found. Please ensure it's installed as a dependency in your package.json.");
1066
- }
1067
- return module;
795
+ const patternMap = {};
796
+ const cacheMap = {};
797
+ /**
798
+ * Physically generate files as virtual modules under node_modules/__mf__virtual/*
799
+ */
800
+ function assertModuleFound(tag, str = "") {
801
+ const module = VirtualModule.findModule(tag, str);
802
+ if (!module) throw new Error(`Module Federation shared module '${str}' not found. Please ensure it's installed as a dependency in your package.json.`);
803
+ return module;
1068
804
  }
1069
- var VirtualModule = /*#__PURE__*/function () {
1070
- function VirtualModule(name, tag, suffix) {
1071
- if (tag === void 0) {
1072
- tag = '__mf_v__';
1073
- }
1074
- if (suffix === void 0) {
1075
- suffix = '';
1076
- }
1077
- this.name = void 0;
1078
- this.tag = void 0;
1079
- this.suffix = void 0;
1080
- this.inited = false;
1081
- this.name = name;
1082
- this.tag = tag;
1083
- this.suffix = suffix || getSuffix(name);
1084
- if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
1085
- cacheMap[this.tag][this.name] = this;
1086
- }
1087
- /**
1088
- * Set the root path for finding node_modules
1089
- * @param root - Root path
1090
- */
1091
- VirtualModule.setRoot = function setRoot(root) {
1092
- rootDir = root;
1093
- // Reset cache to ensure using the new root path
1094
- cachedNodeModulesDir = undefined;
1095
- }
1096
- /**
1097
- * Ensure virtual package directory exists
1098
- */;
1099
- VirtualModule.ensureVirtualPackageExists = function ensureVirtualPackageExists() {
1100
- var nodeModulesDir = getNodeModulesDir();
1101
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
1102
- virtualModuleDir = _getNormalizeModuleFe.virtualModuleDir;
1103
- var virtualPackagePath = path.resolve(nodeModulesDir, virtualModuleDir);
1104
- if (!fs.existsSync(virtualPackagePath)) {
1105
- fs.mkdirSync(virtualPackagePath);
1106
- fs.writeFileSync(path.resolve(virtualPackagePath, 'empty.js'), '');
1107
- fs.writeFileSync(path.resolve(virtualPackagePath, 'package.json'), JSON.stringify({
1108
- name: virtualModuleDir,
1109
- main: 'empty.js'
1110
- }));
1111
- }
1112
- };
1113
- VirtualModule.findModule = function findModule(tag, str) {
1114
- if (str === void 0) {
1115
- str = '';
1116
- }
1117
- if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
1118
- var moduleName = (str.match(patternMap[tag]) || [])[2];
1119
- if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
1120
- return undefined;
1121
- };
1122
- var _proto = VirtualModule.prototype;
1123
- _proto.getPath = function getPath() {
1124
- return path.resolve(getNodeModulesDir(), this.getImportId());
1125
- };
1126
- _proto.getImportId = function getImportId() {
1127
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
1128
- mfName = _getNormalizeModuleFe2.name,
1129
- virtualModuleDir = _getNormalizeModuleFe2.virtualModuleDir;
1130
- return virtualModuleDir + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
1131
- };
1132
- _proto.writeSync = function writeSync(code, force) {
1133
- if (!force && this.inited) return;
1134
- if (!this.inited) {
1135
- this.inited = true;
1136
- }
1137
- fs.writeFileSync(this.getPath(), code);
1138
- };
1139
- _proto.write = function write(code) {
1140
- fs.writeFile(this.getPath(), code, function () {});
1141
- };
1142
- return VirtualModule;
1143
- }();
805
+ var VirtualModule = class {
806
+ /**
807
+ * Set the root path for finding node_modules
808
+ * @param root - Root path
809
+ */
810
+ static setRoot(root) {
811
+ rootDir = root;
812
+ cachedNodeModulesDir = void 0;
813
+ }
814
+ /**
815
+ * Ensure virtual package directory exists
816
+ */
817
+ static ensureVirtualPackageExists() {
818
+ const nodeModulesDir = getNodeModulesDir();
819
+ const { virtualModuleDir } = getNormalizeModuleFederationOptions();
820
+ const virtualPackagePath = (0, pathe.resolve)(nodeModulesDir, virtualModuleDir);
821
+ if (!(0, fs.existsSync)(virtualPackagePath)) {
822
+ (0, fs.mkdirSync)(virtualPackagePath);
823
+ (0, fs.writeFileSync)((0, pathe.resolve)(virtualPackagePath, "empty.js"), "");
824
+ (0, fs.writeFileSync)((0, pathe.resolve)(virtualPackagePath, "package.json"), JSON.stringify({
825
+ name: virtualModuleDir,
826
+ main: "empty.js"
827
+ }));
828
+ }
829
+ }
830
+ static findModule(tag, str = "") {
831
+ if (!patternMap[tag]) patternMap[tag] = new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);
832
+ const moduleName = (str.match(patternMap[tag]) || [])[2];
833
+ if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
834
+ }
835
+ constructor(name, tag = "__mf_v__", suffix = "") {
836
+ this.inited = false;
837
+ this.name = name;
838
+ this.tag = tag;
839
+ this.suffix = suffix || getSuffix(name);
840
+ if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
841
+ cacheMap[this.tag][this.name] = this;
842
+ }
843
+ getPath() {
844
+ return (0, pathe.resolve)(getNodeModulesDir(), this.getImportId());
845
+ }
846
+ getImportId() {
847
+ const { name: mfName, virtualModuleDir } = getNormalizeModuleFederationOptions();
848
+ return `${virtualModuleDir}/${packageNameEncode(`${mfName}${this.tag}${this.name}${this.tag}`)}${this.suffix}`;
849
+ }
850
+ writeSync(code, force) {
851
+ if (!force && this.inited) return;
852
+ if (!this.inited) this.inited = true;
853
+ (0, fs.writeFileSync)(this.getPath(), code);
854
+ }
855
+ write(code) {
856
+ (0, fs.writeFile)(this.getPath(), code, function() {});
857
+ }
858
+ };
1144
859
 
1145
- var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
860
+ //#endregion
861
+ //#region src/virtualModules/virtualExposes.ts
862
+ const VIRTUAL_EXPOSES = "virtual:mf-exposes";
1146
863
  function generateExposes() {
1147
- var options = getNormalizeModuleFederationOptions();
1148
- return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
1149
- return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
1150
- }).join(',') + "\n }\n ";
864
+ const options = getNormalizeModuleFederationOptions();
865
+ return `
866
+ export default {
867
+ ${Object.keys(options.exposes).map((key) => {
868
+ return `
869
+ ${JSON.stringify(key)}: async () => {
870
+ const importModule = await import(${JSON.stringify(options.exposes[key].import)})
871
+ const exportModule = {}
872
+ Object.assign(exportModule, importModule)
873
+ Object.defineProperty(exportModule, "__esModule", {
874
+ value: true,
875
+ enumerable: false
876
+ })
877
+ return exportModule
878
+ }
879
+ `;
880
+ }).join(",")}
881
+ }
882
+ `;
1151
883
  }
1152
884
 
1153
- var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
1154
- function writeRuntimeInitStatus() {
1155
- // Use globalThis singleton to ensure only one initPromise exists
1156
- var globalKey = "__mf_init__" + virtualRuntimeInitStatus.getImportId() + "__";
1157
- virtualRuntimeInitStatus.writeSync("\n const globalKey = " + JSON.stringify(globalKey) + "\n if (!globalThis[globalKey]) {\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n globalThis[globalKey] = {\n initPromise,\n initResolve,\n initReject\n }\n }\n module.exports = globalThis[globalKey]\n ");
885
+ //#endregion
886
+ //#region src/virtualModules/virtualRuntimeInitStatus.ts
887
+ const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
888
+ function writeRuntimeInitStatus(command) {
889
+ const globalKey = `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
890
+ const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject } = globalThis[globalKey];
891
+ export { initPromise, initResolve, initReject };` : `module.exports = globalThis[globalKey];`;
892
+ virtualRuntimeInitStatus.writeSync(`
893
+ const globalKey = ${JSON.stringify(globalKey)};
894
+ if (!globalThis[globalKey]) {
895
+ let initResolve, initReject;
896
+ const initPromise = new Promise((re, rj) => {
897
+ initResolve = re;
898
+ initReject = rj;
899
+ });
900
+ globalThis[globalKey] = {
901
+ initPromise,
902
+ initResolve,
903
+ initReject,
904
+ };
905
+ }
906
+ ${exportStatement}
907
+ `);
1158
908
  }
1159
909
 
1160
- var cacheRemoteMap = {};
1161
- var LOAD_REMOTE_TAG = '__loadRemote__';
910
+ //#endregion
911
+ //#region src/virtualModules/virtualRemotes.ts
912
+ const cacheRemoteMap = {};
913
+ const LOAD_REMOTE_TAG = "__loadRemote__";
1162
914
  function getRemoteVirtualModule(remote, command) {
1163
- if (!cacheRemoteMap[remote]) {
1164
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
1165
- cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
1166
- }
1167
- var virtual = cacheRemoteMap[remote];
1168
- return virtual;
915
+ if (!cacheRemoteMap[remote]) {
916
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
917
+ cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
918
+ }
919
+ return cacheRemoteMap[remote];
1169
920
  }
1170
- var usedRemotesMap = {
1171
- // remote1: {remote1/App, remote1, remote1/Button}
1172
- };
921
+ const usedRemotesMap = {};
1173
922
  function addUsedRemote(remoteKey, remoteModule) {
1174
- if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
1175
- usedRemotesMap[remoteKey].add(remoteModule);
923
+ if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = /* @__PURE__ */ new Set();
924
+ usedRemotesMap[remoteKey].add(remoteModule);
1176
925
  }
1177
926
  function getUsedRemotesMap() {
1178
- return usedRemotesMap;
927
+ return usedRemotesMap;
1179
928
  }
1180
929
  function generateRemotes(id, command) {
1181
- return "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
930
+ const isBuild = command === "build";
931
+ const importLine = isBuild ? `import { initPromise } from "${virtualRuntimeInitStatus.getImportId()}"` : `const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")`;
932
+ const awaitOrPlaceholder = isBuild ? "await " : "/*mf top-level-await placeholder replacement mf*/";
933
+ const exportLine = isBuild ? "export default exportModule" : "module.exports = exportModule";
934
+ return `
935
+ ${importLine}
936
+ const res = initPromise.then(runtime => runtime.loadRemote(${JSON.stringify(id)}))
937
+ const exportModule = ${awaitOrPlaceholder}initPromise.then(_ => res)
938
+ ${exportLine}
939
+ `;
1182
940
  }
1183
941
 
1184
- /**
1185
- * Even the resolveId hook cannot interfere with vite pre-build,
1186
- * and adding query parameter virtual modules will also fail.
1187
- * You can only proxy to the real file through alias
1188
- */
1189
- // *** __prebuild__
1190
- var preBuildCacheMap = {};
1191
- var PREBUILD_TAG = '__prebuild__';
942
+ //#endregion
943
+ //#region src/virtualModules/virtualShared_preBuild.ts
944
+ const preBuildCacheMap = {};
945
+ const PREBUILD_TAG = "__prebuild__";
1192
946
  function writePreBuildLibPath(pkg) {
1193
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1194
- preBuildCacheMap[pkg].writeSync('');
947
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
948
+ preBuildCacheMap[pkg].writeSync("");
1195
949
  }
1196
950
  function getPreBuildLibImportId(pkg) {
1197
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1198
- var importId = preBuildCacheMap[pkg].getImportId();
1199
- return importId;
951
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
952
+ return preBuildCacheMap[pkg].getImportId();
1200
953
  }
1201
- // *** __loadShare__
1202
- var LOAD_SHARE_TAG = '__loadShare__';
1203
- var loadShareCacheMap = {};
954
+ const LOAD_SHARE_TAG = "__loadShare__";
955
+ const loadShareCacheMap = {};
1204
956
  function getLoadShareModulePath(pkg) {
1205
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
1206
- var filepath = loadShareCacheMap[pkg].getPath();
1207
- return filepath;
957
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
958
+ return loadShareCacheMap[pkg].getPath();
1208
959
  }
1209
960
  function writeLoadShareModule(pkg, shareItem, command) {
1210
- loadShareCacheMap[pkg].writeSync("\n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== 'build' ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}\n }))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "res.then(factory => factory())\n module.exports = exportModule\n ");
961
+ const isBuild = command === "build";
962
+ const importLine = isBuild ? `import { initPromise } from "${virtualRuntimeInitStatus.getImportId()}"` : `const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")`;
963
+ const awaitOrPlaceholder = isBuild ? "await " : "/*mf top-level-await placeholder replacement mf*/";
964
+ const exportLine = isBuild ? "export default exportModule" : "module.exports = exportModule";
965
+ loadShareCacheMap[pkg].writeSync(`
966
+ ;() => import(${JSON.stringify(getPreBuildLibImportId(pkg))}).catch(() => {});
967
+ ${command !== "build" ? `;() => import(${JSON.stringify(pkg)}).catch(() => {});` : ""}
968
+ ${importLine}
969
+ const res = initPromise.then(runtime => runtime.loadShare(${JSON.stringify(pkg)}, {
970
+ customShareInfo: {shareConfig:{
971
+ singleton: ${shareItem.shareConfig.singleton},
972
+ strictVersion: ${shareItem.shareConfig.strictVersion},
973
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)}
974
+ }}
975
+ }))
976
+ const exportModule = ${awaitOrPlaceholder}res.then(factory => factory())
977
+ ${exportLine}
978
+ `);
1211
979
  }
1212
980
 
1213
- var usedShares = new Set();
981
+ //#endregion
982
+ //#region src/virtualModules/virtualRemoteEntry.ts
983
+ let usedShares = /* @__PURE__ */ new Set();
1214
984
  function getUsedShares() {
1215
- return usedShares;
985
+ return usedShares;
1216
986
  }
1217
987
  function addUsedShares(pkg) {
1218
- usedShares.add(pkg);
988
+ usedShares.add(pkg);
1219
989
  }
1220
- // *** Expose locally provided shared modules here
1221
- new VirtualModule('localSharedImportMap');
990
+ new VirtualModule("localSharedImportMap");
1222
991
  function getLocalSharedImportMapPath() {
1223
- return getLocalSharedImportMapPath_temp();
1224
- // return localSharedImportMapModule.getPath()
992
+ return getLocalSharedImportMapPath_temp();
1225
993
  }
1226
- var prevSharedCount;
994
+ let prevSharedCount;
1227
995
  function writeLocalSharedImportMap() {
1228
- var sharedCount = getUsedShares().size;
1229
- if (prevSharedCount !== sharedCount) {
1230
- prevSharedCount = sharedCount;
1231
- writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1232
- // localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true)
1233
- }
996
+ const sharedCount = getUsedShares().size;
997
+ if (prevSharedCount !== sharedCount) {
998
+ prevSharedCount = sharedCount;
999
+ writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1000
+ }
1234
1001
  }
1235
1002
  function generateLocalSharedImportMap() {
1236
- var options = getNormalizeModuleFederationOptions();
1237
- return "\n import {loadShare} from \"@module-federation/runtime\";\n const importMap = {\n " + Array.from(getUsedShares()).sort().map(function (pkg) {
1238
- var shareItem = getNormalizeShareItem(pkg);
1239
- return "\n " + JSON.stringify(pkg) + ": async () => {\n " + ((shareItem == null ? void 0 : shareItem.shareConfig["import"]) === false ? "throw new Error(`Shared module '${" + JSON.stringify(pkg) + "}' must be provided by host`);" : "let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\");\n return pkg;") + "\n }\n ";
1240
- }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).sort().map(function (key) {
1241
- var shareItem = getNormalizeShareItem(key);
1242
- if (!shareItem) return null;
1243
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n if (" + (shareItem.shareConfig["import"] === false) + ") {\n throw new Error(`Shared module '${" + JSON.stringify(key) + "}' must be provided by host`);\n }\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap\n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + ",\n " + (shareItem.shareConfig["import"] === false ? 'import: false,' : '') + "\n }\n }\n ";
1244
- }).filter(function (x) {
1245
- return x !== null;
1246
- }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
1247
- var _JSON$stringify;
1248
- var remote = options.remotes[key];
1249
- if (!remote) return null;
1250
- return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n shareScope: " + ((_JSON$stringify = JSON.stringify(remote.shareScope)) != null ? _JSON$stringify : 'default') + ",\n }\n ";
1251
- }).filter(function (x) {
1252
- return x !== null;
1253
- }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
1003
+ const options = getNormalizeModuleFederationOptions();
1004
+ return `
1005
+ import {loadShare} from "@module-federation/runtime";
1006
+ const importMap = {
1007
+ ${Array.from(getUsedShares()).sort().map((pkg) => {
1008
+ const shareItem = getNormalizeShareItem(pkg);
1009
+ return `
1010
+ ${JSON.stringify(pkg)}: async () => {
1011
+ ${shareItem?.shareConfig.import === false ? `throw new Error(\`Shared module '\${${JSON.stringify(pkg)}}' must be provided by host\`);` : `let pkg = await import("${getPreBuildLibImportId(pkg)}");
1012
+ return pkg;`}
1013
+ }
1014
+ `;
1015
+ }).join(",")}
1016
+ }
1017
+ const usedShared = {
1018
+ ${Array.from(getUsedShares()).sort().map((key) => {
1019
+ const shareItem = getNormalizeShareItem(key);
1020
+ if (!shareItem) return null;
1021
+ return `
1022
+ ${JSON.stringify(key)}: {
1023
+ name: ${JSON.stringify(key)},
1024
+ version: ${JSON.stringify(shareItem.version)},
1025
+ scope: [${JSON.stringify(shareItem.scope)}],
1026
+ loaded: false,
1027
+ from: ${JSON.stringify(options.name)},
1028
+ async get () {
1029
+ if (${shareItem.shareConfig.import === false}) {
1030
+ throw new Error(\`Shared module '\${${JSON.stringify(key)}}' must be provided by host\`);
1031
+ }
1032
+ usedShared[${JSON.stringify(key)}].loaded = true
1033
+ const {${JSON.stringify(key)}: pkgDynamicImport} = importMap
1034
+ const res = await pkgDynamicImport()
1035
+ const exportModule = {...res}
1036
+ // All npm packages pre-built by vite will be converted to esm
1037
+ Object.defineProperty(exportModule, "__esModule", {
1038
+ value: true,
1039
+ enumerable: false
1040
+ })
1041
+ return function () {
1042
+ return exportModule
1043
+ }
1044
+ },
1045
+ shareConfig: {
1046
+ singleton: ${shareItem.shareConfig.singleton},
1047
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)},
1048
+ ${shareItem.shareConfig.import === false ? "import: false," : ""}
1049
+ }
1050
+ }
1051
+ `;
1052
+ }).filter((x) => x !== null).join(",")}
1053
+ }
1054
+ const usedRemotes = [${Object.keys(getUsedRemotesMap()).map((key) => {
1055
+ const remote = options.remotes[key];
1056
+ if (!remote) return null;
1057
+ return `
1058
+ {
1059
+ entryGlobalName: ${JSON.stringify(remote.entryGlobalName)},
1060
+ name: ${JSON.stringify(remote.name)},
1061
+ type: ${JSON.stringify(remote.type)},
1062
+ entry: ${JSON.stringify(remote.entry)},
1063
+ shareScope: ${JSON.stringify(remote.shareScope) ?? "default"},
1064
+ }
1065
+ `;
1066
+ }).filter((x) => x !== null).join(",")}
1067
+ ]
1068
+ export {
1069
+ usedShared,
1070
+ usedRemotes
1071
+ }
1072
+ `;
1254
1073
  }
1255
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1074
+ const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
1256
1075
  function generateRemoteEntry(options) {
1257
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1258
- if (typeof p === 'string') {
1259
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1260
- } else {
1261
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1076
+ const pluginImportNames = options.runtimePlugins.map((p, i) => {
1077
+ if (typeof p === "string") return [
1078
+ `$runtimePlugin_${i}`,
1079
+ `import $runtimePlugin_${i} from "${p}";`,
1080
+ `undefined`
1081
+ ];
1082
+ else return [
1083
+ `$runtimePlugin_${i}`,
1084
+ `import $runtimePlugin_${i} from "${p[0]}";`,
1085
+ serializeRuntimeOptions(p[1])
1086
+ ];
1087
+ });
1088
+ return `
1089
+ import {init as runtimeInit, loadRemote} from "@module-federation/runtime";
1090
+ ${pluginImportNames.map((item) => item[1]).join("\n")}
1091
+ import exposesMap from "${VIRTUAL_EXPOSES}"
1092
+ import {usedShared, usedRemotes} from "${getLocalSharedImportMapPath()}"
1093
+ import {
1094
+ initResolve
1095
+ } from "${virtualRuntimeInitStatus.getImportId()}"
1096
+ const initTokens = {}
1097
+ const shareScopeName = ${JSON.stringify(options.shareScope)}
1098
+ const mfName = ${JSON.stringify(options.name)}
1099
+ async function init(shared = {}, initScope = []) {
1100
+ const initRes = runtimeInit({
1101
+ name: mfName,
1102
+ remotes: usedRemotes,
1103
+ shared: usedShared,
1104
+ plugins: [${pluginImportNames.map((item) => `${item[0]}(${item[2]})`).join(", ")}],
1105
+ ${options.shareStrategy ? `shareStrategy: '${options.shareStrategy}'` : ""}
1106
+ });
1107
+ // handling circular init calls
1108
+ var initToken = initTokens[shareScopeName];
1109
+ if (!initToken)
1110
+ initToken = initTokens[shareScopeName] = { from: mfName };
1111
+ if (initScope.indexOf(initToken) >= 0) return;
1112
+ initScope.push(initToken);
1113
+ initRes.initShareScopeMap('${options.shareScope}', shared);
1114
+ try {
1115
+ await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1116
+ strategy: '${options.shareStrategy}',
1117
+ from: "build",
1118
+ initScope
1119
+ }));
1120
+ } catch (e) {
1121
+ console.error(e)
1262
1122
  }
1263
- });
1264
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1265
- return item[1];
1266
- }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
1267
- return item[0] + "(" + item[2] + ")";
1268
- }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
1123
+ initResolve(initRes)
1124
+ return initRes
1125
+ }
1126
+
1127
+ function getExposes(moduleName) {
1128
+ if (!(moduleName in exposesMap)) throw new Error(\`Module \${moduleName} does not exist in container.\`)
1129
+ return (exposesMap[moduleName])().then(res => () => res)
1130
+ }
1131
+ export {
1132
+ init,
1133
+ getExposes as get
1134
+ }
1135
+ `;
1269
1136
  }
1270
- /**
1271
- * Inject entry file, automatically init when used as host,
1272
- * and will not inject remoteEntry
1273
- */
1274
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
1275
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1137
+ /**
1138
+ * Inject entry file, automatically init when used as host,
1139
+ * and will not inject remoteEntry
1140
+ */
1141
+ const HOST_AUTO_INIT_TAG = "__H_A_I__";
1142
+ const hostAutoInitModule = new VirtualModule("hostAutoInit", HOST_AUTO_INIT_TAG);
1276
1143
  function writeHostAutoInit() {
1277
- hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1144
+ hostAutoInitModule.writeSync(`
1145
+ const remoteEntryPromise = import("${REMOTE_ENTRY_ID}")
1146
+ // __tla only serves as a hack for vite-plugin-top-level-await.
1147
+ Promise.resolve(remoteEntryPromise)
1148
+ .then(remoteEntry => {
1149
+ return Promise.resolve(remoteEntry.__tla)
1150
+ .then(remoteEntry.init).catch(remoteEntry.init)
1151
+ })
1152
+ `);
1278
1153
  }
1279
1154
  function getHostAutoInitImportId() {
1280
- return hostAutoInitModule.getImportId();
1155
+ return hostAutoInitModule.getImportId();
1281
1156
  }
1282
1157
  function getHostAutoInitPath() {
1283
- return hostAutoInitModule.getPath();
1158
+ return hostAutoInitModule.getPath();
1284
1159
  }
1285
1160
 
1286
- function initVirtualModules() {
1287
- writeLocalSharedImportMap();
1288
- writeHostAutoInit();
1289
- writeRuntimeInitStatus();
1161
+ //#endregion
1162
+ //#region src/virtualModules/index.ts
1163
+ function initVirtualModules(command) {
1164
+ writeLocalSharedImportMap();
1165
+ writeHostAutoInit();
1166
+ writeRuntimeInitStatus(command);
1290
1167
  }
1291
1168
 
1292
- var ASSET_TYPES = ['js', 'css'];
1293
- var LOAD_TIMINGS = ['sync', 'async'];
1294
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1295
- /**
1296
- * Creates an empty asset map structure for tracking JS and CSS assets
1297
- * @returns Initialized asset map with sync/async arrays for JS and CSS
1298
- */
1299
- var createEmptyAssetMap = function createEmptyAssetMap() {
1300
- return {
1301
- js: {
1302
- sync: [],
1303
- async: []
1304
- },
1305
- css: {
1306
- sync: [],
1307
- async: []
1308
- }
1309
- };
1169
+ //#endregion
1170
+ //#region src/utils/bundleHelpers.ts
1171
+ function findRemoteEntryFile(filename, bundle) {
1172
+ for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
1173
+ }
1174
+
1175
+ //#endregion
1176
+ //#region src/utils/cssModuleHelpers.ts
1177
+ const ASSET_TYPES = ["js", "css"];
1178
+ const LOAD_TIMINGS = ["sync", "async"];
1179
+ const JS_EXTENSIONS = [
1180
+ ".ts",
1181
+ ".tsx",
1182
+ ".jsx",
1183
+ ".mjs",
1184
+ ".cjs"
1185
+ ];
1186
+ /**
1187
+ * Creates an empty asset map structure for tracking JS and CSS assets
1188
+ * @returns Initialized asset map with sync/async arrays for JS and CSS
1189
+ */
1190
+ const createEmptyAssetMap = () => ({
1191
+ js: {
1192
+ sync: [],
1193
+ async: []
1194
+ },
1195
+ css: {
1196
+ sync: [],
1197
+ async: []
1198
+ }
1199
+ });
1200
+ /**
1201
+ * Tracks an asset in the preload map with deduplication
1202
+ * @param map - The preload map to update
1203
+ * @param key - The module key to track under
1204
+ * @param fileName - The asset filename to track
1205
+ * @param isAsync - Whether the asset is loaded async
1206
+ * @param type - The asset type ('js' or 'css')
1207
+ */
1208
+ const trackAsset = (map, key, fileName, isAsync, type) => {
1209
+ if (!map[key]) map[key] = createEmptyAssetMap();
1210
+ const target = isAsync ? map[key][type].async : map[key][type].sync;
1211
+ if (!target.includes(fileName)) target.push(fileName);
1310
1212
  };
1311
- /**
1312
- * Tracks an asset in the preload map with deduplication
1313
- * @param map - The preload map to update
1314
- * @param key - The module key to track under
1315
- * @param fileName - The asset filename to track
1316
- * @param isAsync - Whether the asset is loaded async
1317
- * @param type - The asset type ('js' or 'css')
1318
- */
1319
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1320
- if (!map[key]) {
1321
- map[key] = createEmptyAssetMap();
1322
- }
1323
- var target = isAsync ? map[key][type].async : map[key][type].sync;
1324
- if (!target.includes(fileName)) {
1325
- target.push(fileName);
1326
- }
1213
+ /**
1214
+ * Checks if a file is a CSS file by extension
1215
+ * @param fileName - The filename to check
1216
+ * @returns True if file has a CSS extension (.css, .scss, .less)
1217
+ */
1218
+ const isCSSFile = (fileName) => {
1219
+ return fileName.endsWith(".css") || fileName.endsWith(".scss") || fileName.endsWith(".less");
1327
1220
  };
1328
- /**
1329
- * Checks if a file is a CSS file by extension
1330
- * @param fileName - The filename to check
1331
- * @returns True if file has a CSS extension (.css, .scss, .less)
1332
- */
1333
- var isCSSFile = function isCSSFile(fileName) {
1334
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1221
+ /**
1222
+ * Collects all CSS assets from the bundle
1223
+ * @param bundle - The Rollup output bundle
1224
+ * @returns Set of CSS asset filenames
1225
+ */
1226
+ const collectCssAssets = (bundle) => {
1227
+ const cssAssets = /* @__PURE__ */ new Set();
1228
+ for (const [fileName, fileData] of Object.entries(bundle)) if (fileData.type === "asset" && isCSSFile(fileName)) cssAssets.add(fileName);
1229
+ return cssAssets;
1335
1230
  };
1336
- /**
1337
- * Collects all CSS assets from the bundle
1338
- * @param bundle - The Rollup output bundle
1339
- * @returns Set of CSS asset filenames
1340
- */
1341
- var collectCssAssets = function collectCssAssets(bundle) {
1342
- var cssAssets = new Set();
1343
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1344
- var _Object$entries$_i = _Object$entries[_i],
1345
- fileName = _Object$entries$_i[0],
1346
- fileData = _Object$entries$_i[1];
1347
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
1348
- cssAssets.add(fileName);
1349
- }
1350
- }
1351
- return cssAssets;
1231
+ /**
1232
+ * Checks if a chunk contains CSS modules (e.g. .css, .vanilla.css, .scss, .less)
1233
+ * by scanning its module list
1234
+ */
1235
+ const chunkContainsCssModules = (modules) => {
1236
+ for (const modulePath of Object.keys(modules)) if (isCSSFile(modulePath)) return true;
1237
+ return false;
1352
1238
  };
1353
- /**
1354
- * Processes module assets and tracks them in the files map
1355
- * @param bundle - The Rollup output bundle
1356
- * @param filesMap - The preload map to populate
1357
- * @param moduleMatcher - Function that matches module paths to keys
1358
- */
1359
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1360
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1361
- var _Object$entries2$_i = _Object$entries2[_i2],
1362
- fileName = _Object$entries2$_i[0],
1363
- fileData = _Object$entries2$_i[1];
1364
- if (fileData.type !== 'chunk') continue;
1365
- if (!fileData.modules) continue;
1366
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1367
- var modulePath = _Object$keys[_i3];
1368
- var matchKey = moduleMatcher(modulePath);
1369
- if (!matchKey) continue;
1370
- // Track main JS chunk
1371
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1372
- // Handle dynamic imports
1373
- if (fileData.dynamicImports) {
1374
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1375
- var dynamicImport = _step.value;
1376
- var importData = bundle[dynamicImport];
1377
- if (!importData) continue;
1378
- var isCss = isCSSFile(dynamicImport);
1379
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1380
- }
1381
- }
1382
- }
1383
- }
1239
+ /**
1240
+ * Processes module assets and tracks them in the files map
1241
+ * @param bundle - The Rollup output bundle
1242
+ * @param filesMap - The preload map to populate
1243
+ * @param moduleMatcher - Function that matches module paths to keys
1244
+ */
1245
+ const processModuleAssets = (bundle, filesMap, moduleMatcher) => {
1246
+ const bundleCssAssets = collectCssAssets(bundle);
1247
+ for (const [fileName, fileData] of Object.entries(bundle)) {
1248
+ if (fileData.type !== "chunk") continue;
1249
+ if (!fileData.modules) continue;
1250
+ for (const modulePath of Object.keys(fileData.modules)) {
1251
+ const matchKey = moduleMatcher(modulePath);
1252
+ if (!matchKey) continue;
1253
+ trackAsset(filesMap, matchKey, fileName, false, "js");
1254
+ let foundCssViaMetadata = false;
1255
+ if (fileData.viteMetadata?.importedCss?.size) for (const cssFile of fileData.viteMetadata.importedCss) {
1256
+ trackAsset(filesMap, matchKey, cssFile, false, "css");
1257
+ foundCssViaMetadata = true;
1258
+ }
1259
+ if (!foundCssViaMetadata && chunkContainsCssModules(fileData.modules)) for (const cssAsset of bundleCssAssets) trackAsset(filesMap, matchKey, cssAsset, false, "css");
1260
+ if (fileData.dynamicImports) for (const dynamicImport of fileData.dynamicImports) {
1261
+ if (!bundle[dynamicImport]) continue;
1262
+ trackAsset(filesMap, matchKey, dynamicImport, true, isCSSFile(dynamicImport) ? "css" : "js");
1263
+ }
1264
+ }
1265
+ }
1384
1266
  };
1385
- /**
1386
- * Deduplicates assets in the files map
1387
- * @param filesMap - The preload map to deduplicate
1388
- * @returns New deduplicated preload map
1389
- */
1390
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1391
- var result = {};
1392
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1393
- var _Object$entries3$_i = _Object$entries3[_i4],
1394
- key = _Object$entries3$_i[0],
1395
- assetMaps = _Object$entries3$_i[1];
1396
- result[key] = createEmptyAssetMap();
1397
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1398
- var type = _ASSET_TYPES[_i5];
1399
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1400
- var timing = _LOAD_TIMINGS[_i6];
1401
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1402
- }
1403
- }
1404
- }
1405
- return result;
1267
+ /**
1268
+ * Deduplicates assets in the files map
1269
+ * @param filesMap - The preload map to deduplicate
1270
+ * @returns New deduplicated preload map
1271
+ */
1272
+ const deduplicateAssets = (filesMap) => {
1273
+ const result = {};
1274
+ for (const [key, assetMaps] of Object.entries(filesMap)) {
1275
+ result[key] = createEmptyAssetMap();
1276
+ for (const type of ASSET_TYPES) for (const timing of LOAD_TIMINGS) result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1277
+ }
1278
+ return result;
1406
1279
  };
1407
- /**
1408
- * Builds a mapping between module files and their share keys
1409
- * @param shareKeys - Set of share keys to map
1410
- * @param resolveFn - Function to resolve module paths
1411
- * @returns Map of file paths to their corresponding share keys
1412
- */
1413
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1414
- try {
1415
- var fileToShareKey = new Map();
1416
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1417
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1418
- var _resolution$id;
1419
- return {
1420
- shareKey: shareKey,
1421
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1422
- };
1423
- })["catch"](function () {
1424
- return null;
1425
- });
1426
- }))).then(function (resolutions) {
1427
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1428
- var resolution = _step2.value;
1429
- if (resolution != null && resolution.file) {
1430
- fileToShareKey.set(resolution.file, resolution.shareKey);
1431
- }
1432
- }
1433
- return fileToShareKey;
1434
- });
1435
- } catch (e) {
1436
- return Promise.reject(e);
1437
- }
1280
+ /**
1281
+ * Builds a mapping between module files and their share keys
1282
+ * @param shareKeys - Set of share keys to map
1283
+ * @param resolveFn - Function to resolve module paths
1284
+ * @returns Map of file paths to their corresponding share keys
1285
+ */
1286
+ const buildFileToShareKeyMap = async (shareKeys, resolveFn) => {
1287
+ const fileToShareKey = /* @__PURE__ */ new Map();
1288
+ const resolutions = await Promise.all(Array.from(shareKeys).map((shareKey) => resolveFn(getPreBuildLibImportId(shareKey)).then((resolution) => ({
1289
+ shareKey,
1290
+ file: resolution?.id?.split("?")[0]
1291
+ })).catch(() => null)));
1292
+ for (const resolution of resolutions) if (resolution?.file) fileToShareKey.set(resolution.file, resolution.shareKey);
1293
+ return fileToShareKey;
1438
1294
  };
1439
1295
 
1440
- /**
1441
- * Resolves the public path for remote entries
1442
- * @param options - Module Federation options
1443
- * @param viteBase - Vite's base config value
1444
- * @param originalBase - Original base config before any transformations
1445
- * @returns The resolved public path
1446
- */
1296
+ //#endregion
1297
+ //#region src/utils/publicPath.ts
1298
+ /**
1299
+ * Resolves the public path for remote entries
1300
+ * @param options - Module Federation options
1301
+ * @param viteBase - Vite's base config value
1302
+ * @param originalBase - Original base config before any transformations
1303
+ * @returns The resolved public path
1304
+ */
1447
1305
  function resolvePublicPath(options, viteBase, originalBase) {
1448
- // Use explicitly set publicPath if provided
1449
- if (options.publicPath) {
1450
- return options.publicPath;
1451
- }
1452
- // Handle empty original base case
1453
- if (originalBase === '') {
1454
- return 'auto';
1455
- }
1456
- // Use viteBase if available, ensuring it ends with a slash
1457
- if (viteBase) {
1458
- return viteBase.replace(/\/?$/, '/');
1459
- }
1460
- // Fallback to auto if no base is specified
1461
- return 'auto';
1306
+ if (options.publicPath) return options.publicPath;
1307
+ if (originalBase === "") return "auto";
1308
+ if (viteBase) return viteBase.replace(/\/?$/, "/");
1309
+ return "auto";
1462
1310
  }
1463
1311
 
1464
- var Manifest = function Manifest() {
1465
- var mfOptions = getNormalizeModuleFederationOptions();
1466
- var name = mfOptions.name,
1467
- filename = mfOptions.filename,
1468
- getPublicPath = mfOptions.getPublicPath,
1469
- manifestOptions = mfOptions.manifest;
1470
- var mfManifestName = '';
1471
- if (manifestOptions === true) {
1472
- mfManifestName = 'mf-manifest.json';
1473
- }
1474
- if (typeof manifestOptions !== 'boolean') {
1475
- mfManifestName = path__namespace.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1476
- }
1477
- var root;
1478
- var remoteEntryFile;
1479
- var publicPath;
1480
- var _command;
1481
- var _originalConfigBase;
1482
- var viteConfig;
1483
- /**
1484
- * Adds global CSS assets to all module exports
1485
- * @param filesMap - The preload map to update
1486
- * @param cssAssets - Set of CSS asset filenames to add
1487
- */
1488
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1489
- Object.keys(filesMap).forEach(function (key) {
1490
- cssAssets.forEach(function (cssAsset) {
1491
- trackAsset(filesMap, key, cssAsset, false, 'css');
1492
- });
1493
- });
1494
- };
1495
- return [{
1496
- name: 'module-federation-manifest',
1497
- apply: 'serve',
1498
- /**
1499
- * Stores resolved Vite config for later use
1500
- */
1501
- /**
1502
- * Finalizes configuration after all plugins are resolved
1503
- * @param config - Fully resolved Vite config
1504
- */
1505
- configResolved: function configResolved(config) {
1506
- viteConfig = config;
1507
- },
1508
- /**
1509
- * Configures dev server middleware to handle manifest requests
1510
- * @param server - Vite dev server instance
1511
- */
1512
- configureServer: function configureServer(server) {
1513
- server.middlewares.use(function (req, res, next) {
1514
- var _req$url;
1515
- if (!mfManifestName) {
1516
- next();
1517
- return;
1518
- }
1519
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1520
- res.setHeader('Content-Type', 'application/json');
1521
- res.setHeader('Access-Control-Allow-Origin', '*');
1522
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1523
- id: name,
1524
- name: name,
1525
- metaData: {
1526
- name: name,
1527
- type: 'app',
1528
- buildInfo: {
1529
- buildVersion: '1.0.0',
1530
- buildName: name
1531
- },
1532
- remoteEntry: {
1533
- name: filename,
1534
- path: '',
1535
- type: 'module'
1536
- },
1537
- ssrRemoteEntry: {
1538
- name: filename,
1539
- path: '',
1540
- type: 'module'
1541
- },
1542
- types: {
1543
- path: '',
1544
- name: ''
1545
- },
1546
- globalName: name,
1547
- pluginVersion: '0.2.5',
1548
- publicPath: publicPath
1549
- }
1550
- })));
1551
- } else {
1552
- next();
1553
- }
1554
- });
1555
- }
1556
- }, {
1557
- name: 'module-federation-manifest',
1558
- enforce: 'post',
1559
- /**
1560
- * Initial plugin configuration
1561
- * @param config - Vite config object
1562
- * @param command - Current Vite command (serve/build)
1563
- */
1564
- config: function config(_config, _ref) {
1565
- var command = _ref.command;
1566
- if (!_config.build) _config.build = {};
1567
- if (!_config.build.manifest) {
1568
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1569
- }
1570
- _command = command;
1571
- _originalConfigBase = _config.base;
1572
- },
1573
- configResolved: function configResolved(config) {
1574
- root = config.root;
1575
- var base = config.base;
1576
- if (_command === 'serve') {
1577
- base = (config.server.origin || '') + config.base;
1578
- }
1579
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1580
- },
1581
- /**
1582
- * Generates the module federation manifest file
1583
- * @param options - Rollup output options
1584
- * @param bundle - Generated bundle assets
1585
- */
1586
- generateBundle: function generateBundle(options, bundle) {
1587
- try {
1588
- var _this = this;
1589
- if (!mfManifestName) return Promise.resolve();
1590
- var filesMap = {};
1591
- // First pass: Find remoteEntry file
1592
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1593
- var _Object$entries$_i = _Object$entries[_i],
1594
- _ = _Object$entries$_i[0],
1595
- fileData = _Object$entries$_i[1];
1596
- if (mfOptions.filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1597
- remoteEntryFile = fileData.fileName;
1598
- break; // We can break early since we only need to find remoteEntry once
1599
- }
1600
- }
1601
- // Second pass: Collect all CSS assets
1602
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1603
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1604
- return mfOptions.exposes[item]["import"];
1605
- });
1606
- // Process exposed modules
1607
- processModuleAssets(bundle, filesMap, function (modulePath) {
1608
- var absoluteModulePath = path__namespace.resolve(root, modulePath);
1609
- return exposesModules.find(function (exposeModule) {
1610
- var exposePath = path__namespace.resolve(root, exposeModule);
1611
- // First try exact path match
1612
- if (absoluteModulePath === exposePath) {
1613
- return true;
1614
- }
1615
- // Then try path match without known extensions
1616
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1617
- var ext = path__namespace.extname(filePath);
1618
- return JS_EXTENSIONS.includes(ext) ? path__namespace.join(path__namespace.dirname(filePath), path__namespace.basename(filePath, ext)) : filePath;
1619
- };
1620
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1621
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1622
- return modulePathNoExt === exposePathNoExt;
1623
- });
1624
- });
1625
- // Process shared modules
1626
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1627
- processModuleAssets(bundle, filesMap, function (modulePath) {
1628
- return fileToShareKey.get(modulePath);
1629
- });
1630
- // Add all CSS assets to every export if bundleAllCSS is enabled
1631
- if (mfOptions.bundleAllCSS) {
1632
- addCssAssetsToAllExports(filesMap, allCssAssets);
1633
- }
1634
- // Final deduplication of all assets
1635
- filesMap = deduplicateAssets(filesMap);
1636
- _this.emitFile({
1637
- type: 'asset',
1638
- fileName: mfManifestName,
1639
- source: JSON.stringify(generateMFManifest(filesMap))
1640
- });
1641
- });
1642
- } catch (e) {
1643
- return Promise.reject(e);
1644
- }
1645
- }
1646
- }];
1647
- /**
1648
- * Generates the final manifest JSON structure
1649
- * @param preloadMap - Map of module assets to include
1650
- * @returns Complete manifest object
1651
- */
1652
- function generateMFManifest(preloadMap) {
1653
- var options = getNormalizeModuleFederationOptions();
1654
- var name = options.name;
1655
- var remoteEntry = {
1656
- name: remoteEntryFile,
1657
- path: '',
1658
- type: 'module'
1659
- };
1660
- // Process remotes
1661
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1662
- var remoteKey = _ref2[0],
1663
- modules = _ref2[1];
1664
- return Array.from(modules).map(function (moduleKey) {
1665
- return {
1666
- federationContainerName: options.remotes[remoteKey].entry,
1667
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1668
- alias: remoteKey,
1669
- entry: '*'
1670
- };
1671
- });
1672
- });
1673
- // Process shared dependencies
1674
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1675
- var shareItem = getNormalizeShareItem(shareKey);
1676
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1677
- return {
1678
- id: name + ":" + shareKey,
1679
- name: shareKey,
1680
- version: shareItem.version,
1681
- requiredVersion: shareItem.shareConfig.requiredVersion,
1682
- assets: {
1683
- js: {
1684
- async: assets.js.async,
1685
- sync: assets.js.sync
1686
- },
1687
- css: {
1688
- async: assets.css.async,
1689
- sync: assets.css.sync
1690
- }
1691
- }
1692
- };
1693
- }).filter(Boolean);
1694
- // Process exposed modules
1695
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1696
- var key = _ref3[0],
1697
- value = _ref3[1];
1698
- var formatKey = key.replace('./', '');
1699
- var sourceFile = value["import"];
1700
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1701
- return {
1702
- id: name + ":" + formatKey,
1703
- name: formatKey,
1704
- assets: {
1705
- js: {
1706
- async: assets.js.async,
1707
- sync: assets.js.sync
1708
- },
1709
- css: {
1710
- async: assets.css.async,
1711
- sync: assets.css.sync
1712
- }
1713
- },
1714
- path: key
1715
- };
1716
- }).filter(Boolean);
1717
- return {
1718
- id: name,
1719
- name: name,
1720
- metaData: _extends({
1721
- name: name,
1722
- type: 'app',
1723
- buildInfo: {
1724
- buildVersion: '1.0.0',
1725
- buildName: name
1726
- },
1727
- remoteEntry: remoteEntry,
1728
- ssrRemoteEntry: remoteEntry,
1729
- types: {
1730
- path: '',
1731
- name: ''
1732
- },
1733
- globalName: name,
1734
- pluginVersion: '0.2.5'
1735
- }, !!getPublicPath ? {
1736
- getPublicPath: getPublicPath
1737
- } : {
1738
- publicPath: publicPath
1739
- }),
1740
- shared: shared,
1741
- remotes: remotes,
1742
- exposes: exposes
1743
- };
1744
- }
1312
+ //#endregion
1313
+ //#region src/plugins/pluginMFManifest.ts
1314
+ const Manifest = () => {
1315
+ const mfOptions = getNormalizeModuleFederationOptions();
1316
+ const { name, filename, getPublicPath, manifest: manifestOptions, varFilename } = mfOptions;
1317
+ let mfManifestName = "";
1318
+ if (manifestOptions === true) mfManifestName = "mf-manifest.json";
1319
+ if (typeof manifestOptions !== "boolean") mfManifestName = pathe.join(manifestOptions?.filePath || "", manifestOptions?.fileName || "");
1320
+ let root;
1321
+ let remoteEntryFile;
1322
+ let publicPath;
1323
+ let _command;
1324
+ let _originalConfigBase;
1325
+ let viteConfig;
1326
+ /**
1327
+ * Adds global CSS assets to all module exports
1328
+ * @param filesMap - The preload map to update
1329
+ * @param cssAssets - Set of CSS asset filenames to add
1330
+ */
1331
+ const addCssAssetsToAllExports = (filesMap, cssAssets) => {
1332
+ Object.keys(filesMap).forEach((key) => {
1333
+ cssAssets.forEach((cssAsset) => {
1334
+ trackAsset(filesMap, key, cssAsset, false, "css");
1335
+ });
1336
+ });
1337
+ };
1338
+ return [{
1339
+ name: "module-federation-manifest",
1340
+ apply: "serve",
1341
+ configResolved(config) {
1342
+ viteConfig = config;
1343
+ },
1344
+ configureServer(server) {
1345
+ server.middlewares.use((req, res, next) => {
1346
+ if (!mfManifestName) {
1347
+ next();
1348
+ return;
1349
+ }
1350
+ if (req.url?.replace(/\?.*/, "") === (viteConfig.base + mfManifestName).replace(/^\/?/, "/")) {
1351
+ res.setHeader("Content-Type", "application/json");
1352
+ res.setHeader("Access-Control-Allow-Origin", "*");
1353
+ res.end(JSON.stringify({
1354
+ ...generateMFManifest({}),
1355
+ id: name,
1356
+ name,
1357
+ metaData: {
1358
+ name,
1359
+ type: "app",
1360
+ buildInfo: {
1361
+ buildVersion: "1.0.0",
1362
+ buildName: name
1363
+ },
1364
+ remoteEntry: {
1365
+ name: filename,
1366
+ path: "",
1367
+ type: "module"
1368
+ },
1369
+ ssrRemoteEntry: {
1370
+ name: filename,
1371
+ path: "",
1372
+ type: "module"
1373
+ },
1374
+ varRemoteEntry: varFilename ? {
1375
+ name: varFilename,
1376
+ path: "",
1377
+ type: "var"
1378
+ } : void 0,
1379
+ types: {
1380
+ path: "",
1381
+ name: ""
1382
+ },
1383
+ globalName: name,
1384
+ pluginVersion: "0.2.5",
1385
+ publicPath
1386
+ }
1387
+ }));
1388
+ } else next();
1389
+ });
1390
+ }
1391
+ }, {
1392
+ name: "module-federation-manifest",
1393
+ enforce: "post",
1394
+ config(config, { command }) {
1395
+ if (!config.build) config.build = {};
1396
+ if (!config.build.manifest) config.build.manifest = config.build.manifest || !!manifestOptions;
1397
+ _command = command;
1398
+ _originalConfigBase = config.base;
1399
+ },
1400
+ configResolved(config) {
1401
+ root = config.root;
1402
+ let base = config.base;
1403
+ if (_command === "serve") base = (config.server.origin || "") + config.base;
1404
+ publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1405
+ },
1406
+ async generateBundle(options, bundle) {
1407
+ if (!mfManifestName) return;
1408
+ let filesMap = {};
1409
+ const foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1410
+ if (foundRemoteEntryFile) remoteEntryFile = foundRemoteEntryFile;
1411
+ const allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : /* @__PURE__ */ new Set();
1412
+ const exposesModules = Object.keys(mfOptions.exposes).map((item) => mfOptions.exposes[item].import);
1413
+ processModuleAssets(bundle, filesMap, (modulePath) => {
1414
+ const absoluteModulePath = pathe.resolve(root, modulePath);
1415
+ return exposesModules.find((exposeModule) => {
1416
+ const exposePath = pathe.resolve(root, exposeModule);
1417
+ if (absoluteModulePath === exposePath) return true;
1418
+ const getPathWithoutKnownExt = (filePath) => {
1419
+ const ext = pathe.extname(filePath);
1420
+ return JS_EXTENSIONS.includes(ext) ? pathe.join(pathe.dirname(filePath), pathe.basename(filePath, ext)) : filePath;
1421
+ };
1422
+ return getPathWithoutKnownExt(absoluteModulePath) === getPathWithoutKnownExt(exposePath);
1423
+ });
1424
+ });
1425
+ const fileToShareKey = await buildFileToShareKeyMap(getUsedShares(), this.resolve.bind(this));
1426
+ processModuleAssets(bundle, filesMap, (modulePath) => fileToShareKey.get(modulePath));
1427
+ if (mfOptions.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
1428
+ filesMap = deduplicateAssets(filesMap);
1429
+ this.emitFile({
1430
+ type: "asset",
1431
+ fileName: mfManifestName,
1432
+ source: JSON.stringify(generateMFManifest(filesMap))
1433
+ });
1434
+ }
1435
+ }];
1436
+ /**
1437
+ * Generates the final manifest JSON structure
1438
+ * @param preloadMap - Map of module assets to include
1439
+ * @returns Complete manifest object
1440
+ */
1441
+ function generateMFManifest(preloadMap) {
1442
+ const options = getNormalizeModuleFederationOptions();
1443
+ const { name, varFilename } = options;
1444
+ const remoteEntry = {
1445
+ name: remoteEntryFile,
1446
+ path: "",
1447
+ type: "module"
1448
+ };
1449
+ const varRemoteEntry = varFilename ? {
1450
+ name: varFilename,
1451
+ path: "",
1452
+ type: "module"
1453
+ } : void 0;
1454
+ const remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(([remoteKey, modules]) => Array.from(modules).map((moduleKey) => ({
1455
+ federationContainerName: options.remotes[remoteKey].entry,
1456
+ moduleName: moduleKey.replace(remoteKey, "").replace("/", ""),
1457
+ alias: remoteKey,
1458
+ entry: "*"
1459
+ })));
1460
+ const shared = Array.from(getUsedShares()).map((shareKey) => {
1461
+ const shareItem = getNormalizeShareItem(shareKey);
1462
+ const assets = preloadMap[shareKey] || createEmptyAssetMap();
1463
+ return {
1464
+ id: `${name}:${shareKey}`,
1465
+ name: shareKey,
1466
+ version: shareItem.version,
1467
+ requiredVersion: shareItem.shareConfig.requiredVersion,
1468
+ assets: {
1469
+ js: {
1470
+ async: assets.js.async,
1471
+ sync: assets.js.sync
1472
+ },
1473
+ css: {
1474
+ async: assets.css.async,
1475
+ sync: assets.css.sync
1476
+ }
1477
+ }
1478
+ };
1479
+ }).filter(Boolean);
1480
+ const exposes = Object.entries(options.exposes).map(([key, value]) => {
1481
+ const formatKey = key.replace("./", "");
1482
+ const assets = preloadMap[value.import] || createEmptyAssetMap();
1483
+ return {
1484
+ id: `${name}:${formatKey}`,
1485
+ name: formatKey,
1486
+ assets: {
1487
+ js: {
1488
+ async: assets.js.async,
1489
+ sync: assets.js.sync
1490
+ },
1491
+ css: {
1492
+ async: assets.css.async,
1493
+ sync: assets.css.sync
1494
+ }
1495
+ },
1496
+ path: key
1497
+ };
1498
+ }).filter(Boolean);
1499
+ return {
1500
+ id: name,
1501
+ name,
1502
+ metaData: {
1503
+ name,
1504
+ type: "app",
1505
+ buildInfo: {
1506
+ buildVersion: "1.0.0",
1507
+ buildName: name
1508
+ },
1509
+ remoteEntry,
1510
+ ssrRemoteEntry: remoteEntry,
1511
+ varRemoteEntry,
1512
+ types: {
1513
+ path: "",
1514
+ name: ""
1515
+ },
1516
+ globalName: name,
1517
+ pluginVersion: "0.2.5",
1518
+ ...!!getPublicPath ? { getPublicPath } : { publicPath }
1519
+ },
1520
+ shared,
1521
+ remotes,
1522
+ exposes
1523
+ };
1524
+ }
1745
1525
  };
1746
1526
 
1747
- var _resolve, _parseTimeout;
1748
- var promise = new Promise(function (resolve, reject) {
1749
- _resolve = function _resolve(v) {
1750
- clearTimeout(_parseTimeout);
1751
- _parseTimeout = null;
1752
- resolve(v);
1753
- };
1527
+ //#endregion
1528
+ //#region src/plugins/pluginModuleParseEnd.ts
1529
+ let _resolve, _parseTimeout;
1530
+ const promise = new Promise((resolve, reject) => {
1531
+ _resolve = (v) => {
1532
+ clearTimeout(_parseTimeout);
1533
+ _parseTimeout = null;
1534
+ resolve(v);
1535
+ };
1754
1536
  });
1755
1537
  function setParseTimeout(timeout) {
1756
- if (!_parseTimeout) {
1757
- _parseTimeout = setTimeout(function () {
1758
- console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1759
- _resolve(1);
1760
- }, timeout * 1000);
1761
- }
1538
+ if (!_parseTimeout) _parseTimeout = setTimeout(() => {
1539
+ console.warn(`Parse timeout (${timeout}s) - forcing resolve`);
1540
+ _resolve(1);
1541
+ }, timeout * 1e3);
1762
1542
  }
1763
- var parsePromise = promise;
1764
- var exposesParseEnd = false;
1765
- var parseStartSet = new Set();
1766
- var parseEndSet = new Set();
1767
- function pluginModuleParseEnd (excludeFn, options) {
1768
- setParseTimeout(options.moduleParseTimeout);
1769
- return [{
1770
- name: '_',
1771
- apply: 'serve',
1772
- config: function config() {
1773
- // No waiting in development mode
1774
- _resolve(1);
1775
- }
1776
- }, {
1777
- enforce: 'pre',
1778
- name: 'parseStart',
1779
- apply: 'build',
1780
- load: function load(id) {
1781
- if (excludeFn(id)) {
1782
- return;
1783
- }
1784
- parseStartSet.add(id);
1785
- }
1786
- }, {
1787
- enforce: 'post',
1788
- name: 'parseEnd',
1789
- apply: 'build',
1790
- moduleParsed: function moduleParsed(module) {
1791
- var id = module.id;
1792
- if (id === VIRTUAL_EXPOSES) {
1793
- // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1794
- exposesParseEnd = true;
1795
- }
1796
- if (excludeFn(id)) {
1797
- return;
1798
- }
1799
- parseEndSet.add(id);
1800
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1801
- _resolve(1);
1802
- }
1803
- }
1804
- }];
1543
+ let parsePromise = promise;
1544
+ let exposesParseEnd = false;
1545
+ const parseStartSet = /* @__PURE__ */ new Set();
1546
+ const parseEndSet = /* @__PURE__ */ new Set();
1547
+ function pluginModuleParseEnd_default(excludeFn, options) {
1548
+ setParseTimeout(options.moduleParseTimeout);
1549
+ return [
1550
+ {
1551
+ name: "_",
1552
+ apply: "serve",
1553
+ config() {
1554
+ _resolve(1);
1555
+ }
1556
+ },
1557
+ {
1558
+ enforce: "pre",
1559
+ name: "parseStart",
1560
+ apply: "build",
1561
+ load(id) {
1562
+ if (excludeFn(id)) return;
1563
+ parseStartSet.add(id);
1564
+ }
1565
+ },
1566
+ {
1567
+ enforce: "post",
1568
+ name: "parseEnd",
1569
+ apply: "build",
1570
+ moduleParsed(module) {
1571
+ const id = module.id;
1572
+ if (id === VIRTUAL_EXPOSES) exposesParseEnd = true;
1573
+ if (excludeFn(id)) return;
1574
+ parseEndSet.add(id);
1575
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) _resolve(1);
1576
+ }
1577
+ }
1578
+ ];
1805
1579
  }
1806
1580
 
1807
- var filter = pluginutils.createFilter();
1808
- function pluginProxyRemoteEntry () {
1809
- var viteConfig, _command;
1810
- return {
1811
- name: 'proxyRemoteEntry',
1812
- enforce: 'post',
1813
- configResolved: function configResolved(config) {
1814
- viteConfig = config;
1815
- },
1816
- config: function config(_config, _ref) {
1817
- var command = _ref.command;
1818
- _command = command;
1819
- },
1820
- resolveId: function resolveId(id) {
1821
- if (id === REMOTE_ENTRY_ID) {
1822
- return REMOTE_ENTRY_ID;
1823
- }
1824
- if (id === VIRTUAL_EXPOSES) {
1825
- return VIRTUAL_EXPOSES;
1826
- }
1827
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1828
- return id;
1829
- }
1830
- },
1831
- load: function load(id) {
1832
- if (id === REMOTE_ENTRY_ID) {
1833
- return parsePromise.then(function (_) {
1834
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1835
- });
1836
- }
1837
- if (id === VIRTUAL_EXPOSES) {
1838
- return generateExposes();
1839
- }
1840
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1841
- return id;
1842
- }
1843
- },
1844
- transform: function transform(code, id) {
1845
- var transformedCode = function () {
1846
- if (!filter(id)) return;
1847
- if (id.includes(REMOTE_ENTRY_ID)) {
1848
- return parsePromise.then(function (_) {
1849
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1850
- });
1851
- }
1852
- if (id === VIRTUAL_EXPOSES) {
1853
- return generateExposes();
1854
- }
1855
- if (id.includes(getHostAutoInitPath())) {
1856
- var options = getNormalizeModuleFederationOptions();
1857
- if (_command === 'serve') {
1858
- var _viteConfig$server, _viteConfig$server2;
1859
- var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1860
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1861
- return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1862
- }
1863
- return code;
1864
- }
1865
- }();
1866
- return mapCodeToCodeWithSourcemap(transformedCode);
1867
- }
1868
- };
1581
+ //#endregion
1582
+ //#region src/plugins/pluginProxyRemoteEntry.ts
1583
+ const filter = (0, _rollup_pluginutils.createFilter)();
1584
+ function pluginProxyRemoteEntry_default() {
1585
+ let viteConfig, _command;
1586
+ return {
1587
+ name: "proxyRemoteEntry",
1588
+ enforce: "post",
1589
+ configResolved(config) {
1590
+ viteConfig = config;
1591
+ },
1592
+ config(config, { command }) {
1593
+ _command = command;
1594
+ },
1595
+ async resolveId(id, importer) {
1596
+ if (id === REMOTE_ENTRY_ID) return REMOTE_ENTRY_ID;
1597
+ if (id === VIRTUAL_EXPOSES) return VIRTUAL_EXPOSES;
1598
+ if (_command === "serve" && id.includes(getHostAutoInitPath())) return id;
1599
+ if (importer === REMOTE_ENTRY_ID && !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !id.startsWith("virtual:")) {
1600
+ typeof __filename === "string" ? __filename : (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
1601
+ const resolved = await this.resolve(id, __filename, { skipSelf: true });
1602
+ if (resolved) return resolved;
1603
+ }
1604
+ },
1605
+ load(id) {
1606
+ if (id === REMOTE_ENTRY_ID) return parsePromise.then((_) => generateRemoteEntry(getNormalizeModuleFederationOptions()));
1607
+ if (id === VIRTUAL_EXPOSES) return generateExposes();
1608
+ if (_command === "serve" && id.includes(getHostAutoInitPath())) return id;
1609
+ },
1610
+ transform(code, id) {
1611
+ return mapCodeToCodeWithSourcemap((() => {
1612
+ if (!filter(id)) return;
1613
+ if (id.includes(REMOTE_ENTRY_ID)) return parsePromise.then((_) => generateRemoteEntry(getNormalizeModuleFederationOptions()));
1614
+ if (id === VIRTUAL_EXPOSES) return generateExposes();
1615
+ if (id.includes(getHostAutoInitPath())) {
1616
+ const options = getNormalizeModuleFederationOptions();
1617
+ if (_command === "serve") {
1618
+ const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
1619
+ const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1620
+ return `
1621
+ const origin = (window && ${!options.ignoreOrigin}) ? window.origin : "//${host}:${viteConfig.server?.port}"
1622
+ const remoteEntryPromise = await import(origin + ${publicPath})
1623
+ // __tla only serves as a hack for vite-plugin-top-level-await.
1624
+ Promise.resolve(remoteEntryPromise)
1625
+ .then(remoteEntry => {
1626
+ return Promise.resolve(remoteEntry.__tla)
1627
+ .then(remoteEntry.init).catch(remoteEntry.init)
1628
+ })
1629
+ `;
1630
+ }
1631
+ return code;
1632
+ }
1633
+ })());
1634
+ }
1635
+ };
1869
1636
  }
1870
1637
 
1871
- pluginutils.createFilter();
1872
- function pluginProxyRemotes (options) {
1873
- var remotes = options.remotes;
1874
- return {
1875
- name: 'proxyRemotes',
1876
- config: function config(_config, _ref) {
1877
- var _command = _ref.command;
1878
- Object.keys(remotes).forEach(function (key) {
1879
- var remote = remotes[key];
1880
- _config.resolve.alias.push({
1881
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1882
- replacement: '$1',
1883
- customResolver: function customResolver(source) {
1884
- var remoteModule = getRemoteVirtualModule(source, _command);
1885
- addUsedRemote(remote.name, source);
1886
- return remoteModule.getPath();
1887
- }
1888
- });
1889
- });
1890
- }
1891
- };
1638
+ //#endregion
1639
+ //#region src/plugins/pluginProxyRemotes.ts
1640
+ (0, _rollup_pluginutils.createFilter)();
1641
+ function pluginProxyRemotes_default(options) {
1642
+ const { remotes } = options;
1643
+ return {
1644
+ name: "proxyRemotes",
1645
+ config(config, { command: _command }) {
1646
+ Object.keys(remotes).forEach((key) => {
1647
+ const remote = remotes[key];
1648
+ config.resolve.alias.push({
1649
+ find: new RegExp(`^(${remote.name}(\/.*|$))`),
1650
+ replacement: "$1",
1651
+ customResolver(source) {
1652
+ const remoteModule = getRemoteVirtualModule(source, _command);
1653
+ addUsedRemote(remote.name, source);
1654
+ return remoteModule.getPath();
1655
+ }
1656
+ });
1657
+ });
1658
+ }
1659
+ };
1892
1660
  }
1893
1661
 
1894
- /**
1895
- * example:
1896
- * const store = new PromiseStore<number>();
1897
- * store.get("example").then((result) => {
1898
- * console.log("Result from example:", result); // 42
1899
- * });
1900
- * setTimeout(() => {
1901
- * store.set("example", Promise.resolve(42));
1902
- * }, 2000);
1903
- */
1904
- var PromiseStore = /*#__PURE__*/function () {
1905
- function PromiseStore() {
1906
- this.promiseMap = new Map();
1907
- this.resolveMap = new Map();
1908
- }
1909
- var _proto = PromiseStore.prototype;
1910
- _proto.set = function set(id, promise) {
1911
- if (this.resolveMap.has(id)) {
1912
- promise.then(this.resolveMap.get(id));
1913
- this.resolveMap["delete"](id);
1914
- }
1915
- this.promiseMap.set(id, promise);
1916
- };
1917
- _proto.get = function get(id) {
1918
- var _this = this;
1919
- if (this.promiseMap.has(id)) {
1920
- return this.promiseMap.get(id);
1921
- }
1922
- var pendingPromise = new Promise(function (resolve) {
1923
- _this.resolveMap.set(id, resolve);
1924
- });
1925
- this.promiseMap.set(id, pendingPromise);
1926
- return pendingPromise;
1927
- };
1928
- return PromiseStore;
1929
- }();
1662
+ //#endregion
1663
+ //#region src/utils/PromiseStore.ts
1664
+ /**
1665
+ * example:
1666
+ * const store = new PromiseStore<number>();
1667
+ * store.get("example").then((result) => {
1668
+ * console.log("Result from example:", result); // 42
1669
+ * });
1670
+ * setTimeout(() => {
1671
+ * store.set("example", Promise.resolve(42));
1672
+ * }, 2000);
1673
+ */
1674
+ var PromiseStore = class {
1675
+ constructor() {
1676
+ this.promiseMap = /* @__PURE__ */ new Map();
1677
+ this.resolveMap = /* @__PURE__ */ new Map();
1678
+ }
1679
+ set(id, promise) {
1680
+ if (this.resolveMap.has(id)) {
1681
+ promise.then(this.resolveMap.get(id));
1682
+ this.resolveMap.delete(id);
1683
+ }
1684
+ this.promiseMap.set(id, promise);
1685
+ }
1686
+ get(id) {
1687
+ if (this.promiseMap.has(id)) return this.promiseMap.get(id);
1688
+ const pendingPromise = new Promise((resolve) => {
1689
+ this.resolveMap.set(id, resolve);
1690
+ });
1691
+ this.promiseMap.set(id, pendingPromise);
1692
+ return pendingPromise;
1693
+ }
1694
+ };
1930
1695
 
1696
+ //#endregion
1697
+ //#region src/plugins/pluginProxySharedModule_preBuild.ts
1931
1698
  function proxySharedModule(options) {
1932
- var _options$shared = options.shared,
1933
- shared = _options$shared === void 0 ? {} : _options$shared;
1934
- var _config;
1935
- return [{
1936
- name: 'generateLocalSharedImportMap',
1937
- enforce: 'post',
1938
- load: function load(id) {
1939
- if (id.includes(getLocalSharedImportMapPath())) {
1940
- return parsePromise.then(function (_) {
1941
- return generateLocalSharedImportMap();
1942
- });
1943
- }
1944
- },
1945
- transform: function transform(_, id) {
1946
- if (id.includes(getLocalSharedImportMapPath())) {
1947
- return mapCodeToCodeWithSourcemap(parsePromise.then(function (_) {
1948
- return generateLocalSharedImportMap();
1949
- }));
1950
- }
1951
- }
1952
- }, {
1953
- name: 'proxyPreBuildShared',
1954
- enforce: 'post',
1955
- configResolved: function configResolved(config) {
1956
- _config = config;
1957
- },
1958
- config: function config(_config2, _ref) {
1959
- var _config2$resolve$alia, _config2$resolve$alia2;
1960
- var command = _ref.command;
1961
- (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
1962
- var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
1963
- return {
1964
- // Intercept all shared requests and proxy them to loadShare
1965
- find: new RegExp(pattern),
1966
- replacement: '$1',
1967
- customResolver: function customResolver(source, importer) {
1968
- if (/\.css$/.test(source)) return;
1969
- var loadSharePath = getLoadShareModulePath(source);
1970
- writeLoadShareModule(source, shared[key], command);
1971
- writePreBuildLibPath(source);
1972
- addUsedShares(source);
1973
- writeLocalSharedImportMap();
1974
- return this.resolve(loadSharePath, importer);
1975
- }
1976
- };
1977
- }));
1978
- var savePrebuild = new PromiseStore();
1979
- (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
1980
- return command === 'build' ? {
1981
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1982
- replacement: function replacement($1) {
1983
- var module = assertModuleFound(PREBUILD_TAG, $1);
1984
- var pkgName = module.name;
1985
- return pkgName;
1986
- }
1987
- } : {
1988
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1989
- replacement: '$1',
1990
- customResolver: function customResolver(source, importer) {
1991
- try {
1992
- var _this = this;
1993
- var module = assertModuleFound(PREBUILD_TAG, source);
1994
- var pkgName = module.name;
1995
- return Promise.resolve(_this.resolve(pkgName, importer).then(function (item) {
1996
- return item.id;
1997
- })).then(function (result) {
1998
- if (!result.includes(_config.cacheDir)) {
1999
- // save pre-bunding module id
2000
- savePrebuild.set(pkgName, Promise.resolve(result));
2001
- }
2002
- // Fix localSharedImportMap import id
2003
- var _resolve = _this.resolve;
2004
- return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
2005
- return Promise.resolve(_resolve.call(_this, _savePrebuild$get, importer));
2006
- });
2007
- });
2008
- } catch (e) {
2009
- return Promise.reject(e);
2010
- }
2011
- }
2012
- };
2013
- }));
2014
- }
2015
- }];
1699
+ let { shared = {}, include, exclude } = options;
1700
+ let _config;
1701
+ return [{
1702
+ name: "generateLocalSharedImportMap",
1703
+ enforce: "post",
1704
+ load(id) {
1705
+ if (id.includes(getLocalSharedImportMapPath())) return parsePromise.then((_) => generateLocalSharedImportMap());
1706
+ },
1707
+ transform(_, id) {
1708
+ if (id.includes(getLocalSharedImportMapPath())) return mapCodeToCodeWithSourcemap(parsePromise.then((_) => generateLocalSharedImportMap()));
1709
+ }
1710
+ }, {
1711
+ name: "proxyPreBuildShared",
1712
+ enforce: "post",
1713
+ configResolved(config) {
1714
+ _config = config;
1715
+ },
1716
+ config(config, { command }) {
1717
+ config.resolve.alias.push(...Object.keys(shared).map((key) => {
1718
+ const pattern = key.endsWith("/") ? `(^${key.replace(/\/$/, "")}(\/.+)?$)` : `(^${key}$)`;
1719
+ return {
1720
+ find: new RegExp(pattern),
1721
+ replacement: "$1",
1722
+ customResolver(source, importer) {
1723
+ if (/\.css$/.test(source)) return;
1724
+ const loadSharePath = getLoadShareModulePath(source);
1725
+ writeLoadShareModule(source, shared[key], command);
1726
+ writePreBuildLibPath(source);
1727
+ addUsedShares(source);
1728
+ writeLocalSharedImportMap();
1729
+ return this.resolve(loadSharePath, importer);
1730
+ }
1731
+ };
1732
+ }));
1733
+ const savePrebuild = new PromiseStore();
1734
+ config.resolve.alias.push(...Object.keys(shared).map((key) => {
1735
+ return command === "build" ? {
1736
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
1737
+ replacement: function($1) {
1738
+ return assertModuleFound(PREBUILD_TAG, $1).name;
1739
+ }
1740
+ } : {
1741
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
1742
+ replacement: "$1",
1743
+ async customResolver(source, importer) {
1744
+ const pkgName = assertModuleFound(PREBUILD_TAG, source).name;
1745
+ const result = await this.resolve(pkgName, importer).then((item) => item.id);
1746
+ if (!result.includes(_config.cacheDir)) savePrebuild.set(pkgName, Promise.resolve(result));
1747
+ return await this.resolve(await savePrebuild.get(pkgName), importer);
1748
+ }
1749
+ };
1750
+ }));
1751
+ }
1752
+ }];
2016
1753
  }
2017
1754
 
2018
- var aliasToArrayPlugin = {
2019
- name: 'alias-transform-plugin',
2020
- config: function config(_config, _ref) {
2021
- if (!_config.resolve) _config.resolve = {};
2022
- if (!_config.resolve.alias) _config.resolve.alias = [];
2023
- var alias = _config.resolve.alias;
2024
- if (typeof alias === 'object' && !Array.isArray(alias)) {
2025
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
2026
- var find = _ref2[0],
2027
- replacement = _ref2[1];
2028
- return {
2029
- find: find,
2030
- replacement: replacement
2031
- };
2032
- });
1755
+ //#endregion
1756
+ //#region src/plugins/pluginVarRemoteEntry.ts
1757
+ const VarRemoteEntry = () => {
1758
+ const mfOptions = getNormalizeModuleFederationOptions();
1759
+ const { name, varFilename, filename } = mfOptions;
1760
+ let viteConfig;
1761
+ return [{
1762
+ name: "module-federation-var-remote-entry",
1763
+ apply: "serve",
1764
+ configResolved(config) {
1765
+ viteConfig = config;
1766
+ },
1767
+ configureServer(server) {
1768
+ server.middlewares.use((req, res, next) => {
1769
+ if (!varFilename) {
1770
+ next();
1771
+ return;
1772
+ }
1773
+ if (req.url?.replace(/\?.*/, "") === (viteConfig.base + varFilename).replace(/^\/?/, "/")) {
1774
+ res.setHeader("Content-Type", "text/javascript");
1775
+ res.setHeader("Access-Control-Allow-Origin", "*");
1776
+ console.log({ filename });
1777
+ res.end(generateVarRemoteEntry(filename));
1778
+ } else next();
1779
+ });
1780
+ }
1781
+ }, {
1782
+ name: "module-federation-var-remote-entry",
1783
+ enforce: "post",
1784
+ config(config, { command }) {
1785
+ if (!config.build) config.build = {};
1786
+ },
1787
+ configResolved(config) {
1788
+ viteConfig = config;
1789
+ },
1790
+ async generateBundle(options, bundle) {
1791
+ if (!varFilename) return;
1792
+ if (!isValidVarName(name)) viteConfig.logger.warn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
1793
+ const remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1794
+ if (!remoteEntryFile) throw new Error(`Couldn't find a remoteEntry chunk file for ${mfOptions.filename}, can't generate varRemoteEntry file`);
1795
+ this.emitFile({
1796
+ type: "asset",
1797
+ fileName: varFilename,
1798
+ source: generateVarRemoteEntry(remoteEntryFile)
1799
+ });
1800
+ }
1801
+ }];
1802
+ function isValidVarName(name) {
1803
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
1804
+ }
1805
+ /**
1806
+ * Generates the final "var" remote entry file
1807
+ * @param remoteEntryFile - Path to esm remote entry file
1808
+ * @returns Complete "var" remoteEntry.js file source
1809
+ */
1810
+ function generateVarRemoteEntry(remoteEntryFile) {
1811
+ const { name, varFilename } = getNormalizeModuleFederationOptions();
1812
+ const isValidName = isValidVarName(name);
1813
+ return `
1814
+ ${isValidName ? `var ${name};` : ""}
1815
+ ${isValidName ? name : `globalThis['${name}']`} = (function () {
1816
+ function getScriptUrl() {
1817
+ const currentScript = document.currentScript;
1818
+ if (!currentScript) {
1819
+ console.error("[VarRemoteEntry] ${varFilename} script should be called from sync <script> tag (document.currentScript is undefined)")
1820
+ return '/';
1821
+ }
1822
+ return document.currentScript.src.replace(/\\/[^/]*$/, '/');
2033
1823
  }
2034
- }
1824
+
1825
+ const entry = getScriptUrl() + '${remoteEntryFile}';
1826
+
1827
+ return {
1828
+ get: (...args) => import(entry).then(m => m.get(...args)),
1829
+ init: (...args) => import(entry).then(m => m.init(...args)),
1830
+ };
1831
+ })();
1832
+ `;
1833
+ }
2035
1834
  };
2036
1835
 
2037
- var normalizeOptimizeDepsPlugin = {
2038
- name: 'normalizeOptimizeDeps',
2039
- config: function config(_config, _ref) {
2040
- var optimizeDeps = _config.optimizeDeps;
2041
- if (!optimizeDeps) {
2042
- _config.optimizeDeps = {};
2043
- optimizeDeps = _config.optimizeDeps;
2044
- }
2045
- // todo: fix this workaround
2046
- optimizeDeps.force = true;
2047
- if (!optimizeDeps.include) optimizeDeps.include = [];
2048
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
2049
- }
1836
+ //#endregion
1837
+ //#region src/utils/aliasToArrayPlugin.ts
1838
+ var aliasToArrayPlugin_default = {
1839
+ name: "alias-transform-plugin",
1840
+ config: (config, { command }) => {
1841
+ if (!config.resolve) config.resolve = {};
1842
+ if (!config.resolve.alias) config.resolve.alias = [];
1843
+ const { alias } = config.resolve;
1844
+ if (typeof alias === "object" && !Array.isArray(alias)) config.resolve.alias = Object.entries(alias).map(([find, replacement]) => ({
1845
+ find,
1846
+ replacement
1847
+ }));
1848
+ }
2050
1849
  };
2051
1850
 
1851
+ //#endregion
1852
+ //#region src/utils/normalizeOptimizeDeps.ts
1853
+ var normalizeOptimizeDeps_default = {
1854
+ name: "normalizeOptimizeDeps",
1855
+ config: (config, { command }) => {
1856
+ let { optimizeDeps } = config;
1857
+ if (!optimizeDeps) {
1858
+ config.optimizeDeps = {};
1859
+ optimizeDeps = config.optimizeDeps;
1860
+ }
1861
+ optimizeDeps.force = true;
1862
+ if (!optimizeDeps.include) optimizeDeps.include = [];
1863
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
1864
+ }
1865
+ };
1866
+
1867
+ //#endregion
1868
+ //#region src/index.ts
2052
1869
  function federation(mfUserOptions) {
2053
- var options = normalizeModuleFederationOptions(mfUserOptions);
2054
- var name = options.name,
2055
- shared = options.shared,
2056
- filename = options.filename,
2057
- hostInitInjectLocation = options.hostInitInjectLocation;
2058
- if (!name) throw new Error('name is required');
2059
- return [{
2060
- name: 'vite:module-federation-config',
2061
- enforce: 'pre',
2062
- configResolved: function configResolved(config) {
2063
- // Set root path
2064
- VirtualModule.setRoot(config.root);
2065
- // Ensure virtual package directory exists
2066
- VirtualModule.ensureVirtualPackageExists();
2067
- initVirtualModules();
2068
- }
2069
- }, aliasToArrayPlugin, checkAliasConflicts({
2070
- shared: shared
2071
- }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
2072
- entryName: 'remoteEntry',
2073
- entryPath: REMOTE_ENTRY_ID,
2074
- fileName: filename
2075
- }), addEntry({
2076
- entryName: 'hostInit',
2077
- entryPath: getHostAutoInitPath(),
2078
- inject: hostInitInjectLocation
2079
- }), addEntry({
2080
- entryName: 'virtualExposes',
2081
- entryPath: VIRTUAL_EXPOSES
2082
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2083
- return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2084
- }, {
2085
- moduleParseTimeout: options.moduleParseTimeout
2086
- }), proxySharedModule({
2087
- shared: shared
2088
- }), [PluginDevProxyModuleTopLevelAwait(), {
2089
- name: 'module-federation-vite',
2090
- enforce: 'post',
2091
- // @ts-expect-error
2092
- // used to expose plugin options: https://github.com/rolldown/rolldown/discussions/2577#discussioncomment-11137593
2093
- _options: options,
2094
- config: function config(_config, _ref) {
2095
- var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3, _config$optimizeDeps4;
2096
- // TODO: singleton
2097
- _config.resolve.alias.push({
2098
- find: '@module-federation/runtime',
2099
- replacement: options.implementation
2100
- });
2101
- _config.build = defu__default["default"](_config.build || {}, {
2102
- commonjsOptions: {
2103
- strictRequires: 'auto'
2104
- }
2105
- });
2106
- var virtualDir = options.virtualModuleDir || '__mf__virtual';
2107
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
2108
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(virtualDir);
2109
- (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2110
- (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2111
- }
2112
- }], Manifest());
1870
+ const options = normalizeModuleFederationOptions(mfUserOptions);
1871
+ const { name, remotes, shared, filename, hostInitInjectLocation } = options;
1872
+ if (!name) throw new Error("name is required");
1873
+ let command;
1874
+ return [
1875
+ {
1876
+ name: "vite:module-federation-config",
1877
+ enforce: "pre",
1878
+ config(_config, env) {
1879
+ command = env.command;
1880
+ },
1881
+ configResolved(config) {
1882
+ VirtualModule.setRoot(config.root);
1883
+ VirtualModule.ensureVirtualPackageExists();
1884
+ initVirtualModules(command);
1885
+ }
1886
+ },
1887
+ aliasToArrayPlugin_default,
1888
+ checkAliasConflicts({ shared }),
1889
+ normalizeOptimizeDeps_default,
1890
+ ...pluginDts(options),
1891
+ ...addEntry({
1892
+ entryName: "remoteEntry",
1893
+ entryPath: REMOTE_ENTRY_ID,
1894
+ fileName: filename
1895
+ }),
1896
+ ...addEntry({
1897
+ entryName: "hostInit",
1898
+ entryPath: getHostAutoInitPath(),
1899
+ inject: hostInitInjectLocation
1900
+ }),
1901
+ ...addEntry({
1902
+ entryName: "virtualExposes",
1903
+ entryPath: VIRTUAL_EXPOSES
1904
+ }),
1905
+ pluginProxyRemoteEntry_default(),
1906
+ pluginProxyRemotes_default(options),
1907
+ ...pluginModuleParseEnd_default((id) => {
1908
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
1909
+ }, { moduleParseTimeout: options.moduleParseTimeout }),
1910
+ ...proxySharedModule({ shared }),
1911
+ {
1912
+ name: "module-federation-esm-shims",
1913
+ enforce: "pre",
1914
+ apply: "build",
1915
+ load(id) {
1916
+ if (id.startsWith("\0")) return;
1917
+ if (id.includes(LOAD_SHARE_TAG) || id.includes(LOAD_REMOTE_TAG)) {
1918
+ let code = (0, fs.readFileSync)(id, "utf-8");
1919
+ /**
1920
+ * Shared/remote shims only have `export default exportModule`.
1921
+ *
1922
+ * We add a second named export (__moduleExports) that holds the full
1923
+ * module namespace and point syntheticNamedExports at it. This lets
1924
+ * Rollup resolve named imports (e.g. `import { useState } from 'react'`)
1925
+ * from the namespace while still applying its normal default-export
1926
+ * interop which is needed for libraries like @emotion/styled where
1927
+ * `import styled from '@emotion/styled'` must receive the .default
1928
+ * function, not the raw namespace object.
1929
+ *
1930
+ * Using 'default' as the syntheticNamedExports key would skip the
1931
+ * interop and break default imports.
1932
+ *
1933
+ * @see https://rollupjs.org/plugin-development/#synthetic-named-exports
1934
+ */
1935
+ code = code.replace("export default exportModule", "export const __moduleExports = exportModule;\nexport default exportModule.__esModule ? exportModule.default : exportModule");
1936
+ return {
1937
+ code,
1938
+ syntheticNamedExports: "__moduleExports"
1939
+ };
1940
+ }
1941
+ }
1942
+ },
1943
+ PluginDevProxyModuleTopLevelAwait(),
1944
+ {
1945
+ name: "module-federation-vite",
1946
+ enforce: "post",
1947
+ _options: options,
1948
+ config(config, { command: _command }) {
1949
+ config.resolve.alias.push({
1950
+ find: "@module-federation/runtime",
1951
+ replacement: options.implementation
1952
+ });
1953
+ config.build = (0, defu.default)(config.build || {}, { commonjsOptions: { strictRequires: "auto" } });
1954
+ const virtualDir = options.virtualModuleDir || "__mf__virtual";
1955
+ config.optimizeDeps?.include?.push("@module-federation/runtime");
1956
+ config.optimizeDeps?.include?.push(virtualDir);
1957
+ config.optimizeDeps?.needsInterop?.push(virtualDir);
1958
+ config.optimizeDeps?.needsInterop?.push(getLocalSharedImportMapPath());
1959
+ const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");
1960
+ if (!config.define) config.define = {};
1961
+ if (!("ENV_TARGET" in config.define)) config.define["ENV_TARGET"] = JSON.stringify(resolvedTarget);
1962
+ if (options.target && "ENV_TARGET" in config.define && config.define["ENV_TARGET"] !== JSON.stringify(options.target)) console.warn(`[module-federation] ENV_TARGET define (${config.define["ENV_TARGET"]}) differs from target option ("${options.target}"). ENV_TARGET will not be overridden.`);
1963
+ }
1964
+ },
1965
+ ...Manifest(),
1966
+ ...VarRemoteEntry()
1967
+ ];
2113
1968
  }
2114
1969
 
2115
- exports.federation = federation;
1970
+ //#endregion
1971
+ exports.federation = federation;