@module-federation/vite 1.0.0-alpha-80b7215 → 1.0.0-alpha-def937d

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