@module-federation/vite 1.0.0-alpha-c13dc95 → 1.0.0-alpha-b1bba84

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,9 +1,9 @@
1
1
  var fs = require('fs');
2
2
  var path = require('pathe');
3
3
  var pluginutils = require('@rollup/pluginutils');
4
- var defu = require('defu');
5
4
  var estreeWalker = require('estree-walker');
6
5
  var MagicString = require('magic-string');
6
+ var defu = require('defu');
7
7
 
8
8
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
9
 
@@ -37,9 +37,14 @@ var addEntry = function addEntry(_ref) {
37
37
  var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
38
38
  var entryFiles = [];
39
39
  var htmlFilePath;
40
+ var _command;
40
41
  return [{
41
42
  name: 'add-entry',
42
43
  apply: "serve",
44
+ config: function config(_config, _ref2) {
45
+ var command = _ref2.command;
46
+ _command = command;
47
+ },
43
48
  configureServer: function configureServer(server) {
44
49
  var _server$httpServer;
45
50
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
@@ -63,7 +68,6 @@ var addEntry = function addEntry(_ref) {
63
68
  }, {
64
69
  name: "add-entry",
65
70
  enforce: "post",
66
- apply: "build",
67
71
  configResolved: function configResolved(config) {
68
72
  var inputOptions = config.build.rollupOptions.input;
69
73
  if (!inputOptions) {
@@ -81,6 +85,7 @@ var addEntry = function addEntry(_ref) {
81
85
  },
82
86
  buildStart: function buildStart() {
83
87
  var _this$emitFile;
88
+ if (_command === "serve") return;
84
89
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
85
90
  this.emitFile((_this$emitFile = {
86
91
  name: entryName
@@ -105,46 +110,105 @@ var addEntry = function addEntry(_ref) {
105
110
  }];
106
111
  };
107
112
 
108
- var _resolve,
109
- promise = new Promise(function (resolve, reject) {
110
- _resolve = resolve;
111
- });
112
- var parsePromise = promise;
113
- var parseStartSet = new Set();
114
- var parseEndSet = new Set();
115
- function pluginModuleParseEnd (excludeFn) {
116
- return [{
117
- name: "_",
113
+ /**
114
+ * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
115
+ */
116
+ function PluginDevProxyModuleTopLevelAwait() {
117
+ var filterFunction = pluginutils.createFilter();
118
+ return {
119
+ name: "dev-proxy-module-top-level-await",
118
120
  apply: "serve",
119
- config: function config() {
120
- // No waiting in development mode
121
- _resolve(1);
122
- }
123
- }, {
124
- enforce: "pre",
125
- name: "parseStart",
126
- apply: "build",
127
- load: function load(id) {
128
- if (excludeFn(id)) {
129
- return;
130
- }
131
- parseStartSet.add(id);
132
- }
133
- }, {
134
- enforce: "post",
135
- name: "parseEnd",
136
- apply: "build",
137
- moduleParsed: function moduleParsed(module) {
138
- var id = module.id;
139
- if (excludeFn(id)) {
140
- return;
121
+ transform: function transform(code, id) {
122
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
123
+ return null;
141
124
  }
142
- parseEndSet.add(id);
143
- if (parseStartSet.size === parseEndSet.size) {
144
- _resolve(1);
125
+ if (!filterFunction(id)) return null;
126
+ var ast;
127
+ try {
128
+ ast = this.parse(code, {
129
+ allowReturnOutsideFunction: true
130
+ });
131
+ } catch (e) {
132
+ throw new Error(id + ": " + e);
145
133
  }
134
+ var magicString = new MagicString__default["default"](code);
135
+ estreeWalker.walk(ast, {
136
+ enter: function enter(node) {
137
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
138
+ var exportSpecifiers = node.specifiers.map(function (specifier) {
139
+ return specifier.exported.name;
140
+ });
141
+ var proxyStatements = exportSpecifiers.map(function (name) {
142
+ return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
143
+ }).join('\n');
144
+ var exportStatements = exportSpecifiers.map(function (name) {
145
+ return "__mfproxy__" + name + " as " + name;
146
+ }).join(', ');
147
+ var start = node.start;
148
+ var end = node.end;
149
+ var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
150
+ magicString.overwrite(start, end, replacement);
151
+ }
152
+ if (node.type === 'ExportDefaultDeclaration') {
153
+ var declaration = node.declaration;
154
+ var _start = node.start;
155
+ var _end = node.end;
156
+ var proxyStatement;
157
+ var exportStatement = 'default';
158
+ if (declaration.type === 'Identifier') {
159
+ // example: export default foo;
160
+ proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
161
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
162
+ // example: export default someFunction();
163
+ var declarationCode = code.slice(declaration.start, declaration.end);
164
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
165
+ } else {
166
+ // other
167
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
168
+ }
169
+ var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
170
+ magicString.overwrite(_start, _end, _replacement);
171
+ }
172
+ }
173
+ });
174
+ return {
175
+ code: magicString.toString(),
176
+ map: magicString.generateMap({
177
+ hires: true
178
+ })
179
+ };
146
180
  }
147
- }];
181
+ };
182
+ }
183
+
184
+ function _arrayLikeToArray(r, a) {
185
+ (null == a || a > r.length) && (a = r.length);
186
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
187
+ return n;
188
+ }
189
+ function _createForOfIteratorHelperLoose(r, e) {
190
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
191
+ if (t) return (t = t.call(r)).next.bind(t);
192
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
193
+ t && (r = t);
194
+ var o = 0;
195
+ return function () {
196
+ return o >= r.length ? {
197
+ done: !0
198
+ } : {
199
+ done: !1,
200
+ value: r[o++]
201
+ };
202
+ };
203
+ }
204
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
205
+ }
206
+ function _unsupportedIterableToArray(r, a) {
207
+ if (r) {
208
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
209
+ var t = {}.toString.call(r).slice(8, -1);
210
+ 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;
211
+ }
148
212
  }
149
213
 
150
214
  function normalizeExposesItem(key, item) {
@@ -197,7 +261,7 @@ function normalizeRemoteItem(key, remote) {
197
261
  entryGlobalName: key
198
262
  }, remote);
199
263
  }
200
- function removePathFromNpmPackage$1(packageString) {
264
+ function removePathFromNpmPackage(packageString) {
201
265
  // 匹配npm包名的正则表达式,忽略路径部分
202
266
  var regex = /^(?:@[^/]+\/)?[^/]+/;
203
267
  // 使用正则表达式匹配并提取包名
@@ -208,7 +272,7 @@ function removePathFromNpmPackage$1(packageString) {
208
272
  function normalizeShareItem(key, shareItem) {
209
273
  var version;
210
274
  try {
211
- version = require(path__namespace.join(removePathFromNpmPackage$1(key), 'package.json')).version;
275
+ version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
212
276
  } catch (e) {
213
277
  console.log(e);
214
278
  }
@@ -256,10 +320,28 @@ function normalizeLibrary(library) {
256
320
  if (!library) return undefined;
257
321
  return library;
258
322
  }
323
+ function normalizeManifest(manifest) {
324
+ if (manifest === void 0) {
325
+ manifest = false;
326
+ }
327
+ if (typeof manifest === "boolean") {
328
+ return manifest;
329
+ }
330
+ return Object.assign({
331
+ filePath: "",
332
+ disableAssetsAnalyze: false,
333
+ fileName: "mf-manifest.json"
334
+ }, manifest);
335
+ }
259
336
  var config;
260
337
  function getNormalizeModuleFederationOptions() {
261
338
  return config;
262
339
  }
340
+ function getNormalizeShareItem(key) {
341
+ var options = getNormalizeModuleFederationOptions();
342
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
343
+ return shareItem;
344
+ }
263
345
  function normalizeModuleFederationOptions(options) {
264
346
  return config = {
265
347
  exposes: normalizeExposes(options.exposes),
@@ -274,7 +356,7 @@ function normalizeModuleFederationOptions(options) {
274
356
  runtimePlugins: options.runtimePlugins || [],
275
357
  getPublicPath: options.getPublicPath,
276
358
  implementation: options.implementation,
277
- manifest: options.manifest,
359
+ manifest: normalizeManifest(options.manifest),
278
360
  dev: options.dev,
279
361
  dts: options.dts
280
362
  };
@@ -289,33 +371,42 @@ function normalizeModuleFederationOptions(options) {
289
371
  * . => 4
290
372
  */
291
373
  /**
292
- * @param {*} name "@scope/xx-xx.xx" => "__$1__scope__$2__xx__$3__xx$__4__xx"
374
+ * Encodes a package name into a valid file name.
375
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
376
+ * @returns {string} - The encoded file name.
293
377
  */
294
378
  function packageNameEncode(name) {
295
379
  if (typeof name !== "string") throw new Error("A string package name is required");
296
- return name.replace(/\@/g, "__$1__").replace(/\//g, "__$2__").replace(/\-/g, "__$3__").replace(/\./g, "__$4__");
380
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
297
381
  }
298
382
  /**
299
- * @param {*} global "__$1__scope__$2__xx__$3__xx$__4__xx" => "@scope/xx-xx.xx"
383
+ * Decodes an encoded file name back to the original package name.
384
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
385
+ * @returns {string} - The decoded package name.
300
386
  */
301
- function packageNameDecode(global) {
302
- if (typeof global !== "string") throw new Error("A string global variable name is required");
303
- return global.replace(/\_\_\$1\_\_/g, "@").replace(/\_\_\$2\_\_/g, "/").replace(/\_\_\$3\_\_/g, "-").replace(/\_\_\$4\_\_/g, ".");
387
+ function packageNameDecode(encoded) {
388
+ if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
389
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
304
390
  }
305
- function removePathFromNpmPackage(packageString) {
306
- // Regular expression to match npm package name, ignoring path parts
307
- var regex = /^(?:@[^/]+\/)?[^/]+/;
308
- // Use regular expression to match and extract the package name
309
- var match = packageString.match(regex);
310
- // Return the matched package name or the original string if no match is found
311
- return match ? match[0] : packageString;
391
+
392
+ /**
393
+ * https://github.com/module-federation/vite/issues/68
394
+ */
395
+ function getLocalSharedImportMapPath_windows() {
396
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
397
+ name = _getNormalizeModuleFe.name;
398
+ return path__default["default"].resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
312
399
  }
313
- function getExtFromNpmPackage(packageString) {
314
- var pkgName = removePathFromNpmPackage(packageString);
315
- var subpath = packageString.replace(pkgName, "");
316
- var parts = subpath.split('.');
317
- var ext = parts.length > 1 ? "." + parts.pop() : undefined;
318
- return ext;
400
+ function writeLocalSharedImportMap_windows(content) {
401
+ var localSharedImportMapId = getLocalSharedImportMapPath_windows();
402
+ createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
403
+ }
404
+ function createFile(filePath, content) {
405
+ var dir = path__default["default"].dirname(filePath);
406
+ fs.mkdirSync(dir, {
407
+ recursive: true
408
+ });
409
+ fs.writeFileSync(filePath, content);
319
410
  }
320
411
 
321
412
  var nodeModulesDir = function findNodeModulesDir(startDir) {
@@ -341,28 +432,47 @@ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "package.json"
341
432
  name: virtualPackageName,
342
433
  main: "empty.js"
343
434
  }));
435
+ var patternMap = {};
436
+ var cacheMap = {};
344
437
  /**
345
438
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
346
439
  */
347
440
  var VirtualModule = /*#__PURE__*/function () {
348
- function VirtualModule(name, ext) {
349
- if (ext === void 0) {
350
- ext = ".js";
441
+ function VirtualModule(name, tag, suffix) {
442
+ var _name$split$slice$pop;
443
+ if (tag === void 0) {
444
+ tag = '__mf_v__';
351
445
  }
352
- this.originName = void 0;
446
+ if (suffix === void 0) {
447
+ suffix = "";
448
+ }
449
+ this.name = void 0;
450
+ this.tag = void 0;
451
+ this.suffix = void 0;
353
452
  this.inited = false;
354
- this.ext = void 0;
355
- this.originName = name;
356
- this.ext = ext;
453
+ this.name = name;
454
+ this.tag = tag;
455
+ this.suffix = suffix || ((_name$split$slice$pop = name.split(".").slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, ".$1")) || ".js";
456
+ if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
457
+ cacheMap[this.tag][this.name] = this;
357
458
  }
459
+ VirtualModule.findModule = function findModule(tag, str) {
460
+ if (str === void 0) {
461
+ str = "";
462
+ }
463
+ if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
464
+ var moduleName = (str.match(patternMap[tag]) || [])[2];
465
+ if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
466
+ return undefined;
467
+ };
358
468
  var _proto = VirtualModule.prototype;
359
469
  _proto.getPath = function getPath() {
360
470
  return path.resolve(nodeModulesDir, this.getImportId());
361
471
  };
362
472
  _proto.getImportId = function getImportId() {
363
473
  var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
364
- name = _getNormalizeModuleFe.name;
365
- return virtualPackageName + "/" + packageNameEncode(name) + "-" + packageNameEncode(this.originName) + this.ext;
474
+ mfName = _getNormalizeModuleFe.name;
475
+ return virtualPackageName + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
366
476
  };
367
477
  _proto.writeSync = function writeSync(code, force) {
368
478
  if (!force && this.inited) return;
@@ -377,24 +487,33 @@ var VirtualModule = /*#__PURE__*/function () {
377
487
  return VirtualModule;
378
488
  }();
379
489
 
380
- /**
381
- * https://github.com/module-federation/vite/issues/68
382
- */
383
- function getLocalSharedImportMapPath_windows() {
384
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
385
- name = _getNormalizeModuleFe.name;
386
- return path__default["default"].resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
490
+ var virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
491
+ function writeRuntimeInitStatus() {
492
+ virtualRuntimeInitStatus.writeSync("\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n export {\n initPromise,\n initResolve,\n initReject\n }\n ");
387
493
  }
388
- function writeLocalSharedImportMap_windows(content) {
389
- var localSharedImportMapId = getLocalSharedImportMapPath_windows();
390
- createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
494
+
495
+ var cacheRemoteMap = {};
496
+ var LOAD_REMOTE_TAG = '__loadRemote__';
497
+ function getRemoteVirtualModule(remote, command) {
498
+ if (!cacheRemoteMap[remote]) {
499
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
500
+ cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
501
+ }
502
+ var virtual = cacheRemoteMap[remote];
503
+ return virtual;
391
504
  }
392
- function createFile(filePath, content) {
393
- var dir = path__default["default"].dirname(filePath);
394
- fs.mkdirSync(dir, {
395
- recursive: true
396
- });
397
- fs.writeFileSync(filePath, content);
505
+ var usedRemotesMap = {
506
+ // remote1: {remote1/App, remote1, remote1/Button}
507
+ };
508
+ function addUsedRemote(remoteKey, remoteModule) {
509
+ if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
510
+ usedRemotesMap[remoteKey].add(remoteModule);
511
+ }
512
+ function getUsedRemotesMap() {
513
+ return usedRemotesMap;
514
+ }
515
+ function generateRemotes(id, command) {
516
+ return "\n const {loadRemote} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
398
517
  }
399
518
 
400
519
  /**
@@ -403,63 +522,35 @@ function createFile(filePath, content) {
403
522
  * You can only proxy to the real file through alias
404
523
  */
405
524
  // *** __prebuild__
406
-
407
- var generateLocalSharedImportMap = function generateLocalSharedImportMap() {
408
- return Promise.resolve(parsePromise).then(function () {
409
- var options = getNormalizeModuleFederationOptions();
410
- return "\n const localSharedImportMap = {\n " + Array.from(shareds).map(function (pkg) {
411
- return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
412
- }).join(",") + "\n }\n const localShared = {\n " + Array.from(shareds).map(function (key) {
413
- var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
414
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
415
- }).join(',') + "\n }\n export default localShared\n ";
416
- });
417
- };
418
- // *** __loadShare__
419
- var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
420
- try {
421
- var _exit;
422
- var sharedCount = shareds.size;
423
- return Promise.resolve(function () {
424
- if (prevSharedCount !== sharedCount) {
425
- var _temp2 = function _temp2(_result) {
426
- if (_exit) return _result;
427
- var _writeSync = localSharedImportMapModule.writeSync;
428
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI2) {
429
- return _writeSync.call(localSharedImportMapModule, _generateLocalSharedI2, true);
430
- });
431
- };
432
- prevSharedCount = sharedCount;
433
- var _temp = function () {
434
- if (process.platform === "win32") {
435
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI) {
436
- var _writeLocalSharedImpo = writeLocalSharedImportMap_windows(_generateLocalSharedI);
437
- _exit = 1;
438
- return _writeLocalSharedImpo;
439
- });
440
- }
441
- }();
442
- return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
443
- }
444
- }());
445
- } catch (e) {
446
- return Promise.reject(e);
447
- }
448
- };
449
525
  var preBuildCacheMap = {};
450
526
  var PREBUILD_TAG = "__prebuild__";
451
527
  function writePreBuildLibPath(pkg) {
452
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
528
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
453
529
  preBuildCacheMap[pkg].writeSync("");
454
530
  }
455
531
  function getPreBuildLibImportId(pkg) {
456
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
532
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
457
533
  var importId = preBuildCacheMap[pkg].getImportId();
458
534
  return importId;
459
535
  }
460
- var shareds = new Set();
461
- function addShare(pkg) {
462
- shareds.add(pkg);
536
+ // *** __loadShare__
537
+ var LOAD_SHARE_TAG = "__loadShare__";
538
+ var loadShareCacheMap = {};
539
+ function getLoadShareModulePath(pkg) {
540
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
541
+ var filepath = loadShareCacheMap[pkg].getPath();
542
+ return filepath;
543
+ }
544
+ function writeLoadShareModule(pkg, shareItem, command) {
545
+ loadShareCacheMap[pkg].writeSync("\n \n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== "build" ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {loadShare} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => 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 ");
546
+ }
547
+
548
+ var usedShares = new Set();
549
+ function getUsedShares() {
550
+ return usedShares;
551
+ }
552
+ function addUsedShares(pkg) {
553
+ usedShares.add(pkg);
463
554
  }
464
555
  // *** Expose locally provided shared modules here
465
556
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
@@ -469,33 +560,42 @@ function getLocalSharedImportMapPath() {
469
560
  }
470
561
  return localSharedImportMapModule.getPath();
471
562
  }
472
- var prevSharedCount = 0;
473
- var LOAD_SHARE_TAG = "__loadShare__";
474
- var loadShareCacheMap = {};
475
- function getLoadShareModulePath(pkg) {
476
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
477
- var filepath = loadShareCacheMap[pkg].getPath();
478
- return filepath;
563
+ var prevSharedCount;
564
+ function writeLocalSharedImportMap() {
565
+ var sharedCount = getUsedShares().size;
566
+ if (prevSharedCount !== sharedCount) {
567
+ prevSharedCount = sharedCount;
568
+ if (process.platform === "win32") {
569
+ writeLocalSharedImportMap_windows(generateLocalSharedImportMap());
570
+ } else {
571
+ localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true);
572
+ }
573
+ }
479
574
  }
480
- function writeLoadShareModule(pkg, shareItem, command) {
481
- loadShareCacheMap[pkg].writeSync("\n () => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== "build" ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {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 ");
575
+ function generateLocalSharedImportMap() {
576
+ var options = getNormalizeModuleFederationOptions();
577
+ return "\n const importMap = {\n " + Array.from(getUsedShares()).map(function (pkg) {
578
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
579
+ }).join(",") + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
580
+ var shareItem = getNormalizeShareItem(key);
581
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap \n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
582
+ }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
583
+ var remote = options.remotes[key];
584
+ 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 ";
585
+ }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
482
586
  }
483
-
484
587
  var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
485
588
  function generateRemoteEntry(options) {
486
589
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
487
590
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
488
591
  });
489
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n \n " + pluginImportNames.map(function (item) {
592
+ return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
490
593
  return item[1];
491
594
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
492
595
  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 ";
493
- }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapPath() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
494
- var remote = options.remotes[key];
495
- 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 ";
496
- }).join(',') + "\n ],\n shared: localSharedImportMap,\n plugins: [" + pluginImportNames.map(function (item) {
596
+ }).join(',') + "\n }\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
497
597
  return item[0] + "()";
498
- }).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 ";
598
+ }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
499
599
  }
500
600
  /**
501
601
  * Inject entry file, automatically init when used as host,
@@ -512,26 +612,401 @@ function getHostAutoInitPath() {
512
612
  return hostAutoInitModule.getPath();
513
613
  }
514
614
 
515
- var remoteVirtualModule = new VirtualModule("remoteModule");
516
- function writeRemote() {
517
- remoteVirtualModule.writeSync("");
518
- }
519
- function generateRemotes(id, command) {
520
- return {
521
- 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 ",
522
- map: null,
523
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
524
- syntheticNamedExports: '__mf__dynamicExports'
525
- };
526
- }
527
-
528
615
  function initVirtualModules() {
529
616
  writeLocalSharedImportMap();
530
617
  writeHostAutoInit();
531
- writeRemote();
618
+ writeRuntimeInitStatus();
532
619
  }
533
620
 
534
- var filter$1 = pluginutils.createFilter();
621
+ var Manifest = function Manifest() {
622
+ var mfOptions = getNormalizeModuleFederationOptions();
623
+ var name = mfOptions.name,
624
+ filename = mfOptions.filename,
625
+ manifestOptions = mfOptions.manifest;
626
+ var mfManifestName = "";
627
+ if (manifestOptions === true) {
628
+ mfManifestName = "mf-manifest.json";
629
+ }
630
+ if (typeof manifestOptions !== "boolean") {
631
+ mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || "", (manifestOptions == null ? void 0 : manifestOptions.fileName) || "");
632
+ }
633
+ var extensions;
634
+ var root;
635
+ var remoteEntryFile;
636
+ return [{
637
+ name: 'moddule-federation-manifest',
638
+ apply: 'serve',
639
+ configureServer: function configureServer(server) {
640
+ server.middlewares.use(function (req, res, next) {
641
+ if (!mfManifestName) {
642
+ next();
643
+ return;
644
+ }
645
+ if (req.url === mfManifestName.replace(/^\/?/, "/")) {
646
+ res.setHeader('Content-Type', 'application/json');
647
+ res.setHeader('Access-Control-Allow-Origin', '*');
648
+ res.end(JSON.stringify({
649
+ id: name,
650
+ name: name,
651
+ metaData: {
652
+ name: name,
653
+ type: 'app',
654
+ buildInfo: {
655
+ buildVersion: '1.0.0',
656
+ buildName: name
657
+ },
658
+ remoteEntry: {
659
+ name: filename,
660
+ path: '',
661
+ type: 'module'
662
+ },
663
+ ssrRemoteEntry: {
664
+ name: filename,
665
+ path: '',
666
+ type: 'module'
667
+ },
668
+ types: {
669
+ path: '',
670
+ name: ''
671
+ },
672
+ globalName: name,
673
+ pluginVersion: '0.2.5',
674
+ publicPath: 'auto'
675
+ },
676
+ shared: Array.from(getUsedShares()).map(function (shareKey) {
677
+ var shareItem = getNormalizeShareItem(shareKey);
678
+ return {
679
+ id: name + ":" + shareKey,
680
+ name: shareKey,
681
+ version: shareItem.version,
682
+ requiredVersion: shareItem.shareConfig.requiredVersion,
683
+ assets: {
684
+ js: {
685
+ async: [],
686
+ sync: []
687
+ },
688
+ css: {
689
+ async: [],
690
+ sync: []
691
+ }
692
+ }
693
+ };
694
+ }),
695
+ remotes: function () {
696
+ var remotes = [];
697
+ var usedRemotesMap = getUsedRemotesMap();
698
+ Object.keys(usedRemotesMap).forEach(function (remoteKey) {
699
+ var usedModules = Array.from(usedRemotesMap[remoteKey]);
700
+ usedModules.forEach(function (moduleKey) {
701
+ remotes.push({
702
+ federationContainerName: mfOptions.remotes[remoteKey].entry,
703
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
704
+ alias: remoteKey,
705
+ entry: '*'
706
+ });
707
+ });
708
+ });
709
+ return remotes;
710
+ }(),
711
+ exposes: Object.keys(mfOptions.exposes).map(function (key) {
712
+ var formatKey = key.replace('./', '');
713
+ return {
714
+ id: name + ':' + formatKey,
715
+ name: formatKey,
716
+ assets: {
717
+ js: {
718
+ async: [],
719
+ sync: []
720
+ },
721
+ css: {
722
+ sync: [],
723
+ async: []
724
+ }
725
+ },
726
+ path: key
727
+ };
728
+ })
729
+ }));
730
+ } else {
731
+ next();
732
+ }
733
+ });
734
+ }
735
+ }, {
736
+ name: 'moddule-federation-manifest',
737
+ enforce: 'post',
738
+ config: function config(_config) {
739
+ if (!_config.build) _config.build = {};
740
+ if (!_config.build.manifest) _config.build.manifest = _config.build.manifest || !!manifestOptions;
741
+ },
742
+ configResolved: function configResolved(config) {
743
+ root = config.root;
744
+ extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
745
+ },
746
+ generateBundle: function generateBundle(options, bundle) {
747
+ try {
748
+ var _this = this;
749
+ // 递归查找模块的同步导入文件
750
+ var _findSynchronousImports = function findSynchronousImports(fileName, array) {
751
+ var fileData = bundle[fileName];
752
+ if (fileData && fileData.type === 'chunk') {
753
+ array.push(fileName); // 将当前文件加入预加载列表
754
+ // 遍历该文件的同步导入文件
755
+ fileData.imports.forEach(function (importedFile) {
756
+ if (array.indexOf(importedFile) === -1) {
757
+ _findSynchronousImports(importedFile, array); // 递归查找同步导入的文件
758
+ }
759
+ });
760
+ }
761
+ };
762
+ if (!mfManifestName) return Promise.resolve();
763
+ var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
764
+ return mfOptions.exposes[item]["import"];
765
+ }); // 获取你提供的 moduleIds
766
+ var filesContainingModules = {};
767
+ // 帮助函数:检查模块路径是否匹配
768
+ var isModuleMatched = function isModuleMatched(relativeModulePath, preloadModule) {
769
+ // 先尝试直接匹配
770
+ if (relativeModulePath === preloadModule) return true;
771
+ // 如果 preloadModule 没有后缀,尝试添加可能的后缀进行匹配
772
+ for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
773
+ var ext = _step.value;
774
+ if (relativeModulePath === "" + preloadModule + ext) {
775
+ return true;
776
+ }
777
+ }
778
+ return false;
779
+ };
780
+ // 遍历打包生成的每个文件
781
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
782
+ var _Object$entries$_i = _Object$entries[_i],
783
+ fileName = _Object$entries$_i[0],
784
+ fileData = _Object$entries$_i[1];
785
+ if (mfOptions.filename.replace(/[\[\]]/g, "_") === fileData.name) {
786
+ remoteEntryFile = fileData.fileName;
787
+ }
788
+ if (fileData.type === 'chunk') {
789
+ // 遍历该文件的所有模块
790
+ for (var _i2 = 0, _Object$keys = Object.keys(fileData.modules); _i2 < _Object$keys.length; _i2++) {
791
+ var modulePath = _Object$keys[_i2];
792
+ // 将绝对路径转换为相对于 Vite root 的相对路径
793
+ var relativeModulePath = path.relative(root, modulePath);
794
+ // 检查模块是否在 preloadModules 列表中
795
+ for (var _iterator2 = _createForOfIteratorHelperLoose(exposesModules), _step2; !(_step2 = _iterator2()).done;) {
796
+ var preloadModule = _step2.value;
797
+ var formatPreloadModule = preloadModule.replace("./", "");
798
+ if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
799
+ var _filesContainingModul;
800
+ if (!filesContainingModules[preloadModule]) {
801
+ filesContainingModules[preloadModule] = {
802
+ sync: [],
803
+ async: []
804
+ };
805
+ }
806
+ console.log(Object.keys(fileData.modules));
807
+ filesContainingModules[preloadModule].sync.push(fileName);
808
+ (_filesContainingModul = filesContainingModules[preloadModule].async).push.apply(_filesContainingModul, fileData.dynamicImports || []);
809
+ _findSynchronousImports(fileName, filesContainingModules[preloadModule].sync);
810
+ break; // 如果找到匹配,跳出循环
811
+ }
812
+ }
813
+ }
814
+ }
815
+ }
816
+ ;
817
+ var fileToShareKey = {};
818
+ return Promise.resolve(Promise.all(Array.from(getUsedShares()).map(function (shareKey) {
819
+ try {
820
+ return Promise.resolve(_this.resolve(getPreBuildLibImportId(shareKey))).then(function (_this$resolve) {
821
+ var file = _this$resolve.id.split("?")[0];
822
+ fileToShareKey[file] = shareKey;
823
+ });
824
+ } catch (e) {
825
+ return Promise.reject(e);
826
+ }
827
+ }))).then(function () {
828
+ // 遍历打包生成的每个文件
829
+ for (var _i3 = 0, _Object$entries2 = Object.entries(bundle); _i3 < _Object$entries2.length; _i3++) {
830
+ var _Object$entries2$_i = _Object$entries2[_i3],
831
+ _fileName = _Object$entries2$_i[0],
832
+ _fileData = _Object$entries2$_i[1];
833
+ if (_fileData.type === 'chunk') {
834
+ // 遍历该文件的所有模块
835
+ for (var _i4 = 0, _Object$keys2 = Object.keys(_fileData.modules); _i4 < _Object$keys2.length; _i4++) {
836
+ var _modulePath = _Object$keys2[_i4];
837
+ var sharedKey = fileToShareKey[_modulePath];
838
+ if (sharedKey) {
839
+ var _filesContainingModul2;
840
+ if (!filesContainingModules[sharedKey]) {
841
+ filesContainingModules[sharedKey] = {
842
+ sync: [],
843
+ async: []
844
+ };
845
+ }
846
+ filesContainingModules[sharedKey].sync.push(_fileName);
847
+ (_filesContainingModul2 = filesContainingModules[sharedKey].async).push.apply(_filesContainingModul2, _fileData.dynamicImports || []);
848
+ _findSynchronousImports(_fileName, filesContainingModules[sharedKey].sync);
849
+ break; // 如果找到匹配,跳出循环
850
+ }
851
+ }
852
+ }
853
+ }
854
+ Object.keys(filesContainingModules).forEach(function (key) {
855
+ filesContainingModules[key].sync = Array.from(new Set(filesContainingModules[key].sync));
856
+ filesContainingModules[key].async = Array.from(new Set(filesContainingModules[key].async));
857
+ });
858
+ _this.emitFile({
859
+ type: 'asset',
860
+ fileName: mfManifestName,
861
+ source: generateMFManifest(filesContainingModules)
862
+ });
863
+ });
864
+ } catch (e) {
865
+ return Promise.reject(e);
866
+ }
867
+ }
868
+ }];
869
+ function generateMFManifest(preloadMap) {
870
+ var options = getNormalizeModuleFederationOptions();
871
+ var name = options.name;
872
+ var remoteEntry = {
873
+ name: remoteEntryFile,
874
+ path: '',
875
+ type: 'module'
876
+ };
877
+ var remotes = [];
878
+ var usedRemotesMap = getUsedRemotesMap();
879
+ Object.keys(usedRemotesMap).forEach(function (remoteKey) {
880
+ var usedModules = Array.from(usedRemotesMap[remoteKey]);
881
+ usedModules.forEach(function (moduleKey) {
882
+ remotes.push({
883
+ federationContainerName: options.remotes[remoteKey].entry,
884
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
885
+ alias: remoteKey,
886
+ entry: '*'
887
+ });
888
+ });
889
+ });
890
+ // @ts-ignore
891
+ var shared = Array.from(getUsedShares()).map(function (shareKey) {
892
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
893
+ if (!preloadMap[shareKey]) return;
894
+ var shareItem = getNormalizeShareItem(shareKey);
895
+ return {
896
+ id: name + ":" + shareKey,
897
+ name: shareKey,
898
+ version: shareItem.version,
899
+ requiredVersion: shareItem.shareConfig.requiredVersion,
900
+ assets: {
901
+ js: {
902
+ async: preloadMap[shareKey].async,
903
+ sync: preloadMap[shareKey].sync
904
+ },
905
+ css: {
906
+ async: [],
907
+ sync: []
908
+ }
909
+ }
910
+ };
911
+ }).filter(function (item) {
912
+ return item;
913
+ });
914
+ var exposes = Object.keys(options.exposes).map(function (key) {
915
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
916
+ var formatKey = key.replace('./', '');
917
+ var sourceFile = options.exposes[key]["import"];
918
+ if (!preloadMap[sourceFile]) return;
919
+ return {
920
+ id: name + ':' + formatKey,
921
+ name: formatKey,
922
+ assets: {
923
+ js: {
924
+ async: preloadMap[sourceFile].async,
925
+ sync: preloadMap[sourceFile].sync
926
+ },
927
+ css: {
928
+ sync: [],
929
+ async: []
930
+ }
931
+ },
932
+ path: key
933
+ };
934
+ }).filter(function (item) {
935
+ return item;
936
+ }); // Filter out any null values
937
+ var result = {
938
+ id: name,
939
+ name: name,
940
+ metaData: {
941
+ name: name,
942
+ type: 'app',
943
+ buildInfo: {
944
+ buildVersion: '1.0.0',
945
+ buildName: name
946
+ },
947
+ remoteEntry: remoteEntry,
948
+ ssrRemoteEntry: remoteEntry,
949
+ types: {
950
+ path: '',
951
+ name: ''
952
+ // "zip": "@mf-types.zip",
953
+ // "api": "@mf-types.d.ts"
954
+ },
955
+ globalName: name,
956
+ pluginVersion: '0.2.5',
957
+ publicPath: 'auto'
958
+ },
959
+ shared: shared,
960
+ remotes: remotes,
961
+ exposes: exposes
962
+ };
963
+ return JSON.stringify(result);
964
+ }
965
+ };
966
+
967
+ var _resolve,
968
+ promise = new Promise(function (resolve, reject) {
969
+ _resolve = resolve;
970
+ });
971
+ var parsePromise = promise;
972
+ var parseStartSet = new Set();
973
+ var parseEndSet = new Set();
974
+ function pluginModuleParseEnd (excludeFn) {
975
+ return [{
976
+ name: "_",
977
+ apply: "serve",
978
+ config: function config() {
979
+ // No waiting in development mode
980
+ _resolve(1);
981
+ }
982
+ }, {
983
+ enforce: "pre",
984
+ name: "parseStart",
985
+ apply: "build",
986
+ load: function load(id) {
987
+ if (excludeFn(id)) {
988
+ return;
989
+ }
990
+ parseStartSet.add(id);
991
+ }
992
+ }, {
993
+ enforce: "post",
994
+ name: "parseEnd",
995
+ apply: "build",
996
+ moduleParsed: function moduleParsed(module) {
997
+ var id = module.id;
998
+ if (excludeFn(id)) {
999
+ return;
1000
+ }
1001
+ parseEndSet.add(id);
1002
+ if (parseStartSet.size === parseEndSet.size) {
1003
+ _resolve(1);
1004
+ }
1005
+ }
1006
+ }];
1007
+ }
1008
+
1009
+ var filter = pluginutils.createFilter();
535
1010
  function pluginProxyRemoteEntry () {
536
1011
  return {
537
1012
  name: 'proxyRemoteEntry',
@@ -543,14 +1018,18 @@ function pluginProxyRemoteEntry () {
543
1018
  },
544
1019
  load: function load(id) {
545
1020
  if (id === REMOTE_ENTRY_ID) {
546
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1021
+ return parsePromise.then(function (_) {
1022
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1023
+ });
547
1024
  }
548
1025
  },
549
1026
  transform: function transform(code, id) {
550
1027
  try {
551
- if (!filter$1(id)) return Promise.resolve();
1028
+ if (!filter(id)) return Promise.resolve();
552
1029
  if (id.includes(REMOTE_ENTRY_ID)) {
553
- return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
1030
+ return Promise.resolve(parsePromise.then(function (_) {
1031
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1032
+ }));
554
1033
  }
555
1034
  return Promise.resolve();
556
1035
  } catch (e) {
@@ -560,50 +1039,25 @@ function pluginProxyRemoteEntry () {
560
1039
  };
561
1040
  }
562
1041
 
563
- var filter = pluginutils.createFilter();
1042
+ pluginutils.createFilter();
564
1043
  function pluginProxyRemotes (options) {
565
- var command;
566
1044
  var remotes = options.remotes;
567
- var matchRemotesList = Object.keys(remotes).map(function (item) {
568
- return item.replace(/\//g, "_");
569
- });
570
1045
  return {
571
1046
  name: "proxyRemotes",
572
1047
  config: function config(_config, _ref) {
573
1048
  var _command = _ref.command;
574
- command = _command;
575
1049
  Object.keys(remotes).forEach(function (key) {
576
1050
  var remote = remotes[key];
577
1051
  _config.resolve.alias.push({
578
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
579
- replacement: '$1',
1052
+ find: new RegExp("^(" + remote.name + "(/.*|$))"),
1053
+ replacement: "$1",
580
1054
  customResolver: function customResolver(source) {
581
- var requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
582
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
583
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
584
- if (_config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) _config.optimizeDeps.needsInterop.push(requestPath);
585
- return this.resolve(requestPath);
1055
+ var remoteModule = getRemoteVirtualModule(source, _command);
1056
+ addUsedRemote(remote.name, source);
1057
+ return remoteModule.getPath();
586
1058
  }
587
1059
  });
588
1060
  });
589
- },
590
- transform: function transform(code, id) {
591
- try {
592
- if (!filter(id)) return Promise.resolve();
593
- var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
594
- devRemoteModuleName = _ref2[0];
595
- if (devRemoteModuleName) {
596
- return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
597
- }
598
- var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
599
- prodRemoteName = _ref3[0];
600
- if (prodRemoteName) {
601
- return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
602
- }
603
- return Promise.resolve();
604
- } catch (e) {
605
- return Promise.reject(e);
606
- }
607
1061
  }
608
1062
  };
609
1063
  }
@@ -645,44 +1099,24 @@ var PromiseStore = /*#__PURE__*/function () {
645
1099
  return PromiseStore;
646
1100
  }();
647
1101
 
648
- function wrapManualChunks(output, manualChunksCb) {
649
- if (!output.manualChunks) output.manualChunks = {};
650
- var wrapManualChunks = function wrapManualChunks(original) {
651
- return function (id) {
652
- var args = [].slice.call(arguments, 1);
653
- var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
654
- if (customRes) return customRes;
655
- if (typeof original === 'function') {
656
- return original.apply(void 0, [id].concat(args));
657
- }
658
- if (typeof original === 'object' && original) {
659
- return original[id];
660
- }
661
- };
662
- };
663
- output.manualChunks = wrapManualChunks(output.manualChunks);
664
- }
665
-
666
1102
  function proxySharedModule(options) {
667
1103
  var _options$shared = options.shared,
668
- shared = _options$shared === void 0 ? {} : _options$shared,
669
- include = options.include,
670
- exclude = options.exclude;
671
- var filterFunction = pluginutils.createFilter(include, exclude);
1104
+ shared = _options$shared === void 0 ? {} : _options$shared;
672
1105
  return [{
673
1106
  name: "generateLocalSharedImportMap",
674
1107
  enforce: "post",
675
- resolveId: function resolveId(id) {
676
- if (id.includes(getLocalSharedImportMapPath())) return id;
677
- },
678
1108
  load: function load(id) {
679
1109
  if (id.includes(getLocalSharedImportMapPath())) {
680
- return generateLocalSharedImportMap();
1110
+ return parsePromise.then(function (_) {
1111
+ return generateLocalSharedImportMap();
1112
+ });
681
1113
  }
682
1114
  },
683
1115
  transform: function transform(code, id) {
684
1116
  if (id.includes(getLocalSharedImportMapPath())) {
685
- return generateLocalSharedImportMap();
1117
+ return parsePromise.then(function (_) {
1118
+ return generateLocalSharedImportMap();
1119
+ });
686
1120
  }
687
1121
  }
688
1122
  }, {
@@ -691,19 +1125,6 @@ function proxySharedModule(options) {
691
1125
  config: function config(_config, _ref) {
692
1126
  var _config$resolve$alias, _config$resolve$alias2;
693
1127
  var command = _ref.command;
694
- if (!_config.build) _config.build = {};
695
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
696
- var rollupOptions = _config.build.rollupOptions;
697
- if (!rollupOptions.output) rollupOptions.output = {};
698
- wrapManualChunks(_config.build.rollupOptions.output, function (id) {
699
- // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
700
- if (id.includes('/preload-helper.js')) {
701
- return "preload-helper";
702
- }
703
- if (id.includes("node_modules/@module-federation/runtime")) {
704
- return "@module-federation/runtime";
705
- }
706
- });
707
1128
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
708
1129
  var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
709
1130
  return {
@@ -711,12 +1132,10 @@ function proxySharedModule(options) {
711
1132
  find: new RegExp(pattern),
712
1133
  replacement: "$1",
713
1134
  customResolver: function customResolver(source, importer) {
714
- var _config$optimizeDeps;
715
1135
  var loadSharePath = getLoadShareModulePath(source);
716
- _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
717
1136
  writeLoadShareModule(source, shared[key], command);
718
1137
  writePreBuildLibPath(source);
719
- addShare(source);
1138
+ addUsedShares(source);
720
1139
  writeLocalSharedImportMap();
721
1140
  return this.resolve(loadSharePath);
722
1141
  }
@@ -725,20 +1144,18 @@ function proxySharedModule(options) {
725
1144
  var savePrebuild = new PromiseStore();
726
1145
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
727
1146
  return command === "build" ? {
728
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1147
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
729
1148
  replacement: function replacement($1) {
730
- $1 = $1.replace(/\.[^.]+$/, "");
731
- var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
732
- return packageNameDecode(pkgName);
1149
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
1150
+ return pkgName;
733
1151
  }
734
1152
  } : {
735
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1153
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
736
1154
  replacement: "$1",
737
1155
  customResolver: function customResolver(source, importer) {
738
1156
  try {
739
1157
  var _this = this;
740
- source = source.replace(/\.[^.]+$/, "");
741
- var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
1158
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, source).name;
742
1159
  if (importer.includes(LOAD_SHARE_TAG)) {
743
1160
  // save pre-bunding module id
744
1161
  savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
@@ -773,69 +1190,6 @@ function proxySharedModule(options) {
773
1190
  watch.ignored = [].concat(watch.ignored);
774
1191
  watch.ignored.push("!**" + getLocalSharedImportMapPath() + "**");
775
1192
  }
776
- }, {
777
- name: "prebuild-top-level-await",
778
- apply: "serve",
779
- transform: function transform(code, id) {
780
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
781
- return null;
782
- }
783
- if (!filterFunction(id)) return null;
784
- var ast;
785
- try {
786
- ast = this.parse(code, {
787
- allowReturnOutsideFunction: true
788
- });
789
- } catch (e) {
790
- throw new Error(id + ": " + e);
791
- }
792
- var magicString = new MagicString__default["default"](code);
793
- estreeWalker.walk(ast, {
794
- enter: function enter(node) {
795
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
796
- var exportSpecifiers = node.specifiers.map(function (specifier) {
797
- return specifier.exported.name;
798
- });
799
- var proxyStatements = exportSpecifiers.map(function (name) {
800
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
801
- }).join('\n');
802
- var exportStatements = exportSpecifiers.map(function (name) {
803
- return "__mfproxy__" + name + " as " + name;
804
- }).join(', ');
805
- var start = node.start;
806
- var end = node.end;
807
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
808
- magicString.overwrite(start, end, replacement);
809
- }
810
- if (node.type === 'ExportDefaultDeclaration') {
811
- var declaration = node.declaration;
812
- var _start = node.start;
813
- var _end = node.end;
814
- var proxyStatement;
815
- var exportStatement = 'default';
816
- if (declaration.type === 'Identifier') {
817
- // example: export default foo;
818
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
819
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
820
- // example: export default someFunction();
821
- var declarationCode = code.slice(declaration.start, declaration.end);
822
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
823
- } else {
824
- // other
825
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
826
- }
827
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
828
- magicString.overwrite(_start, _end, _replacement);
829
- }
830
- }
831
- });
832
- return {
833
- code: magicString.toString(),
834
- map: magicString.generateMap({
835
- hires: true
836
- })
837
- };
838
- }
839
1193
  }];
840
1194
  }
841
1195
 
@@ -891,7 +1245,7 @@ function federation(mfUserOptions) {
891
1245
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
892
1246
  }), proxySharedModule({
893
1247
  shared: shared
894
- }), [{
1248
+ }), [PluginDevProxyModuleTopLevelAwait(), {
895
1249
  name: 'module-federation-vite',
896
1250
  enforce: 'post',
897
1251
  config: function config(_config, _ref) {
@@ -901,11 +1255,8 @@ function federation(mfUserOptions) {
901
1255
  replacement: require.resolve('@module-federation/runtime')
902
1256
  });
903
1257
  (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
904
- // Object.keys(shared).forEach((key) => {
905
- // config.optimizeDeps?.include?.push(key);
906
- // });
907
1258
  }
908
- }]);
1259
+ }], Manifest());
909
1260
  }
910
1261
 
911
1262
  exports.federation = federation;