@module-federation/vite 1.0.0-alpha-51eeeb6 → 1.0.0-alpha-661e052

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,8 +1,9 @@
1
1
  import * as fs from 'fs';
2
- import { writeFileSync } from 'fs';
2
+ import { existsSync, mkdirSync, writeFileSync, writeFile } from 'fs';
3
3
  import * as path from 'pathe';
4
- import { resolve } from 'pathe';
4
+ import { parse, join, dirname, resolve } from 'pathe';
5
5
  import { createFilter } from '@rollup/pluginutils';
6
+ import { defu } from 'defu';
6
7
  import { walk } from 'estree-walker';
7
8
  import MagicString from 'magic-string';
8
9
 
@@ -80,6 +81,48 @@ var addEntry = function addEntry(_ref) {
80
81
  }];
81
82
  };
82
83
 
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: "_",
94
+ 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;
117
+ }
118
+ parseEndSet.add(id);
119
+ if (parseStartSet.size === parseEndSet.size) {
120
+ _resolve(1);
121
+ }
122
+ }
123
+ }];
124
+ }
125
+
83
126
  function normalizeExposesItem(key, item) {
84
127
  var importPath = '';
85
128
  if (typeof item === 'string') {
@@ -130,7 +173,7 @@ function normalizeRemoteItem(key, remote) {
130
173
  entryGlobalName: key
131
174
  }, remote);
132
175
  }
133
- function removePathFromNpmPackage(packageString) {
176
+ function removePathFromNpmPackage$1(packageString) {
134
177
  // 匹配npm包名的正则表达式,忽略路径部分
135
178
  var regex = /^(?:@[^/]+\/)?[^/]+/;
136
179
  // 使用正则表达式匹配并提取包名
@@ -141,7 +184,7 @@ function removePathFromNpmPackage(packageString) {
141
184
  function normalizeShareItem(key, shareItem) {
142
185
  var version;
143
186
  try {
144
- version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
187
+ version = require(path.join(removePathFromNpmPackage$1(key), 'package.json')).version;
145
188
  } catch (e) {
146
189
  console.log(e);
147
190
  }
@@ -214,62 +257,151 @@ function normalizeModuleFederationOptions(options) {
214
257
  }
215
258
 
216
259
  /**
217
- * Even the resolveId hook cannot interfere with vite pre-build,
218
- * and adding query parameter virtual modules will also fail.
219
- * You can only proxy to the real file through alias
260
+ * Escaping rules:
261
+ * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
262
+ * @ => 1
263
+ * / => 2
264
+ * - => 3
265
+ * . => 4
220
266
  */
221
- var emptyNpmDir = resolve(require.resolve("an-empty-js-file"), "../");
222
267
  /**
223
- * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
268
+ * @param {*} name "@scope/xx-xx.xx" => "__$1__scope__$2__xx__$3__xx$__4__xx"
224
269
  */
225
- var cacheMap2 = {};
226
- function getPreBuildLibPath(pkg) {
227
- if (!cacheMap2[pkg]) cacheMap2[pkg] = "__mf__prebuildwrap_" + npmPackageNameToFileName(pkg) + ".js";
228
- var filename = cacheMap2[pkg];
229
- return filename;
230
- }
231
- function getLocalSharedImportMapFileName() {
232
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
233
- name = _getNormalizeModuleFe.name;
234
- return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
270
+ function packageNameEncode(name) {
271
+ 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__");
235
273
  }
236
- // Only npm package name import can trigger pre-build, absolute path cannot
237
- function getLocalSharedImportMapId() {
238
- return "an-empty-js-file/" + getLocalSharedImportMapFileName();
274
+ /**
275
+ * @param {*} global "__$1__scope__$2__xx__$3__xx$__4__xx" => "@scope/xx-xx.xx"
276
+ */
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, ".");
239
280
  }
240
- function getLocalSharedImportMapPath() {
241
- return resolve(emptyNpmDir, getLocalSharedImportMapFileName());
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;
242
288
  }
243
- function writeLocalSharedImportMap(pkgList) {
244
- writeFileSync(getLocalSharedImportMapPath(), "\n export default {\n " + pkgList.map(function (pkg) {
245
- return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
246
- }).join(",") + "\n }\n ");
289
+
290
+ var nodeModulesDir = function findNodeModulesDir(startDir) {
291
+ if (startDir === void 0) {
292
+ startDir = process.cwd();
293
+ }
294
+ var currentDir = startDir;
295
+ while (currentDir !== parse(currentDir).root) {
296
+ var nodeModulesPath = join(currentDir, 'node_modules');
297
+ if (existsSync(nodeModulesPath)) {
298
+ return nodeModulesPath;
299
+ }
300
+ currentDir = dirname(currentDir);
301
+ }
302
+ return "";
303
+ }();
304
+ var virtualPackageName = "__mf__virtual";
305
+ if (!existsSync(resolve(nodeModulesDir, virtualPackageName))) {
306
+ mkdirSync(resolve(nodeModulesDir, virtualPackageName));
247
307
  }
248
- var LOAD_SHARE_TAG = "__mf__loadShare_";
308
+ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "empty.js"), "");
309
+ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.stringify({
310
+ name: virtualPackageName,
311
+ main: "empty.js"
312
+ }));
249
313
  /**
250
- * generate loadShare virtual module
314
+ * Physically generate files as virtual modules under node_modules/__mf__virtual/*
251
315
  */
252
- var cacheMap1 = {};
316
+ var VirtualModule = /*#__PURE__*/function () {
317
+ function VirtualModule(name) {
318
+ this.originName = void 0;
319
+ this.originName = name;
320
+ }
321
+ var _proto = VirtualModule.prototype;
322
+ _proto.getPath = function getPath() {
323
+ return resolve(nodeModulesDir, this.getImportId());
324
+ };
325
+ _proto.getImportId = function getImportId() {
326
+ return virtualPackageName + "/" + packageNameEncode(this.originName);
327
+ };
328
+ _proto.writeSync = function writeSync(code) {
329
+ writeFileSync(this.getPath() + ".js", code);
330
+ };
331
+ _proto.write = function write(code) {
332
+ writeFile(this.getPath() + ".js", code, function () {});
333
+ };
334
+ return VirtualModule;
335
+ }();
336
+
337
+ /**
338
+ * Even the resolveId hook cannot interfere with vite pre-build,
339
+ * and adding query parameter virtual modules will also fail.
340
+ * You can only proxy to the real file through alias
341
+ */
342
+ // *** __prebuild__
343
+
344
+ var generateLocalSharedImportMap = function generateLocalSharedImportMap() {
345
+ return Promise.resolve(parsePromise).then(function () {
346
+ var options = getNormalizeModuleFederationOptions();
347
+ return "\n const localSharedImportMap = {\n " + Array.from(shareds).map(function (pkg) {
348
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
349
+ }).join(",") + "\n }\n const localShared = {\n " + Array.from(shareds).map(function (key) {
350
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
351
+ 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 ";
352
+ }).join(',') + "\n }\n export default localShared\n ";
353
+ });
354
+ };
355
+ // *** __loadShare__
356
+ var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
357
+ try {
358
+ var sharedCount = shareds.size;
359
+ return Promise.resolve(function () {
360
+ if (prevSharedCount !== sharedCount) {
361
+ prevSharedCount = sharedCount;
362
+ var _writeSync = localSharedImportMapModule.writeSync;
363
+ return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI) {
364
+ return _writeSync.call(localSharedImportMapModule, _generateLocalSharedI);
365
+ });
366
+ }
367
+ }());
368
+ } catch (e) {
369
+ return Promise.reject(e);
370
+ }
371
+ };
372
+ var preBuildCacheMap = {};
373
+ var PREBUILD_TAG = "__prebuild__";
374
+ function writePreBuildLibPath(pkg) {
375
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
376
+ preBuildCacheMap[pkg].writeSync("");
377
+ }
378
+ function getPreBuildLibImportId(pkg) {
379
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
380
+ var importId = preBuildCacheMap[pkg].getImportId();
381
+ return importId;
382
+ }
383
+ var shareds = new Set();
384
+ function addShare(pkg) {
385
+ shareds.add(pkg);
386
+ }
387
+ // *** Expose locally provided shared modules here
388
+ var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
389
+ localSharedImportMapModule.writeSync("");
390
+ function getLocalSharedImportMapId() {
391
+ return localSharedImportMapModule.getPath();
392
+ }
393
+ var prevSharedCount = 0;
394
+ var LOAD_SHARE_TAG = "__loadShare__";
395
+ var loadShareCacheMap = {};
253
396
  function getLoadShareModulePath(pkg) {
254
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
255
- name = _getNormalizeModuleFe2.name;
256
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("" + LOAD_SHARE_TAG + npmPackageNameToFileName(pkg) + ".js");
257
- var filename = cacheMap1[pkg];
258
- return resolve(emptyNpmDir, filename);
397
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
398
+ var filepath = loadShareCacheMap[pkg].getPath();
399
+ return filepath;
259
400
  }
260
401
  function writeLoadShareModule(pkg, shareItem, command) {
261
- writeFileSync(getLoadShareModulePath(pkg), "\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 ");
262
- }
263
- function npmPackageNameToFileName(packageName) {
264
- // 1. 去掉包名前的 "@"
265
- // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
266
- // 3. 去掉不合法的文件名字符
267
- return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
268
- .replace(/\//g, '__') // 将 "/" 替换为 "__"
269
- .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
402
+ 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 ");
270
403
  }
271
404
 
272
- var emptyPath = require.resolve('an-empty-js-file');
273
405
  var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
274
406
  function generateRemoteEntry(options) {
275
407
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
@@ -279,30 +411,25 @@ function generateRemoteEntry(options) {
279
411
  return item[1];
280
412
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
281
413
  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 ";
282
- }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
283
- var shareItem = options.shared[key];
284
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n 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 ";
285
- }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
414
+ }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
286
415
  var remote = options.remotes[key];
287
416
  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 ";
288
- }).join(',') + "\n ],\n shared: localShared,\n plugins: [" + pluginImportNames.map(function (item) {
417
+ }).join(',') + "\n ],\n shared: localSharedImportMap,\n plugins: [" + pluginImportNames.map(function (item) {
289
418
  return item[0] + "()";
290
419
  }).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 ";
291
420
  }
292
- var WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
293
- var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
294
- function generateWrapRemoteEntry() {
295
- return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
296
- }
421
+ var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
422
+ wrapRemoteEntryModule.writeSync("\nimport {init, get} from \"" + REMOTE_ENTRY_ID + "\"\nexport {init, get}\n");
423
+ var WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
424
+ var WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
297
425
  /**
298
426
  * Inject entry file, automatically init when used as host,
299
427
  * and will not inject remoteEntry
300
428
  */
301
- var HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
302
- var HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
303
- function generateWrapHostInit() {
304
- return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
305
- }
429
+ var hostAutoInitModule = new VirtualModule("hostAutoInit");
430
+ hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
431
+ var HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
432
+ var HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
306
433
 
307
434
  var filter$1 = createFilter();
308
435
  function pluginProxyRemoteEntry () {
@@ -325,12 +452,6 @@ function pluginProxyRemoteEntry () {
325
452
  if (id.includes(REMOTE_ENTRY_ID)) {
326
453
  return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
327
454
  }
328
- if (id.includes(WRAP_REMOTE_ENTRY_QUERY_STR)) {
329
- return Promise.resolve(generateWrapRemoteEntry());
330
- }
331
- if (id.includes(HOST_AUTO_INIT_QUERY_STR)) {
332
- return Promise.resolve(generateWrapHostInit());
333
- }
334
455
  return Promise.resolve();
335
456
  } catch (e) {
336
457
  return Promise.reject(e);
@@ -339,6 +460,8 @@ function pluginProxyRemoteEntry () {
339
460
  };
340
461
  }
341
462
 
463
+ var remoteVirtualModule = new VirtualModule("remoteModule");
464
+ remoteVirtualModule.writeSync("");
342
465
  function generateRemotes(id, command) {
343
466
  return {
344
467
  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 ",
@@ -366,10 +489,11 @@ function pluginProxyRemotes (options) {
366
489
  find: new RegExp("(" + remote.name + "(/.*|$)?)"),
367
490
  replacement: '$1',
368
491
  customResolver: function customResolver(source) {
492
+ var requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
369
493
  if (!_config.optimizeDeps) _config.optimizeDeps = {};
370
494
  if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
371
- if (_config.optimizeDeps.needsInterop.indexOf(source) === -1) _config.optimizeDeps.needsInterop.push(source);
372
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
495
+ if (_config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) _config.optimizeDeps.needsInterop.push(requestPath);
496
+ return this.resolve(requestPath);
373
497
  }
374
498
  });
375
499
  });
@@ -395,6 +519,43 @@ function pluginProxyRemotes (options) {
395
519
  };
396
520
  }
397
521
 
522
+ /**
523
+ * example:
524
+ * const store = new PromiseStore<number>();
525
+ * store.get("example").then((result) => {
526
+ * console.log("Result from example:", result); // 42
527
+ * });
528
+ * setTimeout(() => {
529
+ * store.set("example", Promise.resolve(42));
530
+ * }, 2000);
531
+ */
532
+ var PromiseStore = /*#__PURE__*/function () {
533
+ function PromiseStore() {
534
+ this.promiseMap = new Map();
535
+ this.resolveMap = new Map();
536
+ }
537
+ var _proto = PromiseStore.prototype;
538
+ _proto.set = function set(id, promise) {
539
+ if (this.resolveMap.has(id)) {
540
+ promise.then(this.resolveMap.get(id));
541
+ this.resolveMap["delete"](id);
542
+ }
543
+ this.promiseMap.set(id, promise);
544
+ };
545
+ _proto.get = function get(id) {
546
+ var _this = this;
547
+ if (this.promiseMap.has(id)) {
548
+ return this.promiseMap.get(id);
549
+ }
550
+ var pendingPromise = new Promise(function (resolve) {
551
+ _this.resolveMap.set(id, resolve);
552
+ });
553
+ this.promiseMap.set(id, pendingPromise);
554
+ return pendingPromise;
555
+ };
556
+ return PromiseStore;
557
+ }();
558
+
398
559
  function wrapManualChunks(output, manualChunksCb) {
399
560
  if (!output.manualChunks) output.manualChunks = {};
400
561
  var wrapManualChunks = function wrapManualChunks(original) {
@@ -419,9 +580,24 @@ function proxySharedModule(options) {
419
580
  include = options.include,
420
581
  exclude = options.exclude;
421
582
  var filterFunction = createFilter(include, exclude);
422
- writeLocalSharedImportMap(Object.keys(shared));
423
583
  return [{
424
- name: 'preBuildShared',
584
+ name: "generateLocalSharedImportMap",
585
+ enforce: "post",
586
+ resolveId: function resolveId(id) {
587
+ if (id.includes(getLocalSharedImportMapId())) return id;
588
+ },
589
+ load: function load(id) {
590
+ if (id.includes(getLocalSharedImportMapId())) {
591
+ return generateLocalSharedImportMap();
592
+ }
593
+ },
594
+ transform: function transform(code, id) {
595
+ if (id.includes(getLocalSharedImportMapId())) {
596
+ return generateLocalSharedImportMap();
597
+ }
598
+ }
599
+ }, {
600
+ name: 'proxyPreBuildShared',
425
601
  enforce: 'post',
426
602
  config: function config(_config, _ref) {
427
603
  var _config$resolve$alias, _config$resolve$alias2;
@@ -430,50 +606,77 @@ function proxySharedModule(options) {
430
606
  if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
431
607
  var rollupOptions = _config.build.rollupOptions;
432
608
  if (!rollupOptions.output) rollupOptions.output = {};
433
- // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
434
- // config.optimizeDeps.needsInterop.push('an-empty-js-file');
435
609
  wrapManualChunks(_config.build.rollupOptions.output, function (id) {
610
+ // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
611
+ if (id.includes('/preload-helper.js')) {
612
+ return "preload-helper";
613
+ }
436
614
  if (id.includes("node_modules/@module-federation/runtime")) {
437
615
  return "@module-federation/runtime";
438
616
  }
439
- if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
440
- return id.split("/").pop();
441
- }
442
617
  });
443
618
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
444
- var _config$optimizeDeps, _config$optimizeDeps2;
445
- _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
446
- // write proxyFile
447
- writeLoadShareModule(key, shared[key], command);
448
- var preBuildLibPath = getLoadShareModulePath(key);
449
- _config == null || (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
619
+ var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
450
620
  return {
451
- // Intercept all dependency requests to the proxy module
452
- // Dependency requests issued by localSharedImportMap are allowed without proxying.
453
- find: new RegExp("^" + key + "$"),
454
- replacement: preBuildLibPath,
621
+ // Intercept all shared requests and proxy them to loadShare
622
+ find: new RegExp(pattern),
623
+ replacement: "$1",
455
624
  customResolver: function customResolver(source, importer) {
456
- var _config$optimizeDeps3;
457
- if (importer.includes("node_modules/" + key + "/")) {
458
- return this.resolve(key);
459
- }
460
- _config == null || (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
461
- return this.resolve(preBuildLibPath);
625
+ var _config$optimizeDeps;
626
+ var loadSharePath = getLoadShareModulePath(source);
627
+ _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
628
+ writeLoadShareModule(source, shared[key], command);
629
+ writePreBuildLibPath(source);
630
+ addShare(source);
631
+ writeLocalSharedImportMap();
632
+ return this.resolve(loadSharePath);
462
633
  }
463
634
  };
464
635
  }));
636
+ var savePrebuild = new PromiseStore();
465
637
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
466
638
  return command === "build" ? {
467
- find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
468
- replacement: key
639
+ find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
640
+ replacement: function replacement(_, $1) {
641
+ return packageNameDecode($1);
642
+ }
469
643
  } : {
470
- find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
644
+ find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
645
+ replacement: "$1",
471
646
  customResolver: function customResolver(source, importer) {
472
- return this.resolve(key);
647
+ try {
648
+ var _this = this;
649
+ if (importer.includes(LOAD_SHARE_TAG)) {
650
+ // save pre-bunding module id
651
+ savePrebuild.set(source, _this.resolve(packageNameDecode(source)).then(function (item) {
652
+ return item.id;
653
+ }));
654
+ }
655
+ // Fix localSharedImportMap import id
656
+ var _resolve = _this.resolve;
657
+ return Promise.resolve(savePrebuild.get(source)).then(function (_savePrebuild$get) {
658
+ return Promise.resolve(_resolve.call(_this, _savePrebuild$get));
659
+ });
660
+ } catch (e) {
661
+ return Promise.reject(e);
662
+ }
473
663
  }
474
664
  };
475
665
  }));
476
666
  }
667
+ }, {
668
+ name: "watchLocalSharedImportMap",
669
+ apply: "serve",
670
+ config: function config(_config2) {
671
+ _config2.server = defu(_config2.server, {
672
+ watch: {
673
+ ignored: []
674
+ }
675
+ });
676
+ var watch = _config2.server.watch;
677
+ watch.ignored = [].concat(watch.ignored);
678
+ watch.ignored.push("!**/node_modules/" + localSharedImportMapModule.getImportId() + ".js");
679
+ }
477
680
  }, {
478
681
  name: "prebuild-top-level-await",
479
682
  apply: "serve",
@@ -493,7 +696,6 @@ function proxySharedModule(options) {
493
696
  var magicString = new MagicString(code);
494
697
  walk(ast, {
495
698
  enter: function enter(node) {
496
- // 处理命名导出
497
699
  if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
498
700
  var exportSpecifiers = node.specifiers.map(function (specifier) {
499
701
  return specifier.exported.name;
@@ -509,7 +711,6 @@ function proxySharedModule(options) {
509
711
  var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
510
712
  magicString.overwrite(start, end, replacement);
511
713
  }
512
- // 处理默认导出
513
714
  if (node.type === 'ExportDefaultDeclaration') {
514
715
  var declaration = node.declaration;
515
716
  var _start = node.start;
@@ -517,14 +718,14 @@ function proxySharedModule(options) {
517
718
  var proxyStatement;
518
719
  var exportStatement = 'default';
519
720
  if (declaration.type === 'Identifier') {
520
- // 处理标识符 (如: export default foo;)
721
+ // example: export default foo;
521
722
  proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
522
723
  } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
523
- // 处理调用表达式或函数声明 (如: export default someFunction();)
724
+ // example: export default someFunction();
524
725
  var declarationCode = code.slice(declaration.start, declaration.end);
525
726
  proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
526
727
  } else {
527
- // 其他类型 (可以根据需要添加更多处理逻辑)
728
+ // other
528
729
  proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
529
730
  }
530
731
  var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
@@ -587,7 +788,9 @@ function federation(mfUserOptions) {
587
788
  }), addEntry({
588
789
  entryName: 'hostInit',
589
790
  entryPath: HOST_AUTO_INIT_PATH
590
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], proxySharedModule({
791
+ }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
792
+ return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapId());
793
+ }), proxySharedModule({
591
794
  shared: shared
592
795
  }), [{
593
796
  name: 'module-federation-vite',