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