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