@module-federation/vite 1.0.0-alpha-80b7215 → 1.0.0-alpha-4a73cd4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.esm.js CHANGED
@@ -1,60 +1,81 @@
1
- import { createFilter } from '@rollup/pluginutils';
2
- import * as path from 'pathe';
3
1
  import * as fs from 'fs';
2
+ import { writeFileSync } from 'fs';
3
+ import * as path from 'pathe';
4
+ import { resolve } from 'pathe';
5
+ import { createFilter } from '@rollup/pluginutils';
4
6
  import { walk } from 'estree-walker';
5
7
  import MagicString from 'magic-string';
6
8
 
7
- var aliasToArrayPlugin = {
8
- name: 'alias-transform-plugin',
9
- config: function config(_config, _ref) {
10
- if (!_config.resolve) _config.resolve = {};
11
- if (!_config.resolve.alias) _config.resolve.alias = [];
12
- var alias = _config.resolve.alias;
13
- if (typeof alias === 'object' && !Array.isArray(alias)) {
14
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
15
- var find = _ref2[0],
16
- replacement = _ref2[1];
17
- return {
18
- find: find,
19
- replacement: replacement
20
- };
9
+ var addEntry = function addEntry(_ref) {
10
+ var entryPath = _ref.entryPath,
11
+ fileName = _ref.fileName;
12
+ var entryFiles = [];
13
+ var htmlFilePath;
14
+ return [{
15
+ name: 'add-entry',
16
+ apply: "serve",
17
+ configureServer: function configureServer(server) {
18
+ var _server$httpServer;
19
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
20
+ var port = server.config.server.port;
21
+ fetch(path.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
21
22
  });
23
+ server.middlewares.use(function (req, res, next) {
24
+ if (!fileName) {
25
+ next();
26
+ return;
27
+ }
28
+ if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
29
+ req.url = entryPath;
30
+ }
31
+ next();
32
+ });
33
+ },
34
+ transformIndexHtml: function transformIndexHtml(c) {
35
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
22
36
  }
23
- }
24
- };
25
-
26
- var normalizeBuildPlugin = (function (singleChunkModules) {
27
- return {
28
- name: 'normalizeBuild',
29
- config: function config(_config, _ref) {
30
- if (!_config.build) _config.build = {};
31
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
32
- var rollupOptions = _config.build.rollupOptions;
33
- if (!rollupOptions.output) rollupOptions.output = {};
34
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
35
- }
36
- };
37
- });
38
- function normalizeManualChunks(output, singleChunkModules) {
39
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
40
- if (!output.manualChunks) output.manualChunks = {};
41
- var wrapManualChunks = function wrapManualChunks(original) {
42
- return function (id) {
43
- var _ref2 = id.match(pattern) || [],
44
- moduleName = _ref2[1];
45
- if (moduleName) {
46
- return moduleName;
37
+ }, {
38
+ name: "add-entry",
39
+ enforce: "post",
40
+ apply: "build",
41
+ configResolved: function configResolved(config) {
42
+ var inputOptions = config.build.rollupOptions.input;
43
+ if (!inputOptions) {
44
+ htmlFilePath = path.resolve(config.root, 'index.html');
45
+ } else if (typeof inputOptions === 'string') {
46
+ entryFiles = [inputOptions];
47
+ htmlFilePath = path.resolve(config.root, inputOptions);
48
+ } else if (Array.isArray(inputOptions)) {
49
+ entryFiles = inputOptions;
50
+ htmlFilePath = path.resolve(config.root, inputOptions[0]);
51
+ } else if (typeof inputOptions === 'object') {
52
+ entryFiles = Object.values(inputOptions);
53
+ htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
47
54
  }
48
- if (typeof original === 'function') {
49
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
55
+ },
56
+ buildStart: function buildStart() {
57
+ var _this$emitFile;
58
+ var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
59
+ this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
60
+ if (htmlFilePath) {
61
+ var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
62
+ var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
63
+ var match;
64
+ while ((match = scriptRegex.exec(htmlContent)) !== null) {
65
+ entryFiles.push(match[1]);
66
+ }
50
67
  }
51
- if (typeof original === 'object' && original) {
52
- return original[id];
68
+ },
69
+ transform: function transform(code, id) {
70
+ if (entryFiles.some(function (file) {
71
+ return id.endsWith(file);
72
+ })) {
73
+ var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
74
+ return injection + code;
53
75
  }
54
- };
55
- };
56
- output.manualChunks = wrapManualChunks(output.manualChunks);
57
- }
76
+ }
77
+ }];
78
+ };
58
79
 
59
80
  function normalizeExposesItem(key, item) {
60
81
  var importPath = '';
@@ -72,7 +93,7 @@ function normalizeExposes(exposes) {
72
93
  if (!exposes) return {};
73
94
  var res = {};
74
95
  Object.keys(exposes).forEach(function (key) {
75
- res[key.replace(/^\.?\/?/, './')] = normalizeExposesItem(key, exposes[key]);
96
+ res[key] = normalizeExposesItem(key, exposes[key]);
76
97
  });
77
98
  return res;
78
99
  }
@@ -157,8 +178,12 @@ function normalizeLibrary(library) {
157
178
  if (!library) return undefined;
158
179
  return library;
159
180
  }
181
+ var config;
182
+ function getNormalizeModuleFederationOptions() {
183
+ return config;
184
+ }
160
185
  function normalizeModuleFederationOptions(options) {
161
- return {
186
+ return config = {
162
187
  exposes: normalizeExposes(options.exposes),
163
188
  filename: options.filename || 'remoteEntry-[hash]',
164
189
  library: normalizeLibrary(options.library),
@@ -177,216 +202,63 @@ function normalizeModuleFederationOptions(options) {
177
202
  };
178
203
  }
179
204
 
180
- var normalizeOptimizeDepsPlugin = {
181
- name: 'normalizeOptimizeDeps',
182
- config: function config(_config, _ref) {
183
- var optimizeDeps = _config.optimizeDeps;
184
- if (!optimizeDeps) {
185
- _config.optimizeDeps = {};
186
- optimizeDeps = _config.optimizeDeps;
187
- }
188
- if (!optimizeDeps.include) optimizeDeps.include = [];
189
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
190
- }
191
- };
192
-
193
- var addEntry = function addEntry(_ref) {
194
- var entryPath = _ref.entryPath,
195
- fileName = _ref.fileName;
196
- var entryFiles = [];
197
- var htmlFilePath;
198
- return [{
199
- name: 'add-entry',
200
- apply: "serve",
201
- configureServer: function configureServer(server) {
202
- var _server$httpServer;
203
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
204
- var port = server.config.server.port;
205
- fetch(path.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
206
- });
207
- server.middlewares.use(function (req, res, next) {
208
- if (!fileName) {
209
- next();
210
- return;
211
- }
212
- if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
213
- req.url = entryPath;
214
- }
215
- next();
216
- });
217
- },
218
- transformIndexHtml: function transformIndexHtml(c) {
219
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
220
- }
221
- }, {
222
- name: "add-entry",
223
- enforce: "post",
224
- apply: "build",
225
- configResolved: function configResolved(config) {
226
- var inputOptions = config.build.rollupOptions.input;
227
- if (!inputOptions) {
228
- htmlFilePath = path.resolve(config.root, 'index.html');
229
- } else if (typeof inputOptions === 'string') {
230
- entryFiles = [inputOptions];
231
- htmlFilePath = path.resolve(config.root, inputOptions);
232
- } else if (Array.isArray(inputOptions)) {
233
- entryFiles = inputOptions;
234
- htmlFilePath = path.resolve(config.root, inputOptions[0]);
235
- } else if (typeof inputOptions === 'object') {
236
- entryFiles = Object.values(inputOptions);
237
- htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
238
- }
239
- },
240
- buildStart: function buildStart() {
241
- var _this$emitFile;
242
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
243
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
244
- if (htmlFilePath) {
245
- var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
246
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
247
- var match;
248
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
249
- entryFiles.push(match[1]);
250
- }
251
- }
252
- },
253
- transform: function transform(code, id) {
254
- if (entryFiles.some(function (file) {
255
- return id.endsWith(file);
256
- })) {
257
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
258
- return injection + code;
259
- }
260
- }
261
- }];
262
- };
263
-
264
- function _arrayLikeToArray(r, a) {
265
- (null == a || a > r.length) && (a = r.length);
266
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
267
- return n;
205
+ /**
206
+ * Even the resolveId hook cannot interfere with vite pre-build,
207
+ * and adding query parameter virtual modules will also fail.
208
+ * You can only proxy to the real file through alias
209
+ */
210
+ var emptyNpmDir = resolve(require.resolve("an-empty-js-file"), "../");
211
+ /**
212
+ * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
213
+ */
214
+ var cacheMap2 = {};
215
+ function getPreBuildLibPath(pkg) {
216
+ if (!cacheMap2[pkg]) cacheMap2[pkg] = "__mf__prebuildwrap_" + npmPackageNameToFileName(pkg) + ".js";
217
+ var filename = cacheMap2[pkg];
218
+ return filename;
268
219
  }
269
- function _createForOfIteratorHelperLoose(r, e) {
270
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
271
- if (t) return (t = t.call(r)).next.bind(t);
272
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
273
- t && (r = t);
274
- var o = 0;
275
- return function () {
276
- return o >= r.length ? {
277
- done: !0
278
- } : {
279
- done: !1,
280
- value: r[o++]
281
- };
282
- };
283
- }
284
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
220
+ function getLocalSharedImportMapFileName() {
221
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
222
+ name = _getNormalizeModuleFe.name;
223
+ return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
285
224
  }
286
- function _unsupportedIterableToArray(r, a) {
287
- if (r) {
288
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
289
- var t = {}.toString.call(r).slice(8, -1);
290
- 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;
291
- }
225
+ // Only npm package name import can trigger pre-build, absolute path cannot
226
+ function getLocalSharedImportMapId() {
227
+ return "an-empty-js-file/" + getLocalSharedImportMapFileName();
292
228
  }
293
-
294
- function overrideModule(options) {
295
- if (options === void 0) {
296
- options = {};
297
- }
298
- var _options = options,
299
- _options$override = _options.override,
300
- _override = _options$override === void 0 ? [] : _options$override,
301
- include = _options.include,
302
- exclude = _options.exclude;
303
- var override = new Set(_override);
304
- var filterFunction = createFilter(include, exclude);
305
- var alias = {};
306
- var keys = override.keys();
307
- for (var _iterator = _createForOfIteratorHelperLoose(keys), _step; !(_step = _iterator()).done;) {
308
- var key = _step.value;
309
- alias['__overrideModule__' + key] = require.resolve("an-empty-js-file") + ("?__overrideModule__=" + encodeURIComponent(key));
310
- }
311
- return {
312
- name: 'overrideModule',
313
- enforce: 'post',
314
- config: function config(_config) {
315
- var _config$resolve$alias;
316
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
317
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
318
- Object.keys(alias).forEach(function (key) {
319
- var _config$optimizeDeps;
320
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(key);
321
- });
322
- _config.optimizeDeps.needsInterop.push('an-empty-js-file');
323
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(alias).map(function (key) {
324
- return {
325
- find: key,
326
- replacement: alias[key]
327
- };
328
- }));
329
- },
330
- resolveId: function resolveId(id) {
331
- return alias[id];
332
- },
333
- transform: {
334
- handler: function handler(code, id) {
335
- if (!filterFunction(id)) return null;
336
- var ast;
337
- try {
338
- ast = this.parse(code, {
339
- allowReturnOutsideFunction: true
340
- });
341
- } catch (e) {
342
- throw new Error(id + ": " + e);
343
- }
344
- var s = new MagicString(code);
345
- walk(ast, {
346
- enter: function enter(node) {
347
- var replaceIfMatch = function replaceIfMatch(sourceNode) {
348
- if (sourceNode && sourceNode.value) {
349
- if (override.has(sourceNode.value)) {
350
- var start = sourceNode.start + 1; // Skip the opening quote
351
- var end = sourceNode.end - 1; // Skip the closing quote
352
- s.overwrite(start, end, '__overrideModule__' + sourceNode.value);
353
- }
354
- }
355
- };
356
- if (node.type === 'ImportDeclaration') {
357
- replaceIfMatch(node.source);
358
- }
359
- if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
360
- replaceIfMatch(node.source);
361
- }
362
- if (node.type === 'ImportExpression') {
363
- replaceIfMatch(node.source);
364
- }
365
- if (node.type === 'CallExpression' && node.callee.name === 'require' && node.arguments.length && node.arguments[0].type === 'Literal') {
366
- replaceIfMatch(node.arguments[0]);
367
- }
368
- }
369
- });
370
- return {
371
- code: s.toString(),
372
- map: s.generateMap({
373
- hires: true
374
- })
375
- };
376
- }
377
- }
378
- };
229
+ function getLocalSharedImportMapPath() {
230
+ return resolve(emptyNpmDir, getLocalSharedImportMapFileName());
379
231
  }
380
-
381
- var emptyPath = require.resolve('an-empty-js-file');
382
- var filter = createFilter();
383
- var command = '';
384
- function wrapRemoteEntry() {
385
- return "\n import {init, get} from \"__mf__cwdRemoteEntry\"\n export {init, get}\n ";
232
+ function writeLocalSharedImportMap(pkgList) {
233
+ writeFileSync(getLocalSharedImportMapPath(), "\n export default {\n " + pkgList.map(function (pkg) {
234
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
235
+ }).join(",") + "\n }\n ");
236
+ }
237
+ /**
238
+ * generate loadShare virtual module
239
+ */
240
+ var cacheMap1 = {};
241
+ function getLoadShareModulePath(pkg) {
242
+ var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
243
+ name = _getNormalizeModuleFe2.name;
244
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
245
+ var filename = cacheMap1[pkg];
246
+ return resolve(emptyNpmDir, filename);
247
+ }
248
+ function writeLoadShareModule(pkg, shareItem, command) {
249
+ writeFileSync(getLoadShareModulePath(pkg), "\n const {loadShare} = require(\"@module-federation/runtime\")\n const res = 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 const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "res.then(factory => factory())\n module.exports = exportModule\n ");
386
250
  }
387
- function wrapHostInit() {
388
- return "\n import {init} from \"__mf__cwdRemoteEntry\"\n init()\n ";
251
+ function npmPackageNameToFileName(packageName) {
252
+ // 1. 去掉包名前的 "@"
253
+ // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
254
+ // 3. 去掉不合法的文件名字符
255
+ return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
256
+ .replace(/\//g, '__') // 将 "/" 替换为 "__"
257
+ .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
389
258
  }
259
+
260
+ var emptyPath = require.resolve('an-empty-js-file');
261
+ var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
390
262
  function generateRemoteEntry(options) {
391
263
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
392
264
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -395,9 +267,9 @@ function generateRemoteEntry(options) {
395
267
  return item[1];
396
268
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
397
269
  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 ";
398
- }).join(',') + "\n }\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
270
+ }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
399
271
  var shareItem = options.shared[key];
400
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const pkg = await import(" + JSON.stringify(key) + ")\n return function () {\n return pkg\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
272
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
401
273
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
402
274
  var remote = options.remotes[key];
403
275
  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 }\n ";
@@ -405,17 +277,55 @@ function generateRemoteEntry(options) {
405
277
  return item[0] + "()";
406
278
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
407
279
  }
408
- function wrapShare(id, shared) {
409
- var shareConfig = shared[id].shareConfig;
280
+ var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?__mf__wrapRemoteEntry__';
281
+ function generateWrapRemoteEntry() {
282
+ return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
283
+ }
284
+ /**
285
+ * Inject entry file, automatically init when used as host,
286
+ * and will not inject remoteEntry
287
+ */
288
+ var HOST_AUTO_INIT = emptyPath + '?__mf__isHostInit';
289
+ function generateWrapHostInit() {
290
+ return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
291
+ }
292
+
293
+ var filter$1 = createFilter();
294
+ function pluginProxyRemoteEntry () {
410
295
  return {
411
- code: "\n import {loadShare} from \"@module-federation/runtime\"\n const res = await loadShare(" + JSON.stringify(id) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareConfig.singleton + ",\n strictVersion: " + JSON.stringify(shareConfig.strictVersion) + ",\n requiredVersion: " + JSON.stringify(shareConfig.requiredVersion) + "\n }}})\n const exportModule = res()\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : exportModule\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
412
- map: null,
413
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
414
- syntheticNamedExports: '__mf__dynamicExports'
296
+ name: 'proxyRemoteEntry',
297
+ enforce: 'post',
298
+ resolveId: function resolveId(id) {
299
+ if (id === REMOTE_ENTRY_ID) {
300
+ return REMOTE_ENTRY_ID;
301
+ }
302
+ },
303
+ load: function load(id) {
304
+ if (id === REMOTE_ENTRY_ID) {
305
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
306
+ }
307
+ },
308
+ transform: function transform(code, id) {
309
+ try {
310
+ if (!filter$1(id)) return Promise.resolve();
311
+ if (id === REMOTE_ENTRY_ID) {
312
+ return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
313
+ }
314
+ if (id.includes(WRAP_REMOTE_ENTRY_PATH)) {
315
+ return Promise.resolve(generateWrapRemoteEntry());
316
+ }
317
+ if (id.includes(HOST_AUTO_INIT)) {
318
+ return Promise.resolve(generateWrapHostInit());
319
+ }
320
+ return Promise.resolve();
321
+ } catch (e) {
322
+ return Promise.reject(e);
323
+ }
324
+ }
415
325
  };
416
326
  }
417
- var con;
418
- function wrapRemote(id) {
327
+
328
+ function generateRemotes(id, command) {
419
329
  return {
420
330
  code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
421
331
  map: null,
@@ -423,108 +333,259 @@ function wrapRemote(id) {
423
333
  syntheticNamedExports: '__mf__dynamicExports'
424
334
  };
425
335
  }
426
- function federation(mfUserOptions) {
427
- var options = normalizeModuleFederationOptions(mfUserOptions);
428
- var remotes = options.remotes,
429
- shared = options.shared,
430
- filename = options.filename;
431
- var alias = [{
432
- find: '@module-federation/runtime',
433
- replacement: require.resolve('@module-federation/runtime')
434
- }];
435
- Object.keys(remotes).forEach(function (key) {
436
- var remote = remotes[key];
437
- alias.push({
438
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
439
- replacement: '$1',
440
- customResolver: function customResolver(source) {
441
- if (!con.optimizeDeps) con.optimizeDeps = {};
442
- if (!con.optimizeDeps.needsInterop) con.optimizeDeps.needsInterop = [];
443
- if (con.optimizeDeps.needsInterop.indexOf(source) === -1) con.optimizeDeps.needsInterop.push(source);
444
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
445
- }
446
- });
447
- });
448
- var remotePrefixList = Object.keys(remotes);
449
- // pkgname will be escaped, and matching path also needs to be processed in the same way:
450
- // @json2csv/plainjs --> .vite/deps/@json2csv_plainjs
451
- var sharedKeyMatchList = Object.keys(shared).map(function (item) {
452
- return "__overrideModule__" + item.replace('/', '_');
336
+
337
+ var filter = createFilter();
338
+ function pluginProxyRemotes (options) {
339
+ var command;
340
+ var remotes = options.remotes;
341
+ var matchRemotesList = Object.keys(remotes).map(function (item) {
342
+ return item.replace(/\//g, "_");
453
343
  });
454
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
455
- entryName: 'remoteEntry',
456
- entryPath: emptyPath + '?__mf__wrapRemoteEntry__',
457
- fileName: filename
458
- }), addEntry({
459
- entryName: 'hostInit',
460
- entryPath: emptyPath + '?__mf__isHostInit'
461
- }), [overrideModule({
462
- override: Object.keys(shared)
463
- }), {
464
- name: 'module-federation-vite',
465
- enforce: 'post',
344
+ return {
345
+ name: "proxyRemotes",
466
346
  config: function config(_config, _ref) {
467
- var _config$resolve$alias, _config$optimizeDeps;
468
347
  var _command = _ref.command;
469
- con = _config;
470
348
  command = _command;
471
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, alias);
472
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
473
- Object.keys(shared).forEach(function (key) {
474
- var _config$optimizeDeps2;
475
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(key);
349
+ Object.keys(remotes).forEach(function (key) {
350
+ var remote = remotes[key];
351
+ _config.resolve.alias.push({
352
+ find: new RegExp("(" + remote.name + "(/.*|$)?)"),
353
+ replacement: '$1',
354
+ customResolver: function customResolver(source) {
355
+ if (!_config.optimizeDeps) _config.optimizeDeps = {};
356
+ if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
357
+ if (_config.optimizeDeps.needsInterop.indexOf(source) === -1) _config.optimizeDeps.needsInterop.push(source);
358
+ return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
359
+ }
360
+ });
476
361
  });
477
362
  },
478
- resolveId: function resolveId(id) {
479
- if (id === '__mf__cwdRemoteEntry') {
480
- return '__mf__cwdRemoteEntry';
481
- }
482
- },
483
- load: function load(id) {
484
- if (id === '__mf__cwdRemoteEntry') {
485
- return generateRemoteEntry(options);
486
- }
487
- },
488
363
  transform: function transform(code, id) {
489
364
  try {
490
365
  if (!filter(id)) return Promise.resolve();
491
- if (id === '__mf__cwdRemoteEntry') {
492
- return Promise.resolve(generateRemoteEntry(options));
493
- }
494
- if (id.indexOf('__mf__wrapRemoteEntry__') > -1) {
495
- return Promise.resolve(wrapRemoteEntry());
496
- }
497
- if (id.indexOf('__mf__isHostInit') > -1) {
498
- return Promise.resolve(wrapHostInit());
499
- }
500
- if (id.indexOf('__mf__cwdRemoteEntry') > -1) {
501
- return Promise.resolve(generateRemoteEntry(options));
502
- }
503
- var _ref2 = sharedKeyMatchList.length && id.match(new RegExp("/(" + sharedKeyMatchList.join('|') + ")(_.*.js|.js)")) || [],
504
- devSharedModuleName = _ref2[0];
505
- if (devSharedModuleName) {
506
- return Promise.resolve(wrapShare(devSharedModuleName.replace('/__overrideModule__', '').replace(/_/g, '/').replace('.js', ''), shared));
507
- }
508
- var _ref3 = id.match(/\_\_overrideModule\_\_=[^&]+/) || [],
509
- prodSharedName = _ref3[0];
510
- if (prodSharedName) {
511
- return Promise.resolve(wrapShare(decodeURIComponent(prodSharedName.replace('__overrideModule__=', '')), shared));
512
- }
513
- var _ref4 = remotePrefixList.length && id.match(new RegExp("/(" + remotePrefixList.join('|') + ")(_.*.js|.js)")) || [],
514
- devRemoteModuleName = _ref4[0];
366
+ var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
367
+ devRemoteModuleName = _ref2[0];
515
368
  if (devRemoteModuleName) {
516
- return Promise.resolve(wrapRemote(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', '')));
369
+ return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
517
370
  }
518
- var _ref5 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
519
- prodRemoteName = _ref5[0];
371
+ var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
372
+ prodRemoteName = _ref3[0];
520
373
  if (prodRemoteName) {
521
- return Promise.resolve(wrapRemote(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', ''))));
374
+ return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
522
375
  }
523
376
  return Promise.resolve();
524
377
  } catch (e) {
525
378
  return Promise.reject(e);
526
379
  }
527
380
  }
381
+ };
382
+ }
383
+
384
+ function proxySharedModule(options) {
385
+ var _options$shared = options.shared,
386
+ shared = _options$shared === void 0 ? {} : _options$shared,
387
+ include = options.include,
388
+ exclude = options.exclude;
389
+ var filterFunction = createFilter(include, exclude);
390
+ writeLocalSharedImportMap(Object.keys(shared));
391
+ return [{
392
+ name: 'preBuildShared',
393
+ enforce: 'post',
394
+ config: function config(_config, _ref) {
395
+ var _config$resolve$alias, _config$resolve$alias2;
396
+ var command = _ref.command;
397
+ // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
398
+ // config.optimizeDeps.needsInterop.push('an-empty-js-file');
399
+ (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
400
+ var _config$optimizeDeps;
401
+ _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
402
+ // write proxyFile
403
+ writeLoadShareModule(key, shared[key], command);
404
+ var preBuildLibPath = getLoadShareModulePath(key);
405
+ return {
406
+ // Intercept all dependency requests to the proxy module
407
+ // Dependency requests issued by localSharedImportMap are allowed without proxying.
408
+ find: new RegExp("^" + key + "$"),
409
+ replacement: preBuildLibPath,
410
+ customResolver: function customResolver(source, importer) {
411
+ if (importer.includes("node_modules/" + key + "/")) {
412
+ return this.resolve(key);
413
+ }
414
+ return this.resolve(preBuildLibPath);
415
+ }
416
+ };
417
+ }));
418
+ (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
419
+ return {
420
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
421
+ customResolver: function customResolver(source, importer) {
422
+ return this.resolve(key);
423
+ }
424
+ };
425
+ }));
426
+ }
427
+ }, {
428
+ name: "prebuild-top-level-await",
429
+ apply: "serve",
430
+ transform: function transform(code, id) {
431
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
432
+ return null;
433
+ }
434
+ if (!filterFunction(id)) return null;
435
+ var ast;
436
+ try {
437
+ ast = this.parse(code, {
438
+ allowReturnOutsideFunction: true
439
+ });
440
+ } catch (e) {
441
+ throw new Error(id + ": " + e);
442
+ }
443
+ var magicString = new MagicString(code);
444
+ walk(ast, {
445
+ enter: function enter(node) {
446
+ // 处理命名导出
447
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
448
+ var exportSpecifiers = node.specifiers.map(function (specifier) {
449
+ return specifier.exported.name;
450
+ });
451
+ var proxyStatements = exportSpecifiers.map(function (name) {
452
+ return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
453
+ }).join('\n');
454
+ var exportStatements = exportSpecifiers.map(function (name) {
455
+ return "__mfproxy__" + name + " as " + name;
456
+ }).join(', ');
457
+ var start = node.start;
458
+ var end = node.end;
459
+ var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
460
+ magicString.overwrite(start, end, replacement);
461
+ }
462
+ // 处理默认导出
463
+ if (node.type === 'ExportDefaultDeclaration') {
464
+ var declaration = node.declaration;
465
+ var _start = node.start;
466
+ var _end = node.end;
467
+ var proxyStatement;
468
+ var exportStatement = 'default';
469
+ if (declaration.type === 'Identifier') {
470
+ // 处理标识符 (如: export default foo;)
471
+ proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
472
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
473
+ // 处理调用表达式或函数声明 (如: export default someFunction();)
474
+ var declarationCode = code.slice(declaration.start, declaration.end);
475
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
476
+ } else {
477
+ // 其他类型 (可以根据需要添加更多处理逻辑)
478
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
479
+ }
480
+ var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
481
+ magicString.overwrite(_start, _end, _replacement);
482
+ }
483
+ }
484
+ });
485
+ return {
486
+ code: magicString.toString(),
487
+ map: magicString.generateMap({
488
+ hires: true
489
+ })
490
+ };
491
+ }
492
+ }];
493
+ }
494
+
495
+ var aliasToArrayPlugin = {
496
+ name: 'alias-transform-plugin',
497
+ config: function config(_config, _ref) {
498
+ if (!_config.resolve) _config.resolve = {};
499
+ if (!_config.resolve.alias) _config.resolve.alias = [];
500
+ var alias = _config.resolve.alias;
501
+ if (typeof alias === 'object' && !Array.isArray(alias)) {
502
+ _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
503
+ var find = _ref2[0],
504
+ replacement = _ref2[1];
505
+ return {
506
+ find: find,
507
+ replacement: replacement
508
+ };
509
+ });
510
+ }
511
+ }
512
+ };
513
+
514
+ var normalizeBuildPlugin = (function (singleChunkModules) {
515
+ return {
516
+ name: 'normalizeBuild',
517
+ config: function config(_config, _ref) {
518
+ if (!_config.build) _config.build = {};
519
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
520
+ var rollupOptions = _config.build.rollupOptions;
521
+ if (!rollupOptions.output) rollupOptions.output = {};
522
+ normalizeManualChunks(rollupOptions.output, singleChunkModules);
523
+ }
524
+ };
525
+ });
526
+ function normalizeManualChunks(output, singleChunkModules) {
527
+ var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
528
+ if (!output.manualChunks) output.manualChunks = {};
529
+ var wrapManualChunks = function wrapManualChunks(original) {
530
+ return function (id) {
531
+ var _ref2 = id.match(pattern) || [],
532
+ moduleName = _ref2[1];
533
+ if (moduleName) {
534
+ return moduleName;
535
+ }
536
+ if (typeof original === 'function') {
537
+ return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
538
+ }
539
+ if (typeof original === 'object' && original) {
540
+ return original[id];
541
+ }
542
+ };
543
+ };
544
+ output.manualChunks = wrapManualChunks(output.manualChunks);
545
+ }
546
+
547
+ var normalizeOptimizeDepsPlugin = {
548
+ name: 'normalizeOptimizeDeps',
549
+ config: function config(_config, _ref) {
550
+ var optimizeDeps = _config.optimizeDeps;
551
+ if (!optimizeDeps) {
552
+ _config.optimizeDeps = {};
553
+ optimizeDeps = _config.optimizeDeps;
554
+ }
555
+ if (!optimizeDeps.include) optimizeDeps.include = [];
556
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
557
+ }
558
+ };
559
+
560
+ function federation(mfUserOptions) {
561
+ var options = normalizeModuleFederationOptions(mfUserOptions);
562
+ var name = options.name,
563
+ shared = options.shared,
564
+ filename = options.filename;
565
+ if (!name) throw new Error("name is required");
566
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
567
+ entryName: 'remoteEntry',
568
+ entryPath: WRAP_REMOTE_ENTRY_PATH,
569
+ fileName: filename
570
+ }), addEntry({
571
+ entryName: 'hostInit',
572
+ entryPath: HOST_AUTO_INIT
573
+ }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], proxySharedModule({
574
+ shared: shared
575
+ }), [{
576
+ name: 'module-federation-vite',
577
+ enforce: 'post',
578
+ config: function config(_config, _ref) {
579
+ var _config$optimizeDeps;
580
+ _config.resolve.alias.push({
581
+ find: '@module-federation/runtime',
582
+ replacement: require.resolve('@module-federation/runtime')
583
+ });
584
+ (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
585
+ // Object.keys(shared).forEach((key) => {
586
+ // config.optimizeDeps?.include?.push(key);
587
+ // });
588
+ }
528
589
  }]);
529
590
  }
530
591