@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.mjs CHANGED
@@ -1,28 +1,151 @@
1
1
  import { createRequire } from "node:module";
2
- import defu from "defu";
3
2
  import * as fs$1 from "fs";
4
- import fs, { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFile, writeFileSync } from "fs";
3
+ import fs, { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFile, writeFileSync } from "fs";
5
4
  import { createRequire as createRequire$1 } from "module";
6
5
  import * as path$1 from "pathe";
7
6
  import path, { basename, dirname, join, parse, resolve } from "pathe";
8
- import MagicString from "magic-string";
9
7
  import { normalizeOptions } from "@module-federation/sdk";
10
8
  import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
11
9
  import { rpc } from "@module-federation/dts-plugin/core";
12
- import { createFilter } from "@rollup/pluginutils";
13
10
  import { fileURLToPath } from "url";
14
11
  import { init, parse as parse$1 } from "es-module-lexer";
15
12
  //#region \0rolldown/runtime.js
16
13
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
17
14
  //#endregion
15
+ //#region src/utils/codeRewriter.ts
16
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
17
+ var CodeRewriter = class {
18
+ replacements = [];
19
+ constructor(original) {
20
+ this.original = original;
21
+ }
22
+ overwrite(start, end, content) {
23
+ if (start < 0 || end < start || end > this.original.length) throw new Error(`Invalid overwrite range: ${start}-${end}`);
24
+ this.replacements.push({
25
+ start,
26
+ end,
27
+ content
28
+ });
29
+ }
30
+ toString() {
31
+ return applyReplacements(this.original, this.getSortedReplacements()).code;
32
+ }
33
+ generateMap(source = "") {
34
+ const { code, replacements } = applyReplacements(this.original, this.getSortedReplacements());
35
+ return {
36
+ version: 3,
37
+ sources: [source],
38
+ sourcesContent: [this.original],
39
+ names: [],
40
+ mappings: generateLineMappings(code, this.original, replacements)
41
+ };
42
+ }
43
+ getSortedReplacements() {
44
+ return [...this.replacements].sort((a, b) => a.start - b.start || a.end - b.end);
45
+ }
46
+ };
47
+ function createSourceMap(code, source = "") {
48
+ return {
49
+ version: 3,
50
+ sources: [source],
51
+ sourcesContent: [code],
52
+ names: [],
53
+ mappings: generateLineMappings(code, code, [])
54
+ };
55
+ }
56
+ function applyReplacements(original, replacements) {
57
+ let code = "";
58
+ let cursor = 0;
59
+ let delta = 0;
60
+ const applied = [];
61
+ for (const replacement of replacements) {
62
+ if (replacement.start < cursor) throw new Error("Overlapping overwrite ranges are not supported");
63
+ code += original.slice(cursor, replacement.start);
64
+ const generatedStart = replacement.start + delta;
65
+ code += replacement.content;
66
+ const generatedEnd = generatedStart + replacement.content.length;
67
+ applied.push({
68
+ ...replacement,
69
+ generatedStart,
70
+ generatedEnd
71
+ });
72
+ cursor = replacement.end;
73
+ delta += replacement.content.length - (replacement.end - replacement.start);
74
+ }
75
+ code += original.slice(cursor);
76
+ return {
77
+ code,
78
+ replacements: applied
79
+ };
80
+ }
81
+ function generateLineMappings(generated, original, replacements) {
82
+ const generatedLineStarts = getLineStarts(generated);
83
+ const originalLineStarts = getLineStarts(original);
84
+ let previousOriginalLine = 0;
85
+ let previousOriginalColumn = 0;
86
+ let mappings = "";
87
+ generatedLineStarts.forEach((generatedOffset, lineIndex) => {
88
+ if (lineIndex > 0) mappings += ";";
89
+ const originalOffset = generatedOffsetToOriginalOffset(generatedOffset, replacements);
90
+ const originalLine = findLine(originalLineStarts, originalOffset);
91
+ const originalColumn = originalOffset - originalLineStarts[originalLine];
92
+ mappings += encodeSegment([
93
+ 0,
94
+ 0,
95
+ originalLine - previousOriginalLine,
96
+ originalColumn - previousOriginalColumn
97
+ ]);
98
+ previousOriginalLine = originalLine;
99
+ previousOriginalColumn = originalColumn;
100
+ });
101
+ return mappings;
102
+ }
103
+ function generatedOffsetToOriginalOffset(offset, replacements) {
104
+ let delta = 0;
105
+ for (const replacement of replacements) {
106
+ if (offset < replacement.generatedStart) break;
107
+ if (offset < replacement.generatedEnd) return replacement.start;
108
+ delta += replacement.content.length - (replacement.end - replacement.start);
109
+ }
110
+ return offset - delta;
111
+ }
112
+ function getLineStarts(code) {
113
+ const starts = [0];
114
+ for (let i = 0; i < code.length; i++) if (code.charCodeAt(i) === 10) starts.push(i + 1);
115
+ return starts;
116
+ }
117
+ function findLine(lineStarts, offset) {
118
+ let low = 0;
119
+ let high = lineStarts.length - 1;
120
+ while (low <= high) {
121
+ const mid = low + high >> 1;
122
+ if (lineStarts[mid] <= offset) low = mid + 1;
123
+ else high = mid - 1;
124
+ }
125
+ return Math.max(0, high);
126
+ }
127
+ function encodeSegment(values) {
128
+ return values.map(encodeVlq).join("");
129
+ }
130
+ function encodeVlq(value) {
131
+ let vlq = value < 0 ? (-value << 1) + 1 : value << 1;
132
+ let encoded = "";
133
+ do {
134
+ let digit = vlq & 31;
135
+ vlq >>>= 5;
136
+ if (vlq > 0) digit |= 32;
137
+ encoded += BASE64_CHARS[digit];
138
+ } while (vlq > 0);
139
+ return encoded;
140
+ }
141
+ //#endregion
18
142
  //#region src/utils/mapCodeToCodeWithSourcemap.ts
19
143
  async function mapCodeToCodeWithSourcemap(code) {
20
144
  const resolvedCode = await code;
21
145
  if (resolvedCode === void 0) return;
22
- const s = new MagicString(resolvedCode);
23
146
  return {
24
- code: s.toString(),
25
- map: s.generateMap({ hires: true })
147
+ code: resolvedCode,
148
+ map: createSourceMap(resolvedCode)
26
149
  };
27
150
  }
28
151
  //#endregion
@@ -623,107 +746,6 @@ var VirtualModule = class {
623
746
  }
624
747
  };
625
748
  //#endregion
626
- //#region src/virtualModules/virtualRuntimeInitStatus.ts
627
- const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
628
- const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
629
- function getRuntimeInitGlobalKey() {
630
- return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
631
- }
632
- function getDeferredInitPromiseCode() {
633
- return `let initResolve, initReject;
634
- const initPromise = new Promise((re, rj) => {
635
- initResolve = re;
636
- initReject = rj;
637
- });`;
638
- }
639
- function getSsrNoopResolveCode() {
640
- return `if (typeof window === 'undefined') {
641
- initResolve({
642
- loadRemote: function() { return Promise.resolve(undefined); },
643
- loadShare: function() { return Promise.resolve(undefined); },
644
- });
645
- }`;
646
- }
647
- function getRuntimeInitStateBootstrapCode(options) {
648
- return `
649
- const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
650
- let ${options.stateVar} = globalThis[${options.globalKeyVar}];
651
- if (!${options.stateVar}) {
652
- ${getDeferredInitPromiseCode()}
653
- ${options.stateVar} = globalThis[${options.globalKeyVar}] = {
654
- initPromise,
655
- initResolve,
656
- initReject,
657
- };
658
- ${getSsrNoopResolveCode()}
659
- }
660
- const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
661
- `;
662
- }
663
- function getRuntimeInitBootstrapCode() {
664
- return `
665
- const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
666
- const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
667
- globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
668
- globalThis[moduleCacheGlobalKey].share ||= {};
669
- globalThis[moduleCacheGlobalKey].remote ||= {};
670
- if (!globalThis[globalKey]) {
671
- ${getDeferredInitPromiseCode()}
672
- globalThis[globalKey] = {
673
- initPromise,
674
- initResolve,
675
- initReject,
676
- moduleCache: globalThis[moduleCacheGlobalKey],
677
- };
678
- ${getSsrNoopResolveCode()}
679
- }
680
- globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
681
- globalThis[globalKey].moduleCache.share ||= {};
682
- globalThis[globalKey].moduleCache.remote ||= {};
683
- `;
684
- }
685
- function getRuntimeModuleCacheBootstrapCode() {
686
- return `
687
- const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
688
- globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
689
- globalThis[__mfCacheGlobalKey].share ||= {};
690
- globalThis[__mfCacheGlobalKey].remote ||= {};
691
- const __mfModuleCache = globalThis[__mfCacheGlobalKey];
692
- `;
693
- }
694
- function getRuntimeInitResolveBootstrapCode() {
695
- return getRuntimeInitStateBootstrapCode({
696
- globalKeyVar: "__mfResolveGlobalKey",
697
- stateVar: "__mfResolveState",
698
- exposedConst: "initResolve",
699
- exposedProperty: "initResolve"
700
- });
701
- }
702
- function writeRuntimeInitStatus(command) {
703
- const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
704
- export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
705
- virtualRuntimeInitStatus.writeSync(`
706
- ${getRuntimeInitBootstrapCode()}
707
- ${exportStatement}
708
- `);
709
- }
710
- //#endregion
711
- //#region src/utils/localSharedImportMap_temp.ts
712
- /**
713
- * https://github.com/module-federation/vite/issues/68
714
- */
715
- function getLocalSharedImportMapPath_temp() {
716
- const { name } = getNormalizeModuleFederationOptions();
717
- return path.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
718
- }
719
- function writeLocalSharedImportMap_temp(content) {
720
- createFile(getLocalSharedImportMapPath_temp() + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
721
- }
722
- function createFile(filePath, content) {
723
- mkdirSync(path.dirname(filePath), { recursive: true });
724
- writeFileSync(filePath, content);
725
- }
726
- //#endregion
727
749
  //#region src/utils/serializeRuntimeOptions.ts
728
750
  /**
729
751
  * Serializes a JavaScript object into a string of source code that can be evaluated.
@@ -854,6 +876,91 @@ function generateExposes(options) {
854
876
  `;
855
877
  }
856
878
  //#endregion
879
+ //#region src/virtualModules/virtualRuntimeInitStatus.ts
880
+ const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
881
+ const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
882
+ function getRuntimeInitGlobalKey() {
883
+ return `__mf_init__${virtualRuntimeInitStatus.getImportId()}__`;
884
+ }
885
+ function getDeferredInitPromiseCode() {
886
+ return `let initResolve, initReject;
887
+ const initPromise = new Promise((re, rj) => {
888
+ initResolve = re;
889
+ initReject = rj;
890
+ });`;
891
+ }
892
+ function getSsrNoopResolveCode() {
893
+ return `if (typeof window === 'undefined') {
894
+ initResolve({
895
+ loadRemote: function() { return Promise.resolve(undefined); },
896
+ loadShare: function() { return Promise.resolve(undefined); },
897
+ });
898
+ }`;
899
+ }
900
+ function getRuntimeInitStateBootstrapCode(options) {
901
+ return `
902
+ const ${options.globalKeyVar} = ${JSON.stringify(getRuntimeInitGlobalKey())};
903
+ let ${options.stateVar} = globalThis[${options.globalKeyVar}];
904
+ if (!${options.stateVar}) {
905
+ ${getDeferredInitPromiseCode()}
906
+ ${options.stateVar} = globalThis[${options.globalKeyVar}] = {
907
+ initPromise,
908
+ initResolve,
909
+ initReject,
910
+ };
911
+ ${getSsrNoopResolveCode()}
912
+ }
913
+ const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
914
+ `;
915
+ }
916
+ function getRuntimeInitBootstrapCode() {
917
+ return `
918
+ const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
919
+ const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
920
+ globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
921
+ globalThis[moduleCacheGlobalKey].share ||= {};
922
+ globalThis[moduleCacheGlobalKey].remote ||= {};
923
+ if (!globalThis[globalKey]) {
924
+ ${getDeferredInitPromiseCode()}
925
+ globalThis[globalKey] = {
926
+ initPromise,
927
+ initResolve,
928
+ initReject,
929
+ moduleCache: globalThis[moduleCacheGlobalKey],
930
+ };
931
+ ${getSsrNoopResolveCode()}
932
+ }
933
+ globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
934
+ globalThis[globalKey].moduleCache.share ||= {};
935
+ globalThis[globalKey].moduleCache.remote ||= {};
936
+ `;
937
+ }
938
+ function getRuntimeModuleCacheBootstrapCode() {
939
+ return `
940
+ const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
941
+ globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
942
+ globalThis[__mfCacheGlobalKey].share ||= {};
943
+ globalThis[__mfCacheGlobalKey].remote ||= {};
944
+ const __mfModuleCache = globalThis[__mfCacheGlobalKey];
945
+ `;
946
+ }
947
+ function getRuntimeInitResolveBootstrapCode() {
948
+ return getRuntimeInitStateBootstrapCode({
949
+ globalKeyVar: "__mfResolveGlobalKey",
950
+ stateVar: "__mfResolveState",
951
+ exposedConst: "initResolve",
952
+ exposedProperty: "initResolve"
953
+ });
954
+ }
955
+ function writeRuntimeInitStatus(command) {
956
+ const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
957
+ export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
958
+ virtualRuntimeInitStatus.writeSync(`
959
+ ${getRuntimeInitBootstrapCode()}
960
+ ${exportStatement}
961
+ `);
962
+ }
963
+ //#endregion
857
964
  //#region src/virtualModules/virtualShared_preBuild.ts
858
965
  /**
859
966
  * Even the resolveId hook cannot interfere with vite pre-build,
@@ -996,7 +1103,16 @@ function getLocalProviderImportPath(pkg) {
996
1103
  const resolved = createRequire$1(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
997
1104
  return isWorkspaceFilePath(resolved) ? resolved : void 0;
998
1105
  } catch {
999
- return;
1106
+ const resolved = getInstalledPackageEntry(pkg, {
1107
+ conditions: [
1108
+ "browser",
1109
+ "import",
1110
+ "module",
1111
+ "default"
1112
+ ],
1113
+ resolveSubpathWithRequire: false
1114
+ });
1115
+ return isWorkspaceFilePath(resolved) ? resolved : void 0;
1000
1116
  }
1001
1117
  }
1002
1118
  function getProjectResolvedImportPath(pkg) {
@@ -1011,7 +1127,12 @@ function getProjectResolvedImportPath(pkg) {
1011
1127
  }
1012
1128
  }
1013
1129
  function isWorkspaceFilePath(resolved) {
1014
- return !!resolved && !resolved.includes("/node_modules/") && !resolved.includes("\\node_modules\\");
1130
+ if (!resolved) return false;
1131
+ let realResolved = resolved;
1132
+ try {
1133
+ realResolved = realpathSync.native(resolved);
1134
+ } catch {}
1135
+ return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
1015
1136
  }
1016
1137
  function isWorkspacePackageEntry(pkg, resolved) {
1017
1138
  if (!resolved || !path.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
@@ -1124,11 +1245,12 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1124
1245
  const isWorkspacePackage = isWorkspacePackageEntry(pkg, localProviderPath) || isWorkspacePackageEntry(pkg, concreteSharedImportSource);
1125
1246
  const lazyLocalFallbackSource = concreteSharedImportSource || localProviderPath || sharedImportSource;
1126
1247
  const skipServePrebuildWarmup = command !== "build" && (pkg === "lit" || pkg.startsWith("lit/"));
1248
+ const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1127
1249
  const namedExports = getPackageNamedExports(pkg);
1128
1250
  let exportLine;
1129
1251
  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(", ")} };`}`;
1252
+ else if (usesLazyLocalFallback) exportLine = `export default exportModule.default ?? exportModule`;
1130
1253
  else exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1131
- const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1132
1254
  const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
1133
1255
  const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
1134
1256
  loadShareCacheMap[pkg].writeSync(`
@@ -1153,15 +1275,24 @@ function getUsedShares() {
1153
1275
  function addUsedShares(pkg) {
1154
1276
  usedShares.add(pkg);
1155
1277
  }
1278
+ const LOCAL_SHARED_IMPORT_MAP_ID = "virtual:mf-localSharedImportMap";
1156
1279
  function getLocalSharedImportMapPath() {
1157
- return getLocalSharedImportMapPath_temp();
1280
+ const { internalName, name } = getNormalizeModuleFederationOptions();
1281
+ return `${LOCAL_SHARED_IMPORT_MAP_ID}:${packageNameEncode(internalName || name)}`;
1282
+ }
1283
+ function getResolvedLocalSharedImportMapId() {
1284
+ return `\0${getLocalSharedImportMapPath()}`;
1285
+ }
1286
+ let invalidateLocalSharedImportMap;
1287
+ function setLocalSharedImportMapInvalidator(invalidator) {
1288
+ invalidateLocalSharedImportMap = invalidator;
1158
1289
  }
1159
1290
  let prevLocalSharedImportMapContent;
1160
1291
  function writeLocalSharedImportMap() {
1161
1292
  const nextContent = generateLocalSharedImportMap();
1162
1293
  if (prevLocalSharedImportMapContent !== nextContent) {
1163
1294
  prevLocalSharedImportMapContent = nextContent;
1164
- writeLocalSharedImportMap_temp(nextContent);
1295
+ invalidateLocalSharedImportMap?.();
1165
1296
  }
1166
1297
  }
1167
1298
  function shouldUseDirectReactImport() {
@@ -1361,14 +1492,40 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1361
1492
  let runtimeInstance
1362
1493
  let localSharedImportMapPromise
1363
1494
  let exposesMapPromise
1495
+ const shouldRetrySharedInitError = ${command !== "build"} && ((error) => {
1496
+ const message = String((error && error.message) || error || '');
1497
+ return message.includes('Importing a module script failed') ||
1498
+ message.includes('Failed to fetch') ||
1499
+ message.includes('Load failed') ||
1500
+ message.includes('Outdated Optimize Dep');
1501
+ });
1502
+ const waitSharedInitRetry = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1503
+ async function retrySharedInit(fn) {
1504
+ for (let attempt = 0; ; attempt++) {
1505
+ try {
1506
+ return await fn();
1507
+ } catch (e) {
1508
+ const canRetry = typeof shouldRetrySharedInitError === 'function' && shouldRetrySharedInitError(e);
1509
+ if (!canRetry || attempt >= 19) throw e;
1510
+ await waitSharedInitRetry(250);
1511
+ }
1512
+ }
1513
+ }
1364
1514
 
1365
1515
  async function getLocalSharedImportMap() {
1366
- localSharedImportMapPromise ??= import("${getLocalSharedImportMapPath()}")
1516
+ if (!localSharedImportMapPromise) {
1517
+ localSharedImportMapPromise = retrySharedInit(() => import("${getLocalSharedImportMapPath()}"))
1518
+ .catch((e) => { localSharedImportMapPromise = undefined; throw e; });
1519
+ }
1367
1520
  return localSharedImportMapPromise
1368
1521
  }
1369
1522
 
1370
1523
  async function getExposesMap() {
1371
- exposesMapPromise ??= import("${virtualExposesId}").then((mod) => mod.default ?? mod)
1524
+ if (!exposesMapPromise) {
1525
+ exposesMapPromise = retrySharedInit(() => import("${virtualExposesId}"))
1526
+ .then((mod) => mod.default ?? mod)
1527
+ .catch((e) => { exposesMapPromise = undefined; throw e; });
1528
+ }
1372
1529
  return exposesMapPromise
1373
1530
  }
1374
1531
 
@@ -1397,11 +1554,13 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
1397
1554
  initRes.initShareScopeMap('${options.shareScope}', shared);
1398
1555
  initResolve(initRes)
1399
1556
  try {
1400
- await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1401
- strategy: '${options.shareStrategy}',
1402
- from: "build",
1403
- initScope
1404
- }));
1557
+ await retrySharedInit(async () => {
1558
+ await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
1559
+ strategy: '${options.shareStrategy}',
1560
+ from: "build",
1561
+ initScope
1562
+ }));
1563
+ });
1405
1564
  } catch (e) {
1406
1565
  console.error('[Module Federation]', e)
1407
1566
  }
@@ -1683,17 +1842,26 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1683
1842
  }
1684
1843
  return patched;
1685
1844
  }
1686
- function getBootstrapSource(initSrc, entrySrc) {
1687
- const remotePreloads = Object.values(getUsedRemotesMap()).flatMap((remotes) => Array.from(remotes)).filter((remote) => remote.includes("/")).sort().map((remote) => `runtime.loadRemote(${JSON.stringify(remote)})`).join(",");
1845
+ function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
1846
+ const remotePreloads = Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `runtime.loadRemote(${JSON.stringify(remote)})`).join(",");
1847
+ const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
1848
+ globalThis.System && typeof globalThis.System.import === 'function'
1849
+ ? globalThis.System.import(src)
1850
+ : import(src);
1851
+ ` : "";
1852
+ const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
1688
1853
  return `${getRuntimeModuleCacheBootstrapCode()}
1689
- (async () => {
1690
- const { initHost } = await import(${JSON.stringify(initSrc)});
1854
+ ${importHelper}(async () => {
1855
+ const { initHost } = await ${importExpression(initSrc)};
1691
1856
  const runtime = await initHost();
1692
1857
  const __mfRemotePreloads = [${remotePreloads}];
1693
1858
  await Promise.all(__mfRemotePreloads);
1694
- })().then(() => import(${JSON.stringify(entrySrc)}));
1859
+ })().then(() => ${importExpression(entrySrc)});
1695
1860
  `;
1696
1861
  }
1862
+ function getSystemBootstrapSource(initSrc, entrySrc) {
1863
+ return getBootstrapSource(initSrc, entrySrc, true);
1864
+ }
1697
1865
  function injectHtml() {
1698
1866
  return inject === "html" && (htmlFilePath || hasPackageDependency("@sveltejs/kit"));
1699
1867
  }
@@ -1833,7 +2001,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1833
2001
  const bootstrapRef = this.emitFile({
1834
2002
  type: "asset",
1835
2003
  fileName: bootstrapFileName,
1836
- source: getBootstrapSource(initPath, entrySrc)
2004
+ source: getSystemBootstrapSource(initPath, entrySrc)
1837
2005
  });
1838
2006
  const bootstrapPath = viteConfig.base + this.getFileName(bootstrapRef);
1839
2007
  return scriptTag.replace(entrySrc, bootstrapPath);
@@ -1978,7 +2146,7 @@ function getHmrWsPath(base, hmrPath) {
1978
2146
  return `${normalizedBase.endsWith("/") ? normalizedBase.slice(0, -1) : normalizedBase}/${normalizedPath.startsWith("/") ? normalizedPath.slice(1) : normalizedPath}`;
1979
2147
  }
1980
2148
  function shouldIgnoreFile(file, options) {
1981
- 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");
2149
+ 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");
1982
2150
  }
1983
2151
  function getRemoteHmrWsUrl(server) {
1984
2152
  const hmr = server.config.server.hmr;
@@ -2019,7 +2187,22 @@ function getStringPreview(value, max = 180) {
2019
2187
  return rawValue.slice(0, max);
2020
2188
  }
2021
2189
  function isRemoteHmrEnabled(dev) {
2022
- return typeof dev === "object" && dev !== null && dev.remoteHmr === true;
2190
+ return typeof dev === "object" && dev !== null && !!dev.remoteHmr;
2191
+ }
2192
+ /**
2193
+ * Detects whether the Vite plugin pipeline includes a framework with
2194
+ * cross-federation HMR support (a shared runtime proxy that works
2195
+ * across module federation boundaries).
2196
+ *
2197
+ * Currently only React is supported via the shared /@react-refresh proxy.
2198
+ */
2199
+ function hasCrossFederationHmr(plugins) {
2200
+ const supportedPlugins = ["vite:react-refresh", "vite:react-swc:refresh"];
2201
+ return plugins.some((p) => supportedPlugins.includes(p.name));
2202
+ }
2203
+ function resolveHmrStrategy(dev, plugins) {
2204
+ if (typeof dev === "object" && dev !== null && dev.remoteHmr === "full-reload") return "full-reload";
2205
+ return hasCrossFederationHmr(plugins) ? "native" : "full-reload";
2023
2206
  }
2024
2207
  function pluginDevRemoteHmr(options) {
2025
2208
  return {
@@ -2029,6 +2212,7 @@ function pluginDevRemoteHmr(options) {
2029
2212
  if (!isRemoteHmrEnabled(options.dev)) return;
2030
2213
  const isRemote = Object.keys(options.exposes).length > 0;
2031
2214
  const isHost = Object.keys(options.remotes).length > 0;
2215
+ const strategy = resolveHmrStrategy(options.dev, server.config.plugins);
2032
2216
  if (isRemote) {
2033
2217
  const endpointPath = getRemoteHmrPath(server.config.base);
2034
2218
  const wsUrl = getRemoteHmrWsUrl(server);
@@ -2052,6 +2236,7 @@ function pluginDevRemoteHmr(options) {
2052
2236
  }));
2053
2237
  });
2054
2238
  const broadcast = (file) => {
2239
+ if (strategy === "native") return;
2055
2240
  if (shouldIgnoreFile(file, options)) return;
2056
2241
  server.ws.send({
2057
2242
  type: "custom",
@@ -2116,6 +2301,7 @@ function pluginDevRemoteHmr(options) {
2116
2301
  }
2117
2302
  const ws = new WebSocket(metadata.wsUrl, "vite-hmr");
2118
2303
  ws.onmessage = (rawEvent) => {
2304
+ if (strategy === "native") return;
2119
2305
  const message = parseRemoteHmrMessage(rawEvent.data);
2120
2306
  if (!message || message.event !== REMOTE_HMR_EVENT) return;
2121
2307
  server.ws.send({ type: "full-reload" });
@@ -2140,6 +2326,7 @@ function pluginDevRemoteHmr(options) {
2140
2326
  };
2141
2327
  for (const [remoteName, remote] of Object.entries(options.remotes)) connectRemote(remoteName, remote);
2142
2328
  const triggerHostReload = (file) => {
2329
+ if (strategy === "native") return;
2143
2330
  if (shouldIgnoreFile(file, options)) return;
2144
2331
  server.ws.send({ type: "full-reload" });
2145
2332
  };
@@ -2462,6 +2649,26 @@ function initVirtualModules(command, remoteEntryId) {
2462
2649
  }
2463
2650
  //#endregion
2464
2651
  //#region src/utils/bundleHelpers.ts
2652
+ function isOutputChunk$1(chunk) {
2653
+ return chunk.type === "chunk";
2654
+ }
2655
+ function escapeRegExp(value) {
2656
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2657
+ }
2658
+ function getProxyBaseName(fileName) {
2659
+ return fileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
2660
+ }
2661
+ function extractFunctionDeclaration(code, functionName) {
2662
+ const funcRe = new RegExp(`function\\s+${functionName}\\s*\\([^)]*\\)\\s*\\{`);
2663
+ const funcStart = code.search(funcRe);
2664
+ if (funcStart < 0) return;
2665
+ let depth = 0;
2666
+ for (let i = code.indexOf("{", funcStart); i < code.length; i++) if (code[i] === "{") depth++;
2667
+ else if (code[i] === "}") {
2668
+ depth--;
2669
+ if (depth === 0) return code.slice(funcStart, i + 1);
2670
+ }
2671
+ }
2465
2672
  /**
2466
2673
  * Resolve the local alias for a non-inlineable proxy binding.
2467
2674
  * If Rollup's deconflict renamed the alias but didn't update references
@@ -2484,6 +2691,147 @@ function resolveProxyAlias(binding, proxyLocal, code, fullImport, claimedLocals
2484
2691
  local
2485
2692
  };
2486
2693
  }
2694
+ function collectLoadShareProxyChunks(bundle, loadShareTag) {
2695
+ const proxyChunks = /* @__PURE__ */ new Map();
2696
+ for (const [fileName, chunk] of Object.entries(bundle)) {
2697
+ if (!isOutputChunk$1(chunk)) continue;
2698
+ if (fileName.includes(loadShareTag) && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
2699
+ code: chunk.code,
2700
+ fileName
2701
+ });
2702
+ }
2703
+ return proxyChunks;
2704
+ }
2705
+ function collectSystemProxyInfos(proxyChunks, loadShareTag) {
2706
+ const systemProxyInfo = /* @__PURE__ */ new Map();
2707
+ for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
2708
+ const depsMatch = proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);
2709
+ if (!depsMatch) continue;
2710
+ const loadShareDep = Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).find((dep) => dep.includes(loadShareTag) && !dep.includes("commonjs-proxy"));
2711
+ if (!loadShareDep) continue;
2712
+ const loadShareBindings = {};
2713
+ 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];
2714
+ const exportMap = {};
2715
+ const objectExportMatch = proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);
2716
+ if (objectExportMatch) for (const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)) {
2717
+ const [, exported, local] = m;
2718
+ const funcBody = extractFunctionDeclaration(proxyInfo.code, local);
2719
+ if (funcBody) exportMap[exported] = {
2720
+ type: "helper",
2721
+ code: funcBody
2722
+ };
2723
+ }
2724
+ for (const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)) {
2725
+ const exported = m[1];
2726
+ const expression = m[2];
2727
+ for (const [local, exportName] of Object.entries(loadShareBindings)) if (new RegExp(`\\b${local}\\b`).test(expression)) {
2728
+ exportMap[exported] = {
2729
+ type: "reexport",
2730
+ exportName
2731
+ };
2732
+ break;
2733
+ }
2734
+ }
2735
+ if (Object.keys(exportMap).length > 0) systemProxyInfo.set(proxyFileName, {
2736
+ loadShareDep,
2737
+ exportMap
2738
+ });
2739
+ }
2740
+ return systemProxyInfo;
2741
+ }
2742
+ function rewriteEsmProxyConsumers(code, proxyChunks) {
2743
+ let nextCode = code;
2744
+ const claimedLocals = /* @__PURE__ */ new Set();
2745
+ for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
2746
+ const proxyBaseName = getProxyBaseName(proxyFileName);
2747
+ const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);
2748
+ if (!importMatch) continue;
2749
+ const fullImport = importMatch[0];
2750
+ const bindings = importMatch[1].split(",").map((s) => {
2751
+ const parts = s.trim().split(/\s+as\s+/);
2752
+ return {
2753
+ imported: parts[0].trim(),
2754
+ local: (parts[1] || parts[0]).trim()
2755
+ };
2756
+ });
2757
+ const exportMapMatch = proxyInfo.code.match(/export\s*\{([^}]+)\}/);
2758
+ if (!exportMapMatch) continue;
2759
+ const exportMap = {};
2760
+ for (const entry of exportMapMatch[1].split(",")) {
2761
+ const parts = entry.trim().split(/\s+as\s+/);
2762
+ if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
2763
+ }
2764
+ const inlineable = [];
2765
+ const nonInlineable = [];
2766
+ const pendingLocals = new Set(bindings.map((binding) => binding.local));
2767
+ for (const b of bindings) {
2768
+ pendingLocals.delete(b.local);
2769
+ const proxyLocal = exportMap[b.imported];
2770
+ if (!proxyLocal) {
2771
+ claimedLocals.add(b.local);
2772
+ nonInlineable.push(b);
2773
+ continue;
2774
+ }
2775
+ const funcBody = extractFunctionDeclaration(proxyInfo.code, proxyLocal);
2776
+ if (funcBody) {
2777
+ inlineable.push({
2778
+ local: b.local,
2779
+ funcBody: funcBody.replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`)
2780
+ });
2781
+ claimedLocals.add(b.local);
2782
+ } else {
2783
+ const unavailableLocals = new Set(claimedLocals);
2784
+ pendingLocals.forEach((local) => unavailableLocals.add(local));
2785
+ const resolvedBinding = resolveProxyAlias(b, proxyLocal, nextCode, fullImport, unavailableLocals);
2786
+ claimedLocals.add(resolvedBinding.local);
2787
+ nonInlineable.push(resolvedBinding);
2788
+ }
2789
+ }
2790
+ const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
2791
+ if (inlineable.length === 0 && !hasRenamedAlias) continue;
2792
+ let replacement = "";
2793
+ if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
2794
+ replacement += inlineable.map((f) => f.funcBody).join("");
2795
+ nextCode = nextCode.replace(fullImport, () => replacement);
2796
+ }
2797
+ return nextCode;
2798
+ }
2799
+ function rewriteSystemProxyConsumers(code, systemProxyInfo) {
2800
+ if (!code.includes("System.register(")) return code;
2801
+ let nextCode = code;
2802
+ for (const [proxyFileName, proxyInfo] of Array.from(systemProxyInfo.entries())) {
2803
+ const proxyBaseName = getProxyBaseName(proxyFileName);
2804
+ const depMatch = new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);
2805
+ if (!depMatch) continue;
2806
+ let setterIndex = 0;
2807
+ const depListMatch = nextCode.match(/System\.register\(\[([\s\S]*?)\]/);
2808
+ if (depListMatch) setterIndex = Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m) => m[1]).findIndex((dep) => dep.includes(proxyBaseName));
2809
+ if (setterIndex < 0) continue;
2810
+ const settersStart = nextCode.indexOf("setters: [");
2811
+ if (settersStart < 0) continue;
2812
+ const setterMatch = Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];
2813
+ if (!setterMatch) continue;
2814
+ const [fullSetter, moduleLocal, setterBody] = setterMatch;
2815
+ const helpersToInline = [];
2816
+ const nextSetterBody = setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`, "g"), (assignment, local, imported) => {
2817
+ const mapped = proxyInfo.exportMap[imported];
2818
+ if (!mapped) return assignment;
2819
+ if (mapped.type === "helper") {
2820
+ helpersToInline.push(mapped.code.replace(new RegExp(`function\\s+${imported}\\s*\\(`), `function ${local}(`));
2821
+ return "";
2822
+ }
2823
+ return `${local} = ${moduleLocal}.${mapped.exportName};`;
2824
+ });
2825
+ if (nextSetterBody === setterBody && helpersToInline.length === 0) continue;
2826
+ const nextSetter = fullSetter.replace(setterBody, () => nextSetterBody);
2827
+ nextCode = nextCode.replace(fullSetter, () => nextSetter);
2828
+ nextCode = nextCode.replace(depMatch[0], JSON.stringify(proxyInfo.loadShareDep));
2829
+ if (helpersToInline.length > 0) nextCode = nextCode.replace("execute: (function() {", () => {
2830
+ return `execute: (function() {${helpersToInline.join("")}`;
2831
+ });
2832
+ }
2833
+ return nextCode;
2834
+ }
2487
2835
  function findRemoteEntryFile(filename, bundle) {
2488
2836
  for (const [_, fileData] of Object.entries(bundle)) if (filename.replace(/[\[\]]/g, "_").replace(/\.[^/.]+$/, "") === fileData.name || fileData.name === "remoteEntry") return fileData.fileName;
2489
2837
  }
@@ -2653,6 +3001,9 @@ function normalizeNodeModulePath(source) {
2653
3001
  function isNodeModulePath(source) {
2654
3002
  return source.includes("/node_modules/") || source.includes("\\node_modules\\");
2655
3003
  }
3004
+ function filterId(id) {
3005
+ return typeof id === "string" && !id.includes("\0");
3006
+ }
2656
3007
  function getMatchingNodeModuleSubpath(source, candidates) {
2657
3008
  const normalized = normalizeNodeModulePath(source);
2658
3009
  return [...candidates].sort((a, b) => b.length - a.length).find((candidate) => normalized.includes(`/node_modules/${candidate}/`) || normalized.includes(`/node_modules/${candidate}.`));
@@ -2837,10 +3188,11 @@ const Manifest = () => {
2837
3188
  alias: remoteKey,
2838
3189
  entry: "*"
2839
3190
  })));
2840
- const shared = Array.from(getUsedShares()).map((shareKey) => {
3191
+ const shared = Array.from(getUsedShares()).flatMap((shareKey) => {
2841
3192
  const shareItem = getNormalizeShareItem(shareKey);
3193
+ if (!shareItem) return [];
2842
3194
  const assets = preloadMap[shareKey] || createEmptyAssetMap();
2843
- return {
3195
+ return [{
2844
3196
  id: `${name}:${shareKey}`,
2845
3197
  name: shareKey,
2846
3198
  version: shareItem.version,
@@ -2856,7 +3208,7 @@ const Manifest = () => {
2856
3208
  sync: assets.css.sync
2857
3209
  }
2858
3210
  }
2859
- };
3211
+ }];
2860
3212
  });
2861
3213
  const exposes = Object.entries(options.exposes).map(([key, value]) => {
2862
3214
  const formatKey = key.replace("./", "");
@@ -3008,7 +3360,6 @@ function pluginModuleParseEnd_default(excludeFn, options) {
3008
3360
  }
3009
3361
  //#endregion
3010
3362
  //#region src/plugins/pluginProxyRemoteEntry.ts
3011
- const filter$1 = createFilter();
3012
3363
  function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId }) {
3013
3364
  let viteConfig, _command, root;
3014
3365
  return {
@@ -3048,14 +3399,14 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3048
3399
  },
3049
3400
  transform(code, id) {
3050
3401
  return mapCodeToCodeWithSourcemap((() => {
3051
- if (!filter$1(id)) return;
3402
+ if (!filterId(id)) return;
3052
3403
  if (id.includes(remoteEntryId)) return parsePromise.then((_) => generateRemoteEntry(options, virtualExposesId, _command));
3053
3404
  if (id === virtualExposesId) return generateExposes(options);
3054
3405
  if (id.includes(getHostAutoInitPath())) {
3055
3406
  if (_command === "serve") {
3056
3407
  const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
3057
3408
  const publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
3058
- const fallbackOrigin = `http://${host}:${viteConfig.server?.port}`;
3409
+ const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
3059
3410
  const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
3060
3411
  return `
3061
3412
  const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
@@ -3106,10 +3457,25 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3106
3457
  }
3107
3458
  //#endregion
3108
3459
  //#region src/plugins/pluginProxyRemotes.ts
3109
- const filter = createFilter();
3110
3460
  function isNodeModulesImporter(importer) {
3111
3461
  return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
3112
3462
  }
3463
+ function appendAlias(config, alias) {
3464
+ config.resolve ??= {};
3465
+ const existingAlias = config.resolve.alias;
3466
+ if (!existingAlias) {
3467
+ config.resolve.alias = [alias];
3468
+ return;
3469
+ }
3470
+ if (Array.isArray(existingAlias)) {
3471
+ existingAlias.push(alias);
3472
+ return;
3473
+ }
3474
+ config.resolve.alias = [...Object.entries(existingAlias).map(([find, replacement]) => ({
3475
+ find,
3476
+ replacement
3477
+ })), alias];
3478
+ }
3113
3479
  function pluginProxyRemotes_default(options) {
3114
3480
  let command;
3115
3481
  let root = process.cwd();
@@ -3126,19 +3492,20 @@ function pluginProxyRemotes_default(options) {
3126
3492
  }
3127
3493
  return {
3128
3494
  name: "proxyRemotes",
3495
+ enforce: "pre",
3129
3496
  config(config, { command: _command }) {
3130
3497
  command = _command;
3131
3498
  root = config.root || process.cwd();
3132
3499
  Object.keys(remotes).forEach((key) => {
3133
3500
  const remote = remotes[key];
3134
- config.resolve.alias.push({
3501
+ appendAlias(config, {
3135
3502
  find: new RegExp(`^(${remote.name}(\/.*|$))`),
3136
3503
  replacement: "$1"
3137
3504
  });
3138
3505
  });
3139
3506
  },
3140
3507
  resolveId(source, importer) {
3141
- if (!filter(source)) return;
3508
+ if (!filterId(source)) return;
3142
3509
  for (const remote of Object.values(remotes)) {
3143
3510
  if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
3144
3511
  return resolveRemoteId(source, importer, remote.name);
@@ -3239,7 +3606,7 @@ function excludeSharedSubDependencies(shared) {
3239
3606
  for (const dep of deps) {
3240
3607
  const depKey = sharedKeyByBase.get(dep);
3241
3608
  if (depKey && depKey !== parentKey) {
3242
- if (shared[depKey]?.shareConfig.import === false) continue;
3609
+ if (shared[depKey]?.shareConfig.singleton === true || shared[depKey]?.shareConfig.import === false) continue;
3243
3610
  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.`);
3244
3611
  delete shared[depKey];
3245
3612
  sharedKeys.delete(depKey);
@@ -3255,15 +3622,27 @@ function proxySharedModule(options) {
3255
3622
  let useDirectReactImport = false;
3256
3623
  let useRolldown = false;
3257
3624
  const savePrebuild = new PromiseStore();
3625
+ let devServer;
3258
3626
  return [
3259
3627
  {
3260
3628
  name: "generateLocalSharedImportMap",
3261
3629
  enforce: "post",
3630
+ configureServer(server) {
3631
+ devServer = server;
3632
+ setLocalSharedImportMapInvalidator(() => {
3633
+ const module = server.moduleGraph.getModuleById(getResolvedLocalSharedImportMapId());
3634
+ if (module) server.moduleGraph.invalidateModule(module);
3635
+ });
3636
+ },
3637
+ resolveId(source) {
3638
+ if (source === getLocalSharedImportMapPath()) return getResolvedLocalSharedImportMapId();
3639
+ },
3262
3640
  load(id) {
3263
- if (id.includes(getLocalSharedImportMapPath())) return parsePromise.then((_) => generateLocalSharedImportMap());
3641
+ if (id === getResolvedLocalSharedImportMapId()) return parsePromise.then((_) => generateLocalSharedImportMap());
3264
3642
  },
3265
- transform(_, id) {
3266
- if (id.includes(getLocalSharedImportMapPath())) return mapCodeToCodeWithSourcemap(parsePromise.then((_) => generateLocalSharedImportMap()));
3643
+ closeBundle() {
3644
+ if (devServer) return;
3645
+ setLocalSharedImportMapInvalidator(void 0);
3267
3646
  }
3268
3647
  },
3269
3648
  {
@@ -3394,7 +3773,7 @@ function wrapDynamicImport(original) {
3394
3773
  }
3395
3774
  function applyRewrites(code, imports, id) {
3396
3775
  if (imports.length === 0) return;
3397
- const ms = new MagicString(code);
3776
+ const ms = new CodeRewriter(code);
3398
3777
  let changed = false;
3399
3778
  let counter = 0;
3400
3779
  for (const imp of imports) switch (imp.kind) {
@@ -3442,7 +3821,7 @@ function applyRewrites(code, imports, id) {
3442
3821
  if (!changed) return;
3443
3822
  return {
3444
3823
  code: ms.toString(),
3445
- map: ms.generateMap({ hires: true })
3824
+ map: ms.generateMap(id)
3446
3825
  };
3447
3826
  }
3448
3827
  async function collectFromAST(ast, code, isRemoteImport) {
@@ -3884,6 +4263,9 @@ function ignoreFederationGeneratedFiles(config, options) {
3884
4263
  function isSharedResolverInternalImporter(importer) {
3885
4264
  return !!importer && (importer.includes("__loadShare__") || importer.includes("__prebuild__"));
3886
4265
  }
4266
+ function isCommonJsImporter(importer) {
4267
+ return !!importer && (importer.endsWith(".cjs") || importer.includes("/cjs/"));
4268
+ }
3887
4269
  function isOutputChunk(chunk) {
3888
4270
  return chunk.type === "chunk";
3889
4271
  }
@@ -3967,9 +4349,10 @@ function createEarlyVirtualModulesPlugin(options) {
3967
4349
  optimizeDeps.rolldownOptions.plugins ??= [];
3968
4350
  optimizeDeps.rolldownOptions.plugins.push({
3969
4351
  name: "module-federation:optimize-shared-resolver",
3970
- resolveId(source, importer) {
4352
+ resolveId(source, importer, options) {
4353
+ if (options?.kind?.startsWith("require")) return;
3971
4354
  if (isSharedResolverInternalImporter(importer)) return;
3972
- if (source !== "react/jsx-runtime" && source !== "react/jsx-dev-runtime") return;
4355
+ if (isCommonJsImporter(importer)) return;
3973
4356
  const key = findSharedKey(source, shared);
3974
4357
  if (!key) return;
3975
4358
  if (source.endsWith(".css")) return;
@@ -4280,87 +4663,17 @@ function federation(mfUserOptions) {
4280
4663
  if (!isFederationControlChunk(fileName, filename)) continue;
4281
4664
  chunk.code = sanitizeFederationControlChunk(chunk.code, fileName, filename);
4282
4665
  }
4283
- const proxyChunks = /* @__PURE__ */ new Map();
4284
- for (const [fileName, chunk] of Object.entries(bundle)) {
4285
- if (!isOutputChunk(chunk)) continue;
4286
- if (fileName.includes("__loadShare__") && fileName.includes("commonjs-proxy")) proxyChunks.set(fileName, {
4287
- code: chunk.code,
4288
- fileName
4289
- });
4290
- }
4291
- if (proxyChunks.size > 0) for (const [fileName, chunk] of Object.entries(bundle)) {
4292
- if (!isOutputChunk(chunk)) continue;
4293
- if (fileName.includes("__loadShare__")) continue;
4294
- let code = chunk.code;
4295
- let modified = false;
4296
- const claimedLocals = /* @__PURE__ */ new Set();
4297
- for (const [proxyFileName, proxyInfo] of Array.from(proxyChunks.entries())) {
4298
- const proxyBaseName = proxyFileName.replace(/^.*\//, "").replace(/\.js$/, "").replace(/-[A-Za-z0-9_-]+$/, "");
4299
- const importMatch = new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${proxyBaseName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[^"']*)["']\\s*;?`).exec(code);
4300
- if (!importMatch) continue;
4301
- const fullImport = importMatch[0];
4302
- const bindings = importMatch[1].split(",").map((s) => {
4303
- const parts = s.trim().split(/\s+as\s+/);
4304
- return {
4305
- imported: parts[0].trim(),
4306
- local: (parts[1] || parts[0]).trim()
4307
- };
4308
- });
4309
- const proxyCode = proxyInfo.code;
4310
- const exportMapMatch = proxyCode.match(/export\s*\{([^}]+)\}/);
4311
- if (!exportMapMatch) continue;
4312
- const exportMap = {};
4313
- for (const entry of exportMapMatch[1].split(",")) {
4314
- const parts = entry.trim().split(/\s+as\s+/);
4315
- if (parts.length === 2) exportMap[parts[1].trim()] = parts[0].trim();
4316
- }
4317
- const inlineable = [];
4318
- const nonInlineable = [];
4319
- const pendingLocals = new Set(bindings.map((binding) => binding.local));
4320
- for (const b of bindings) {
4321
- pendingLocals.delete(b.local);
4322
- const proxyLocal = exportMap[b.imported];
4323
- if (!proxyLocal) {
4324
- claimedLocals.add(b.local);
4325
- nonInlineable.push(b);
4326
- continue;
4327
- }
4328
- const funcRe = new RegExp(`function\\s+${proxyLocal}\\s*\\([^)]*\\)\\s*\\{`);
4329
- if (funcRe.test(proxyCode)) {
4330
- const funcStart = proxyCode.search(funcRe);
4331
- let depth = 0;
4332
- let funcEnd = funcStart;
4333
- for (let i = proxyCode.indexOf("{", funcStart); i < proxyCode.length; i++) if (proxyCode[i] === "{") depth++;
4334
- else if (proxyCode[i] === "}") {
4335
- depth--;
4336
- if (depth === 0) {
4337
- funcEnd = i + 1;
4338
- break;
4339
- }
4340
- }
4341
- const renamedFunc = proxyCode.slice(funcStart, funcEnd).replace(new RegExp(`function\\s+${proxyLocal}\\s*\\(`), `function ${b.local}(`);
4342
- inlineable.push({
4343
- local: b.local,
4344
- funcBody: renamedFunc
4345
- });
4346
- claimedLocals.add(b.local);
4347
- } else {
4348
- const unavailableLocals = new Set(claimedLocals);
4349
- pendingLocals.forEach((local) => unavailableLocals.add(local));
4350
- const resolvedBinding = resolveProxyAlias(b, proxyLocal, code, fullImport, unavailableLocals);
4351
- claimedLocals.add(resolvedBinding.local);
4352
- nonInlineable.push(resolvedBinding);
4353
- }
4354
- }
4355
- const hasRenamedAlias = nonInlineable.some((b) => bindings.find((ob) => ob.imported === b.imported)?.local !== b.local);
4356
- if (inlineable.length === 0 && !hasRenamedAlias) continue;
4357
- let replacement = "";
4358
- if (nonInlineable.length > 0) replacement = `import{${nonInlineable.map((b) => b.imported === b.local ? b.imported : `${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;
4359
- replacement += inlineable.map((f) => f.funcBody).join("");
4360
- code = code.replace(fullImport, () => replacement);
4361
- modified = true;
4666
+ const proxyChunks = collectLoadShareProxyChunks(bundle, LOAD_SHARE_TAG);
4667
+ if (proxyChunks.size > 0) {
4668
+ const systemProxyInfo = collectSystemProxyInfos(proxyChunks, LOAD_SHARE_TAG);
4669
+ for (const [fileName, chunk] of Object.entries(bundle)) {
4670
+ if (!isOutputChunk(chunk)) continue;
4671
+ if (proxyChunks.has(fileName)) continue;
4672
+ let code = chunk.code;
4673
+ if (!fileName.includes("__loadShare__")) code = rewriteEsmProxyConsumers(code, proxyChunks);
4674
+ code = rewriteSystemProxyConsumers(code, systemProxyInfo);
4675
+ if (code !== chunk.code) chunk.code = code;
4362
4676
  }
4363
- if (modified) chunk.code = code;
4364
4677
  }
4365
4678
  }
4366
4679
  },
@@ -4398,12 +4711,14 @@ function federation(mfUserOptions) {
4398
4711
  find: "@module-federation/runtime",
4399
4712
  replacement: implementation
4400
4713
  });
4401
- config.build = defu(config.build || {}, { commonjsOptions: { strictRequires: "auto" } });
4714
+ config.build ||= {};
4715
+ config.build.commonjsOptions ||= {};
4716
+ config.build.commonjsOptions.strictRequires ??= "auto";
4402
4717
  const virtualDir = options.virtualModuleDir;
4403
4718
  config.optimizeDeps ||= {};
4404
4719
  config.optimizeDeps.include ||= [];
4405
4720
  config.optimizeDeps.include.push("@module-federation/runtime");
4406
- config.optimizeDeps.include.push(virtualDir);
4721
+ if (!isRolldown) config.optimizeDeps.include.push(virtualDir);
4407
4722
  config.ssr ||= {};
4408
4723
  config.ssr.noExternal ||= [];
4409
4724
  if (Array.isArray(config.ssr.noExternal)) config.ssr.noExternal.push(virtualDir);
@@ -4411,11 +4726,12 @@ function federation(mfUserOptions) {
4411
4726
  const pluginPath = typeof p === "string" ? p : p[0];
4412
4727
  if (pluginPath && !pluginPath.startsWith(".") && !pluginPath.startsWith("/") && !pluginPath.startsWith("\0") && !pluginPath.startsWith("virtual:")) config.optimizeDeps.include.push(pluginPath);
4413
4728
  });
4414
- if (isRolldown) config.build = defu(config.build || {}, { target: "esnext" });
4415
- else {
4729
+ if (isRolldown) {
4730
+ config.build ??= {};
4731
+ config.build.target ??= "esnext";
4732
+ } else {
4416
4733
  config.optimizeDeps.needsInterop ||= [];
4417
4734
  config.optimizeDeps.needsInterop.push(virtualDir);
4418
- config.optimizeDeps.needsInterop.push(getLocalSharedImportMapPath());
4419
4735
  }
4420
4736
  const isAstro = hasPackageDependency("astro");
4421
4737
  const resolvedTarget = options.target ?? (config.build?.ssr ? "node" : "web");