@module-federation/vite 1.15.0 → 1.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -21,29 +21,150 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  enumerable: true
22
22
  }) : target, mod));
23
23
  //#endregion
24
- let defu = require("defu");
25
- defu = __toESM(defu);
26
24
  let fs = require("fs");
27
25
  fs = __toESM(fs);
28
26
  let module$1 = require("module");
29
27
  let pathe = require("pathe");
30
28
  pathe = __toESM(pathe);
31
- let magic_string = require("magic-string");
32
- magic_string = __toESM(magic_string);
33
29
  let _module_federation_sdk = require("@module-federation/sdk");
34
30
  let _module_federation_dts_plugin = require("@module-federation/dts-plugin");
35
31
  let _module_federation_dts_plugin_core = require("@module-federation/dts-plugin/core");
36
- let _rollup_pluginutils = require("@rollup/pluginutils");
37
32
  let url = require("url");
38
33
  let es_module_lexer = require("es-module-lexer");
34
+ //#region src/utils/codeRewriter.ts
35
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
36
+ var CodeRewriter = class {
37
+ replacements = [];
38
+ constructor(original) {
39
+ this.original = original;
40
+ }
41
+ overwrite(start, end, content) {
42
+ if (start < 0 || end < start || end > this.original.length) throw new Error(`Invalid overwrite range: ${start}-${end}`);
43
+ this.replacements.push({
44
+ start,
45
+ end,
46
+ content
47
+ });
48
+ }
49
+ toString() {
50
+ return applyReplacements(this.original, this.getSortedReplacements()).code;
51
+ }
52
+ generateMap(source = "") {
53
+ const { code, replacements } = applyReplacements(this.original, this.getSortedReplacements());
54
+ return {
55
+ version: 3,
56
+ sources: [source],
57
+ sourcesContent: [this.original],
58
+ names: [],
59
+ mappings: generateLineMappings(code, this.original, replacements)
60
+ };
61
+ }
62
+ getSortedReplacements() {
63
+ return [...this.replacements].sort((a, b) => a.start - b.start || a.end - b.end);
64
+ }
65
+ };
66
+ function createSourceMap(code, source = "") {
67
+ return {
68
+ version: 3,
69
+ sources: [source],
70
+ sourcesContent: [code],
71
+ names: [],
72
+ mappings: generateLineMappings(code, code, [])
73
+ };
74
+ }
75
+ function applyReplacements(original, replacements) {
76
+ let code = "";
77
+ let cursor = 0;
78
+ let delta = 0;
79
+ const applied = [];
80
+ for (const replacement of replacements) {
81
+ if (replacement.start < cursor) throw new Error("Overlapping overwrite ranges are not supported");
82
+ code += original.slice(cursor, replacement.start);
83
+ const generatedStart = replacement.start + delta;
84
+ code += replacement.content;
85
+ const generatedEnd = generatedStart + replacement.content.length;
86
+ applied.push({
87
+ ...replacement,
88
+ generatedStart,
89
+ generatedEnd
90
+ });
91
+ cursor = replacement.end;
92
+ delta += replacement.content.length - (replacement.end - replacement.start);
93
+ }
94
+ code += original.slice(cursor);
95
+ return {
96
+ code,
97
+ replacements: applied
98
+ };
99
+ }
100
+ function generateLineMappings(generated, original, replacements) {
101
+ const generatedLineStarts = getLineStarts(generated);
102
+ const originalLineStarts = getLineStarts(original);
103
+ let previousOriginalLine = 0;
104
+ let previousOriginalColumn = 0;
105
+ let mappings = "";
106
+ generatedLineStarts.forEach((generatedOffset, lineIndex) => {
107
+ if (lineIndex > 0) mappings += ";";
108
+ const originalOffset = generatedOffsetToOriginalOffset(generatedOffset, replacements);
109
+ const originalLine = findLine(originalLineStarts, originalOffset);
110
+ const originalColumn = originalOffset - originalLineStarts[originalLine];
111
+ mappings += encodeSegment([
112
+ 0,
113
+ 0,
114
+ originalLine - previousOriginalLine,
115
+ originalColumn - previousOriginalColumn
116
+ ]);
117
+ previousOriginalLine = originalLine;
118
+ previousOriginalColumn = originalColumn;
119
+ });
120
+ return mappings;
121
+ }
122
+ function generatedOffsetToOriginalOffset(offset, replacements) {
123
+ let delta = 0;
124
+ for (const replacement of replacements) {
125
+ if (offset < replacement.generatedStart) break;
126
+ if (offset < replacement.generatedEnd) return replacement.start;
127
+ delta += replacement.content.length - (replacement.end - replacement.start);
128
+ }
129
+ return offset - delta;
130
+ }
131
+ function getLineStarts(code) {
132
+ const starts = [0];
133
+ for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
134
+ return starts;
135
+ }
136
+ function findLine(lineStarts, offset) {
137
+ let low = 0;
138
+ let high = lineStarts.length - 1;
139
+ while (low <= high) {
140
+ const mid = low + high >> 1;
141
+ if (lineStarts[mid] <= offset) low = mid + 1;
142
+ else high = mid - 1;
143
+ }
144
+ return Math.max(0, high);
145
+ }
146
+ function encodeSegment(values) {
147
+ return values.map(encodeVlq).join("");
148
+ }
149
+ function encodeVlq(value) {
150
+ let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
151
+ let encoded = "";
152
+ do {
153
+ let digit = vlq & 31;
154
+ vlq >>>= 5;
155
+ if (vlq > 0) digit |= 32;
156
+ encoded += BASE64_CHARS[digit];
157
+ } while (vlq > 0);
158
+ return encoded;
159
+ }
160
+ //#endregion
39
161
  //#region src/utils/mapCodeToCodeWithSourcemap.ts
40
162
  async function mapCodeToCodeWithSourcemap(code) {
41
163
  const resolvedCode = await code;
42
164
  if (resolvedCode === void 0) return;
43
- const s = new magic_string.default(resolvedCode);
44
165
  return {
45
- code: s.toString(),
46
- map: s.generateMap({ hires: true })
166
+ code: resolvedCode,
167
+ map: createSourceMap(resolvedCode)
47
168
  };
48
169
  }
49
170
  //#endregion
@@ -645,107 +766,6 @@ var VirtualModule = class {
645
766
  }
646
767
  };
647
768
  //#endregion
648
- //#region src/virtualModules/virtualRuntimeInitStatus.ts
649
- const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
650
- const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
651
- function getRuntimeInitGlobalKey() {
652
- return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
653
- }
654
- function getDeferredInitPromiseCode() {
655
- return `let initResolve, initReject;
656
- const initPromise = new Promise((re, rj) => {
657
- initResolve = re;
658
- initReject = rj;
659
- });`;
660
- }
661
- function getSsrNoopResolveCode() {
662
- return `if (typeof window === 'undefined') {
663
- initResolve({
664
- loadRemote: function() { return Promise.resolve(undefined); },
665
- loadShare: function() { return Promise.resolve(undefined); },
666
- });
667
- }`;
668
- }
669
- function getRuntimeInitStateBootstrapCode(options) {
670
- return `
671
- const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
672
- let ${options.stateVar} = globalThis[${options.globalKeyVar}];
673
- if (!${options.stateVar}) {
674
- ${getDeferredInitPromiseCode()}
675
- ${options.stateVar} = globalThis[${options.globalKeyVar}] = {
676
- initPromise,
677
- initResolve,
678
- initReject,
679
- };
680
- ${getSsrNoopResolveCode()}
681
- }
682
- const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
683
- `;
684
- }
685
- function getRuntimeInitBootstrapCode() {
686
- return `
687
- const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
688
- const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
689
- globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
690
- globalThis[moduleCacheGlobalKey].share ||= {};
691
- globalThis[moduleCacheGlobalKey].remote ||= {};
692
- if (!globalThis[globalKey]) {
693
- ${getDeferredInitPromiseCode()}
694
- globalThis[globalKey] = {
695
- initPromise,
696
- initResolve,
697
- initReject,
698
- moduleCache: globalThis[moduleCacheGlobalKey],
699
- };
700
- ${getSsrNoopResolveCode()}
701
- }
702
- globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
703
- globalThis[globalKey].moduleCache.share ||= {};
704
- globalThis[globalKey].moduleCache.remote ||= {};
705
- `;
706
- }
707
- function getRuntimeModuleCacheBootstrapCode() {
708
- return `
709
- const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
710
- globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
711
- globalThis[__mfCacheGlobalKey].share ||= {};
712
- globalThis[__mfCacheGlobalKey].remote ||= {};
713
- const __mfModuleCache = globalThis[__mfCacheGlobalKey];
714
- `;
715
- }
716
- function getRuntimeInitResolveBootstrapCode() {
717
- return getRuntimeInitStateBootstrapCode({
718
- globalKeyVar: "__mfResolveGlobalKey",
719
- stateVar: "__mfResolveState",
720
- exposedConst: "initResolve",
721
- exposedProperty: "initResolve"
722
- });
723
- }
724
- function writeRuntimeInitStatus(command) {
725
- const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
726
- export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
727
- virtualRuntimeInitStatus.writeSync(`
728
- ${getRuntimeInitBootstrapCode()}
729
- ${exportStatement}
730
- `);
731
- }
732
- //#endregion
733
- //#region src/utils/localSharedImportMap_temp.ts
734
- /**
735
- * https://github.com/module-federation/vite/issues/68
736
- */
737
- function getLocalSharedImportMapPath_temp() {
738
- const { name } = getNormalizeModuleFederationOptions();
739
- return pathe.default.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
740
- }
741
- function writeLocalSharedImportMap_temp(content) {
742
- createFile(getLocalSharedImportMapPath_temp() + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
743
- }
744
- function createFile(filePath, content) {
745
- (0, fs.mkdirSync)(pathe.default.dirname(filePath), { recursive: true });
746
- (0, fs.writeFileSync)(filePath, content);
747
- }
748
- //#endregion
749
769
  //#region src/utils/serializeRuntimeOptions.ts
750
770
  /**
751
771
  * Serializes a JavaScript object into a string of source code that can be evaluated.
@@ -876,6 +896,91 @@ function generateExposes(options) {
876
896
  `;
877
897
  }
878
898
  //#endregion
899
+ //#region src/virtualModules/virtualRuntimeInitStatus.ts
900
+ const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
901
+ const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
902
+ function getRuntimeInitGlobalKey() {
903
+ return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
904
+ }
905
+ function getDeferredInitPromiseCode() {
906
+ return `let initResolve, initReject;
907
+ const initPromise = new Promise((re, rj) => {
908
+ initResolve = re;
909
+ initReject = rj;
910
+ });`;
911
+ }
912
+ function getSsrNoopResolveCode() {
913
+ return `if (typeof window === 'undefined') {
914
+ initResolve({
915
+ loadRemote: function() { return Promise.resolve(undefined); },
916
+ loadShare: function() { return Promise.resolve(undefined); },
917
+ });
918
+ }`;
919
+ }
920
+ function getRuntimeInitStateBootstrapCode(options) {
921
+ return `
922
+ const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
923
+ let ${options.stateVar} = globalThis[${options.globalKeyVar}];
924
+ if (!${options.stateVar}) {
925
+ ${getDeferredInitPromiseCode()}
926
+ ${options.stateVar} = globalThis[${options.globalKeyVar}] = {
927
+ initPromise,
928
+ initResolve,
929
+ initReject,
930
+ };
931
+ ${getSsrNoopResolveCode()}
932
+ }
933
+ const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
934
+ `;
935
+ }
936
+ function getRuntimeInitBootstrapCode() {
937
+ return `
938
+ const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
939
+ const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
940
+ globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
941
+ globalThis[moduleCacheGlobalKey].share ||= {};
942
+ globalThis[moduleCacheGlobalKey].remote ||= {};
943
+ if (!globalThis[globalKey]) {
944
+ ${getDeferredInitPromiseCode()}
945
+ globalThis[globalKey] = {
946
+ initPromise,
947
+ initResolve,
948
+ initReject,
949
+ moduleCache: globalThis[moduleCacheGlobalKey],
950
+ };
951
+ ${getSsrNoopResolveCode()}
952
+ }
953
+ globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
954
+ globalThis[globalKey].moduleCache.share ||= {};
955
+ globalThis[globalKey].moduleCache.remote ||= {};
956
+ `;
957
+ }
958
+ function getRuntimeModuleCacheBootstrapCode() {
959
+ return `
960
+ const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
961
+ globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
962
+ globalThis[__mfCacheGlobalKey].share ||= {};
963
+ globalThis[__mfCacheGlobalKey].remote ||= {};
964
+ const __mfModuleCache = globalThis[__mfCacheGlobalKey];
965
+ `;
966
+ }
967
+ function getRuntimeInitResolveBootstrapCode() {
968
+ return getRuntimeInitStateBootstrapCode({
969
+ globalKeyVar: "__mfResolveGlobalKey",
970
+ stateVar: "__mfResolveState",
971
+ exposedConst: "initResolve",
972
+ exposedProperty: "initResolve"
973
+ });
974
+ }
975
+ function writeRuntimeInitStatus(command) {
976
+ const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
977
+ export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
978
+ virtualRuntimeInitStatus.writeSync(`
979
+ ${getRuntimeInitBootstrapCode()}
980
+ ${exportStatement}
981
+ `);
982
+ }
983
+ //#endregion
879
984
  //#region src/virtualModules/virtualShared_preBuild.ts
880
985
  /**
881
986
  * Even the resolveId hook cannot interfere with vite pre-build,
@@ -1018,7 +1123,16 @@ function getLocalProviderImportPath(pkg) {
1018
1123
  const resolved = (0, module$1.createRequire)(new URL(`file://${pathe.default.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
1019
1124
  return isWorkspaceFilePath(resolved) ? resolved : void 0;
1020
1125
  } catch {
1021
- return;
1126
+ const resolved = getInstalledPackageEntry(pkg, {
1127
+ conditions: [
1128
+ "browser",
1129
+ "import",
1130
+ "module",
1131
+ "default"
1132
+ ],
1133
+ resolveSubpathWithRequire: false
1134
+ });
1135
+ return isWorkspaceFilePath(resolved) ? resolved : void 0;
1022
1136
  }
1023
1137
  }
1024
1138
  function getProjectResolvedImportPath(pkg) {
@@ -1033,7 +1147,12 @@ function getProjectResolvedImportPath(pkg) {
1033
1147
  }
1034
1148
  }
1035
1149
  function isWorkspaceFilePath(resolved) {
1036
- return !!resolved && !resolved.includes("/node_modules/") && !resolved.includes("\\node_modules\\");
1150
+ if (!resolved) return false;
1151
+ let realResolved = resolved;
1152
+ try {
1153
+ realResolved = fs.realpathSync.native(resolved);
1154
+ } catch {}
1155
+ return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
1037
1156
  }
1038
1157
  function isWorkspacePackageEntry(pkg, resolved) {
1039
1158
  if (!resolved || !pathe.default.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
@@ -1146,11 +1265,12 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1146
1265
  const isWorkspacePackage = isWorkspacePackageEntry(pkg, localProviderPath) || isWorkspacePackageEntry(pkg, concreteSharedImportSource);
1147
1266
  const lazyLocalFallbackSource = concreteSharedImportSource || localProviderPath || sharedImportSource;
1148
1267
  const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
1268
+ const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1149
1269
  const namedExports = getPackageNamedExports(pkg);
1150
1270
  let exportLine;
1151
1271
  if (namedExports.length > 0) exportLine = `export default exportModule.default ?? exportModule;\n ${`const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`}\n ${`export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`}`;
1272
+ else if (usesLazyLocalFallback) exportLine = `export default exportModule.default ?? exportModule`;
1152
1273
  else exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1153
- const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1154
1274
  const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
1155
1275
  const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
1156
1276
  loadShareCacheMap[pkg].writeSync(`
@@ -1175,15 +1295,24 @@ function getUsedShares() {
1175
1295
  function addUsedShares(pkg) {
1176
1296
  usedShares.add(pkg);
1177
1297
  }
1298
+ const LOCAL_SHARED_IMPORT_MAP_ID = "virtual:mf-localSharedImportMap";
1178
1299
  function getLocalSharedImportMapPath() {
1179
- return getLocalSharedImportMapPath_temp();
1300
+ const { internalName, name } = getNormalizeModuleFederationOptions();
1301
+ return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(internalName || name)}`;
1302
+ }
1303
+ function getResolvedLocalSharedImportMapId() {
1304
+ return `\0${getLocalSharedImportMapPath()}`;
1305
+ }
1306
+ let invalidateLocalSharedImportMap;
1307
+ function setLocalSharedImportMapInvalidator(invalidator) {
1308
+ invalidateLocalSharedImportMap = invalidator;
1180
1309
  }
1181
1310
  let prevLocalSharedImportMapContent;
1182
1311
  function writeLocalSharedImportMap() {
1183
1312
  const nextContent = generateLocalSharedImportMap();
1184
1313
  if (prevLocalSharedImportMapContent !== nextContent) {
1185
1314
  prevLocalSharedImportMapContent = nextContent;
1186
- writeLocalSharedImportMap_temp(nextContent);
1315
+ invalidateLocalSharedImportMap?.();
1187
1316
  }
1188
1317
  }
1189
1318
  function shouldUseDirectReactImport() {
@@ -1292,7 +1421,7 @@ function getOrderedUsedShares() {
1292
1421
  const shares = new Set(getUsedShares());
1293
1422
  try {
1294
1423
  Object.keys(getNormalizeModuleFederationOptions().shared).forEach((pkg) => {
1295
- shares.add(pkg.endsWith("/") ? pkg.slice(0, -1) : pkg);
1424
+ if (!pkg.endsWith("/")) shares.add(pkg);
1296
1425
  });
1297
1426
  } catch {}
1298
1427
  return Array.from(shares).sort((a, b) => {
@@ -1306,12 +1435,8 @@ function getShareItemForPreload(pkg) {
1306
1435
  if (isExplicitSharedKey(pkg)) return shared[pkg];
1307
1436
  if (isExplicitSharedKey(wildcardKey)) return shared[wildcardKey];
1308
1437
  }
1309
- function generateDirectSharedCacheSeedCode(command = "build") {
1310
- return getOrderedUsedShares().map((pkg) => {
1311
- const shareItem = getShareItemForPreload(pkg);
1312
- if (!shareItem || shareItem.shareConfig.import === false) return null;
1313
- const importPath = command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem);
1314
- return `if (__mfModuleCache.share[${JSON.stringify(pkg)}] === undefined) {
1438
+ function generateSharedCacheSeedItem(pkg, importPath) {
1439
+ return `if (__mfModuleCache.share[${JSON.stringify(pkg)}] === undefined) {
1315
1440
  const mod = await import(${JSON.stringify(importPath)});
1316
1441
  const exportModule = ${JSON.stringify(shouldUseDirectReactImport())} && ${JSON.stringify(pkg)} === "react"
1317
1442
  ? (mod?.default ?? mod)
@@ -1322,6 +1447,33 @@ function generateDirectSharedCacheSeedCode(command = "build") {
1322
1447
  });
1323
1448
  __mfModuleCache.share[${JSON.stringify(pkg)}] = exportModule;
1324
1449
  }`;
1450
+ }
1451
+ function generateDirectSharedCacheSeedCode(command = "build") {
1452
+ return getOrderedUsedShares().map((pkg) => {
1453
+ const shareItem = getShareItemForPreload(pkg);
1454
+ if (!shareItem || shareItem.shareConfig.import === false) return null;
1455
+ return generateSharedCacheSeedItem(pkg, command === "serve" ? getLocalSharedPackagePath(pkg, shareItem) : getDirectSharedCacheSeedImportPath(pkg, shareItem));
1456
+ }).filter((item) => item !== null).join("\n");
1457
+ }
1458
+ function getBrowserImportPath(importPath) {
1459
+ if (/^(?:[a-zA-Z]:[\\/]|\/)/.test(importPath) && !importPath.startsWith("/@")) return `/@fs/${importPath}`;
1460
+ return importPath;
1461
+ }
1462
+ function getHostAutoInitSharedSeedItems() {
1463
+ return getOrderedUsedShares().map((pkg) => ({
1464
+ pkg,
1465
+ shareItem: getShareItemForPreload(pkg)
1466
+ })).filter(({ shareItem }) => shareItem?.shareConfig.import === false).sort((a, b) => {
1467
+ const priority = (pkg) => pkg === "vue" ? 0 : pkg === "pinia" ? 1 : 2;
1468
+ const aIsLocal = !!getLocalProviderImportPath(a.pkg);
1469
+ const bIsLocal = !!getLocalProviderImportPath(b.pkg);
1470
+ return priority(a.pkg) - priority(b.pkg) || Number(aIsLocal) - Number(bIsLocal) || a.pkg.localeCompare(b.pkg);
1471
+ });
1472
+ }
1473
+ function generateHostAutoInitSharedCacheSeedCode() {
1474
+ return getHostAutoInitSharedSeedItems().map(({ pkg, shareItem }) => {
1475
+ if (!shareItem) return null;
1476
+ return generateSharedCacheSeedItem(pkg, getBrowserImportPath(getDirectSharedCacheSeedImportPath(pkg, shareItem)));
1325
1477
  }).filter((item) => item !== null).join("\n");
1326
1478
  }
1327
1479
  const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
@@ -1360,14 +1512,40 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1360
1512
  let runtimeInstance
1361
1513
  let localSharedImportMapPromise
1362
1514
  let exposesMapPromise
1515
+ const shouldRetrySharedInitError = ${command !== "build"} && ((error) => {
1516
+ const message = String((error && error.message) || error || '');
1517
+ return message.includes('Importing a module script failed') ||
1518
+ message.includes('Failed to fetch') ||
1519
+ message.includes('Load failed') ||
1520
+ message.includes('Outdated Optimize Dep');
1521
+ });
1522
+ const waitSharedInitRetry = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1523
+ async function retrySharedInit(fn) {
1524
+ for (let attempt = 0; ; attempt++) {
1525
+ try {
1526
+ return await fn();
1527
+ } catch (e) {
1528
+ const canRetry = typeof shouldRetrySharedInitError === 'function' && shouldRetrySharedInitError(e);
1529
+ if (!canRetry || attempt >= 19) throw e;
1530
+ await waitSharedInitRetry(250);
1531
+ }
1532
+ }
1533
+ }
1363
1534
 
1364
1535
  async function getLocalSharedImportMap() {
1365
- localSharedImportMapPromise ??= import("${getLocalSharedImportMapPath()}")
1536
+ if (!localSharedImportMapPromise) {
1537
+ localSharedImportMapPromise = retrySharedInit(() => import("${getLocalSharedImportMapPath()}"))
1538
+ .catch((e) => { localSharedImportMapPromise = undefined; throw e; });
1539
+ }
1366
1540
  return localSharedImportMapPromise
1367
1541
  }
1368
1542
 
1369
1543
  async function getExposesMap() {
1370
- exposesMapPromise ??= import("${virtualExposesId}").then((mod) => mod.default ?? mod)
1544
+ if (!exposesMapPromise) {
1545
+ exposesMapPromise = retrySharedInit(() => import("${virtualExposesId}"))
1546
+ .then((mod) => mod.default ?? mod)
1547
+ .catch((e) => { exposesMapPromise = undefined; throw e; });
1548
+ }
1371
1549
  return exposesMapPromise
1372
1550
  }
1373
1551
 
@@ -1396,11 +1574,13 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1396
1574
  initRes.initShareScopeMap('${options.shareScope}', shared);
1397
1575
  initResolve(initRes)
1398
1576
  try {
1399
- await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1400
- strategy: '${options.shareStrategy}',
1401
- from: "build",
1402
- initScope
1403
- }));
1577
+ await retrySharedInit(async () => {
1578
+ await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1579
+ strategy: '${options.shareStrategy}',
1580
+ from: "build",
1581
+ initScope
1582
+ }));
1583
+ });
1404
1584
  } catch (e) {
1405
1585
  console.error('[Module Federation]', e)
1406
1586
  }
@@ -1428,6 +1608,7 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build") {
1428
1608
  async function initHost() {
1429
1609
  if (!hostInitPromise) {
1430
1610
  hostInitPromise = (async () => {
1611
+ ${generateHostAutoInitSharedCacheSeedCode()}
1431
1612
  const remoteEntry = await import(${remoteEntryImport});
1432
1613
  const runtime = await remoteEntry.init();
1433
1614
  const usedShared = ${generateUsedSharedPreloadConfig()};
@@ -1681,17 +1862,26 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1681
1862
  }
1682
1863
  return patched;
1683
1864
  }
1684
- function getBootstrapSource(initSrc, entrySrc) {
1685
- const remotePreloads = Object.values(getUsedRemotesMap()).flatMap((remotes) => Array.from(remotes)).filter((remote) => remote.includes("/")).sort().map((remote) => `runtime.loadRemote(${JSON.stringify(remote)})`).join(",");
1865
+ function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
1866
+ const remotePreloads = Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `runtime.loadRemote(${JSON.stringify(remote)})`).join(",");
1867
+ const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
1868
+ globalThis.System && typeof globalThis.System.import === 'function'
1869
+ ? globalThis.System.import(src)
1870
+ : import(src);
1871
+ ` : "";
1872
+ const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
1686
1873
  return `${getRuntimeModuleCacheBootstrapCode()}
1687
- (async () => {
1688
- const { initHost } = await import(${JSON.stringify(initSrc)});
1874
+ ${importHelper}(async () => {
1875
+ const { initHost } = await ${importExpression(initSrc)};
1689
1876
  const runtime = await initHost();
1690
1877
  const __mfRemotePreloads = [${remotePreloads}];
1691
1878
  await Promise.all(__mfRemotePreloads);
1692
- })().then(() => import(${JSON.stringify(entrySrc)}));
1879
+ })().then(() => ${importExpression(entrySrc)});
1693
1880
  `;
1694
1881
  }
1882
+ function getSystemBootstrapSource(initSrc, entrySrc) {
1883
+ return getBootstrapSource(initSrc, entrySrc, true);
1884
+ }
1695
1885
  function injectHtml() {
1696
1886
  return inject === "html" && (htmlFilePath || hasPackageDependency("@sveltejs/kit"));
1697
1887
  }
@@ -1831,7 +2021,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1831
2021
  const bootstrapRef = this.emitFile({
1832
2022
  type: "asset",
1833
2023
  fileName: bootstrapFileName,
1834
- source: getBootstrapSource(initPath, entrySrc)
2024
+ source: getSystemBootstrapSource(initPath, entrySrc)
1835
2025
  });
1836
2026
  const bootstrapPath = viteConfig.base + this.getFileName(bootstrapRef);
1837
2027
  return scriptTag.replace(entrySrc, bootstrapPath);
@@ -1976,7 +2166,7 @@ function getHmrWsPath(base, hmrPath) {
1976
2166
  return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
1977
2167
  }
1978
2168
  function shouldIgnoreFile(file, options) {
1979
- return file.includes("/node_modules/") || file.includes("\\node_modules\\") || file.includes(`/${options.virtualModuleDir}/`) || file.includes(`\\${options.virtualModuleDir}\\`) || file.includes("/.vite/") || file.includes("\\.vite\\") || file.includes("/.__mf__temp/") || file.includes("\\.__mf__temp\\") || file.includes("/.mf/") || file.includes("\\.mf\\") || file.includes("/mf-manifest.json") || file.includes("\\mf-manifest.json") || file.includes("/mf-stats.json") || file.includes("\\mf-stats.json");
2169
+ return file.includes("/node_modules/") || file.includes("\\node_modules\\") || file.includes(`/${options.virtualModuleDir}/`) || file.includes(`\\${options.virtualModuleDir}\\`) || file.includes("/.vite/") || file.includes("\\.vite\\") || file.includes("/.mf/") || file.includes("\\.mf\\") || file.includes("/mf-manifest.json") || file.includes("\\mf-manifest.json") || file.includes("/mf-stats.json") || file.includes("\\mf-stats.json");
1980
2170
  }
1981
2171
  function getRemoteHmrWsUrl(server) {
1982
2172
  const hmr = server.config.server.hmr;
@@ -2017,7 +2207,22 @@ function getStringPreview(value, max = 180) {
2017
2207
  return rawValue.slice(0, max);
2018
2208
  }
2019
2209
  function isRemoteHmrEnabled(dev) {
2020
- return typeof dev === "object" && dev !== null && dev.remoteHmr === true;
2210
+ return typeof dev === "object" && dev !== null && !!dev.remoteHmr;
2211
+ }
2212
+ /**
2213
+ * Detects whether the Vite plugin pipeline includes a framework with
2214
+ * cross-federation HMR support (a shared runtime proxy that works
2215
+ * across module federation boundaries).
2216
+ *
2217
+ * Currently only React is supported via the shared /@react-refresh proxy.
2218
+ */
2219
+ function hasCrossFederationHmr(plugins) {
2220
+ const supportedPlugins = ["vite:react-refresh", "vite:react-swc:refresh"];
2221
+ return plugins.some((p) => supportedPlugins.includes(p.name));
2222
+ }
2223
+ function resolveHmrStrategy(dev, plugins) {
2224
+ if (typeof dev === "object" && dev !== null && dev.remoteHmr === "full-reload") return "full-reload";
2225
+ return hasCrossFederationHmr(plugins) ? "native" : "full-reload";
2021
2226
  }
2022
2227
  function pluginDevRemoteHmr(options) {
2023
2228
  return {
@@ -2027,6 +2232,7 @@ function pluginDevRemoteHmr(options) {
2027
2232
  if (!isRemoteHmrEnabled(options.dev)) return;
2028
2233
  const isRemote = Object.keys(options.exposes).length > 0;
2029
2234
  const isHost = Object.keys(options.remotes).length > 0;
2235
+ const strategy = resolveHmrStrategy(options.dev, server.config.plugins);
2030
2236
  if (isRemote) {
2031
2237
  const endpointPath = getRemoteHmrPath(server.config.base);
2032
2238
  const wsUrl = getRemoteHmrWsUrl(server);
@@ -2050,6 +2256,7 @@ function pluginDevRemoteHmr(options) {
2050
2256
  }));
2051
2257
  });
2052
2258
  const broadcast = (file) => {
2259
+ if (strategy === "native") return;
2053
2260
  if (shouldIgnoreFile(file, options)) return;
2054
2261
  server.ws.send({
2055
2262
  type: "custom",
@@ -2114,6 +2321,7 @@ function pluginDevRemoteHmr(options) {
2114
2321
  }
2115
2322
  const ws = new WebSocket(metadata.wsUrl, "vite-hmr");
2116
2323
  ws.onmessage = (rawEvent) => {
2324
+ if (strategy === "native") return;
2117
2325
  const message = parseRemoteHmrMessage(rawEvent.data);
2118
2326
  if (!message || message.event !== REMOTE_HMR_EVENT) return;
2119
2327
  server.ws.send({ type: "full-reload" });
@@ -2138,6 +2346,7 @@ function pluginDevRemoteHmr(options) {
2138
2346
  };
2139
2347
  for (const [remoteName, remote] of Object.entries(options.remotes)) connectRemote(remoteName, remote);
2140
2348
  const triggerHostReload = (file) => {
2349
+ if (strategy === "native") return;
2141
2350
  if (shouldIgnoreFile(file, options)) return;
2142
2351
  server.ws.send({ type: "full-reload" });
2143
2352
  };
@@ -2460,6 +2669,26 @@ function initVirtualModules(command, remoteEntryId) {
2460
2669
  }
2461
2670
  //#endregion
2462
2671
  //#region src/utils/bundleHelpers.ts
2672
+ function isOutputChunk$1(chunk) {
2673
+ return chunk.type === "chunk";
2674
+ }
2675
+ function escapeRegExp(value) {
2676
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2677
+ }
2678
+ function getProxyBaseName(fileName) {
2679
+ return fileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
2680
+ }
2681
+ function extractFunctionDeclaration(code, functionName) {
2682
+ const funcRe = new RegExp(`function\\s+${functionName}\\s*\\([^)]*\\)\\s*\\{`);
2683
+ const funcStart = code.search(funcRe);
2684
+ if (funcStart < 0) return;
2685
+ let depth = 0;
2686
+ for (let i = code.indexOf("{", funcStart); i < code.length; i++) if (code[i] === "{") depth++;
2687
+ else if (code[i] === "}") {
2688
+ depth--;
2689
+ if (depth === 0) return code.slice(funcStart, i + 1);
2690
+ }
2691
+ }
2463
2692
  /**
2464
2693
  * Resolve the local alias for a non-inlineable proxy binding.
2465
2694
  * If Rollup's deconflict renamed the alias but didn't update references
@@ -2482,6 +2711,147 @@ function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals
2482
2711
  local
2483
2712
  };
2484
2713
  }
2714
+ function collectLoadShareProxyChunks(bundle, loadShareTag) {
2715
+ const proxyChunks = /* @__PURE__ */ new Map();
2716
+ for (const [fileName, chunk] of Object.entries(bundle)) {
2717
+ if (!isOutputChunk$1(chunk)) continue;
2718
+ if (fileName.includes(loadShareTag) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
2719
+ code: chunk.code,
2720
+ fileName
2721
+ });
2722
+ }
2723
+ return proxyChunks;
2724
+ }
2725
+ function collectSystemProxyInfos(proxyChunks, loadShareTag) {
2726
+ const systemProxyInfo = /* @__PURE__ */ new Map();
2727
+ for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
2728
+ const depsMatch = proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);
2729
+ if (!depsMatch) continue;
2730
+ const loadShareDep = Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).find((dep) => dep.includes(loadShareTag) && !dep.includes("commonjs-proxy"));
2731
+ if (!loadShareDep) continue;
2732
+ const loadShareBindings = {};
2733
+ for (const m of proxyInfo.code.matchAll(/([A-Za-z_$][\w$]*)\s*=\s*module\d+\.([A-Za-z_$][\w$]*)/g)) loadShareBindings[m[1]] = m[2];
2734
+ const exportMap = {};
2735
+ const objectExportMatch = proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);
2736
+ if (objectExportMatch) for (const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)) {
2737
+ const [, exported, local] = m;
2738
+ const funcBody = extractFunctionDeclaration(proxyInfo.code, local);
2739
+ if (funcBody) exportMap[exported] = {
2740
+ type: "helper",
2741
+ code: funcBody
2742
+ };
2743
+ }
2744
+ for (const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)) {
2745
+ const exported = m[1];
2746
+ const expression = m[2];
2747
+ for (const [local, exportName] of Object.entries(loadShareBindings)) if (new RegExp(`\\b${local}\\b`).test(expression)) {
2748
+ exportMap[exported] = {
2749
+ type: "reexport",
2750
+ exportName
2751
+ };
2752
+ break;
2753
+ }
2754
+ }
2755
+ if (Object.keys(exportMap).length > 0) systemProxyInfo.set(proxyFileName, {
2756
+ loadShareDep,
2757
+ exportMap
2758
+ });
2759
+ }
2760
+ return systemProxyInfo;
2761
+ }
2762
+ function rewriteEsmProxyConsumers(code, proxyChunks) {
2763
+ let nextCode = code;
2764
+ const claimedLocals = /* @__PURE__ */ new Set();
2765
+ for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
2766
+ const proxyBaseName = getProxyBaseName(proxyFileName);
2767
+ const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);
2768
+ if (!importMatch) continue;
2769
+ const fullImport = importMatch[0];
2770
+ const bindings = importMatch[1].split(",").map((s) => {
2771
+ const parts = s.trim().split(/\s+as\s+/);
2772
+ return {
2773
+ imported: parts[0].trim(),
2774
+ local: (parts[1] || parts[0]).trim()
2775
+ };
2776
+ });
2777
+ const exportMapMatch = proxyInfo.code.match(/export\s*\{([^}]+)\}/);
2778
+ if (!exportMapMatch) continue;
2779
+ const exportMap = {};
2780
+ for (const entry of exportMapMatch[1].split(",")) {
2781
+ const parts = entry.trim().split(/\s+as\s+/);
2782
+ if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
2783
+ }
2784
+ const inlineable = [];
2785
+ const nonInlineable = [];
2786
+ const pendingLocals = new Set(bindings.map((binding) => binding.local));
2787
+ for (const b of bindings) {
2788
+ pendingLocals.delete(b.local);
2789
+ const proxyLocal = exportMap[b.imported];
2790
+ if (!proxyLocal) {
2791
+ claimedLocals.add(b.local);
2792
+ nonInlineable.push(b);
2793
+ continue;
2794
+ }
2795
+ const funcBody = extractFunctionDeclaration(proxyInfo.code, proxyLocal);
2796
+ if (funcBody) {
2797
+ inlineable.push({
2798
+ local: b.local,
2799
+ funcBody: funcBody.replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`)
2800
+ });
2801
+ claimedLocals.add(b.local);
2802
+ } else {
2803
+ const unavailableLocals = new Set(claimedLocals);
2804
+ pendingLocals.forEach((local) => unavailableLocals.add(local));
2805
+ const resolvedBinding = resolveProxyAlias(b, proxyLocal, nextCode, fullImport, unavailableLocals);
2806
+ claimedLocals.add(resolvedBinding.local);
2807
+ nonInlineable.push(resolvedBinding);
2808
+ }
2809
+ }
2810
+ const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
2811
+ if (inlineable.length === 0 && !hasRenamedAlias) continue;
2812
+ let replacement = "";
2813
+ if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
2814
+ replacement += inlineable.map((f) => f.funcBody).join("");
2815
+ nextCode = nextCode.replace(fullImport, () => replacement);
2816
+ }
2817
+ return nextCode;
2818
+ }
2819
+ function rewriteSystemProxyConsumers(code, systemProxyInfo) {
2820
+ if (!code.includes("System.register(")) return code;
2821
+ let nextCode = code;
2822
+ for (const [proxyFileName, proxyInfo] of Array.from(systemProxyInfo.entries())) {
2823
+ const proxyBaseName = getProxyBaseName(proxyFileName);
2824
+ const depMatch = new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);
2825
+ if (!depMatch) continue;
2826
+ let setterIndex = 0;
2827
+ const depListMatch = nextCode.match(/System\.register\(\[([\s\S]*?)\]/);
2828
+ if (depListMatch) setterIndex = Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).findIndex((dep) => dep.includes(proxyBaseName));
2829
+ if (setterIndex < 0) continue;
2830
+ const settersStart = nextCode.indexOf("setters: [");
2831
+ if (settersStart < 0) continue;
2832
+ const setterMatch = Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];
2833
+ if (!setterMatch) continue;
2834
+ const [fullSetter, moduleLocal, setterBody] = setterMatch;
2835
+ const helpersToInline = [];
2836
+ const nextSetterBody = setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`, "g"), (assignment, local, imported) => {
2837
+ const mapped = proxyInfo.exportMap[imported];
2838
+ if (!mapped) return assignment;
2839
+ if (mapped.type === "helper") {
2840
+ helpersToInline.push(mapped.code.replace(new RegExp(`function\\s+${imported}\\s*\\(`), `function ${local}(`));
2841
+ return "";
2842
+ }
2843
+ return `${local} = ${moduleLocal}.${mapped.exportName};`;
2844
+ });
2845
+ if (nextSetterBody === setterBody && helpersToInline.length === 0) continue;
2846
+ const nextSetter = fullSetter.replace(setterBody, () => nextSetterBody);
2847
+ nextCode = nextCode.replace(fullSetter, () => nextSetter);
2848
+ nextCode = nextCode.replace(depMatch[0], JSON.stringify(proxyInfo.loadShareDep));
2849
+ if (helpersToInline.length > 0) nextCode = nextCode.replace("execute: (function() {", () => {
2850
+ return `execute: (function() {${helpersToInline.join("")}`;
2851
+ });
2852
+ }
2853
+ return nextCode;
2854
+ }
2485
2855
  function findRemoteEntryFile(filename, bundle) {
2486
2856
  for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
2487
2857
  }
@@ -2631,6 +3001,12 @@ const COMMON_SHARED_SUBPATHS = {
2631
3001
  "react-dom/client",
2632
3002
  "react-dom/server",
2633
3003
  "react-dom/server.browser"
3004
+ ],
3005
+ "solid-js": [
3006
+ "solid-js/web",
3007
+ "solid-js/store",
3008
+ "solid-js/html",
3009
+ "solid-js/h"
2634
3010
  ]
2635
3011
  };
2636
3012
  function removeTrailingSlash(value) {
@@ -2645,6 +3021,9 @@ function normalizeNodeModulePath(source) {
2645
3021
  function isNodeModulePath(source) {
2646
3022
  return source.includes("/node_modules/") || source.includes("\\node_modules\\");
2647
3023
  }
3024
+ function filterId(id) {
3025
+ return typeof id === "string" && !id.includes("\0");
3026
+ }
2648
3027
  function getMatchingNodeModuleSubpath(source, candidates) {
2649
3028
  const normalized = normalizeNodeModulePath(source);
2650
3029
  return [...candidates].sort((a, b) => b.length - a.length).find((candidate) => normalized.includes(`/node_modules/${candidate}/`) || normalized.includes(`/node_modules/${candidate}.`));
@@ -2829,10 +3208,11 @@ const Manifest = () => {
2829
3208
  alias: remoteKey,
2830
3209
  entry: "*"
2831
3210
  })));
2832
- const shared = Array.from(getUsedShares()).map((shareKey) => {
3211
+ const shared = Array.from(getUsedShares()).flatMap((shareKey) => {
2833
3212
  const shareItem = getNormalizeShareItem(shareKey);
3213
+ if (!shareItem) return [];
2834
3214
  const assets = preloadMap[shareKey] || createEmptyAssetMap();
2835
- return {
3215
+ return [{
2836
3216
  id: `${name}:${shareKey}`,
2837
3217
  name: shareKey,
2838
3218
  version: shareItem.version,
@@ -2848,7 +3228,7 @@ const Manifest = () => {
2848
3228
  sync: assets.css.sync
2849
3229
  }
2850
3230
  }
2851
- };
3231
+ }];
2852
3232
  });
2853
3233
  const exposes = Object.entries(options.exposes).map(([key, value]) => {
2854
3234
  const formatKey = key.replace("./", "");
@@ -3000,7 +3380,6 @@ function pluginModuleParseEnd_default(excludeFn, options) {
3000
3380
  }
3001
3381
  //#endregion
3002
3382
  //#region src/plugins/pluginProxyRemoteEntry.ts
3003
- const filter$1 = (0, _rollup_pluginutils.createFilter)();
3004
3383
  function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
3005
3384
  let viteConfig, _command, root;
3006
3385
  return {
@@ -3040,14 +3419,14 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3040
3419
  },
3041
3420
  transform(code, id) {
3042
3421
  return mapCodeToCodeWithSourcemap((() => {
3043
- if (!filter$1(id)) return;
3422
+ if (!filterId(id)) return;
3044
3423
  if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
3045
3424
  if (id === virtualExposesId) return generateExposes(options);
3046
3425
  if (id.includes(getHostAutoInitPath())) {
3047
3426
  if (_command === "serve") {
3048
3427
  const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
3049
3428
  const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
3050
- const fallbackOrigin = `http://${host}:${viteConfig.server?.port}`;
3429
+ const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
3051
3430
  const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
3052
3431
  return `
3053
3432
  const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
@@ -3098,10 +3477,25 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3098
3477
  }
3099
3478
  //#endregion
3100
3479
  //#region src/plugins/pluginProxyRemotes.ts
3101
- const filter = (0, _rollup_pluginutils.createFilter)();
3102
3480
  function isNodeModulesImporter(importer) {
3103
3481
  return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
3104
3482
  }
3483
+ function appendAlias(config, alias) {
3484
+ config.resolve ??= {};
3485
+ const existingAlias = config.resolve.alias;
3486
+ if (!existingAlias) {
3487
+ config.resolve.alias = [alias];
3488
+ return;
3489
+ }
3490
+ if (Array.isArray(existingAlias)) {
3491
+ existingAlias.push(alias);
3492
+ return;
3493
+ }
3494
+ config.resolve.alias = [...Object.entries(existingAlias).map(([find, replacement]) => ({
3495
+ find,
3496
+ replacement
3497
+ })), alias];
3498
+ }
3105
3499
  function pluginProxyRemotes_default(options) {
3106
3500
  let command;
3107
3501
  let root = process.cwd();
@@ -3118,19 +3512,20 @@ function pluginProxyRemotes_default(options) {
3118
3512
  }
3119
3513
  return {
3120
3514
  name: "proxyRemotes",
3515
+ enforce: "pre",
3121
3516
  config(config, { command: _command }) {
3122
3517
  command = _command;
3123
3518
  root = config.root || process.cwd();
3124
3519
  Object.keys(remotes).forEach((key) => {
3125
3520
  const remote = remotes[key];
3126
- config.resolve.alias.push({
3521
+ appendAlias(config, {
3127
3522
  find: new RegExp(`^(${remote.name}(\/.*|$))`),
3128
3523
  replacement: "$1"
3129
3524
  });
3130
3525
  });
3131
3526
  },
3132
3527
  resolveId(source, importer) {
3133
- if (!filter(source)) return;
3528
+ if (!filterId(source)) return;
3134
3529
  for (const remote of Object.values(remotes)) {
3135
3530
  if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
3136
3531
  return resolveRemoteId(source, importer, remote.name);
@@ -3231,7 +3626,7 @@ function excludeSharedSubDependencies(shared) {
3231
3626
  for (const dep of deps) {
3232
3627
  const depKey = sharedKeyByBase.get(dep);
3233
3628
  if (depKey && depKey !== parentKey) {
3234
- if (shared[depKey]?.shareConfig.import === false) continue;
3629
+ if (shared[depKey]?.shareConfig.singleton === true || shared[depKey]?.shareConfig.import === false) continue;
3235
3630
  mfWarn(`"${dep}" is a dependency of shared package "${parentKey}" and is also shared separately. This may cause initialization order issues in dev mode. Consider sharing only "${parentKey}".\n Auto-excluding "${dep}" from shared modules for dev mode.`);
3236
3631
  delete shared[depKey];
3237
3632
  sharedKeys.delete(depKey);
@@ -3247,15 +3642,27 @@ function proxySharedModule(options) {
3247
3642
  let useDirectReactImport = false;
3248
3643
  let useRolldown = false;
3249
3644
  const savePrebuild = new PromiseStore();
3645
+ let devServer;
3250
3646
  return [
3251
3647
  {
3252
3648
  name: "generateLocalSharedImportMap",
3253
3649
  enforce: "post",
3650
+ configureServer(server) {
3651
+ devServer = server;
3652
+ setLocalSharedImportMapInvalidator(() => {
3653
+ const module = server.moduleGraph.getModuleById(getResolvedLocalSharedImportMapId());
3654
+ if (module) server.moduleGraph.invalidateModule(module);
3655
+ });
3656
+ },
3657
+ resolveId(source) {
3658
+ if (source === getLocalSharedImportMapPath()) return getResolvedLocalSharedImportMapId();
3659
+ },
3254
3660
  load(id) {
3255
- if (id.includes(getLocalSharedImportMapPath())) return parsePromise.then((_) => generateLocalSharedImportMap());
3661
+ if (id === getResolvedLocalSharedImportMapId()) return parsePromise.then((_) => generateLocalSharedImportMap());
3256
3662
  },
3257
- transform(_, id) {
3258
- if (id.includes(getLocalSharedImportMapPath())) return mapCodeToCodeWithSourcemap(parsePromise.then((_) => generateLocalSharedImportMap()));
3663
+ closeBundle() {
3664
+ if (devServer) return;
3665
+ setLocalSharedImportMapInvalidator(void 0);
3259
3666
  }
3260
3667
  },
3261
3668
  {
@@ -3302,7 +3709,6 @@ function proxySharedModule(options) {
3302
3709
  if (importer && (importer.includes("hostAutoInit") || importer.includes("__H_A_I__"))) return;
3303
3710
  if (importer && importer.includes("__loadShare__")) return;
3304
3711
  if (importer && importer.includes("__prebuild__")) return;
3305
- if (key.endsWith("/") && source !== key.slice(0, -1)) return;
3306
3712
  const shareSource = isNodeModulePath(source) ? getCommonSharedSubpathFromNodeModulePath(source, key) || key : source;
3307
3713
  const loadSharePath = getLoadShareModulePath(shareSource, useRolldown);
3308
3714
  writeLoadShareModule(shareSource, shared[key], _command, useRolldown);
@@ -3387,7 +3793,7 @@ function wrapDynamicImport(original) {
3387
3793
  }
3388
3794
  function applyRewrites(code, imports, id) {
3389
3795
  if (imports.length === 0) return;
3390
- const ms = new magic_string.default(code);
3796
+ const ms = new CodeRewriter(code);
3391
3797
  let changed = false;
3392
3798
  let counter = 0;
3393
3799
  for (const imp of imports) switch (imp.kind) {
@@ -3435,7 +3841,7 @@ function applyRewrites(code, imports, id) {
3435
3841
  if (!changed) return;
3436
3842
  return {
3437
3843
  code: ms.toString(),
3438
- map: ms.generateMap({ hires: true })
3844
+ map: ms.generateMap(id)
3439
3845
  };
3440
3846
  }
3441
3847
  async function collectFromAST(ast, code, isRemoteImport) {
@@ -3877,6 +4283,9 @@ function ignoreFederationGeneratedFiles(config, options) {
3877
4283
  function isSharedResolverInternalImporter(importer) {
3878
4284
  return !!importer && (importer.includes("__loadShare__") || importer.includes("__prebuild__"));
3879
4285
  }
4286
+ function isCommonJsImporter(importer) {
4287
+ return !!importer && (importer.endsWith(".cjs") || importer.includes("/cjs/"));
4288
+ }
3880
4289
  function isOutputChunk(chunk) {
3881
4290
  return chunk.type === "chunk";
3882
4291
  }
@@ -3960,9 +4369,10 @@ function createEarlyVirtualModulesPlugin(options) {
3960
4369
  optimizeDeps.rolldownOptions.plugins ??= [];
3961
4370
  optimizeDeps.rolldownOptions.plugins.push({
3962
4371
  name: "module-federation:optimize-shared-resolver",
3963
- resolveId(source, importer) {
4372
+ resolveId(source, importer, options) {
4373
+ if (options?.kind?.startsWith("require")) return;
3964
4374
  if (isSharedResolverInternalImporter(importer)) return;
3965
- if (source !== "react/jsx-runtime" && source !== "react/jsx-dev-runtime") return;
4375
+ if (isCommonJsImporter(importer)) return;
3966
4376
  const key = findSharedKey(source, shared);
3967
4377
  if (!key) return;
3968
4378
  if (source.endsWith(".css")) return;
@@ -4043,7 +4453,7 @@ export default __mfShared.default ?? __mfShared;`
4043
4453
  optimizeDeps.include ??= [];
4044
4454
  optimizeDeps.exclude ??= [];
4045
4455
  const shouldBypassOptimizeDep = isLitShare(key);
4046
- if (isRolldown || shouldBypassOptimizeDep) optimizeDeps.exclude.push(key);
4456
+ if (shouldBypassOptimizeDep) optimizeDeps.exclude.push(key);
4047
4457
  if (!isRolldown && !shouldBypassOptimizeDep) optimizeDeps.include.push(getLoadShareImportId(key, isRolldown));
4048
4458
  optimizeDeps.include.push(getPreBuildLibImportId(key));
4049
4459
  for (const subpath of getCommonSharedSubpaths(key)) {
@@ -4273,87 +4683,17 @@ function federation(mfUserOptions) {
4273
4683
  if (!isFederationControlChunk(fileName, filename)) continue;
4274
4684
  chunk.code = sanitizeFederationControlChunk(chunk.code, fileName, filename);
4275
4685
  }
4276
- const proxyChunks = /* @__PURE__ */ new Map();
4277
- for (const [fileName, chunk] of Object.entries(bundle)) {
4278
- if (!isOutputChunk(chunk)) continue;
4279
- if (fileName.includes("__loadShare__") && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
4280
- code: chunk.code,
4281
- fileName
4282
- });
4283
- }
4284
- if (proxyChunks.size > 0) for (const [fileName, chunk] of Object.entries(bundle)) {
4285
- if (!isOutputChunk(chunk)) continue;
4286
- if (fileName.includes("__loadShare__")) continue;
4287
- let code = chunk.code;
4288
- let modified = false;
4289
- const claimedLocals = /* @__PURE__ */ new Set();
4290
- for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
4291
- const proxyBaseName = proxyFileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
4292
- const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${proxyBaseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^"']*)["']\\s*;?`).exec(code);
4293
- if (!importMatch) continue;
4294
- const fullImport = importMatch[0];
4295
- const bindings = importMatch[1].split(",").map((s) => {
4296
- const parts = s.trim().split(/\s+as\s+/);
4297
- return {
4298
- imported: parts[0].trim(),
4299
- local: (parts[1] || parts[0]).trim()
4300
- };
4301
- });
4302
- const proxyCode = proxyInfo.code;
4303
- const exportMapMatch = proxyCode.match(/export\s*\{([^}]+)\}/);
4304
- if (!exportMapMatch) continue;
4305
- const exportMap = {};
4306
- for (const entry of exportMapMatch[1].split(",")) {
4307
- const parts = entry.trim().split(/\s+as\s+/);
4308
- if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
4309
- }
4310
- const inlineable = [];
4311
- const nonInlineable = [];
4312
- const pendingLocals = new Set(bindings.map((binding) => binding.local));
4313
- for (const b of bindings) {
4314
- pendingLocals.delete(b.local);
4315
- const proxyLocal = exportMap[b.imported];
4316
- if (!proxyLocal) {
4317
- claimedLocals.add(b.local);
4318
- nonInlineable.push(b);
4319
- continue;
4320
- }
4321
- const funcRe = new RegExp(`function\\s+${proxyLocal}\\s*\\([^)]*\\)\\s*\\{`);
4322
- if (funcRe.test(proxyCode)) {
4323
- const funcStart = proxyCode.search(funcRe);
4324
- let depth = 0;
4325
- let funcEnd = funcStart;
4326
- for (let i = proxyCode.indexOf("{", funcStart); i < proxyCode.length; i++) if (proxyCode[i] === "{") depth++;
4327
- else if (proxyCode[i] === "}") {
4328
- depth--;
4329
- if (depth === 0) {
4330
- funcEnd = i + 1;
4331
- break;
4332
- }
4333
- }
4334
- const renamedFunc = proxyCode.slice(funcStart, funcEnd).replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`);
4335
- inlineable.push({
4336
- local: b.local,
4337
- funcBody: renamedFunc
4338
- });
4339
- claimedLocals.add(b.local);
4340
- } else {
4341
- const unavailableLocals = new Set(claimedLocals);
4342
- pendingLocals.forEach((local) => unavailableLocals.add(local));
4343
- const resolvedBinding = resolveProxyAlias(b, proxyLocal, code, fullImport, unavailableLocals);
4344
- claimedLocals.add(resolvedBinding.local);
4345
- nonInlineable.push(resolvedBinding);
4346
- }
4347
- }
4348
- const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
4349
- if (inlineable.length === 0 && !hasRenamedAlias) continue;
4350
- let replacement = "";
4351
- if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
4352
- replacement += inlineable.map((f) => f.funcBody).join("");
4353
- code = code.replace(fullImport, () => replacement);
4354
- modified = true;
4686
+ const proxyChunks = collectLoadShareProxyChunks(bundle, LOAD_SHARE_TAG);
4687
+ if (proxyChunks.size > 0) {
4688
+ const systemProxyInfo = collectSystemProxyInfos(proxyChunks, LOAD_SHARE_TAG);
4689
+ for (const [fileName, chunk] of Object.entries(bundle)) {
4690
+ if (!isOutputChunk(chunk)) continue;
4691
+ if (proxyChunks.has(fileName)) continue;
4692
+ let code = chunk.code;
4693
+ if (!fileName.includes("__loadShare__")) code = rewriteEsmProxyConsumers(code, proxyChunks);
4694
+ code = rewriteSystemProxyConsumers(code, systemProxyInfo);
4695
+ if (code !== chunk.code) chunk.code = code;
4355
4696
  }
4356
- if (modified) chunk.code = code;
4357
4697
  }
4358
4698
  }
4359
4699
  },
@@ -4391,12 +4731,14 @@ function federation(mfUserOptions) {
4391
4731
  find: "@module-federation/runtime",
4392
4732
  replacement: implementation
4393
4733
  });
4394
- config.build = (0, defu.default)(config.build || {}, { commonjsOptions: { strictRequires: "auto" } });
4734
+ config.build ||= {};
4735
+ config.build.commonjsOptions ||= {};
4736
+ config.build.commonjsOptions.strictRequires ??= "auto";
4395
4737
  const virtualDir = options.virtualModuleDir;
4396
4738
  config.optimizeDeps ||= {};
4397
4739
  config.optimizeDeps.include ||= [];
4398
4740
  config.optimizeDeps.include.push("@module-federation/runtime");
4399
- config.optimizeDeps.include.push(virtualDir);
4741
+ if (!isRolldown) config.optimizeDeps.include.push(virtualDir);
4400
4742
  config.ssr ||= {};
4401
4743
  config.ssr.noExternal ||= [];
4402
4744
  if (Array.isArray(config.ssr.noExternal)) config.ssr.noExternal.push(virtualDir);
@@ -4404,11 +4746,12 @@ function federation(mfUserOptions) {
4404
4746
  const pluginPath = typeof p === "string" ? p : p[0];
4405
4747
  if (pluginPath && !pluginPath.startsWith(".") && !pluginPath.startsWith("/") && !pluginPath.startsWith("\0") && !pluginPath.startsWith("virtual:")) config.optimizeDeps.include.push(pluginPath);
4406
4748
  });
4407
- if (isRolldown) config.build = (0, defu.default)(config.build || {}, { target: "esnext" });
4408
- else {
4749
+ if (isRolldown) {
4750
+ config.build ??= {};
4751
+ config.build.target ??= "esnext";
4752
+ } else {
4409
4753
  config.optimizeDeps.needsInterop ||= [];
4410
4754
  config.optimizeDeps.needsInterop.push(virtualDir);
4411
- config.optimizeDeps.needsInterop.push(getLocalSharedImportMapPath());
4412
4755
  }
4413
4756
  const isAstro = hasPackageDependency("astro");
4414
4757
  const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");