@module-federation/vite 1.0.0-alpha-2f53b4e → 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,26 +1,32 @@
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,
12
12
  entryPath = _ref.entryPath,
13
13
  fileName = _ref.fileName;
14
+ var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
14
15
  var entryFiles = [];
15
16
  var htmlFilePath;
17
+ var _command;
16
18
  return [{
17
19
  name: 'add-entry',
18
20
  apply: "serve",
21
+ config: function config(_config, _ref2) {
22
+ var command = _ref2.command;
23
+ _command = command;
24
+ },
19
25
  configureServer: function configureServer(server) {
20
26
  var _server$httpServer;
21
27
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
22
28
  var port = server.config.server.port;
23
- fetch(path.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
29
+ fetch(path.join("http://localhost:" + port, "" + devEntryPath))["catch"](function (e) {});
24
30
  });
25
31
  server.middlewares.use(function (req, res, next) {
26
32
  if (!fileName) {
@@ -28,18 +34,17 @@ var addEntry = function addEntry(_ref) {
28
34
  return;
29
35
  }
30
36
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
31
- req.url = entryPath;
37
+ req.url = devEntryPath;
32
38
  }
33
39
  next();
34
40
  });
35
41
  },
36
42
  transformIndexHtml: function transformIndexHtml(c) {
37
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
43
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
38
44
  }
39
45
  }, {
40
46
  name: "add-entry",
41
47
  enforce: "post",
42
- apply: "build",
43
48
  configResolved: function configResolved(config) {
44
49
  var inputOptions = config.build.rollupOptions.input;
45
50
  if (!inputOptions) {
@@ -57,6 +62,7 @@ var addEntry = function addEntry(_ref) {
57
62
  },
58
63
  buildStart: function buildStart() {
59
64
  var _this$emitFile;
65
+ if (_command === "serve") return;
60
66
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
61
67
  this.emitFile((_this$emitFile = {
62
68
  name: entryName
@@ -81,46 +87,105 @@ var addEntry = function addEntry(_ref) {
81
87
  }];
82
88
  };
83
89
 
84
- var _resolve,
85
- promise = new Promise(function (resolve, reject) {
86
- _resolve = resolve;
87
- });
88
- var parsePromise = promise;
89
- var parseStartSet = new Set();
90
- var parseEndSet = new Set();
91
- function pluginModuleParseEnd (excludeFn) {
92
- return [{
93
- 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",
94
97
  apply: "serve",
95
- config: function config() {
96
- // No waiting in development mode
97
- _resolve(1);
98
- }
99
- }, {
100
- enforce: "pre",
101
- name: "parseStart",
102
- apply: "build",
103
- load: function load(id) {
104
- if (excludeFn(id)) {
105
- return;
106
- }
107
- parseStartSet.add(id);
108
- }
109
- }, {
110
- enforce: "post",
111
- name: "parseEnd",
112
- apply: "build",
113
- moduleParsed: function moduleParsed(module) {
114
- var id = module.id;
115
- if (excludeFn(id)) {
116
- return;
98
+ transform: function transform(code, id) {
99
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
100
+ return null;
117
101
  }
118
- parseEndSet.add(id);
119
- if (parseStartSet.size === parseEndSet.size) {
120
- _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);
121
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
+ };
122
157
  }
123
- }];
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
+ }
124
189
  }
125
190
 
126
191
  function normalizeExposesItem(key, item) {
@@ -173,7 +238,7 @@ function normalizeRemoteItem(key, remote) {
173
238
  entryGlobalName: key
174
239
  }, remote);
175
240
  }
176
- function removePathFromNpmPackage$1(packageString) {
241
+ function removePathFromNpmPackage(packageString) {
177
242
  // 匹配npm包名的正则表达式,忽略路径部分
178
243
  var regex = /^(?:@[^/]+\/)?[^/]+/;
179
244
  // 使用正则表达式匹配并提取包名
@@ -184,7 +249,7 @@ function removePathFromNpmPackage$1(packageString) {
184
249
  function normalizeShareItem(key, shareItem) {
185
250
  var version;
186
251
  try {
187
- version = require(path.join(removePathFromNpmPackage$1(key), 'package.json')).version;
252
+ version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
188
253
  } catch (e) {
189
254
  console.log(e);
190
255
  }
@@ -232,10 +297,28 @@ function normalizeLibrary(library) {
232
297
  if (!library) return undefined;
233
298
  return library;
234
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
+ }
235
313
  var config;
236
314
  function getNormalizeModuleFederationOptions() {
237
315
  return config;
238
316
  }
317
+ function getNormalizeShareItem(key) {
318
+ var options = getNormalizeModuleFederationOptions();
319
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
320
+ return shareItem;
321
+ }
239
322
  function normalizeModuleFederationOptions(options) {
240
323
  return config = {
241
324
  exposes: normalizeExposes(options.exposes),
@@ -250,7 +333,7 @@ function normalizeModuleFederationOptions(options) {
250
333
  runtimePlugins: options.runtimePlugins || [],
251
334
  getPublicPath: options.getPublicPath,
252
335
  implementation: options.implementation,
253
- manifest: options.manifest,
336
+ manifest: normalizeManifest(options.manifest),
254
337
  dev: options.dev,
255
338
  dts: options.dts
256
339
  };
@@ -265,33 +348,42 @@ function normalizeModuleFederationOptions(options) {
265
348
  * . => 4
266
349
  */
267
350
  /**
268
- * @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.
269
354
  */
270
355
  function packageNameEncode(name) {
271
356
  if (typeof name !== "string") throw new Error("A string package name is required");
272
- 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_");
273
358
  }
274
359
  /**
275
- * @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.
276
363
  */
277
- function packageNameDecode(global) {
278
- if (typeof global !== "string") throw new Error("A string global variable name is required");
279
- 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, ".");
280
367
  }
281
- function removePathFromNpmPackage(packageString) {
282
- // Regular expression to match npm package name, ignoring path parts
283
- var regex = /^(?:@[^/]+\/)?[^/]+/;
284
- // Use regular expression to match and extract the package name
285
- var match = packageString.match(regex);
286
- // Return the matched package name or the original string if no match is found
287
- 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");
376
+ }
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);
288
380
  }
289
- function getExtFromNpmPackage(packageString) {
290
- var pkgName = removePathFromNpmPackage(packageString);
291
- var subpath = packageString.replace(pkgName, "");
292
- var parts = subpath.split('.');
293
- var ext = parts.length > 1 ? "." + parts.pop() : undefined;
294
- return ext;
381
+ function createFile(filePath, content) {
382
+ var dir = path__default.dirname(filePath);
383
+ mkdirSync(dir, {
384
+ recursive: true
385
+ });
386
+ writeFileSync(filePath, content);
295
387
  }
296
388
 
297
389
  var nodeModulesDir = function findNodeModulesDir(startDir) {
@@ -317,28 +409,47 @@ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.
317
409
  name: virtualPackageName,
318
410
  main: "empty.js"
319
411
  }));
412
+ var patternMap = {};
413
+ var cacheMap = {};
320
414
  /**
321
415
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
322
416
  */
323
417
  var VirtualModule = /*#__PURE__*/function () {
324
- function VirtualModule(name, ext) {
325
- if (ext === void 0) {
326
- ext = ".js";
418
+ function VirtualModule(name, tag, suffix) {
419
+ var _name$split$slice$pop;
420
+ if (tag === void 0) {
421
+ tag = '__mf_v__';
422
+ }
423
+ if (suffix === void 0) {
424
+ suffix = "";
327
425
  }
328
- this.originName = void 0;
426
+ this.name = void 0;
427
+ this.tag = void 0;
428
+ this.suffix = void 0;
329
429
  this.inited = false;
330
- this.ext = void 0;
331
- this.originName = name;
332
- 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;
333
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
+ };
334
445
  var _proto = VirtualModule.prototype;
335
446
  _proto.getPath = function getPath() {
336
447
  return resolve(nodeModulesDir, this.getImportId());
337
448
  };
338
449
  _proto.getImportId = function getImportId() {
339
450
  var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
340
- name = _getNormalizeModuleFe.name;
341
- 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;
342
453
  };
343
454
  _proto.writeSync = function writeSync(code, force) {
344
455
  if (!force && this.inited) return;
@@ -353,24 +464,33 @@ var VirtualModule = /*#__PURE__*/function () {
353
464
  return VirtualModule;
354
465
  }();
355
466
 
356
- /**
357
- * https://github.com/module-federation/vite/issues/68
358
- */
359
- function getLocalSharedImportMapPath_windows() {
360
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
361
- name = _getNormalizeModuleFe.name;
362
- 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 ");
363
470
  }
364
- function writeLocalSharedImportMap_windows(content) {
365
- var localSharedImportMapId = getLocalSharedImportMapPath_windows();
366
- 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;
367
481
  }
368
- function createFile(filePath, content) {
369
- var dir = path__default.dirname(filePath);
370
- mkdirSync(dir, {
371
- recursive: true
372
- });
373
- 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 ";
374
494
  }
375
495
 
376
496
  /**
@@ -379,63 +499,35 @@ function createFile(filePath, content) {
379
499
  * You can only proxy to the real file through alias
380
500
  */
381
501
  // *** __prebuild__
382
-
383
- var generateLocalSharedImportMap = function generateLocalSharedImportMap() {
384
- return Promise.resolve(parsePromise).then(function () {
385
- var options = getNormalizeModuleFederationOptions();
386
- return "\n const localSharedImportMap = {\n " + Array.from(shareds).map(function (pkg) {
387
- return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
388
- }).join(",") + "\n }\n const localShared = {\n " + Array.from(shareds).map(function (key) {
389
- var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
390
- 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 ";
391
- }).join(',') + "\n }\n export default localShared\n ";
392
- });
393
- };
394
- // *** __loadShare__
395
- var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
396
- try {
397
- var _exit;
398
- var sharedCount = shareds.size;
399
- return Promise.resolve(function () {
400
- if (prevSharedCount !== sharedCount) {
401
- var _temp2 = function _temp2(_result) {
402
- if (_exit) return _result;
403
- var _writeSync = localSharedImportMapModule.writeSync;
404
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI2) {
405
- return _writeSync.call(localSharedImportMapModule, _generateLocalSharedI2, true);
406
- });
407
- };
408
- prevSharedCount = sharedCount;
409
- var _temp = function () {
410
- if (process.platform === "win32") {
411
- return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI) {
412
- var _writeLocalSharedImpo = writeLocalSharedImportMap_windows(_generateLocalSharedI);
413
- _exit = 1;
414
- return _writeLocalSharedImpo;
415
- });
416
- }
417
- }();
418
- return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
419
- }
420
- }());
421
- } catch (e) {
422
- return Promise.reject(e);
423
- }
424
- };
425
502
  var preBuildCacheMap = {};
426
503
  var PREBUILD_TAG = "__prebuild__";
427
504
  function writePreBuildLibPath(pkg) {
428
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
505
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
429
506
  preBuildCacheMap[pkg].writeSync("");
430
507
  }
431
508
  function getPreBuildLibImportId(pkg) {
432
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
509
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
433
510
  var importId = preBuildCacheMap[pkg].getImportId();
434
511
  return importId;
435
512
  }
436
- var shareds = new Set();
437
- function addShare(pkg) {
438
- 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);
439
531
  }
440
532
  // *** Expose locally provided shared modules here
441
533
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
@@ -445,43 +537,42 @@ function getLocalSharedImportMapPath() {
445
537
  }
446
538
  return localSharedImportMapModule.getPath();
447
539
  }
448
- var prevSharedCount = 0;
449
- var LOAD_SHARE_TAG = "__loadShare__";
450
- var loadShareCacheMap = {};
451
- function getLoadShareModulePath(pkg) {
452
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
453
- var filepath = loadShareCacheMap[pkg].getPath();
454
- 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
+ }
455
551
  }
456
- function writeLoadShareModule(pkg, shareItem, command) {
457
- 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 ";
458
563
  }
459
-
460
- var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
564
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
461
565
  function generateRemoteEntry(options) {
462
566
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
463
567
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
464
568
  });
465
- 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) {
466
570
  return item[1];
467
571
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
468
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 ";
469
- }).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) {
470
- var remote = options.remotes[key];
471
- 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 ";
472
- }).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) {
473
574
  return item[0] + "()";
474
- }).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 ";
475
- }
476
- var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
477
- function writeWrapRemoteEntry() {
478
- wrapRemoteEntryModule.writeSync("\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ");
479
- }
480
- function getWrapRemoteEntryImportId() {
481
- return wrapRemoteEntryModule.getImportId();
482
- }
483
- function getWrapRemoteEntryPath() {
484
- return wrapRemoteEntryModule.getPath();
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 ";
485
576
  }
486
577
  /**
487
578
  * Inject entry file, automatically init when used as host,
@@ -498,27 +589,401 @@ function getHostAutoInitPath() {
498
589
  return hostAutoInitModule.getPath();
499
590
  }
500
591
 
501
- var remoteVirtualModule = new VirtualModule("remoteModule");
502
- function writeRemote() {
503
- remoteVirtualModule.writeSync("");
504
- }
505
- function generateRemotes(id, command) {
506
- return {
507
- 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 ",
508
- map: null,
509
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
510
- syntheticNamedExports: '__mf__dynamicExports'
511
- };
512
- }
513
-
514
592
  function initVirtualModules() {
515
593
  writeLocalSharedImportMap();
516
- writeWrapRemoteEntry();
517
594
  writeHostAutoInit();
518
- writeRemote();
595
+ writeRuntimeInitStatus();
596
+ }
597
+
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
+ }];
519
984
  }
520
985
 
521
- var filter$1 = createFilter();
986
+ var filter = createFilter();
522
987
  function pluginProxyRemoteEntry () {
523
988
  return {
524
989
  name: 'proxyRemoteEntry',
@@ -530,14 +995,18 @@ function pluginProxyRemoteEntry () {
530
995
  },
531
996
  load: function load(id) {
532
997
  if (id === REMOTE_ENTRY_ID) {
533
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
998
+ return parsePromise.then(function (_) {
999
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1000
+ });
534
1001
  }
535
1002
  },
536
1003
  transform: function transform(code, id) {
537
1004
  try {
538
- if (!filter$1(id)) return Promise.resolve();
1005
+ if (!filter(id)) return Promise.resolve();
539
1006
  if (id.includes(REMOTE_ENTRY_ID)) {
540
- return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
1007
+ return Promise.resolve(parsePromise.then(function (_) {
1008
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1009
+ }));
541
1010
  }
542
1011
  return Promise.resolve();
543
1012
  } catch (e) {
@@ -547,50 +1016,25 @@ function pluginProxyRemoteEntry () {
547
1016
  };
548
1017
  }
549
1018
 
550
- var filter = createFilter();
1019
+ createFilter();
551
1020
  function pluginProxyRemotes (options) {
552
- var command;
553
1021
  var remotes = options.remotes;
554
- var matchRemotesList = Object.keys(remotes).map(function (item) {
555
- return item.replace(/\//g, "_");
556
- });
557
1022
  return {
558
1023
  name: "proxyRemotes",
559
1024
  config: function config(_config, _ref) {
560
1025
  var _command = _ref.command;
561
- command = _command;
562
1026
  Object.keys(remotes).forEach(function (key) {
563
1027
  var remote = remotes[key];
564
1028
  _config.resolve.alias.push({
565
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
566
- replacement: '$1',
1029
+ find: new RegExp("^(" + remote.name + "(/.*|$))"),
1030
+ replacement: "$1",
567
1031
  customResolver: function customResolver(source) {
568
- var requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
569
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
570
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
571
- if (_config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) _config.optimizeDeps.needsInterop.push(requestPath);
572
- return this.resolve(requestPath);
1032
+ var remoteModule = getRemoteVirtualModule(source, _command);
1033
+ addUsedRemote(remote.name, source);
1034
+ return remoteModule.getPath();
573
1035
  }
574
1036
  });
575
1037
  });
576
- },
577
- transform: function transform(code, id) {
578
- try {
579
- if (!filter(id)) return Promise.resolve();
580
- var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
581
- devRemoteModuleName = _ref2[0];
582
- if (devRemoteModuleName) {
583
- return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
584
- }
585
- var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
586
- prodRemoteName = _ref3[0];
587
- if (prodRemoteName) {
588
- return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
589
- }
590
- return Promise.resolve();
591
- } catch (e) {
592
- return Promise.reject(e);
593
- }
594
1038
  }
595
1039
  };
596
1040
  }
@@ -632,44 +1076,24 @@ var PromiseStore = /*#__PURE__*/function () {
632
1076
  return PromiseStore;
633
1077
  }();
634
1078
 
635
- function wrapManualChunks(output, manualChunksCb) {
636
- if (!output.manualChunks) output.manualChunks = {};
637
- var wrapManualChunks = function wrapManualChunks(original) {
638
- return function (id) {
639
- var args = [].slice.call(arguments, 1);
640
- var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
641
- if (customRes) return customRes;
642
- if (typeof original === 'function') {
643
- return original.apply(void 0, [id].concat(args));
644
- }
645
- if (typeof original === 'object' && original) {
646
- return original[id];
647
- }
648
- };
649
- };
650
- output.manualChunks = wrapManualChunks(output.manualChunks);
651
- }
652
-
653
1079
  function proxySharedModule(options) {
654
1080
  var _options$shared = options.shared,
655
- shared = _options$shared === void 0 ? {} : _options$shared,
656
- include = options.include,
657
- exclude = options.exclude;
658
- var filterFunction = createFilter(include, exclude);
1081
+ shared = _options$shared === void 0 ? {} : _options$shared;
659
1082
  return [{
660
1083
  name: "generateLocalSharedImportMap",
661
1084
  enforce: "post",
662
- resolveId: function resolveId(id) {
663
- if (id.includes(getLocalSharedImportMapPath())) return id;
664
- },
665
1085
  load: function load(id) {
666
1086
  if (id.includes(getLocalSharedImportMapPath())) {
667
- return generateLocalSharedImportMap();
1087
+ return parsePromise.then(function (_) {
1088
+ return generateLocalSharedImportMap();
1089
+ });
668
1090
  }
669
1091
  },
670
1092
  transform: function transform(code, id) {
671
1093
  if (id.includes(getLocalSharedImportMapPath())) {
672
- return generateLocalSharedImportMap();
1094
+ return parsePromise.then(function (_) {
1095
+ return generateLocalSharedImportMap();
1096
+ });
673
1097
  }
674
1098
  }
675
1099
  }, {
@@ -678,19 +1102,6 @@ function proxySharedModule(options) {
678
1102
  config: function config(_config, _ref) {
679
1103
  var _config$resolve$alias, _config$resolve$alias2;
680
1104
  var command = _ref.command;
681
- if (!_config.build) _config.build = {};
682
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
683
- var rollupOptions = _config.build.rollupOptions;
684
- if (!rollupOptions.output) rollupOptions.output = {};
685
- wrapManualChunks(_config.build.rollupOptions.output, function (id) {
686
- // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
687
- if (id.includes('/preload-helper.js')) {
688
- return "preload-helper";
689
- }
690
- if (id.includes("node_modules/@module-federation/runtime")) {
691
- return "@module-federation/runtime";
692
- }
693
- });
694
1105
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
695
1106
  var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
696
1107
  return {
@@ -698,12 +1109,10 @@ function proxySharedModule(options) {
698
1109
  find: new RegExp(pattern),
699
1110
  replacement: "$1",
700
1111
  customResolver: function customResolver(source, importer) {
701
- var _config$optimizeDeps;
702
1112
  var loadSharePath = getLoadShareModulePath(source);
703
- _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
704
1113
  writeLoadShareModule(source, shared[key], command);
705
1114
  writePreBuildLibPath(source);
706
- addShare(source);
1115
+ addUsedShares(source);
707
1116
  writeLocalSharedImportMap();
708
1117
  return this.resolve(loadSharePath);
709
1118
  }
@@ -712,20 +1121,18 @@ function proxySharedModule(options) {
712
1121
  var savePrebuild = new PromiseStore();
713
1122
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
714
1123
  return command === "build" ? {
715
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1124
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
716
1125
  replacement: function replacement($1) {
717
- $1 = $1.replace(/\.[^.]+$/, "");
718
- var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
719
- return packageNameDecode(pkgName);
1126
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
1127
+ return pkgName;
720
1128
  }
721
1129
  } : {
722
- find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
1130
+ find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
723
1131
  replacement: "$1",
724
1132
  customResolver: function customResolver(source, importer) {
725
1133
  try {
726
1134
  var _this = this;
727
- source = source.replace(/\.[^.]+$/, "");
728
- var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
1135
+ var pkgName = VirtualModule.findModule(PREBUILD_TAG, source).name;
729
1136
  if (importer.includes(LOAD_SHARE_TAG)) {
730
1137
  // save pre-bunding module id
731
1138
  savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
@@ -760,69 +1167,6 @@ function proxySharedModule(options) {
760
1167
  watch.ignored = [].concat(watch.ignored);
761
1168
  watch.ignored.push("!**" + getLocalSharedImportMapPath() + "**");
762
1169
  }
763
- }, {
764
- name: "prebuild-top-level-await",
765
- apply: "serve",
766
- transform: function transform(code, id) {
767
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
768
- return null;
769
- }
770
- if (!filterFunction(id)) return null;
771
- var ast;
772
- try {
773
- ast = this.parse(code, {
774
- allowReturnOutsideFunction: true
775
- });
776
- } catch (e) {
777
- throw new Error(id + ": " + e);
778
- }
779
- var magicString = new MagicString(code);
780
- walk(ast, {
781
- enter: function enter(node) {
782
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
783
- var exportSpecifiers = node.specifiers.map(function (specifier) {
784
- return specifier.exported.name;
785
- });
786
- var proxyStatements = exportSpecifiers.map(function (name) {
787
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
788
- }).join('\n');
789
- var exportStatements = exportSpecifiers.map(function (name) {
790
- return "__mfproxy__" + name + " as " + name;
791
- }).join(', ');
792
- var start = node.start;
793
- var end = node.end;
794
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
795
- magicString.overwrite(start, end, replacement);
796
- }
797
- if (node.type === 'ExportDefaultDeclaration') {
798
- var declaration = node.declaration;
799
- var _start = node.start;
800
- var _end = node.end;
801
- var proxyStatement;
802
- var exportStatement = 'default';
803
- if (declaration.type === 'Identifier') {
804
- // example: export default foo;
805
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
806
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
807
- // example: export default someFunction();
808
- var declarationCode = code.slice(declaration.start, declaration.end);
809
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
810
- } else {
811
- // other
812
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
813
- }
814
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
815
- magicString.overwrite(_start, _end, _replacement);
816
- }
817
- }
818
- });
819
- return {
820
- code: magicString.toString(),
821
- map: magicString.generateMap({
822
- hires: true
823
- })
824
- };
825
- }
826
1170
  }];
827
1171
  }
828
1172
 
@@ -869,16 +1213,16 @@ function federation(mfUserOptions) {
869
1213
  if (!name) throw new Error("name is required");
870
1214
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
871
1215
  entryName: 'remoteEntry',
872
- entryPath: getWrapRemoteEntryPath(),
1216
+ entryPath: REMOTE_ENTRY_ID,
873
1217
  fileName: filename
874
1218
  }), addEntry({
875
1219
  entryName: 'hostInit',
876
1220
  entryPath: getHostAutoInitPath()
877
1221
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
878
- return id.includes(getHostAutoInitImportId()) || id.includes(getWrapRemoteEntryImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
1222
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
879
1223
  }), proxySharedModule({
880
1224
  shared: shared
881
- }), [{
1225
+ }), [PluginDevProxyModuleTopLevelAwait(), {
882
1226
  name: 'module-federation-vite',
883
1227
  enforce: 'post',
884
1228
  config: function config(_config, _ref) {
@@ -888,11 +1232,8 @@ function federation(mfUserOptions) {
888
1232
  replacement: require.resolve('@module-federation/runtime')
889
1233
  });
890
1234
  (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
891
- // Object.keys(shared).forEach((key) => {
892
- // config.optimizeDeps?.include?.push(key);
893
- // });
894
1235
  }
895
- }]);
1236
+ }], Manifest());
896
1237
  }
897
1238
 
898
1239
  export { federation };