@module-federation/vite 1.16.5 → 1.16.7

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.js CHANGED
@@ -1,48 +1,15 @@
1
- import { a as getPackageName, c as hasPackageDependency, d as packageNameEncode, f as resolveImportPath, g as mfWarn, i as getPackageDetectionCwd, l as isNuxtProjectRoot, m as createModuleFederationError, n as getInstalledPackageJson, o as getPackageNameFromNodeModulePath, p as setPackageDetectionCwd, r as getIsRolldown, s as getSharedCacheKey, t as getInstalledPackageEntry, u as packageNameDecode } from "./packageUtils-CxYRnFwy.js";
1
+ import { _ as mfWarn, a as getIsRolldown, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as packageNameDecode, g as createModuleFederationError, h as setPackageDetectionCwd, i as getInstalledPackageJson, l as getSharedCacheKey, m as resolveImportPath, o as getPackageDetectionCwd, p as packageNameEncode, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as normalizePathForImport, y as rebaseImport } from "./pluginDts-Cpmdbbr0.js";
2
+ import { createRequire } from "node:module";
2
3
  import * as fs$1 from "fs";
3
4
  import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from "fs";
4
- import { createRequire } from "module";
5
- import * as path$1 from "pathe";
6
- import path, { basename } from "pathe";
5
+ import { createRequire as createRequire$1 } from "module";
6
+ import * as path$1 from "node:path";
7
+ import path, { basename } from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "url";
7
9
  import { version } from "vite";
8
10
  import { createHash } from "node:crypto";
9
- import { fileURLToPath } from "url";
10
- import { init, parse } from "es-module-lexer";
11
- //#region src/utils/buildPaths.ts
12
- /**
13
- * Rebase an import path for a bootstrap file that moved from root into `dir`.
14
- *
15
- * When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
16
- * the bootstrap file moves there too. Paths that resolved from the HTML root
17
- * must resolve from the new directory instead.
18
- *
19
- * Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
20
- * `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
21
- * `https://cdn.example.com` → unchanged (absolute URL)
22
- */
23
- function rebaseImport(importSrc, dir) {
24
- if (!dir) return importSrc;
25
- if (isAbsoluteUrl(importSrc)) return importSrc;
26
- const absPrefix = "/" + dir;
27
- if (importSrc.startsWith(absPrefix)) {
28
- const remainder = importSrc.slice(absPrefix.length);
29
- return remainder ? "./" + remainder : "./";
30
- }
31
- if (importSrc.startsWith(dir)) {
32
- const remainder = importSrc.slice(dir.length);
33
- return remainder ? "./" + remainder : "./";
34
- }
35
- const upLevels = dir.split("/").filter(Boolean).length;
36
- const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
37
- if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
38
- if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
39
- return prefix + importSrc;
40
- }
41
- const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
42
- function isAbsoluteUrl(src) {
43
- return EXTERNAL_URL_RE.test(src);
44
- }
45
- //#endregion
11
+ import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
12
+ import { pathToFileURL as pathToFileURL$1 } from "node:url";
46
13
  //#region src/utils/codeRewriter.ts
47
14
  const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
48
15
  var CodeRewriter = class {
@@ -452,6 +419,7 @@ function getSuffix(name) {
452
419
  }
453
420
  const patternMap = {};
454
421
  const cacheMap = {};
422
+ const idCacheMap = {};
455
423
  const VITE_ID_PREFIX = "/@id/";
456
424
  const VITE_ENCODED_NULL_BYTE_PREFIX = `${VITE_ID_PREFIX}__x00__`;
457
425
  function escapeRegExp$1(value) {
@@ -486,6 +454,8 @@ var VirtualModule = class VirtualModule {
486
454
  suffix;
487
455
  inited = false;
488
456
  code;
457
+ importId;
458
+ importIdKey;
489
459
  static findName(tag, str = "") {
490
460
  if (!patternMap[tag]) patternMap[tag] = new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);
491
461
  const moduleName = (normalizeVirtualModuleId(str).match(patternMap[tag]) || [])[2];
@@ -497,7 +467,7 @@ var VirtualModule = class VirtualModule {
497
467
  }
498
468
  static findById(id) {
499
469
  const normalized = normalizeVirtualModuleId(id);
500
- for (const modules of Object.values(cacheMap)) for (const module of Object.values(modules)) if (module.getImportId() === normalized) return module;
470
+ return normalized.startsWith("virtual:mf:") ? idCacheMap[normalized] : void 0;
501
471
  }
502
472
  constructor(name, tag = "__mf_v__", suffix = "") {
503
473
  this.name = name;
@@ -508,7 +478,13 @@ var VirtualModule = class VirtualModule {
508
478
  }
509
479
  getImportId() {
510
480
  const { internalName: mfName } = getNormalizeModuleFederationOptions();
511
- return `virtual:mf:${packageNameEncode(`${mfName}${this.tag}${this.name}${this.tag}`)}${this.suffix}`;
481
+ const importIdKey = `${mfName}${this.tag}${this.name}${this.tag}`;
482
+ if (this.importId && this.importIdKey === importIdKey) return this.importId;
483
+ if (this.importId) delete idCacheMap[this.importId];
484
+ this.importIdKey = importIdKey;
485
+ this.importId = `virtual:mf:${packageNameEncode(importIdKey)}${this.suffix}`;
486
+ idCacheMap[this.importId] = this;
487
+ return this.importId;
512
488
  }
513
489
  getResolvedId() {
514
490
  return `\0${this.getImportId()}`;
@@ -670,20 +646,31 @@ let _ssrRemotes = [];
670
646
  function setSsrRemotes(remotes) {
671
647
  _ssrRemotes = remotes;
672
648
  }
673
- function getSsrNoopResolveCode(enableSsrInit) {
649
+ function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpression = "initResolve") {
674
650
  if (!enableSsrInit) return "";
675
651
  return `if (typeof window === 'undefined') {
676
652
  var _noop = { loadRemote: function() { return Promise.resolve(undefined); }, loadShare: function() { return Promise.resolve(undefined); } };
677
- import(/* @vite-ignore */ '@module-federation/runtime').then(function(runtimeMod) {
678
- return import(/* @vite-ignore */ '@module-federation/vite/ssrEntryLoader').then(
679
- function(loaderMod) { return [runtimeMod, [loaderMod.default()]]; },
680
- function() { return [runtimeMod, []]; }
681
- );
682
- }).then(function(pair) {
683
- var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${JSON.stringify(_ssrRemotes)}, shared: {}, plugins: pair[1] });
684
- initResolve(runtime);
685
- }, function() {
686
- initResolve(_noop);
653
+ ${hostInitImportId ? `import(${JSON.stringify(hostInitImportId)})
654
+ .then(function(mod) { return mod.hostInitPromise; })
655
+ .then(function(runtime) {
656
+ ${initResolveExpression}(runtime);
657
+ return true;
658
+ })
659
+ .catch(function() {
660
+ return false;
661
+ })` : "Promise.resolve(false)"}.then(function(resolved) {
662
+ if (resolved) return;
663
+ return import(/* @vite-ignore */ '@module-federation/runtime').then(function(runtimeMod) {
664
+ return import(/* @vite-ignore */ '@module-federation/vite/ssrEntryLoader').then(
665
+ function(loaderMod) { return [runtimeMod, [loaderMod.default()]]; },
666
+ function() { return [runtimeMod, []]; }
667
+ );
668
+ }).then(function(pair) {
669
+ var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${JSON.stringify(_ssrRemotes)}, shared: {}, plugins: pair[1] });
670
+ ${initResolveExpression}(runtime);
671
+ }, function() {
672
+ ${initResolveExpression}(_noop);
673
+ });
687
674
  });
688
675
  }`;
689
676
  }
@@ -703,7 +690,7 @@ if (!${options.stateVar}) {
703
690
  const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
704
691
  `;
705
692
  }
706
- function getRuntimeInitBootstrapCode(enableSsrInit = false) {
693
+ function getRuntimeInitBootstrapCode(enableSsrInit = false, hostInitImportId) {
707
694
  return `
708
695
  const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
709
696
  const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
@@ -712,14 +699,18 @@ globalThis[moduleCacheGlobalKey].share ||= {};
712
699
  globalThis[moduleCacheGlobalKey].remote ||= {};
713
700
  if (!globalThis[globalKey]) {
714
701
  ${getDeferredInitPromiseCode()}
715
- globalThis[globalKey] = {
702
+ globalThis[globalKey] = {
716
703
  initPromise,
717
704
  initResolve,
718
705
  initReject,
719
706
  moduleCache: globalThis[moduleCacheGlobalKey],
720
707
  };
721
- ${getSsrNoopResolveCode(enableSsrInit)}
722
708
  }
709
+ ${enableSsrInit ? `
710
+ if (typeof window === 'undefined' && !globalThis[globalKey].ssrInitStarted) {
711
+ globalThis[globalKey].ssrInitStarted = true;
712
+ ${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve")}
713
+ }` : ""}
723
714
  globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
724
715
  globalThis[globalKey].moduleCache.share ||= {};
725
716
  globalThis[globalKey].moduleCache.remote ||= {};
@@ -752,11 +743,11 @@ function getRuntimeInitResolveBootstrapCode(enableSsrInit = false) {
752
743
  enableSsrInit
753
744
  });
754
745
  }
755
- function writeRuntimeInitStatus(command, enableSsrInit = false) {
746
+ function writeRuntimeInitStatus(command, enableSsrInit = false, hostInitImportId) {
756
747
  const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
757
748
  export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
758
749
  virtualRuntimeInitStatus.writeSync(`
759
- ${getRuntimeInitBootstrapCode(enableSsrInit)}
750
+ ${getRuntimeInitBootstrapCode(enableSsrInit, hostInitImportId)}
760
751
  ${exportStatement}
761
752
  `);
762
753
  }
@@ -791,10 +782,9 @@ function isValidEsmExportName(name) {
791
782
  return !!name && name !== "default" && name !== "__esModule" && isValidJsIdentifier(name);
792
783
  }
793
784
  const JS_IDENTIFIER_PATTERN = `[\$_\\p{ID_Start}][\$_\\u200C\\u200D\\p{ID_Continue}]*`;
794
- const localRequire = createRequire(import.meta.url);
795
785
  function resolvePackageEntryFromProjectRoot(pkg) {
796
786
  try {
797
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
787
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
798
788
  } catch {
799
789
  return;
800
790
  }
@@ -811,29 +801,20 @@ function getPackageEsmEntryPath(pkg) {
811
801
  }) || resolvePackageEntryFromProjectRoot(pkg);
812
802
  }
813
803
  function getEsmNamedExportsFromFile(entryPath) {
814
- let source = "";
815
804
  try {
816
805
  if (!entryPath) return [];
817
- const { initSync, parse } = localRequire("es-module-lexer");
818
- initSync();
819
- source = readFileSync(entryPath, "utf-8");
820
- const [, exports] = parse(source, entryPath);
821
- const names = exports.map((item) => item.n).filter((name) => isValidEsmExportName(name));
822
- const regexNames = getNamedExportsViaRegex(source, entryPath);
823
- const filteredNames = names.filter((name) => name !== "type" || regexNames.includes(name));
824
- if (filteredNames.length > 0) return Array.from(new Set([...filteredNames, ...regexNames]));
825
- return regexNames;
806
+ return getNamedExportsViaRegex(readFileSync(entryPath, "utf-8"), entryPath);
826
807
  } catch {
827
- return source ? getNamedExportsViaRegex(source, entryPath) : [];
808
+ return [];
828
809
  }
829
810
  }
830
811
  function getEsmNamedExports(pkg) {
831
812
  return getEsmNamedExportsFromFile(getPackageEsmEntryPath(pkg));
832
813
  }
833
814
  function resolveConfiguredImportPath(importSource) {
834
- if (path.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
815
+ if (path$1.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
835
816
  const projectRoot = getPackageDetectionCwd();
836
- if (importSource.startsWith(".")) return resolveFileLikeModule(path.resolve(projectRoot, importSource));
817
+ if (importSource.startsWith(".")) return resolveFileLikeModule(path$1.resolve(projectRoot, importSource));
837
818
  const esmEntry = getInstalledPackageEntry(importSource, {
838
819
  conditions: [
839
820
  "browser",
@@ -845,7 +826,7 @@ function resolveConfiguredImportPath(importSource) {
845
826
  });
846
827
  if (esmEntry) return esmEntry;
847
828
  try {
848
- return createRequire(new URL(`file://${path.join(projectRoot, "package.json")}`)).resolve(importSource);
829
+ return createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(importSource);
849
830
  } catch {
850
831
  return;
851
832
  }
@@ -865,13 +846,13 @@ function resolveFileLikeModule(filePath) {
865
846
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
866
847
  }
867
848
  for (const ext of extensions) {
868
- const candidate = path.join(filePath, "index" + ext);
849
+ const candidate = path$1.join(filePath, "index" + ext);
869
850
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
870
851
  }
871
852
  }
872
853
  function resolveRelativeModule(filePath, specifier) {
873
- const dir = path.dirname(filePath);
874
- const exact = path.resolve(dir, specifier);
854
+ const dir = path$1.dirname(filePath);
855
+ const exact = path$1.resolve(dir, specifier);
875
856
  if (existsSync(exact) && !statSync(exact).isDirectory()) return exact;
876
857
  const extensions = [
877
858
  ".ts",
@@ -882,12 +863,12 @@ function resolveRelativeModule(filePath, specifier) {
882
863
  ".mts"
883
864
  ];
884
865
  for (const ext of extensions) {
885
- const candidate = path.resolve(dir, specifier + ext);
866
+ const candidate = path$1.resolve(dir, specifier + ext);
886
867
  if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
887
868
  }
888
- const resolved = path.resolve(dir, specifier);
869
+ const resolved = path$1.resolve(dir, specifier);
889
870
  for (const ext of extensions) {
890
- const candidate = path.join(resolved, "index" + ext);
871
+ const candidate = path$1.join(resolved, "index" + ext);
891
872
  if (existsSync(candidate)) return candidate;
892
873
  }
893
874
  }
@@ -928,6 +909,8 @@ function getNamedExportsViaRegex(source, filePath, visited) {
928
909
  if (isValidEsmExportName(name)) names.add(name);
929
910
  }
930
911
  }
912
+ const namespaceReExportRegex = new RegExp(`export\\s+\\*\\s+as\\s+(${JS_IDENTIFIER_PATTERN})\\s+from\\s+['"][^'"]+['"]`, "gu");
913
+ while ((match = namespaceReExportRegex.exec(source)) !== null) if (isValidEsmExportName(match[1])) names.add(match[1]);
931
914
  if (filePath) {
932
915
  const starExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g;
933
916
  while ((match = starExportRegex.exec(source)) !== null) {
@@ -945,7 +928,7 @@ function getNamedExportsViaRegex(source, filePath, visited) {
945
928
  }
946
929
  function getPackageNamedExports(pkg) {
947
930
  try {
948
- const mod = createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`))(pkg);
931
+ const mod = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json")))(pkg);
949
932
  return Object.keys(mod).filter((k) => isValidEsmExportName(k));
950
933
  } catch {
951
934
  return getEsmNamedExports(pkg);
@@ -961,7 +944,7 @@ function getSharedNamedExports(pkg, shareItem) {
961
944
  }
962
945
  function getLocalProviderImportPath(pkg) {
963
946
  try {
964
- const resolved = createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
947
+ const resolved = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
965
948
  return isWorkspaceFilePath(resolved) ? resolved : void 0;
966
949
  } catch {
967
950
  const resolved = getInstalledPackageEntry(pkg, {
@@ -982,7 +965,7 @@ function getProjectResolvedImportPath(pkg) {
982
965
  if (esmEntry) return esmEntry;
983
966
  }
984
967
  try {
985
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(pkg);
968
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
986
969
  } catch {
987
970
  return;
988
971
  }
@@ -996,7 +979,7 @@ function isWorkspaceFilePath(resolved) {
996
979
  return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
997
980
  }
998
981
  function isWorkspacePackageEntry(pkg, resolved) {
999
- if (!resolved || !path.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
982
+ if (!resolved || !path$1.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
1000
983
  return !!getInstalledPackageJson(pkg, {
1001
984
  packageName: getPackageName(pkg),
1002
985
  fromResolvedEntry: resolved
@@ -1004,7 +987,7 @@ function isWorkspacePackageEntry(pkg, resolved) {
1004
987
  }
1005
988
  function tryResolveImportFromPackageRoot(pkg, root) {
1006
989
  try {
1007
- return createRequire(new URL(`file://${path.join(root, "package.json")}`)).resolve(pkg);
990
+ return createRequire$1(pathToFileURL(path$1.join(root, "package.json"))).resolve(pkg);
1008
991
  } catch {
1009
992
  return;
1010
993
  }
@@ -1014,11 +997,11 @@ function getConcreteSharedImportSource(pkg, shareItem) {
1014
997
  if (typeof configuredImport === "string") return configuredImport;
1015
998
  const projectRoot = getPackageDetectionCwd();
1016
999
  if (tryResolveImportFromPackageRoot(pkg, projectRoot)) return;
1017
- let currentDir = path.dirname(projectRoot);
1018
- while (currentDir !== path.dirname(currentDir)) {
1000
+ let currentDir = path$1.dirname(projectRoot);
1001
+ while (currentDir !== path$1.dirname(currentDir)) {
1019
1002
  const resolved = tryResolveImportFromPackageRoot(pkg, currentDir);
1020
1003
  if (resolved) return resolved;
1021
- currentDir = path.dirname(currentDir);
1004
+ currentDir = path$1.dirname(currentDir);
1022
1005
  }
1023
1006
  return tryResolveImportFromPackageRoot(pkg, currentDir);
1024
1007
  }
@@ -1110,11 +1093,15 @@ function toViteOptimizedDepVirtualId(id) {
1110
1093
  return toViteEncodedId(id);
1111
1094
  }
1112
1095
  function getCachedLoadSharePkg(id) {
1096
+ if (!id.includes("__loadShare__")) return;
1113
1097
  const normalized = normalizeVirtualModuleId(id);
1114
1098
  if (!normalized.startsWith("virtual:mf:")) return;
1115
- const pkg = VirtualModule.findName(LOAD_SHARE_TAG, normalized);
1116
- if (!pkg) return;
1117
- return pkg;
1099
+ const start = normalized.indexOf(LOAD_SHARE_TAG);
1100
+ if (start === -1) return;
1101
+ const encodedPkgStart = start + 13;
1102
+ const end = normalized.indexOf(LOAD_SHARE_TAG, encodedPkgStart);
1103
+ if (end === -1) return;
1104
+ return packageNameDecode(normalized.slice(encodedPkgStart, end));
1118
1105
  }
1119
1106
  function materializeCachedLoadShareModule(options) {
1120
1107
  const pkg = getCachedLoadSharePkg(options.id);
@@ -1127,6 +1114,33 @@ function materializeCachedLoadShareModule(options) {
1127
1114
  options.addUsedShares(pkg);
1128
1115
  options.writeLocalSharedImportMap();
1129
1116
  }
1117
+ function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheKey, eagerLocalFallback) {
1118
+ const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
1119
+ const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
1120
+ const assignments = namedExports.length > 0 ? [...namedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), "__mf_default = mod.default ?? mod;"].join("\n ") : "__mf_default = mod.default ?? mod;";
1121
+ const namedExportLine = namedExports.length > 0 ? `\n export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
1122
+ const body = `${declarations}
1123
+ const __mfApplyLazyShareExports = (mod) => {
1124
+ ${assignments}
1125
+ };
1126
+ let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}];
1127
+ if (exportModule === undefined) {
1128
+ ${eagerLocalFallback ? `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1129
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
1130
+ __mfApplyLazyShareExports(exportModule);` : `initPromise.then(() =>
1131
+ import(${escapeGeneratedStringLiteral(importSource)}).then((mod) => {
1132
+ exportModule = __mfNormalizeShareModule(mod);
1133
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
1134
+ __mfApplyLazyShareExports(exportModule);
1135
+ })
1136
+ );`}
1137
+ } else {
1138
+ __mfApplyLazyShareExports(exportModule);
1139
+ }
1140
+ export { __mf_default as default };${namedExportLine}`;
1141
+ return eagerLocalFallback ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(importSource)};
1142
+ ${body}` : body;
1143
+ }
1130
1144
  function generateDeferredHostProvidedExports(namedExports, pkg, cacheKey) {
1131
1145
  const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
1132
1146
  const declarations = ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ");
@@ -1169,7 +1183,7 @@ const normalizeLocalShareModuleCode = `const __mfNormalizeShareModule = (mod) =>
1169
1183
  };`;
1170
1184
  function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1171
1185
  if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
1172
- const importLine = getRuntimeModuleCacheBootstrapCode();
1186
+ let importLine = getRuntimeModuleCacheBootstrapCode();
1173
1187
  const cacheKey = getSharedCacheKey(pkg, shareItem);
1174
1188
  if (shareItem.shareConfig.import === false) {
1175
1189
  const namedExports = getPackageNamedExports(pkg);
@@ -1196,7 +1210,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1196
1210
  const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
1197
1211
  const namedExports = getSharedNamedExports(pkg, shareItem);
1198
1212
  let exportLine;
1199
- if (namedExports.length > 0) {
1213
+ let initBlock = "";
1214
+ if (usesLazyLocalFallback) {
1215
+ importLine = `${getRuntimeInitPromiseBootstrapCode()}\n ${importLine}`;
1216
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheKey, command !== "build");
1217
+ } else if (namedExports.length > 0) {
1200
1218
  const destructure = `const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`;
1201
1219
  const namedExportLine = `export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`;
1202
1220
  exportLine = `const __mfDefaultExport = (() => {
@@ -1209,23 +1227,33 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
1209
1227
  export default __mfDefaultExport;
1210
1228
  ${destructure}
1211
1229
  ${namedExportLine}`;
1212
- } else if (usesLazyLocalFallback) exportLine = `export default exportModule.default ?? exportModule`;
1213
- else exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1230
+ initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1231
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
1232
+ } else {
1233
+ exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
1234
+ initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1235
+ __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
1236
+ }
1214
1237
  const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
1215
1238
  const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
1216
- loadShareCacheMap[pkg].writeSync(`
1239
+ const moduleBody = usesLazyLocalFallback ? `
1240
+ ${prebuildImportLine}
1241
+ ${devDynamicImportLine}
1242
+ ${importLine}
1243
+ ${normalizeLocalShareModuleCode}
1244
+ ${exportLine}
1245
+ ` : `
1217
1246
  ${prebuildImportLine}
1218
1247
  ${devDynamicImportLine}
1219
1248
  ${importLine}
1220
1249
  ${normalizeLocalShareModuleCode}
1221
1250
  let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}]
1222
1251
  if (exportModule === undefined) {
1223
- ${usesLazyLocalFallback ? `exportModule = __mfNormalizeShareModule(await import(${escapeGeneratedStringLiteral(lazyLocalFallbackSource)}));
1224
- __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;` : `exportModule = __mfNormalizeShareModule(__mfLocalShare);
1225
- __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`}
1252
+ ${initBlock}
1226
1253
  }
1227
1254
  ${exportLine}
1228
- `, true);
1255
+ `;
1256
+ loadShareCacheMap[pkg].writeSync(moduleBody, true);
1229
1257
  }
1230
1258
  //#endregion
1231
1259
  //#region src/virtualModules/virtualRemoteEntry.ts
@@ -1248,13 +1276,8 @@ let invalidateLocalSharedImportMap;
1248
1276
  function setLocalSharedImportMapInvalidator(invalidator) {
1249
1277
  invalidateLocalSharedImportMap = invalidator;
1250
1278
  }
1251
- let prevLocalSharedImportMapContent;
1252
1279
  function writeLocalSharedImportMap() {
1253
- const nextContent = generateLocalSharedImportMap();
1254
- if (prevLocalSharedImportMapContent !== nextContent) {
1255
- prevLocalSharedImportMapContent = nextContent;
1256
- invalidateLocalSharedImportMap?.();
1257
- }
1280
+ invalidateLocalSharedImportMap?.();
1258
1281
  }
1259
1282
  function shouldUseDirectReactImport() {
1260
1283
  const isVinext = hasPackageDependency("vinext");
@@ -1365,10 +1388,36 @@ function getOrderedUsedShares() {
1365
1388
  if (!pkg.endsWith("/")) shares.add(pkg);
1366
1389
  });
1367
1390
  } catch {}
1368
- return Array.from(shares).sort((a, b) => {
1391
+ return orderSharedDependenciesFirst(Array.from(shares).sort((a, b) => {
1369
1392
  const priority = (pkg) => pkg === "react" ? 0 : pkg === "react-dom" ? 1 : pkg.startsWith("react/") ? 2 : 3;
1370
1393
  return priority(a) - priority(b) || a.localeCompare(b);
1371
- });
1394
+ }));
1395
+ }
1396
+ function orderSharedDependenciesFirst(sharedPackages) {
1397
+ const sharedKeyByPackageName = new Map(sharedPackages.map((pkg) => [getPackageName(pkg), pkg]));
1398
+ const visiting = /* @__PURE__ */ new Set();
1399
+ const visited = /* @__PURE__ */ new Set();
1400
+ const ordered = [];
1401
+ const visit = (pkg) => {
1402
+ if (visited.has(pkg)) return;
1403
+ if (visiting.has(pkg)) return;
1404
+ visiting.add(pkg);
1405
+ const packageJson = getInstalledPackageJson(pkg)?.packageJson;
1406
+ const dependencies = {
1407
+ ...packageJson?.dependencies || {},
1408
+ ...packageJson?.peerDependencies || {},
1409
+ ...packageJson?.optionalDependencies || {}
1410
+ };
1411
+ Object.keys(dependencies).forEach((dependency) => {
1412
+ const sharedDependency = sharedKeyByPackageName.get(dependency);
1413
+ if (sharedDependency) visit(sharedDependency);
1414
+ });
1415
+ visiting.delete(pkg);
1416
+ visited.add(pkg);
1417
+ ordered.push(pkg);
1418
+ };
1419
+ sharedPackages.forEach(visit);
1420
+ return ordered;
1372
1421
  }
1373
1422
  function getShareItemForPreload(pkg) {
1374
1423
  const shared = getNormalizeModuleFederationOptions().shared;
@@ -1653,11 +1702,12 @@ function getHostAutoInitPath() {
1653
1702
  //#region src/virtualModules/virtualRemotes.ts
1654
1703
  const cacheRemoteMap = {};
1655
1704
  const LOAD_REMOTE_TAG = "__loadRemote__";
1656
- function getRemoteVirtualModule(remote, command, enableSsrInit = false) {
1657
- const cacheKey = `${remote}__${command}__${enableSsrInit ? "ssr" : "no-ssr"}`;
1705
+ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer = "unified") {
1706
+ const { shareStrategy } = getNormalizeModuleFederationOptions();
1707
+ const cacheKey = `${remote}__${command}__${shareStrategy}__${consumer}__${enableSsrInit ? "ssr-init" : "no-ssr-init"}`;
1658
1708
  if (!cacheRemoteMap[cacheKey]) {
1659
1709
  cacheRemoteMap[cacheKey] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
1660
- cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit));
1710
+ cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit, consumer));
1661
1711
  }
1662
1712
  return cacheRemoteMap[cacheKey];
1663
1713
  }
@@ -1673,138 +1723,94 @@ function getRemoteFromId(id, remotes) {
1673
1723
  const remoteName = Object.keys(remotes).filter((name) => id === name || id.startsWith(name + "/")).sort((a, b) => b.length - a.length)[0];
1674
1724
  return remoteName ? remotes[remoteName] : void 0;
1675
1725
  }
1676
- function generateRemotes(id, command, enableSsrInit = false) {
1677
- const useReactProxy = hasPackageDependency("react");
1678
- const useVueProxy = !useReactProxy && hasPackageDependency("vue");
1679
- const options = getNormalizeModuleFederationOptions();
1680
- const isLoadedFirst = options.shareStrategy === "loaded-first";
1681
- const remote = getRemoteFromId(id, options.remotes);
1682
- const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
1683
- entryGlobalName: remote.entryGlobalName,
1684
- name: remote.name,
1685
- type: remote.type,
1686
- entry: remote.entry,
1687
- shareScope: remote.shareScope ?? "default"
1688
- })}]);` : "";
1689
- const reactImportLine = useReactProxy ? `import __mfReactDefault from "react";
1690
- import * as __mfReactNamespace from "react";
1691
- const __mfReact = __mfReactDefault ?? __mfReactNamespace.default ?? __mfReactNamespace;` : "";
1692
- const vueImportLine = useVueProxy ? `import { defineAsyncComponent as __mfDefineAsyncComponent } from "vue";` : "";
1693
- const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
1694
- import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${getRuntimeInitBootstrapCode(enableSsrInit)}
1695
- const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];
1696
- if (typeof window !== "undefined") {
1697
- import(${JSON.stringify(getHostAutoInitPath())})
1698
- .then((mod) => mod.hostInitPromise)
1699
- .then(initResolve, initReject);
1700
- }`;
1701
- const exportLine = command === "serve" ? `if (__mfRemotePending) {
1702
- __mfRemotePending = __mfRemotePending.then((mod) => {
1703
- if (mod !== undefined) exportModule = mod;
1704
- return exportModule;
1705
- });
1726
+ function resolveRemoteInitMode(shareStrategy, consumer) {
1727
+ if (shareStrategy !== "loaded-first") return "eager";
1728
+ if (consumer === "server") return "loaded-first-ssr";
1729
+ if (consumer === "client") return "loaded-first-client";
1730
+ return "loaded-first-unified";
1706
1731
  }
1707
- export { exportModule as __moduleExports };
1708
- export const __mf_remote_pending = __mfRemotePending || Promise.resolve(exportModule);
1709
- export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?.__esModule ? exportModule.default : exportModule.default ?? exportModule` : command === "build" ? `if (__mfRemotePending) {
1710
- __mfRemotePending = __mfRemotePending.then((mod) => {
1711
- if (mod !== undefined) exportModule = mod;
1712
- return exportModule;
1713
- });
1732
+ function shouldDeferRemoteLoad(initMode) {
1733
+ return initMode === "loaded-first-client" || initMode === "loaded-first-unified";
1714
1734
  }
1715
- export { exportModule as __moduleExports };
1716
- export const __mf_remote_pending = __mfRemotePending || Promise.resolve(exportModule);
1717
- export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?.__esModule ? exportModule.default : exportModule.default ?? exportModule` : "export default exportModule";
1718
- const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
1719
- const remoteLoadFailureHandler = command === "build" ? `.catch((error) => {
1720
- delete __mfModuleCache.remote[pendingKey];
1721
- throw error;
1722
- })` : `.catch(() => {
1723
- delete __mfModuleCache.remote[pendingKey];
1724
- })`;
1735
+ /** Dev client wrappers can preload remotes while exposing stable proxies. */
1736
+ function shouldEagerLoadClientRemoteInDev(command, enableSsrInit) {
1737
+ return enableSsrInit && command === "serve";
1738
+ }
1739
+ function getEagerDeferredClientInit() {
1740
+ return `__mfRemotePending = __mfStartRemoteLoad().then(__mfAssignRemoteModule);
1741
+ exportModule = __mfCreateDeferredRemoteProxy();`;
1742
+ }
1743
+ function shouldIncludeDeferredProxy(initMode, consumer, eagerLoadClientRemote, deferRemoteLoad) {
1744
+ if (eagerLoadClientRemote && consumer !== "server") return true;
1745
+ if (initMode === "eager") return consumer !== "server" && (consumer === "unified" || !eagerLoadClientRemote);
1746
+ if (consumer === "client" && eagerLoadClientRemote) return false;
1747
+ return deferRemoteLoad || consumer !== "server";
1748
+ }
1749
+ /** Codegen shared by every remote virtual module (no top-level await). */
1750
+ function getRemoteModuleRuntimeHelpers() {
1725
1751
  return `
1726
- ${reactImportLine}
1727
- ${vueImportLine}
1728
- ${importLine}
1729
- ${`
1730
- function __mfStartRemoteLoad() {
1731
- ${`
1732
- const pendingKey = ${JSON.stringify(`__mf_pending__${id}`)};
1733
- if (!__mfModuleCache.remote[pendingKey]) {
1734
- __mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
1735
- .then((runtime) => {
1736
- ${registerRemoteCode}
1737
- return runtime.loadRemote(${JSON.stringify(id)});
1738
- })
1739
- .then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
1740
- .then((mod) => {
1741
- __mfModuleCache.remote[${JSON.stringify(id)}] = mod;
1742
- delete __mfModuleCache.remote[pendingKey];
1743
- return mod;
1744
- })
1745
- ${remoteLoadFailureHandler};
1746
- }
1747
- return __mfModuleCache.remote[pendingKey];`}
1752
+ function __mfUnwrapRemoteDefault(mod) {
1753
+ if (mod == null) return mod;
1754
+ if (mod.__esModule && mod.default != null) return mod.default;
1755
+ return mod.default ?? mod;
1748
1756
  }
1749
- function __mfCreateRemoteProxy(pendingPromise) {
1757
+ let __mfDefaultExport;
1758
+ function __mfSyncDefaultExport() {
1759
+ __mfDefaultExport = exportModule?.__mf_is_remote_proxy
1760
+ ? exportModule
1761
+ : __mfUnwrapRemoteDefault(exportModule);
1762
+ }
1763
+ function __mfAssignRemoteModule(mod) {
1764
+ if (mod !== undefined) exportModule = mod;
1765
+ __mfSyncDefaultExport();
1766
+ return exportModule;
1767
+ }`;
1768
+ }
1769
+ function getDeferredProxyHelper(remoteId) {
1770
+ return `
1771
+ function __mfCreateDeferredRemoteProxy() {
1772
+ let pendingPromise;
1750
1773
  const ensurePending = () => {
1751
1774
  pendingPromise ||= __mfStartRemoteLoad();
1752
- ${useVueProxy ? "" : `pendingPromise?.finally(() => {
1753
- for (const listener of listeners) listener();
1754
- });`}
1755
1775
  return pendingPromise;
1756
1776
  };
1757
- ${useVueProxy ? `return __mfDefineAsyncComponent(() =>
1758
- ensurePending().then((mod) => mod?.default ?? mod)
1759
- );` : `
1760
- const listeners = new Set();
1761
- const getModule = () => __mfModuleCache.remote[${JSON.stringify(id)}];
1777
+ const getModule = () => __mfModuleCache.remote[${JSON.stringify(remoteId)}];
1762
1778
  const proxyTarget = function (...args) {
1763
- ${useReactProxy ? `const [, setVersion] = __mfReact.useState(0);
1764
- __mfReact.useEffect(() => {
1765
- ensurePending();
1766
- const listener = () => setVersion((value) => value + 1);
1767
- listeners.add(listener);
1768
- if (getModule()) listener();
1769
- return () => listeners.delete(listener);
1770
- }, []);` : ""}
1779
+ pendingPromise ||= __mfStartRemoteLoad();
1771
1780
  const mod = getModule();
1772
1781
  const fn = mod && (mod.default ?? mod);
1773
1782
  if (fn !== undefined && fn !== null) {
1774
- ${useReactProxy ? `return __mfReact.createElement(fn, args[0]);` : `return fn.apply(this, args);`}
1783
+ return fn.apply(this, args);
1775
1784
  }
1776
- ${useReactProxy ? `return null;` : `throw ensurePending();`}
1785
+ return null;
1777
1786
  };
1778
1787
  return new Proxy(proxyTarget, {
1779
1788
  get(_target, prop) {
1780
1789
  if (prop === "__mf_is_remote_proxy") return true;
1781
1790
  if (prop === "__esModule") return true;
1782
1791
  if (prop === "then") return undefined;
1783
- // Allow React's dev-mode console.warn to stringify the proxy without
1784
- // throwing "Cannot convert object to primitive value".
1785
1792
  if (prop === Symbol.toPrimitive || prop === "toString")
1786
- return () => "[MF remote proxy: pending]";
1793
+ return () => "[MF remote: pending]";
1787
1794
  const mod = getModule();
1788
1795
  if (mod) {
1789
1796
  return prop in mod ? mod[prop] : mod.default?.[prop];
1790
1797
  }
1791
- // When the module is pending and React.lazy() checks for "default",
1792
- // return the proxy function itself so React renders it (returns null)
1793
- // rather than crashing on undefined.
1794
- ${useReactProxy ? `if (prop === "default") return proxyTarget;
1795
- return undefined;` : `throw ensurePending();`}
1798
+ pendingPromise ||= __mfStartRemoteLoad();
1799
+ if (prop === "default") return proxyTarget;
1800
+ throw ensurePending();
1796
1801
  },
1797
1802
  has(_target, prop) {
1798
1803
  const mod = getModule();
1799
1804
  if (mod) return prop in mod;
1800
- // Tell React that "default" exists when module is pending so it
1801
- // doesn't warn "lazy: Expected the result of a dynamic import()".
1802
- ${useReactProxy ? `return prop === "default" || prop === "__esModule" || prop === "__mf_is_remote_proxy";` : `return false;`}
1805
+ return (
1806
+ prop === "default" ||
1807
+ prop === "__esModule" ||
1808
+ prop === "__mf_is_remote_proxy"
1809
+ );
1803
1810
  },
1804
1811
  ownKeys() {
1805
1812
  const mod = getModule();
1806
1813
  const keys = new Set(mod ? Reflect.ownKeys(mod) : []);
1807
- // Proxy invariant: must include non-configurable target own keys
1808
1814
  for (const k of Reflect.ownKeys(proxyTarget)) {
1809
1815
  const d = Object.getOwnPropertyDescriptor(proxyTarget, k);
1810
1816
  if (d && !d.configurable) keys.add(k);
@@ -1812,7 +1818,6 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
1812
1818
  return Array.from(keys);
1813
1819
  },
1814
1820
  getOwnPropertyDescriptor(_target, prop) {
1815
- // Proxy invariant: non-configurable target props must be reported accurately
1816
1821
  const targetDesc = Object.getOwnPropertyDescriptor(proxyTarget, prop);
1817
1822
  if (targetDesc && !targetDesc.configurable) return targetDesc;
1818
1823
  const mod = getModule();
@@ -1826,19 +1831,153 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
1826
1831
  apply(target, thisArg, args) {
1827
1832
  return target.apply(thisArg, args);
1828
1833
  }
1829
- });`}
1830
- }`}
1834
+ });
1835
+ }`;
1836
+ }
1837
+ function getLazyRemotePendingExport() {
1838
+ return `export const __mf_remote_pending = __mfRemotePending ?? {
1839
+ then(onFulfilled, onRejected) {
1840
+ return (__mfRemotePending ??= __mfStartRemoteLoad().then(__mfAssignRemoteModule)).then(onFulfilled, onRejected);
1841
+ },
1842
+ };`;
1843
+ }
1844
+ function getEagerRemotePendingExport() {
1845
+ return `export const __mf_remote_pending =
1846
+ __mfRemotePending ??
1847
+ __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
1848
+ }
1849
+ function getServerThenExport() {
1850
+ return `export function then(onFulfilled, onRejected) {
1851
+ return (__mfRemotePending ?? Promise.resolve(exportModule))
1852
+ .then(__mfAssignRemoteModule)
1853
+ .then(() => {
1854
+ __mfSyncDefaultExport();
1855
+ return {
1856
+ ...exportModule,
1857
+ default: __mfDefaultExport,
1858
+ __moduleExports: exportModule,
1859
+ __mf_remote_pending: __mfRemotePending,
1860
+ };
1861
+ })
1862
+ .then(onFulfilled, onRejected);
1863
+ }`;
1864
+ }
1865
+ function getRemoteExportBlock(command, deferRemoteLoad, consumer) {
1866
+ if (command !== "serve" && command !== "build") return `__mfSyncDefaultExport();
1867
+ export { __mfDefaultExport as default };`;
1868
+ return `__mfSyncDefaultExport();
1869
+ __mfRemotePending?.then(__mfSyncDefaultExport);
1870
+ export { exportModule as __moduleExports };
1871
+ ${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()}
1872
+ ${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
1873
+ export { __mfDefaultExport as default };`;
1874
+ }
1875
+ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified") {
1876
+ const options = getNormalizeModuleFederationOptions();
1877
+ const isLoadedFirst = options.shareStrategy === "loaded-first";
1878
+ const initMode = resolveRemoteInitMode(options.shareStrategy, consumer);
1879
+ const deferRemoteLoad = shouldDeferRemoteLoad(initMode);
1880
+ const remote = getRemoteFromId(id, options.remotes);
1881
+ const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
1882
+ entryGlobalName: remote.entryGlobalName,
1883
+ name: remote.name,
1884
+ type: remote.type,
1885
+ entry: remote.entry,
1886
+ shareScope: remote.shareScope ?? "default"
1887
+ })}]);` : "";
1888
+ const browserHostInitCode = `import(${JSON.stringify(getHostAutoInitPath())})
1889
+ .then((mod) => mod.hostInitPromise)
1890
+ .then(initResolve, initReject);`;
1891
+ const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getHostAutoInitPath())}
1892
+ const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
1893
+ const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
1894
+ import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${devRuntimeBootstrap}
1895
+ ${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
1896
+ const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
1897
+ const remoteLoadFailureHandler = command === "build" ? `.catch((error) => {
1898
+ delete __mfModuleCache.remote[pendingKey];
1899
+ throw error;
1900
+ })` : `.catch(() => {
1901
+ delete __mfModuleCache.remote[pendingKey];
1902
+ })`;
1903
+ const remoteLoadCode = `
1904
+ function __mfStartRemoteLoad() {
1905
+ ${`
1906
+ const pendingKey = ${JSON.stringify(`__mf_pending__${id}`)};
1907
+ if (!__mfModuleCache.remote[pendingKey]) {
1908
+ __mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
1909
+ .then((runtime) => {
1910
+ ${registerRemoteCode}
1911
+ return runtime.loadRemote(${JSON.stringify(id)});
1912
+ })
1913
+ .then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
1914
+ .then((mod) => {
1915
+ __mfModuleCache.remote[${JSON.stringify(id)}] = mod;
1916
+ delete __mfModuleCache.remote[pendingKey];
1917
+ return mod;
1918
+ })
1919
+ ${remoteLoadFailureHandler};
1920
+ }
1921
+ return __mfModuleCache.remote[pendingKey];`}
1922
+ }`;
1923
+ const realRemoteInit = `__mfRemotePending = __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
1924
+ const deferredClientInit = `exportModule = __mfCreateDeferredRemoteProxy();`;
1925
+ const eagerLoadClientRemote = shouldEagerLoadClientRemoteInDev(command, enableSsrInit);
1926
+ const eagerClientInit = eagerLoadClientRemote ? getEagerDeferredClientInit() : deferredClientInit;
1927
+ const loadedFirstClientInit = eagerLoadClientRemote ? getEagerDeferredClientInit() : deferredClientInit;
1928
+ const environmentSplitInit = (clientInit, serverInit) => consumer === "client" ? clientInit : consumer === "server" ? serverInit : `if (typeof window === "undefined") {
1929
+ ${serverInit}
1930
+ } else {
1931
+ ${clientInit}
1932
+ }`;
1933
+ const initExportModule = initMode === "eager" ? environmentSplitInit(eagerClientInit, realRemoteInit) : environmentSplitInit(loadedFirstClientInit, realRemoteInit);
1934
+ const includeProxyHelper = shouldIncludeDeferredProxy(initMode, consumer, eagerLoadClientRemote, deferRemoteLoad);
1935
+ const deferredProxyCode = getDeferredProxyHelper(id);
1936
+ return `
1937
+ ${importLine}
1938
+ ${remoteLoadCode}
1939
+ ${includeProxyHelper ? deferredProxyCode : ""}
1940
+ ${getRemoteModuleRuntimeHelpers()}
1831
1941
  let __mfRemotePending;
1832
1942
  let exportModule = __mfModuleCache.remote[${JSON.stringify(id)}]
1833
1943
  if (exportModule === undefined) {
1834
- __mfRemotePending = __mfStartRemoteLoad();
1835
- exportModule = __mfCreateRemoteProxy(__mfRemotePending);
1944
+ ${initExportModule}
1836
1945
  }
1837
- ${exportLine}
1946
+ ${getRemoteExportBlock(command, deferRemoteLoad, consumer)}
1838
1947
  `;
1839
1948
  }
1840
1949
  //#endregion
1841
1950
  //#region src/plugins/pluginAddEntry.ts
1951
+ const HOST_INIT_PRELOAD_CHUNKS = [
1952
+ (name) => name === "hostInit",
1953
+ (name) => name === "remoteEntry",
1954
+ (name) => name.startsWith("_virtual_mf"),
1955
+ (name) => name === "index"
1956
+ ];
1957
+ function escapeHtmlAttr(value) {
1958
+ return value.replace(/&/g, "&").replace(/"/g, """);
1959
+ }
1960
+ function getExistingHrefSet(html) {
1961
+ return new Set(Array.from(html.matchAll(/\bhref\s*=\s*["']([^"']+)["']/gi), (match) => match[1]));
1962
+ }
1963
+ function injectHostInitPreloads(html, bundle, resolvePath) {
1964
+ const existingHrefs = getExistingHrefSet(html);
1965
+ const seenFiles = /* @__PURE__ */ new Set();
1966
+ const hrefs = [];
1967
+ for (const chunk of Object.values(bundle)) {
1968
+ if (chunk.type !== "chunk") continue;
1969
+ if (!HOST_INIT_PRELOAD_CHUNKS.some((match) => match(chunk.name))) continue;
1970
+ if (seenFiles.has(chunk.fileName)) continue;
1971
+ seenFiles.add(chunk.fileName);
1972
+ const href = resolvePath(chunk.fileName);
1973
+ if (existingHrefs.has(href)) continue;
1974
+ existingHrefs.add(href);
1975
+ hrefs.push(href);
1976
+ }
1977
+ if (hrefs.length === 0) return html;
1978
+ const tags = hrefs.map((href) => `<link rel="modulepreload" crossorigin href="${escapeHtmlAttr(href)}">`).join("");
1979
+ return html.includes("</head>") ? html.replace("</head>", `${tags}</head>`) : `${tags}${html}`;
1980
+ }
1842
1981
  function getFirstHtmlEntryFile(entryFiles) {
1843
1982
  return entryFiles.find((file) => file.endsWith(".html"));
1844
1983
  }
@@ -1901,6 +2040,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1901
2040
  function rewriteSvelteKitInlineStart(html, initPath) {
1902
2041
  return html.replace(/<script>([\s\S]*?)<\/script>/gi, (scriptTag, body) => {
1903
2042
  if (!body.includes("kit.start(app, element);") || !body.includes("Promise.all([")) return scriptTag;
2043
+ if (body.includes("initHost")) return scriptTag;
1904
2044
  const blockStart = body.indexOf("{");
1905
2045
  const blockEnd = body.lastIndexOf("}");
1906
2046
  if (blockStart === -1 || blockEnd <= blockStart) return scriptTag;
@@ -1924,7 +2064,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1924
2064
  return walkFiles(dir, (fileName) => fileName.endsWith(".html"));
1925
2065
  }
1926
2066
  function toRelativeImport(fromFile, targetFile) {
1927
- const relative = path$1.relative(path$1.dirname(fromFile), targetFile).replace(/\\/g, "/");
2067
+ const relative = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), targetFile));
1928
2068
  return relative.startsWith(".") ? relative : `./${relative}`;
1929
2069
  }
1930
2070
  function patchSvelteKitStaticHtml() {
@@ -1946,14 +2086,14 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
1946
2086
  }
1947
2087
  return patched;
1948
2088
  }
1949
- function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
2089
+ function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false, options) {
1950
2090
  const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
1951
2091
  globalThis.System && typeof globalThis.System.import === 'function'
1952
2092
  ? globalThis.System.import(src)
1953
2093
  : import(src);
1954
2094
  ` : "";
1955
2095
  const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
1956
- const remotePreloads = getNormalizeModuleFederationOptions()?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(remote)})`).join(",") : "";
2096
+ const remotePreloads = !options?.skipRemotePreload && getNormalizeModuleFederationOptions()?.shareStrategy !== "loaded-first" ? Object.entries(getUsedRemotesMap()).flatMap(([remoteKey, remotes]) => Array.from(remotes).filter((remote) => remote !== remoteKey)).sort().map((remote) => `__mfPreloadRemote(${JSON.stringify(remote)})`).join(",") : "";
1957
2097
  const preloadBlock = remotePreloads ? `
1958
2098
  const runtime = await initHost();
1959
2099
  const __mfPreloadRemote = (remote) => {
@@ -2144,9 +2284,9 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2144
2284
  emittedFileName = file;
2145
2285
  const lastSlash = file.lastIndexOf("/");
2146
2286
  bootstrapDir = lastSlash !== -1 ? file.slice(0, lastSlash + 1) : "";
2147
- const resolvePath = (htmlFileName) => {
2148
- if (!viteConfig.experimental?.renderBuiltUrl) return viteConfig.base + file;
2149
- const result = viteConfig.experimental.renderBuiltUrl(file, {
2287
+ const resolvePath = (builtFileName, htmlFileName) => {
2288
+ if (!viteConfig.experimental?.renderBuiltUrl) return viteConfig.base + builtFileName;
2289
+ const result = viteConfig.experimental.renderBuiltUrl(builtFileName, {
2150
2290
  hostId: htmlFileName,
2151
2291
  hostType: "html",
2152
2292
  type: "asset",
@@ -2156,11 +2296,11 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2156
2296
  if (result && typeof result === "object") {
2157
2297
  if ("runtime" in result) {
2158
2298
  mfWarn("renderBuiltUrl returned runtime code for HTML injection. Runtime code cannot be used in <script src=\"\">. Falling back to base path.");
2159
- return viteConfig.base + file;
2299
+ return viteConfig.base + builtFileName;
2160
2300
  }
2161
- if (result.relative) return file;
2301
+ if (result.relative) return builtFileName;
2162
2302
  }
2163
- return viteConfig.base + file;
2303
+ return viteConfig.base + builtFileName;
2164
2304
  };
2165
2305
  const basePrefix = viteConfig.base?.replace(/\/$/, "") ?? "";
2166
2306
  const stripBase = (p) => basePrefix && p.startsWith(basePrefix + "/") ? p.slice(basePrefix.length) : p;
@@ -2169,7 +2309,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2169
2309
  let htmlAsset = bundle[fileName];
2170
2310
  if (htmlAsset.type === "chunk") return;
2171
2311
  let htmlContent = htmlAsset.source.toString() || "";
2172
- const initPath = resolvePath(fileName);
2312
+ const initPath = resolvePath(file, fileName);
2173
2313
  const scriptRegex = /<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>\s*<\/script>/gi;
2174
2314
  let rewritten = false;
2175
2315
  htmlContent = htmlContent.replace(scriptRegex, (scriptTag, entrySrc) => {
@@ -2189,15 +2329,15 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2189
2329
  });
2190
2330
  if (!rewritten) {
2191
2331
  const svelteKitHtml = rewriteSvelteKitInlineStart(htmlContent, initPath);
2192
- if (svelteKitHtml !== htmlContent) {
2193
- htmlAsset.source = svelteKitHtml;
2194
- continue;
2195
- }
2196
- const scriptContent = `
2332
+ if (svelteKitHtml !== htmlContent) htmlContent = svelteKitHtml;
2333
+ else {
2334
+ const scriptContent = `
2197
2335
  <script type="module" src="${initPath}"><\/script>
2198
2336
  `;
2199
- htmlContent = htmlContent.replace("<head>", `<head>${scriptContent}`);
2337
+ htmlContent = htmlContent.replace("<head>", `<head>${scriptContent}`);
2338
+ }
2200
2339
  }
2340
+ if (waitsForInit) htmlContent = injectHostInitPreloads(htmlContent, bundle, (builtFileName) => resolvePath(builtFileName, fileName));
2201
2341
  htmlAsset.source = htmlContent;
2202
2342
  }
2203
2343
  },
@@ -2241,12 +2381,13 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
2241
2381
  return mapCodeToCodeWithSourcemap(code.replace("vueApp.mount(vueAppRootContainer);", `${injection}vueApp.mount(vueAppRootContainer);`));
2242
2382
  }
2243
2383
  const isHydrationEntryFallback = inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !id.includes("node_modules") && (id.startsWith("\0") || /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id)) && /hydrateRoot|createRoot|ReactDOM\.render/.test(code);
2244
- const isNuxtClientEntryFallback = _command === "serve" && inject === "entry" && entryFiles.length === 0 && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !hasEntryBootstrapParam(id) && !id.includes("node_modules/.vite") && /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
2245
- if (injectEntry() && entryFiles.some((file) => resolveProjectId(id) === file) || _command === "serve" && inject === "html" && !isVinext && !clientInjected && !id.startsWith("\0") && !id.includes("node_modules") && /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id) || isHydrationEntryFallback || isNuxtClientEntryFallback) {
2384
+ const isNuxtEntryAsyncModule = /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
2385
+ const isNuxtClientEntryFallback = _command === "serve" && inject === "entry" && (!htmlFilePath || !fs$1.existsSync(htmlFilePath)) && !clientInjected && !hasEntryBootstrapParam(id) && !id.includes("node_modules/.vite") && isNuxtEntryAsyncModule && !entryFiles.some((file) => resolveProjectId(id) === file);
2386
+ if (!(_command === "serve" && isNuxtEntryAsyncModule) && (injectEntry() && entryFiles.some((file) => resolveProjectId(id) === file) || _command === "serve" && inject === "html" && !isVinext && !clientInjected && !id.startsWith("\0") && !id.includes("node_modules") && /\.(js|ts|mjs|vue|jsx|tsx)(\?|$)/.test(id) || isHydrationEntryFallback || isNuxtClientEntryFallback)) {
2246
2387
  clientInjected = true;
2247
2388
  if (!waitsForInit || _command === "serve" && inject === "entry" && isHydrationEntryFallback) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
2248
2389
  const entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
2249
- return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc));
2390
+ return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
2250
2391
  }
2251
2392
  }
2252
2393
  }];
@@ -2297,17 +2438,35 @@ function checkAliasConflicts(options) {
2297
2438
  }
2298
2439
  //#endregion
2299
2440
  //#region src/plugins/hmr/react.ts
2441
+ const REACT_REFRESH_PATH = "/@react-refresh";
2442
+ const LOCAL_REACT_REFRESH_PATH = "/@mf-react-refresh-local";
2443
+ function stripQuery(url) {
2444
+ return url?.replace(/\?.*$/, "");
2445
+ }
2446
+ function resolveReactRefreshRuntime(root) {
2447
+ const reactPluginEntry = createRequire(pathToFileURL$1(path.join(root, "package.json"))).resolve("@vitejs/plugin-react");
2448
+ const requireFromReactPlugin = createRequire(reactPluginEntry);
2449
+ const reactPluginRoot = path.dirname(reactPluginEntry);
2450
+ const runtimePath = path.join(reactPluginRoot, "refresh-runtime.js");
2451
+ const refreshUtilsPath = path.join(reactPluginRoot, "refreshUtils.js");
2452
+ if (existsSync$1(runtimePath)) return readFileSync$1(runtimePath, "utf-8");
2453
+ const reactRefreshDir = path.dirname(requireFromReactPlugin.resolve("react-refresh/package.json"));
2454
+ return [
2455
+ "const exports = {}",
2456
+ readFileSync$1(path.join(reactRefreshDir, "cjs/react-refresh-runtime.development.js"), "utf-8"),
2457
+ readFileSync$1(refreshUtilsPath, "utf-8"),
2458
+ "export default exports"
2459
+ ].join("\n");
2460
+ }
2300
2461
  /**
2301
2462
  * Proxy module served for `/@react-refresh` on MF remote dev servers.
2302
- * Delegates to the host page's RefreshRuntime instance via
2303
- * `window.location.origin`, ensuring a single shared component registry
2304
- * across federation boundaries. A `configureServer` middleware is used
2305
- * instead of `resolveId` because `@vitejs/plugin-react`'s
2306
- * `vite:react-refresh` sub-plugin uses `enforce: 'pre'` and typically
2307
- * wins the `resolveId` race.
2463
+ * Delegates to the host page's RefreshRuntime when consumed by a host, but
2464
+ * falls back to this remote's local runtime when the remote is opened directly.
2308
2465
  */
2309
2466
  const REACT_REFRESH_PROXY_MODULE = [
2310
- `const __rt = await import(window.location.origin + '/@react-refresh');`,
2467
+ `const __remoteOrigin = new URL(import.meta.url).origin;`,
2468
+ `const __target = window.location.origin === __remoteOrigin ? '${LOCAL_REACT_REFRESH_PATH}' : window.location.origin + '${REACT_REFRESH_PATH}';`,
2469
+ `const __rt = await import(__target);`,
2311
2470
  `export const injectIntoGlobalHook = __rt.injectIntoGlobalHook;`,
2312
2471
  `export const register = __rt.register;`,
2313
2472
  `export const createSignatureFunctionForTransform = __rt.createSignatureFunctionForTransform;`,
@@ -2320,8 +2479,17 @@ const reactAdapter = {
2320
2479
  name: "react",
2321
2480
  pluginNames: ["vite:react-refresh", "vite:react-swc:refresh"],
2322
2481
  remote: { configureServer({ server }) {
2482
+ let reactRefreshRuntime;
2323
2483
  server.middlewares.use((req, res, next) => {
2324
- if (req.url?.replace(/\?.*$/, "") !== "/@react-refresh") return next();
2484
+ const url = stripQuery(req.url);
2485
+ if (url === LOCAL_REACT_REFRESH_PATH) {
2486
+ reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
2487
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
2488
+ res.setHeader("Access-Control-Allow-Origin", "*");
2489
+ res.end(reactRefreshRuntime);
2490
+ return;
2491
+ }
2492
+ if (url !== REACT_REFRESH_PATH) return next();
2325
2493
  res.setHeader("Content-Type", "application/javascript; charset=utf-8");
2326
2494
  res.setHeader("Access-Control-Allow-Origin", "*");
2327
2495
  res.end(REACT_REFRESH_PROXY_MODULE);
@@ -2746,7 +2914,7 @@ function pluginDevRemoteHmr(options) {
2746
2914
  function initVirtualModules(command, remoteEntryId, enableSsrInit = false) {
2747
2915
  writeLocalSharedImportMap();
2748
2916
  writeHostAutoInit(remoteEntryId, command);
2749
- writeRuntimeInitStatus(command, enableSsrInit);
2917
+ writeRuntimeInitStatus(command, enableSsrInit, getHostAutoInitPath());
2750
2918
  }
2751
2919
  //#endregion
2752
2920
  //#region src/utils/bundleHelpers.ts
@@ -3012,11 +3180,11 @@ const processModuleAssets = (bundle, filesMap, moduleMatcher, options = {}) => {
3012
3180
  if (fileData.type !== "chunk") continue;
3013
3181
  if (!fileData.modules) continue;
3014
3182
  for (const modulePath of Object.keys(fileData.modules)) {
3015
- const comparableModulePath = options.root ? path.resolve(options.root, modulePath) : modulePath;
3183
+ const comparableModulePath = options.root ? path$1.resolve(options.root, modulePath) : modulePath;
3016
3184
  const comparableModulePaths = [comparableModulePath];
3017
3185
  if (options.stripKnownJsExtensions) {
3018
- const ext = path.extname(comparableModulePath);
3019
- if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path.join(path.dirname(comparableModulePath), path.basename(comparableModulePath, ext)));
3186
+ const ext = path$1.extname(comparableModulePath);
3187
+ if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path$1.join(path$1.dirname(comparableModulePath), path$1.basename(comparableModulePath, ext)));
3020
3188
  }
3021
3189
  const matchKey = comparableModulePaths.map(moduleMatcher).find(Boolean);
3022
3190
  if (!matchKey) continue;
@@ -3273,6 +3441,34 @@ function generateRemoteEntrySSR(options) {
3273
3441
  function getBuildVersion() {
3274
3442
  return process.env["MF_BUILD_VERSION"] ?? "1.0.0";
3275
3443
  }
3444
+ /**
3445
+ * Builds the manifest `metaData.types` entry.
3446
+ *
3447
+ * When type generation is enabled, the dts plugin serves the type archive
3448
+ * (`<typesFolder>.zip`) and api file (`<typesFolder>.d.ts`). Consumers using
3449
+ * `@module-federation/dts-plugin` read `metaData.types.zip` to download those
3450
+ * types and throw `Can not get <remote>'s types archive url!` when it is absent.
3451
+ * Advertising the relative paths here (resolved against `publicPath` by the
3452
+ * consumer) mirrors the webpack/rspack (`@module-federation/enhanced`) plugins.
3453
+ */
3454
+ function resolveTypesMeta(dts) {
3455
+ if (dts === false) return {
3456
+ path: "",
3457
+ name: ""
3458
+ };
3459
+ const generateTypes = typeof dts === "object" && dts ? dts.generateTypes : void 0;
3460
+ if (generateTypes === false) return {
3461
+ path: "",
3462
+ name: ""
3463
+ };
3464
+ const typesFolder = typeof generateTypes === "object" && generateTypes?.typesFolder || "@mf-types";
3465
+ return {
3466
+ path: "",
3467
+ name: "",
3468
+ zip: `${typesFolder}.zip`,
3469
+ api: `${typesFolder}.d.ts`
3470
+ };
3471
+ }
3276
3472
  const Manifest = () => {
3277
3473
  const mfOptions = getNormalizeModuleFederationOptions();
3278
3474
  const { name, filename, getPublicPath, manifest: manifestOptions, varFilename } = mfOptions;
@@ -3336,10 +3532,7 @@ const Manifest = () => {
3336
3532
  path: "",
3337
3533
  type: "var"
3338
3534
  } : void 0,
3339
- types: {
3340
- path: "",
3341
- name: ""
3342
- },
3535
+ types: resolveTypesMeta(mfOptions.dts),
3343
3536
  globalName: name,
3344
3537
  pluginVersion: "0.2.5",
3345
3538
  publicPath
@@ -3490,10 +3683,7 @@ const Manifest = () => {
3490
3683
  remoteEntry,
3491
3684
  ssrRemoteEntry,
3492
3685
  varRemoteEntry,
3493
- types: {
3494
- path: "",
3495
- name: ""
3496
- },
3686
+ types: resolveTypesMeta(options.dts),
3497
3687
  globalName: name,
3498
3688
  pluginVersion: "0.2.5",
3499
3689
  ...!!getPublicPath ? { getPublicPath } : { publicPath }
@@ -3577,7 +3767,7 @@ function resetIdleTimeout(timeout) {
3577
3767
  }, timeout * 1e3);
3578
3768
  }
3579
3769
  function pluginModuleParseEnd_default(excludeFn, options) {
3580
- const idleTimeout = options.moduleParseIdleTimeout;
3770
+ const idleTimeout = options.moduleParseIdleTimeout ?? options.moduleParseTimeout;
3581
3771
  return [
3582
3772
  {
3583
3773
  name: "_",
@@ -3612,6 +3802,9 @@ function pluginModuleParseEnd_default(excludeFn, options) {
3612
3802
  if (excludeFn(id)) return;
3613
3803
  parseEndSet.add(id);
3614
3804
  if (parseStartSet.size === parseEndSet.size && (!expectsExposesParseEnd || exposesParseEnd)) _resolve?.(1);
3805
+ },
3806
+ buildEnd() {
3807
+ _resolve?.(1);
3615
3808
  }
3616
3809
  }
3617
3810
  ];
@@ -3692,7 +3885,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3692
3885
  });
3693
3886
  if (options.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
3694
3887
  const ensureRelativeImportPath = (fromFile, toFile) => {
3695
- let relativePath = path$1.relative(path$1.dirname(fromFile), toFile);
3888
+ let relativePath = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), toFile));
3696
3889
  if (!relativePath.startsWith(".")) relativePath = `./${relativePath}`;
3697
3890
  return relativePath;
3698
3891
  };
@@ -3715,6 +3908,40 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
3715
3908
  };
3716
3909
  }
3717
3910
  //#endregion
3911
+ //#region src/utils/remoteConsumerTarget.ts
3912
+ function getPluginEnvironmentName(ctx) {
3913
+ if (ctx == null || typeof ctx !== "object") return void 0;
3914
+ const environment = ctx["environment"];
3915
+ if (environment == null || typeof environment !== "object") return void 0;
3916
+ const name = environment["name"];
3917
+ return typeof name === "string" ? name : void 0;
3918
+ }
3919
+ function resolveRemoteConsumer(ctx, hasMultiEnvironment) {
3920
+ if (!hasMultiEnvironment) return "unified";
3921
+ const envName = getPluginEnvironmentName(ctx);
3922
+ if (!envName || envName === "client") return "client";
3923
+ return "server";
3924
+ }
3925
+ //#endregion
3926
+ //#region src/utils/ssrCapabilities.ts
3927
+ /**
3928
+ * Single source of truth for SSR-related feature gates.
3929
+ *
3930
+ * - Vite 8+ dev: ModuleRunner + FetchableDevEnvironment for `/__mf_ssr__/` entries.
3931
+ * - Any Vite major on build/preview: HTTP fetch + temp-file import via ssrEntryLoader.
3932
+ */
3933
+ function getSsrCapabilities(viteMajor, command, hasRemotes) {
3934
+ if (!hasRemotes) return {
3935
+ enableSsrInitBootstrap: false,
3936
+ injectSsrEntryLoader: false
3937
+ };
3938
+ const supported = command === "build" || command === "serve" && viteMajor >= 8;
3939
+ return {
3940
+ enableSsrInitBootstrap: supported,
3941
+ injectSsrEntryLoader: supported
3942
+ };
3943
+ }
3944
+ //#endregion
3718
3945
  //#region src/plugins/pluginProxyRemotes.ts
3719
3946
  function isNodeModulesImporter(importer) {
3720
3947
  return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
@@ -3739,13 +3966,15 @@ function pluginProxyRemotes_default(options) {
3739
3966
  let command;
3740
3967
  let root = process.cwd();
3741
3968
  let enableSsrInit = false;
3969
+ let hasMultiEnvironment = false;
3742
3970
  const { remotes } = options;
3743
- function resolveRemoteId(source, importer, remoteName) {
3971
+ function resolveRemoteId(pluginContext, source, importer, remoteName) {
3744
3972
  if (source === remoteName) {
3745
3973
  const installedPackageEntry = getInstalledPackageEntry(source, { cwd: root });
3746
3974
  if (installedPackageEntry && (importer === void 0 || isNodeModulesImporter(importer))) return installedPackageEntry;
3747
3975
  }
3748
- const remoteModule = getRemoteVirtualModule(source, command, enableSsrInit);
3976
+ const consumer = resolveRemoteConsumer(pluginContext, hasMultiEnvironment);
3977
+ const remoteModule = getRemoteVirtualModule(source, command, enableSsrInit, consumer);
3749
3978
  addUsedRemote(remoteName, source);
3750
3979
  refreshHostAutoInit();
3751
3980
  return remoteModule.getImportId();
@@ -3753,6 +3982,9 @@ function pluginProxyRemotes_default(options) {
3753
3982
  return {
3754
3983
  name: "proxyRemotes",
3755
3984
  enforce: "pre",
3985
+ applyToEnvironment() {
3986
+ return true;
3987
+ },
3756
3988
  config(config, { command: _command }) {
3757
3989
  command = _command;
3758
3990
  root = config.root || process.cwd();
@@ -3764,14 +3996,15 @@ function pluginProxyRemotes_default(options) {
3764
3996
  });
3765
3997
  });
3766
3998
  },
3767
- configResolved() {
3768
- enableSsrInit = command === "serve" && parseInt(version, 10) >= 8;
3999
+ configResolved(config) {
4000
+ hasMultiEnvironment = Boolean(config.environments?.ssr);
4001
+ enableSsrInit = getSsrCapabilities(parseInt(version, 10), command, Object.keys(remotes).length > 0).enableSsrInitBootstrap;
3769
4002
  },
3770
4003
  resolveId(source, importer) {
3771
4004
  if (!filterId(source)) return;
3772
4005
  for (const remote of Object.values(remotes)) {
3773
4006
  if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
3774
- return resolveRemoteId(source, importer, remote.name);
4007
+ return resolveRemoteId(this, source, importer, remote.name);
3775
4008
  }
3776
4009
  }
3777
4010
  };
@@ -3813,11 +4046,11 @@ function getPrebuildResolutionSource(pkgName, shareItem) {
3813
4046
  return getConcreteSharedImportSource(pkgName, shareItem) || pkgName;
3814
4047
  }
3815
4048
  function tryResolveFromProjectRoot(source) {
3816
- if (path.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
4049
+ if (path$1.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
3817
4050
  const browserEntry = getInstalledPackageEntry(source, { cwd: getPackageDetectionCwd() });
3818
4051
  if (browserEntry) return browserEntry;
3819
4052
  try {
3820
- return createRequire(new URL(`file://${path.join(getPackageDetectionCwd(), "package.json")}`)).resolve(source);
4053
+ return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(source);
3821
4054
  } catch {
3822
4055
  return;
3823
4056
  }
@@ -3834,8 +4067,42 @@ function matchesSharedSource(source, key) {
3834
4067
  return source === keyBase;
3835
4068
  }
3836
4069
  function findSharedKey(source, shared) {
3837
- const keys = Object.keys(shared || {});
3838
- return keys.find((key) => source === key) ?? keys.find((key) => matchesSharedSource(source, key));
4070
+ return getSharedKeyMatcher(shared).find(source);
4071
+ }
4072
+ const emptySharedKeyMatcher = { find: () => void 0 };
4073
+ const sharedKeyMatcherCache = /* @__PURE__ */ new WeakMap();
4074
+ function getSharedKeyMatcher(shared) {
4075
+ if (!shared) return emptySharedKeyMatcher;
4076
+ const cached = sharedKeyMatcherCache.get(shared);
4077
+ if (cached) return cached;
4078
+ const keys = Object.keys(shared);
4079
+ const exactKeys = new Set(keys);
4080
+ const commonSubpathKeys = /* @__PURE__ */ new Map();
4081
+ const wildcardKeys = [];
4082
+ let vueKey;
4083
+ for (const key of keys) {
4084
+ const keyBase = key.endsWith("/") ? key.slice(0, -1) : key;
4085
+ if (!vueKey && keyBase === "vue") vueKey = key;
4086
+ if (key.endsWith("/")) wildcardKeys.push({
4087
+ key,
4088
+ base: keyBase
4089
+ });
4090
+ for (const subpath of getCommonSharedSubpaths(keyBase)) if (!commonSubpathKeys.has(subpath)) commonSubpathKeys.set(subpath, key);
4091
+ }
4092
+ const sourceCache = /* @__PURE__ */ new Map();
4093
+ const matcher = { find(source) {
4094
+ if (sourceCache.has(source)) return sourceCache.get(source);
4095
+ let result = exactKeys.has(source) ? source : void 0;
4096
+ if (!result && vueKey) {
4097
+ if (source === "vue/dist/vue.esm-bundler.js" || source === "vue/dist/vue.runtime.esm-bundler.js") result = vueKey;
4098
+ }
4099
+ if (!result) result = commonSubpathKeys.get(source);
4100
+ if (!result) result = wildcardKeys.find(({ base }) => source === base || source.startsWith(`${base}/`))?.key;
4101
+ sourceCache.set(source, result);
4102
+ return result;
4103
+ } };
4104
+ sharedKeyMatcherCache.set(shared, matcher);
4105
+ return matcher;
3839
4106
  }
3840
4107
  function findSharedKeyForSource(source, shared) {
3841
4108
  const key = findSharedKey(source, shared);
@@ -4005,36 +4272,28 @@ function proxySharedModule(options) {
4005
4272
  ];
4006
4273
  }
4007
4274
  //#endregion
4008
- //#region src/utils/loadWalk.ts
4009
- let walkPromise = null;
4010
- function loadWalk() {
4011
- walkPromise ||= import("estree-walker").then(({ walk }) => walk);
4012
- return walkPromise;
4013
- }
4014
- //#endregion
4015
4275
  //#region src/plugins/pluginRemoteNamedExports.ts
4016
- /**
4017
- * Transforms consumer-side imports of remote modules so that named exports
4018
- * are accessible even when the bundler does not support syntheticNamedExports
4019
- * (Rolldown / Vite 8+).
4020
- *
4021
- * The remote proxy module exports:
4022
- * export const __moduleExports = exportModule; // full namespace
4023
- * export default exportModule.default ?? exportModule; // unwrapped default
4024
- *
4025
- * This plugin rewrites consumer code:
4026
- * import { foo } from "remote/xxx"
4027
- * → import { __moduleExports as __mf_ns_0 } from "remote/xxx"; const { foo } = __mf_ns_0;
4028
- *
4029
- * import("remote/xxx")
4030
- * → import("remote/xxx").then(…) // spreads __moduleExports into namespace
4031
- *
4032
- * NOTE: `export * from "remote/xxx"` is not supported — Rolldown cannot
4033
- * statically resolve the set of exported names from a federated remote at
4034
- * build time. Use explicit named re-exports instead.
4035
- */
4036
4276
  const JS_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?|vue|svelte)(?:\?|$)/;
4037
4277
  const REGEX_FALLBACK_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?)(?:\?|$)/;
4278
+ function isAstNode(value) {
4279
+ return !!value && typeof value === "object" && typeof value.type === "string";
4280
+ }
4281
+ function walkAST(root, visitor) {
4282
+ const seen = /* @__PURE__ */ new WeakSet();
4283
+ function visit(node) {
4284
+ if (!isAstNode(node)) return;
4285
+ if (seen.has(node)) return;
4286
+ seen.add(node);
4287
+ let skipped = false;
4288
+ visitor.enter.call({ skip() {
4289
+ skipped = true;
4290
+ } }, node);
4291
+ if (skipped) return;
4292
+ for (const value of Object.values(node)) if (Array.isArray(value)) for (const item of value) visit(item);
4293
+ else visit(value);
4294
+ }
4295
+ visit(root);
4296
+ }
4038
4297
  function parseNamedSpecifiers(specifiersRaw, kind) {
4039
4298
  return specifiersRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0 && !s.startsWith("type ")).map((s) => {
4040
4299
  const asMatch = s.match(/^(\w+)\s+as\s+(\w+)$/);
@@ -4050,7 +4309,7 @@ function parseNamedSpecifiers(specifiersRaw, kind) {
4050
4309
  });
4051
4310
  }
4052
4311
  function wrapDynamicImport(original) {
4053
- return `${original}.then(function(__mf_m__) {\n var __mf_ready__ = __mf_m__ && __mf_m__.__mf_remote_pending ? __mf_m__.__mf_remote_pending.then(function(__mf_resolved__) { return __mf_resolved__ || __mf_m__; }) : __mf_m__;\n return Promise.resolve(__mf_ready__).then(function(__mf_m__) {\n if (!__mf_m__ || !__mf_m__.__moduleExports) {\n if (__mf_m__ && __mf_m__.default && typeof __mf_m__.default === "object" && __mf_m__.default.__esModule) {\n var __mf_nested_e__ = __mf_m__.default;\n var __mf_nested_ns__ = Object.create(null);\n Object.defineProperty(__mf_nested_ns__, Symbol.toStringTag, { value: "Module" });\n Object.keys(__mf_nested_e__).forEach(function(k) { if (k !== "__esModule") __mf_nested_ns__[k] = __mf_nested_e__[k] });\n if ("default" in __mf_nested_e__) __mf_nested_ns__.default = __mf_nested_e__.default;\n return __mf_nested_ns__;\n }\n return __mf_m__;\n }\n var __mf_ns__ = Object.create(null);\n Object.defineProperty(__mf_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_e__ = __mf_m__.__moduleExports;\n if (__mf_e__ && __mf_e__.default && typeof __mf_e__.default === "object" && __mf_e__.default.__esModule) __mf_e__ = __mf_e__.default;\n Object.keys(__mf_e__).forEach(function(k) { if (k !== "__esModule") __mf_ns__[k] = __mf_e__[k] });\n if ("default" in __mf_e__) __mf_ns__.default = __mf_e__.default;\n else if ("default" in __mf_m__) __mf_ns__.default = __mf_m__.default;\n return __mf_ns__;\n });\n})`;
4312
+ return `${original}.then(function(__mf_m__) {\n var __mf_pending__ = __mf_m__ && __mf_m__.__mf_remote_pending;\n var __mf_ready__ = __mf_pending__ && typeof __mf_pending__.then === "function"\n ? __mf_pending__.then(function(__mf_resolved__) { return __mf_resolved__ || __mf_m__; })\n : Promise.resolve(__mf_m__);\n return __mf_ready__.then(function(__mf_m__) {\n if (!__mf_m__ || !__mf_m__.__moduleExports) {\n if (__mf_m__ && __mf_m__.default && typeof __mf_m__.default === "object" && __mf_m__.default.__esModule) {\n var __mf_nested_e__ = __mf_m__.default;\n var __mf_nested_ns__ = Object.create(null);\n Object.defineProperty(__mf_nested_ns__, Symbol.toStringTag, { value: "Module" });\n Object.keys(__mf_nested_e__).forEach(function(k) { if (k !== "__esModule") __mf_nested_ns__[k] = __mf_nested_e__[k] });\n if ("default" in __mf_nested_e__) __mf_nested_ns__.default = __mf_nested_e__.default;\n return __mf_nested_ns__;\n }\n var __mf_flat_ns__ = Object.create(null);\n Object.defineProperty(__mf_flat_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_src__ = __mf_m__;\n if (__mf_src__ && __mf_src__.default && typeof __mf_src__.default === "object" && __mf_src__.default.__esModule) __mf_src__ = __mf_src__.default;\n if (__mf_src__) {\n Object.keys(__mf_src__).forEach(function(k) { if (k !== "__esModule") __mf_flat_ns__[k] = __mf_src__[k]; });\n __mf_flat_ns__.default = "default" in __mf_src__ ? __mf_src__.default : __mf_src__;\n }\n return __mf_flat_ns__;\n }\n var __mf_ns__ = Object.create(null);\n Object.defineProperty(__mf_ns__, Symbol.toStringTag, { value: "Module" });\n var __mf_e__ = __mf_m__.__moduleExports;\n if (__mf_e__ && __mf_e__.default && typeof __mf_e__.default === "object" && __mf_e__.default.__esModule) __mf_e__ = __mf_e__.default;\n Object.keys(__mf_e__).forEach(function(k) { if (k !== "__esModule") __mf_ns__[k] = __mf_e__[k] });\n if ("default" in __mf_e__) __mf_ns__.default = __mf_e__.default;\n else if ("default" in __mf_m__) __mf_ns__.default = __mf_m__.default;\n return __mf_ns__;\n });\n})`;
4054
4313
  }
4055
4314
  function applyRewrites(code, imports, id) {
4056
4315
  if (imports.length === 0) return;
@@ -4150,9 +4409,8 @@ function applyRewrites(code, imports, id) {
4150
4409
  };
4151
4410
  }
4152
4411
  async function collectFromAST(ast, code, isRemoteImport) {
4153
- const walk = await loadWalk();
4154
4412
  const result = [];
4155
- walk(ast, { enter(node) {
4413
+ walkAST(ast, { enter(node) {
4156
4414
  if (node.type === "ImportDeclaration" && node.source?.value) {
4157
4415
  if (!isRemoteImport(node.source.value)) return;
4158
4416
  const specifiers = node.specifiers || [];
@@ -4211,86 +4469,11 @@ async function collectFromAST(ast, code, isRemoteImport) {
4211
4469
  } });
4212
4470
  return result;
4213
4471
  }
4214
- async function collectFromEsLexer(code, isRemoteImport) {
4215
- await init;
4216
- let imports;
4217
- try {
4218
- [imports] = parse(code);
4219
- } catch {
4220
- return;
4221
- }
4222
- const result = [];
4223
- for (const imp of imports) {
4224
- if (imp.d === -2) continue;
4225
- if (!imp.n || !isRemoteImport(imp.n)) continue;
4226
- const stmtText = code.slice(imp.ss, imp.se);
4227
- if (imp.d >= 0) {
4228
- result.push({
4229
- kind: "dynamic",
4230
- start: imp.ss,
4231
- end: imp.se,
4232
- originalText: stmtText
4233
- });
4234
- continue;
4235
- }
4236
- if (/^\s*export\s*\*\s/.test(stmtText)) {
4237
- result.push({
4238
- kind: "export-all",
4239
- source: imp.n,
4240
- start: imp.ss,
4241
- end: imp.se
4242
- });
4243
- continue;
4244
- }
4245
- if (/^\s*export\s/.test(stmtText)) {
4246
- const braceMatch = stmtText.match(/\{([^}]*)\}/);
4247
- if (!braceMatch) continue;
4248
- const specifiers = parseNamedSpecifiers(braceMatch[1], "export");
4249
- if (specifiers.length === 0) continue;
4250
- result.push({
4251
- kind: "reexport",
4252
- source: imp.n,
4253
- start: imp.ss,
4254
- end: imp.se,
4255
- specifiers
4256
- });
4257
- continue;
4258
- }
4259
- const importMatch = stmtText.match(/^import\s+([\s\S]*?)\s+from\s/);
4260
- if (!importMatch) continue;
4261
- const specifiersPart = importMatch[1].trim();
4262
- if (/^type\s/.test(specifiersPart)) continue;
4263
- const nsMatch = specifiersPart.match(/^\*\s+as\s+(\w+)$/);
4264
- if (nsMatch) {
4265
- result.push({
4266
- kind: "static",
4267
- source: imp.n,
4268
- start: imp.ss,
4269
- end: imp.se,
4270
- named: [],
4271
- namespaceLocal: nsMatch[1]
4272
- });
4273
- continue;
4274
- }
4275
- const braceMatch = specifiersPart.match(/\{([^}]*)\}/);
4276
- if (!braceMatch) continue;
4277
- const named = parseNamedSpecifiers(braceMatch[1], "import");
4278
- if (named.length === 0) continue;
4279
- const defaultMatch = specifiersPart.match(/^(\w+)\s*,/);
4280
- result.push({
4281
- kind: "static",
4282
- source: imp.n,
4283
- start: imp.ss,
4284
- end: imp.se,
4285
- named,
4286
- defaultLocal: defaultMatch?.[1]
4287
- });
4288
- }
4289
- return result;
4290
- }
4291
4472
  function collectFromRegex(code, isRemoteImport) {
4292
4473
  const result = [];
4293
- for (const match of code.matchAll(/^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2\s*;?/gm)) {
4474
+ const importAttributes = String.raw`(?:\s+(?:with|assert)\s+\{[^;]*\})?`;
4475
+ const staticRe = new RegExp(String.raw`^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
4476
+ for (const match of code.matchAll(staticRe)) {
4294
4477
  const [full, specifiersPartRaw, , source] = match;
4295
4478
  if (!isRemoteImport(source)) continue;
4296
4479
  const specifiersPart = specifiersPartRaw.trim();
@@ -4321,7 +4504,8 @@ function collectFromRegex(code, isRemoteImport) {
4321
4504
  defaultLocal: defaultMatch?.[1]
4322
4505
  });
4323
4506
  }
4324
- for (const match of code.matchAll(/^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2\s*;?/gm)) {
4507
+ const reexportRe = new RegExp(String.raw`^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
4508
+ for (const match of code.matchAll(reexportRe)) {
4325
4509
  const [full, specifiersRaw, , source] = match;
4326
4510
  if (!isRemoteImport(source)) continue;
4327
4511
  const specifiers = parseNamedSpecifiers(specifiersRaw, "export");
@@ -4334,7 +4518,8 @@ function collectFromRegex(code, isRemoteImport) {
4334
4518
  specifiers
4335
4519
  });
4336
4520
  }
4337
- for (const match of code.matchAll(/^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1\s*;?/gm)) {
4521
+ const exportAllRe = new RegExp(String.raw`^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1${importAttributes}\s*;?`, "gm");
4522
+ for (const match of code.matchAll(exportAllRe)) {
4338
4523
  const [full, , source] = match;
4339
4524
  if (!isRemoteImport(source)) continue;
4340
4525
  result.push({
@@ -4344,7 +4529,7 @@ function collectFromRegex(code, isRemoteImport) {
4344
4529
  end: match.index + full.length
4345
4530
  });
4346
4531
  }
4347
- for (const match of code.matchAll(/import\(\s*(['"])([^'"]+)\1\s*\)/g)) {
4532
+ for (const match of code.matchAll(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])([^'"]+)\1\s*\)/g)) {
4348
4533
  const [full, , source] = match;
4349
4534
  if (!isRemoteImport(source)) continue;
4350
4535
  result.push({
@@ -4379,7 +4564,8 @@ function pluginRemoteNamedExports(options) {
4379
4564
  try {
4380
4565
  imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
4381
4566
  } catch {
4382
- imports = await collectFromEsLexer(code, matchesRemoteImport);
4567
+ if ((id.includes(".vue") || id.includes(".svelte")) && /^\s*</.test(code)) return;
4568
+ imports = collectFromRegex(code, matchesRemoteImport);
4383
4569
  }
4384
4570
  if ((!imports || imports.length === 0) && REGEX_FALLBACK_EXTENSIONS_RE.test(id)) imports = collectFromRegex(code, matchesRemoteImport);
4385
4571
  if (!imports) return;
@@ -4514,10 +4700,10 @@ function pluginSSRRemoteEntry(options) {
4514
4700
  const bareId = decodeViteId(id);
4515
4701
  try {
4516
4702
  const { createRequire } = await import("module");
4517
- const resolved = createRequire(new URL(`file://${server.config.root}/package.json`)).resolve(bareId.replace(/^\0/, ""));
4703
+ const path = await import("path");
4518
4704
  const { pathToFileURL } = await import("url");
4519
4705
  result = {
4520
- externalize: pathToFileURL(resolved).href,
4706
+ externalize: pathToFileURL(createRequire(pathToFileURL(path.join(server.config.root, "package.json"))).resolve(bareId.replace(/^\0/, ""))).href,
4521
4707
  type: "module"
4522
4708
  };
4523
4709
  } catch {
@@ -4539,6 +4725,12 @@ function pluginSSRRemoteEntry(options) {
4539
4725
  res.setHeader("Access-Control-Allow-Origin", "*");
4540
4726
  res.end(code);
4541
4727
  });
4728
+ const exposesPath = `${base}/${options.filename.replace(/\.[^.]+$/, "")}.exposes.js`;
4729
+ server.middlewares.use(exposesPath, (_req, res) => {
4730
+ res.setHeader("Content-Type", "application/javascript");
4731
+ res.setHeader("Access-Control-Allow-Origin", "*");
4732
+ res.end(generateExposesSSR(options));
4733
+ });
4542
4734
  },
4543
4735
  resolveId(id) {
4544
4736
  if (id === remoteEntrySSRId || id.startsWith(remoteEntrySSRId)) return id;
@@ -4831,13 +5023,13 @@ function escapeUnsafeJsSourceChars(str) {
4831
5023
  });
4832
5024
  }
4833
5025
  function isFederationHtmlPreloadDependency(dep, includeSharedRuntime = false) {
4834
- const file = path.basename(dep);
5026
+ const file = path$1.basename(dep);
4835
5027
  if (file.includes("__mfe_internal__") || file.includes("virtual_mf-") || file.includes("virtualExposes") || file.includes("localSharedImportMap") || file.includes("hostInit")) return true;
4836
5028
  return includeSharedRuntime && (file.includes("preload-helper") || file.includes("rolldown-runtime") || file.startsWith("dist-"));
4837
5029
  }
4838
5030
  function canResolveSharedSubpath(subpath, projectRoot) {
4839
5031
  try {
4840
- createRequire(new URL(`file://${projectRoot}/package.json`)).resolve(subpath);
5032
+ createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(subpath);
4841
5033
  return true;
4842
5034
  } catch {
4843
5035
  return false;
@@ -4972,7 +5164,7 @@ export default __mfShared.default ?? __mfShared;`
4972
5164
  const optimizeDeps = config.optimizeDeps ??= {};
4973
5165
  optimizeDeps.include ??= [];
4974
5166
  optimizeDeps.exclude ??= [];
4975
- if (isLitShare(key)) optimizeDeps.exclude.push(key);
5167
+ if (isLitShare(key) || key === "react" && hasPackageDependency("react-redux", root)) optimizeDeps.exclude.push(key);
4976
5168
  else optimizeDeps.include.push(key);
4977
5169
  for (const subpath of getCommonSharedSubpaths(key)) {
4978
5170
  getLoadShareModulePath(subpath, isRolldown);
@@ -4988,12 +5180,13 @@ export default __mfShared.default ?? __mfShared;`
4988
5180
  }
4989
5181
  },
4990
5182
  configResolved(config) {
4991
- if (parseInt(version, 10) < 8) return;
4992
- if (!(Object.keys(options.exposes).length > 0 || Object.keys(options.remotes).length > 0)) return;
5183
+ const viteMajor = parseInt(version, 10);
5184
+ const hasRemotes = Object.keys(options.remotes).length > 0;
5185
+ if (!getSsrCapabilities(viteMajor, config.command, hasRemotes).injectSsrEntryLoader) return;
4993
5186
  if (options.runtimePlugins.some((p) => {
4994
5187
  return (typeof p === "string" ? p : p[0]) === "@module-federation/vite/ssrEntryLoader";
4995
5188
  })) return;
4996
- const projectRequire = createRequire(new URL(`file://${config.root}/package.json`));
5189
+ const projectRequire = createRequire$1(pathToFileURL(path$1.join(config.root, "package.json")));
4997
5190
  const sharedKeys = Object.keys(options.shared ?? {});
4998
5191
  const commonSharedPkgs = [
4999
5192
  "react",
@@ -5024,7 +5217,7 @@ export default __mfShared.default ?? __mfShared;`
5024
5217
  const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
5025
5218
  function loadPluginDts(options) {
5026
5219
  if (options.dts === false) return [];
5027
- return [import("./pluginDts-Bgdw5ODE.js").then(({ default: pluginDts }) => pluginDts(options))];
5220
+ return [import("./pluginDts-Cpmdbbr0.js").then((n) => n.n).then(({ default: pluginDts }) => pluginDts(options))];
5028
5221
  }
5029
5222
  function federation(mfUserOptions) {
5030
5223
  if (isTestEnv()) return [];
@@ -5079,8 +5272,8 @@ function federation(mfUserOptions) {
5079
5272
  const environmentName = this.environment?.name;
5080
5273
  if (!environmentName || environmentName === "client") return;
5081
5274
  const target = reactServerEntryMap[id];
5082
- const reactPackageJson = createRequire(new URL(`file://${process.cwd()}/package.json`)).resolve("react/package.json");
5083
- return path.join(path.dirname(reactPackageJson), target.replace(/^react\//, ""));
5275
+ const reactPackageJson = createRequire$1(pathToFileURL(path$1.join(process.cwd(), "package.json"))).resolve("react/package.json");
5276
+ return path$1.join(path$1.dirname(reactPackageJson), target.replace(/^react\//, ""));
5084
5277
  }
5085
5278
  }] : [],
5086
5279
  {
@@ -5090,7 +5283,8 @@ function federation(mfUserOptions) {
5090
5283
  command = env.command;
5091
5284
  },
5092
5285
  configResolved() {
5093
- initVirtualModules(command, remoteEntryId, parseInt(version, 10) >= 8);
5286
+ const ssrCapabilities = getSsrCapabilities(parseInt(version, 10), command, Object.keys(options.remotes).length > 0);
5287
+ initVirtualModules(command, remoteEntryId, ssrCapabilities.enableSsrInitBootstrap);
5094
5288
  }
5095
5289
  },
5096
5290
  aliasToArrayPlugin_default,
@@ -5134,7 +5328,7 @@ function federation(mfUserOptions) {
5134
5328
  pluginProxyRemotes_default(options),
5135
5329
  pluginRemoteNamedExports(options),
5136
5330
  ...pluginModuleParseEnd_default((id) => {
5137
- return id.includes(getHostAutoInitImportId()) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes(getLocalSharedImportMapPath());
5331
+ return id.includes(getHostAutoInitImportId()) || id.includes(remoteEntryId) || id.includes(virtualExposesId) || id.includes(getLocalSharedImportMapPath()) || id.includes("__loadShare__") || id.includes("__prebuild__");
5138
5332
  }, {
5139
5333
  moduleParseTimeout: options.moduleParseTimeout,
5140
5334
  moduleParseIdleTimeout: options.moduleParseIdleTimeout,
@@ -5155,7 +5349,7 @@ function federation(mfUserOptions) {
5155
5349
  ...currentModulePreload,
5156
5350
  resolveDependencies(filename, deps, context) {
5157
5351
  const resolvedDeps = existingResolveDependencies ? existingResolveDependencies(filename, deps, context) : deps;
5158
- const hostFile = path.basename(context.hostId);
5352
+ const hostFile = path$1.basename(context.hostId);
5159
5353
  if (context.hostType === "js" && (hostFile === options.filename || hostFile.includes("hostInit") || hostFile.includes("virtualExposes") || hostFile.includes("localSharedImportMap"))) return [];
5160
5354
  const hasFederationHtmlDeps = context.hostType === "html" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
5161
5355
  const hasFederationJsDeps = context.hostType === "js" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
@@ -5269,23 +5463,7 @@ function federation(mfUserOptions) {
5269
5463
  let code = VirtualModule.findById(id)?.code ?? readFileSync(id, "utf-8");
5270
5464
  code = code.replace(/import\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
5271
5465
  code = code.replace(/export\s+\*\s+from\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
5272
- /**
5273
- * Shared/remote shims only have `export default exportModule`.
5274
- *
5275
- * We add a second named export (__moduleExports) that holds the full
5276
- * module namespace and point syntheticNamedExports at it. This lets
5277
- * Rollup resolve named imports (e.g. `import { useState } from 'react'`)
5278
- * from the namespace while still applying its normal default-export
5279
- * interop — which is needed for libraries like @emotion/styled where
5280
- * `import styled from '@emotion/styled'` must receive the .default
5281
- * function, not the raw namespace object.
5282
- *
5283
- * Using 'default' as the syntheticNamedExports key would skip the
5284
- * interop and break default imports.
5285
- *
5286
- * @see https://rollupjs.org/plugin-development/#synthetic-named-exports
5287
- */
5288
- if (!/\bexport\s+const\s+__moduleExports\b/.test(code) && !/\bexport\s*\{[^}]*__moduleExports/.test(code)) {
5466
+ if (!(/\b(?:var|let|const)\s+__moduleExports\b/.test(code) || /\bexport\s+const\s+__moduleExports\b/.test(code) || /\bexport\s*\{[^}]*__moduleExports/.test(code))) {
5289
5467
  const nextCode = code.replace("export default exportModule", "export const __moduleExports = exportModule;\nexport default exportModule.__esModule ? exportModule.default : exportModule");
5290
5468
  code = nextCode === code ? `${code}\nexport const __moduleExports = exportModule;\n` : nextCode;
5291
5469
  }
@@ -5333,7 +5511,7 @@ function federation(mfUserOptions) {
5333
5511
  for (const chunk of Object.values(bundle)) {
5334
5512
  if (!isOutputChunk(chunk)) continue;
5335
5513
  if (!isFederationControlChunk(chunk.fileName, filename)) continue;
5336
- const outputPath = path.join(outputOptions.dir, chunk.fileName);
5514
+ const outputPath = path$1.join(outputOptions.dir, chunk.fileName);
5337
5515
  writeFileSync(outputPath, sanitizeFederationControlChunk(readFileSync(outputPath, "utf-8"), chunk.fileName, filename));
5338
5516
  }
5339
5517
  }
@@ -5428,16 +5606,16 @@ function federation(mfUserOptions) {
5428
5606
  for (const chunk of Object.values(bundle)) {
5429
5607
  if (!isOutputChunk(chunk)) continue;
5430
5608
  if (!chunk.code.includes("modulepreload")) continue;
5431
- const chunkDir = path.dirname(chunk.fileName);
5432
- const prefixToRoot = chunkDir === "." ? "" : `${path.relative(chunkDir, ".")}/`;
5609
+ const chunkDir = path$1.dirname(chunk.fileName);
5610
+ const prefixToRoot = chunkDir === "." ? "" : `${normalizePathForImport(path$1.relative(chunkDir, "."))}/`;
5433
5611
  const replacementExpr = prefixToRoot ? `${escapeUnsafeJsSourceChars(JSON.stringify(prefixToRoot))}+$1` : "$1";
5434
5612
  const replacement = `=function($1){return new URL(${replacementExpr},import.meta.url).href}`;
5435
- const replaced = chunk.code.replace(/=\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/, replacement);
5613
+ const replaced = chunk.code.replace(/=\s*\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/, replacement);
5436
5614
  if (replaced !== chunk.code) {
5437
5615
  chunk.code = replaced;
5438
5616
  continue;
5439
5617
  }
5440
- chunk.code = chunk.code.replace(/=function\((\w+)(?:,\w+)?\)\{return\s*[`"'][./][^`"']*[`"']\s*\+\s*\1\s*\}/, replacement);
5618
+ chunk.code = chunk.code.replace(/=\s*function\((\w+)(?:,\w+)?\)\s*\{\s*return\s*[`"'][./][^`"']*[`"']\s*\+\s*\1;?\s*\}/, replacement);
5441
5619
  chunk.code = chunk.code.replace(/=function\((\w+)(?:,\w+)?\)\{return new URL\("\.\.\/"\+\1,import\.meta\.url\)\.href\}/, replacement);
5442
5620
  chunk.code = chunk.code.replace(/new URL\("\.\.\/"\+(\w+),import\.meta\.url\)\.href/g, `new URL(${replacementExpr},import.meta.url).href`);
5443
5621
  }