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