@module-federation/vite 1.15.1 → 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() {
@@ -1383,14 +1512,40 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1383
1512
  let runtimeInstance
1384
1513
  let localSharedImportMapPromise
1385
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
+ }
1386
1534
 
1387
1535
  async function getLocalSharedImportMap() {
1388
- localSharedImportMapPromise ??= import("${getLocalSharedImportMapPath()}")
1536
+ if (!localSharedImportMapPromise) {
1537
+ localSharedImportMapPromise = retrySharedInit(() => import("${getLocalSharedImportMapPath()}"))
1538
+ .catch((e) => { localSharedImportMapPromise = undefined; throw e; });
1539
+ }
1389
1540
  return localSharedImportMapPromise
1390
1541
  }
1391
1542
 
1392
1543
  async function getExposesMap() {
1393
- 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
+ }
1394
1549
  return exposesMapPromise
1395
1550
  }
1396
1551
 
@@ -1419,11 +1574,13 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1419
1574
  initRes.initShareScopeMap('${options.shareScope}', shared);
1420
1575
  initResolve(initRes)
1421
1576
  try {
1422
- await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1423
- strategy: '${options.shareStrategy}',
1424
- from: "build",
1425
- initScope
1426
- }));
1577
+ await retrySharedInit(async () => {
1578
+ await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1579
+ strategy: '${options.shareStrategy}',
1580
+ from: "build",
1581
+ initScope
1582
+ }));
1583
+ });
1427
1584
  } catch (e) {
1428
1585
  console.error('[Module Federation]', e)
1429
1586
  }
@@ -1705,17 +1862,26 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1705
1862
  }
1706
1863
  return patched;
1707
1864
  }
1708
- function getBootstrapSource(initSrc, entrySrc) {
1709
- 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)})`;
1710
1873
  return `${getRuntimeModuleCacheBootstrapCode()}
1711
- (async () => {
1712
- const { initHost } = await import(${JSON.stringify(initSrc)});
1874
+ ${importHelper}(async () => {
1875
+ const { initHost } = await ${importExpression(initSrc)};
1713
1876
  const runtime = await initHost();
1714
1877
  const __mfRemotePreloads = [${remotePreloads}];
1715
1878
  await Promise.all(__mfRemotePreloads);
1716
- })().then(() => import(${JSON.stringify(entrySrc)}));
1879
+ })().then(() => ${importExpression(entrySrc)});
1717
1880
  `;
1718
1881
  }
1882
+ function getSystemBootstrapSource(initSrc, entrySrc) {
1883
+ return getBootstrapSource(initSrc, entrySrc, true);
1884
+ }
1719
1885
  function injectHtml() {
1720
1886
  return inject === "html" && (htmlFilePath || hasPackageDependency("@sveltejs/kit"));
1721
1887
  }
@@ -1855,7 +2021,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1855
2021
  const bootstrapRef = this.emitFile({
1856
2022
  type: "asset",
1857
2023
  fileName: bootstrapFileName,
1858
- source: getBootstrapSource(initPath, entrySrc)
2024
+ source: getSystemBootstrapSource(initPath, entrySrc)
1859
2025
  });
1860
2026
  const bootstrapPath = viteConfig.base + this.getFileName(bootstrapRef);
1861
2027
  return scriptTag.replace(entrySrc, bootstrapPath);
@@ -2000,7 +2166,7 @@ function getHmrWsPath(base, hmrPath) {
2000
2166
  return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
2001
2167
  }
2002
2168
  function shouldIgnoreFile(file, options) {
2003
- 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");
2004
2170
  }
2005
2171
  function getRemoteHmrWsUrl(server) {
2006
2172
  const hmr = server.config.server.hmr;
@@ -2041,7 +2207,22 @@ function getStringPreview(value, max = 180) {
2041
2207
  return rawValue.slice(0, max);
2042
2208
  }
2043
2209
  function isRemoteHmrEnabled(dev) {
2044
- 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";
2045
2226
  }
2046
2227
  function pluginDevRemoteHmr(options) {
2047
2228
  return {
@@ -2051,6 +2232,7 @@ function pluginDevRemoteHmr(options) {
2051
2232
  if (!isRemoteHmrEnabled(options.dev)) return;
2052
2233
  const isRemote = Object.keys(options.exposes).length > 0;
2053
2234
  const isHost = Object.keys(options.remotes).length > 0;
2235
+ const strategy = resolveHmrStrategy(options.dev, server.config.plugins);
2054
2236
  if (isRemote) {
2055
2237
  const endpointPath = getRemoteHmrPath(server.config.base);
2056
2238
  const wsUrl = getRemoteHmrWsUrl(server);
@@ -2074,6 +2256,7 @@ function pluginDevRemoteHmr(options) {
2074
2256
  }));
2075
2257
  });
2076
2258
  const broadcast = (file) => {
2259
+ if (strategy === "native") return;
2077
2260
  if (shouldIgnoreFile(file, options)) return;
2078
2261
  server.ws.send({
2079
2262
  type: "custom",
@@ -2138,6 +2321,7 @@ function pluginDevRemoteHmr(options) {
2138
2321
  }
2139
2322
  const ws = new WebSocket(metadata.wsUrl, "vite-hmr");
2140
2323
  ws.onmessage = (rawEvent) => {
2324
+ if (strategy === "native") return;
2141
2325
  const message = parseRemoteHmrMessage(rawEvent.data);
2142
2326
  if (!message || message.event !== REMOTE_HMR_EVENT) return;
2143
2327
  server.ws.send({ type: "full-reload" });
@@ -2162,6 +2346,7 @@ function pluginDevRemoteHmr(options) {
2162
2346
  };
2163
2347
  for (const [remoteName, remote] of Object.entries(options.remotes)) connectRemote(remoteName, remote);
2164
2348
  const triggerHostReload = (file) => {
2349
+ if (strategy === "native") return;
2165
2350
  if (shouldIgnoreFile(file, options)) return;
2166
2351
  server.ws.send({ type: "full-reload" });
2167
2352
  };
@@ -2484,6 +2669,26 @@ function initVirtualModules(command, remoteEntryId) {
2484
2669
  }
2485
2670
  //#endregion
2486
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
+ }
2487
2692
  /**
2488
2693
  * Resolve the local alias for a non-inlineable proxy binding.
2489
2694
  * If Rollup's deconflict renamed the alias but didn't update references
@@ -2506,6 +2711,147 @@ function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals
2506
2711
  local
2507
2712
  };
2508
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
+ }
2509
2855
  function findRemoteEntryFile(filename, bundle) {
2510
2856
  for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
2511
2857
  }
@@ -2675,6 +3021,9 @@ function normalizeNodeModulePath(source) {
2675
3021
  function isNodeModulePath(source) {
2676
3022
  return source.includes("/node_modules/") || source.includes("\\node_modules\\");
2677
3023
  }
3024
+ function filterId(id) {
3025
+ return typeof id === "string" && !id.includes("\0");
3026
+ }
2678
3027
  function getMatchingNodeModuleSubpath(source, candidates) {
2679
3028
  const normalized = normalizeNodeModulePath(source);
2680
3029
  return [...candidates].sort((a, b) => b.length - a.length).find((candidate) => normalized.includes(`/node_modules/${candidate}/`) || normalized.includes(`/node_modules/${candidate}.`));
@@ -2859,10 +3208,11 @@ const Manifest = () => {
2859
3208
  alias: remoteKey,
2860
3209
  entry: "*"
2861
3210
  })));
2862
- const shared = Array.from(getUsedShares()).map((shareKey) => {
3211
+ const shared = Array.from(getUsedShares()).flatMap((shareKey) => {
2863
3212
  const shareItem = getNormalizeShareItem(shareKey);
3213
+ if (!shareItem) return [];
2864
3214
  const assets = preloadMap[shareKey] || createEmptyAssetMap();
2865
- return {
3215
+ return [{
2866
3216
  id: `${name}:${shareKey}`,
2867
3217
  name: shareKey,
2868
3218
  version: shareItem.version,
@@ -2878,7 +3228,7 @@ const Manifest = () => {
2878
3228
  sync: assets.css.sync
2879
3229
  }
2880
3230
  }
2881
- };
3231
+ }];
2882
3232
  });
2883
3233
  const exposes = Object.entries(options.exposes).map(([key, value]) => {
2884
3234
  const formatKey = key.replace("./", "");
@@ -3030,7 +3380,6 @@ function pluginModuleParseEnd_default(excludeFn, options) {
3030
3380
  }
3031
3381
  //#endregion
3032
3382
  //#region src/plugins/pluginProxyRemoteEntry.ts
3033
- const filter$1 = (0, _rollup_pluginutils.createFilter)();
3034
3383
  function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
3035
3384
  let viteConfig, _command, root;
3036
3385
  return {
@@ -3070,14 +3419,14 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3070
3419
  },
3071
3420
  transform(code, id) {
3072
3421
  return mapCodeToCodeWithSourcemap((() => {
3073
- if (!filter$1(id)) return;
3422
+ if (!filterId(id)) return;
3074
3423
  if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
3075
3424
  if (id === virtualExposesId) return generateExposes(options);
3076
3425
  if (id.includes(getHostAutoInitPath())) {
3077
3426
  if (_command === "serve") {
3078
3427
  const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
3079
3428
  const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
3080
- const fallbackOrigin = `http://${host}:${viteConfig.server?.port}`;
3429
+ const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
3081
3430
  const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
3082
3431
  return `
3083
3432
  const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
@@ -3128,10 +3477,25 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3128
3477
  }
3129
3478
  //#endregion
3130
3479
  //#region src/plugins/pluginProxyRemotes.ts
3131
- const filter = (0, _rollup_pluginutils.createFilter)();
3132
3480
  function isNodeModulesImporter(importer) {
3133
3481
  return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
3134
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
+ }
3135
3499
  function pluginProxyRemotes_default(options) {
3136
3500
  let command;
3137
3501
  let root = process.cwd();
@@ -3148,19 +3512,20 @@ function pluginProxyRemotes_default(options) {
3148
3512
  }
3149
3513
  return {
3150
3514
  name: "proxyRemotes",
3515
+ enforce: "pre",
3151
3516
  config(config, { command: _command }) {
3152
3517
  command = _command;
3153
3518
  root = config.root || process.cwd();
3154
3519
  Object.keys(remotes).forEach((key) => {
3155
3520
  const remote = remotes[key];
3156
- config.resolve.alias.push({
3521
+ appendAlias(config, {
3157
3522
  find: new RegExp(`^(${remote.name}(\/.*|$))`),
3158
3523
  replacement: "$1"
3159
3524
  });
3160
3525
  });
3161
3526
  },
3162
3527
  resolveId(source, importer) {
3163
- if (!filter(source)) return;
3528
+ if (!filterId(source)) return;
3164
3529
  for (const remote of Object.values(remotes)) {
3165
3530
  if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
3166
3531
  return resolveRemoteId(source, importer, remote.name);
@@ -3261,7 +3626,7 @@ function excludeSharedSubDependencies(shared) {
3261
3626
  for (const dep of deps) {
3262
3627
  const depKey = sharedKeyByBase.get(dep);
3263
3628
  if (depKey && depKey !== parentKey) {
3264
- if (shared[depKey]?.shareConfig.import === false) continue;
3629
+ if (shared[depKey]?.shareConfig.singleton === true || shared[depKey]?.shareConfig.import === false) continue;
3265
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.`);
3266
3631
  delete shared[depKey];
3267
3632
  sharedKeys.delete(depKey);
@@ -3277,15 +3642,27 @@ function proxySharedModule(options) {
3277
3642
  let useDirectReactImport = false;
3278
3643
  let useRolldown = false;
3279
3644
  const savePrebuild = new PromiseStore();
3645
+ let devServer;
3280
3646
  return [
3281
3647
  {
3282
3648
  name: "generateLocalSharedImportMap",
3283
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
+ },
3284
3660
  load(id) {
3285
- if (id.includes(getLocalSharedImportMapPath())) return parsePromise.then((_) => generateLocalSharedImportMap());
3661
+ if (id === getResolvedLocalSharedImportMapId()) return parsePromise.then((_) => generateLocalSharedImportMap());
3286
3662
  },
3287
- transform(_, id) {
3288
- if (id.includes(getLocalSharedImportMapPath())) return mapCodeToCodeWithSourcemap(parsePromise.then((_) => generateLocalSharedImportMap()));
3663
+ closeBundle() {
3664
+ if (devServer) return;
3665
+ setLocalSharedImportMapInvalidator(void 0);
3289
3666
  }
3290
3667
  },
3291
3668
  {
@@ -3416,7 +3793,7 @@ function wrapDynamicImport(original) {
3416
3793
  }
3417
3794
  function applyRewrites(code, imports, id) {
3418
3795
  if (imports.length === 0) return;
3419
- const ms = new magic_string.default(code);
3796
+ const ms = new CodeRewriter(code);
3420
3797
  let changed = false;
3421
3798
  let counter = 0;
3422
3799
  for (const imp of imports) switch (imp.kind) {
@@ -3464,7 +3841,7 @@ function applyRewrites(code, imports, id) {
3464
3841
  if (!changed) return;
3465
3842
  return {
3466
3843
  code: ms.toString(),
3467
- map: ms.generateMap({ hires: true })
3844
+ map: ms.generateMap(id)
3468
3845
  };
3469
3846
  }
3470
3847
  async function collectFromAST(ast, code, isRemoteImport) {
@@ -3906,6 +4283,9 @@ function ignoreFederationGeneratedFiles(config, options) {
3906
4283
  function isSharedResolverInternalImporter(importer) {
3907
4284
  return !!importer && (importer.includes("__loadShare__") || importer.includes("__prebuild__"));
3908
4285
  }
4286
+ function isCommonJsImporter(importer) {
4287
+ return !!importer && (importer.endsWith(".cjs") || importer.includes("/cjs/"));
4288
+ }
3909
4289
  function isOutputChunk(chunk) {
3910
4290
  return chunk.type === "chunk";
3911
4291
  }
@@ -3989,9 +4369,10 @@ function createEarlyVirtualModulesPlugin(options) {
3989
4369
  optimizeDeps.rolldownOptions.plugins ??= [];
3990
4370
  optimizeDeps.rolldownOptions.plugins.push({
3991
4371
  name: "module-federation:optimize-shared-resolver",
3992
- resolveId(source, importer) {
4372
+ resolveId(source, importer, options) {
4373
+ if (options?.kind?.startsWith("require")) return;
3993
4374
  if (isSharedResolverInternalImporter(importer)) return;
3994
- if (source !== "react/jsx-runtime" && source !== "react/jsx-dev-runtime") return;
4375
+ if (isCommonJsImporter(importer)) return;
3995
4376
  const key = findSharedKey(source, shared);
3996
4377
  if (!key) return;
3997
4378
  if (source.endsWith(".css")) return;
@@ -4302,87 +4683,17 @@ function federation(mfUserOptions) {
4302
4683
  if (!isFederationControlChunk(fileName, filename)) continue;
4303
4684
  chunk.code = sanitizeFederationControlChunk(chunk.code, fileName, filename);
4304
4685
  }
4305
- const proxyChunks = /* @__PURE__ */ new Map();
4306
- for (const [fileName, chunk] of Object.entries(bundle)) {
4307
- if (!isOutputChunk(chunk)) continue;
4308
- if (fileName.includes("__loadShare__") && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
4309
- code: chunk.code,
4310
- fileName
4311
- });
4312
- }
4313
- if (proxyChunks.size > 0) for (const [fileName, chunk] of Object.entries(bundle)) {
4314
- if (!isOutputChunk(chunk)) continue;
4315
- if (fileName.includes("__loadShare__")) continue;
4316
- let code = chunk.code;
4317
- let modified = false;
4318
- const claimedLocals = /* @__PURE__ */ new Set();
4319
- for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
4320
- const proxyBaseName = proxyFileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
4321
- const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${proxyBaseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^"']*)["']\\s*;?`).exec(code);
4322
- if (!importMatch) continue;
4323
- const fullImport = importMatch[0];
4324
- const bindings = importMatch[1].split(",").map((s) => {
4325
- const parts = s.trim().split(/\s+as\s+/);
4326
- return {
4327
- imported: parts[0].trim(),
4328
- local: (parts[1] || parts[0]).trim()
4329
- };
4330
- });
4331
- const proxyCode = proxyInfo.code;
4332
- const exportMapMatch = proxyCode.match(/export\s*\{([^}]+)\}/);
4333
- if (!exportMapMatch) continue;
4334
- const exportMap = {};
4335
- for (const entry of exportMapMatch[1].split(",")) {
4336
- const parts = entry.trim().split(/\s+as\s+/);
4337
- if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
4338
- }
4339
- const inlineable = [];
4340
- const nonInlineable = [];
4341
- const pendingLocals = new Set(bindings.map((binding) => binding.local));
4342
- for (const b of bindings) {
4343
- pendingLocals.delete(b.local);
4344
- const proxyLocal = exportMap[b.imported];
4345
- if (!proxyLocal) {
4346
- claimedLocals.add(b.local);
4347
- nonInlineable.push(b);
4348
- continue;
4349
- }
4350
- const funcRe = new RegExp(`function\\s+${proxyLocal}\\s*\\([^)]*\\)\\s*\\{`);
4351
- if (funcRe.test(proxyCode)) {
4352
- const funcStart = proxyCode.search(funcRe);
4353
- let depth = 0;
4354
- let funcEnd = funcStart;
4355
- for (let i = proxyCode.indexOf("{", funcStart); i < proxyCode.length; i++) if (proxyCode[i] === "{") depth++;
4356
- else if (proxyCode[i] === "}") {
4357
- depth--;
4358
- if (depth === 0) {
4359
- funcEnd = i + 1;
4360
- break;
4361
- }
4362
- }
4363
- const renamedFunc = proxyCode.slice(funcStart, funcEnd).replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`);
4364
- inlineable.push({
4365
- local: b.local,
4366
- funcBody: renamedFunc
4367
- });
4368
- claimedLocals.add(b.local);
4369
- } else {
4370
- const unavailableLocals = new Set(claimedLocals);
4371
- pendingLocals.forEach((local) => unavailableLocals.add(local));
4372
- const resolvedBinding = resolveProxyAlias(b, proxyLocal, code, fullImport, unavailableLocals);
4373
- claimedLocals.add(resolvedBinding.local);
4374
- nonInlineable.push(resolvedBinding);
4375
- }
4376
- }
4377
- const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
4378
- if (inlineable.length === 0 && !hasRenamedAlias) continue;
4379
- let replacement = "";
4380
- if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
4381
- replacement += inlineable.map((f) => f.funcBody).join("");
4382
- code = code.replace(fullImport, () => replacement);
4383
- 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;
4384
4696
  }
4385
- if (modified) chunk.code = code;
4386
4697
  }
4387
4698
  }
4388
4699
  },
@@ -4420,12 +4731,14 @@ function federation(mfUserOptions) {
4420
4731
  find: "@module-federation/runtime",
4421
4732
  replacement: implementation
4422
4733
  });
4423
- config.build = (0, defu.default)(config.build || {}, { commonjsOptions: { strictRequires: "auto" } });
4734
+ config.build ||= {};
4735
+ config.build.commonjsOptions ||= {};
4736
+ config.build.commonjsOptions.strictRequires ??= "auto";
4424
4737
  const virtualDir = options.virtualModuleDir;
4425
4738
  config.optimizeDeps ||= {};
4426
4739
  config.optimizeDeps.include ||= [];
4427
4740
  config.optimizeDeps.include.push("@module-federation/runtime");
4428
- config.optimizeDeps.include.push(virtualDir);
4741
+ if (!isRolldown) config.optimizeDeps.include.push(virtualDir);
4429
4742
  config.ssr ||= {};
4430
4743
  config.ssr.noExternal ||= [];
4431
4744
  if (Array.isArray(config.ssr.noExternal)) config.ssr.noExternal.push(virtualDir);
@@ -4433,11 +4746,12 @@ function federation(mfUserOptions) {
4433
4746
  const pluginPath = typeof p === "string" ? p : p[0];
4434
4747
  if (pluginPath && !pluginPath.startsWith(".") && !pluginPath.startsWith("/") && !pluginPath.startsWith("\0") && !pluginPath.startsWith("virtual:")) config.optimizeDeps.include.push(pluginPath);
4435
4748
  });
4436
- if (isRolldown) config.build = (0, defu.default)(config.build || {}, { target: "esnext" });
4437
- else {
4749
+ if (isRolldown) {
4750
+ config.build ??= {};
4751
+ config.build.target ??= "esnext";
4752
+ } else {
4438
4753
  config.optimizeDeps.needsInterop ||= [];
4439
4754
  config.optimizeDeps.needsInterop.push(virtualDir);
4440
- config.optimizeDeps.needsInterop.push(getLocalSharedImportMapPath());
4441
4755
  }
4442
4756
  const isAstro = hasPackageDependency("astro");
4443
4757
  const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");