@module-federation/vite 1.16.4 → 1.16.6
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/README.md +21 -8
- package/lib/{index.d.cts → index.d.ts} +9 -1
- package/lib/{index.mjs → index.js} +518 -394
- package/lib/{packageUtils-Bbc6r6__.mjs → packageUtils-CYnJFfPP.js} +77 -23
- package/lib/{pluginDts-DDx4TPN8.mjs → pluginDts-BaVhdR6i.js} +4 -4
- package/lib/utils/{ssrEntryLoader.mjs → ssrEntryLoader.js} +3 -3
- package/package.json +14 -24
- package/lib/index.cjs +0 -5381
- package/lib/index.d.mts +0 -167
- package/lib/packageUtils-se-UDhCa.cjs +0 -367
- package/lib/pluginDts-7EoFboCu.cjs +0 -311
- package/lib/utils/ssrEntryLoader.cjs +0 -301
- package/lib/utils/ssrEntryLoader.d.cts +0 -65
- /package/lib/utils/{ssrEntryLoader.d.mts → ssrEntryLoader.d.ts} +0 -0
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import { a as getPackageName, c as hasPackageDependency, d as packageNameEncode, f as
|
|
1
|
+
import { _ as normalizePathForImport, 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, v as rebaseImport } from "./packageUtils-CYnJFfPP.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 "
|
|
6
|
-
import path, { basename } from "
|
|
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 {
|
|
10
|
-
import {
|
|
11
|
+
import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "node:fs";
|
|
12
|
+
import { pathToFileURL as pathToFileURL$1 } from "node:url";
|
|
11
13
|
//#region src/utils/codeRewriter.ts
|
|
12
14
|
const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
13
15
|
var CodeRewriter = class {
|
|
@@ -355,9 +357,9 @@ function normalizeManifest(manifest) {
|
|
|
355
357
|
let config;
|
|
356
358
|
let explicitSharedKeys = /* @__PURE__ */ new Set();
|
|
357
359
|
function resolveRuntimeImplementation() {
|
|
358
|
-
const fallback =
|
|
360
|
+
const fallback = resolveImportPath("@module-federation/runtime");
|
|
359
361
|
try {
|
|
360
|
-
const packageJsonPath =
|
|
362
|
+
const packageJsonPath = resolveImportPath("@module-federation/runtime/package.json");
|
|
361
363
|
const packageJson = JSON.parse(fs$1.readFileSync(packageJsonPath, "utf-8"));
|
|
362
364
|
const importExport = packageJson.exports?.["."];
|
|
363
365
|
const exportImport = typeof importExport === "object" ? typeof importExport.import === "string" ? importExport.import : importExport.import?.default : void 0;
|
|
@@ -635,20 +637,31 @@ let _ssrRemotes = [];
|
|
|
635
637
|
function setSsrRemotes(remotes) {
|
|
636
638
|
_ssrRemotes = remotes;
|
|
637
639
|
}
|
|
638
|
-
function getSsrNoopResolveCode(enableSsrInit) {
|
|
640
|
+
function getSsrNoopResolveCode(enableSsrInit, hostInitImportId, initResolveExpression = "initResolve") {
|
|
639
641
|
if (!enableSsrInit) return "";
|
|
640
642
|
return `if (typeof window === 'undefined') {
|
|
641
643
|
var _noop = { loadRemote: function() { return Promise.resolve(undefined); }, loadShare: function() { return Promise.resolve(undefined); } };
|
|
642
|
-
import(
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
644
|
+
${hostInitImportId ? `import(${JSON.stringify(hostInitImportId)})
|
|
645
|
+
.then(function(mod) { return mod.hostInitPromise; })
|
|
646
|
+
.then(function(runtime) {
|
|
647
|
+
${initResolveExpression}(runtime);
|
|
648
|
+
return true;
|
|
649
|
+
})
|
|
650
|
+
.catch(function() {
|
|
651
|
+
return false;
|
|
652
|
+
})` : "Promise.resolve(false)"}.then(function(resolved) {
|
|
653
|
+
if (resolved) return;
|
|
654
|
+
return import(/* @vite-ignore */ '@module-federation/runtime').then(function(runtimeMod) {
|
|
655
|
+
return import(/* @vite-ignore */ '@module-federation/vite/ssrEntryLoader').then(
|
|
656
|
+
function(loaderMod) { return [runtimeMod, [loaderMod.default()]]; },
|
|
657
|
+
function() { return [runtimeMod, []]; }
|
|
658
|
+
);
|
|
659
|
+
}).then(function(pair) {
|
|
660
|
+
var runtime = pair[0].init({ name: '__mf_ssr_host__', remotes: ${JSON.stringify(_ssrRemotes)}, shared: {}, plugins: pair[1] });
|
|
661
|
+
${initResolveExpression}(runtime);
|
|
662
|
+
}, function() {
|
|
663
|
+
${initResolveExpression}(_noop);
|
|
664
|
+
});
|
|
652
665
|
});
|
|
653
666
|
}`;
|
|
654
667
|
}
|
|
@@ -668,7 +681,7 @@ if (!${options.stateVar}) {
|
|
|
668
681
|
const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
|
|
669
682
|
`;
|
|
670
683
|
}
|
|
671
|
-
function getRuntimeInitBootstrapCode(enableSsrInit = false) {
|
|
684
|
+
function getRuntimeInitBootstrapCode(enableSsrInit = false, hostInitImportId) {
|
|
672
685
|
return `
|
|
673
686
|
const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey())};
|
|
674
687
|
const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
|
|
@@ -677,14 +690,18 @@ globalThis[moduleCacheGlobalKey].share ||= {};
|
|
|
677
690
|
globalThis[moduleCacheGlobalKey].remote ||= {};
|
|
678
691
|
if (!globalThis[globalKey]) {
|
|
679
692
|
${getDeferredInitPromiseCode()}
|
|
680
|
-
|
|
693
|
+
globalThis[globalKey] = {
|
|
681
694
|
initPromise,
|
|
682
695
|
initResolve,
|
|
683
696
|
initReject,
|
|
684
697
|
moduleCache: globalThis[moduleCacheGlobalKey],
|
|
685
698
|
};
|
|
686
|
-
${getSsrNoopResolveCode(enableSsrInit)}
|
|
687
699
|
}
|
|
700
|
+
${enableSsrInit ? `
|
|
701
|
+
if (typeof window === 'undefined' && !globalThis[globalKey].ssrInitStarted) {
|
|
702
|
+
globalThis[globalKey].ssrInitStarted = true;
|
|
703
|
+
${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve")}
|
|
704
|
+
}` : ""}
|
|
688
705
|
globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
|
|
689
706
|
globalThis[globalKey].moduleCache.share ||= {};
|
|
690
707
|
globalThis[globalKey].moduleCache.remote ||= {};
|
|
@@ -717,11 +734,11 @@ function getRuntimeInitResolveBootstrapCode(enableSsrInit = false) {
|
|
|
717
734
|
enableSsrInit
|
|
718
735
|
});
|
|
719
736
|
}
|
|
720
|
-
function writeRuntimeInitStatus(command, enableSsrInit = false) {
|
|
737
|
+
function writeRuntimeInitStatus(command, enableSsrInit = false, hostInitImportId) {
|
|
721
738
|
const exportStatement = command === "build" ? `const { initPromise, initResolve, initReject, moduleCache } = globalThis[globalKey];
|
|
722
739
|
export { initPromise, initResolve, initReject, moduleCache };` : `module.exports = globalThis[globalKey];`;
|
|
723
740
|
virtualRuntimeInitStatus.writeSync(`
|
|
724
|
-
${getRuntimeInitBootstrapCode(enableSsrInit)}
|
|
741
|
+
${getRuntimeInitBootstrapCode(enableSsrInit, hostInitImportId)}
|
|
725
742
|
${exportStatement}
|
|
726
743
|
`);
|
|
727
744
|
}
|
|
@@ -756,10 +773,9 @@ function isValidEsmExportName(name) {
|
|
|
756
773
|
return !!name && name !== "default" && name !== "__esModule" && isValidJsIdentifier(name);
|
|
757
774
|
}
|
|
758
775
|
const JS_IDENTIFIER_PATTERN = `[\$_\\p{ID_Start}][\$_\\u200C\\u200D\\p{ID_Continue}]*`;
|
|
759
|
-
const localRequire = createRequire(import.meta.url);
|
|
760
776
|
function resolvePackageEntryFromProjectRoot(pkg) {
|
|
761
777
|
try {
|
|
762
|
-
return createRequire(
|
|
778
|
+
return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
|
|
763
779
|
} catch {
|
|
764
780
|
return;
|
|
765
781
|
}
|
|
@@ -776,29 +792,20 @@ function getPackageEsmEntryPath(pkg) {
|
|
|
776
792
|
}) || resolvePackageEntryFromProjectRoot(pkg);
|
|
777
793
|
}
|
|
778
794
|
function getEsmNamedExportsFromFile(entryPath) {
|
|
779
|
-
let source = "";
|
|
780
795
|
try {
|
|
781
796
|
if (!entryPath) return [];
|
|
782
|
-
|
|
783
|
-
initSync();
|
|
784
|
-
source = readFileSync(entryPath, "utf-8");
|
|
785
|
-
const [, exports] = parse(source, entryPath);
|
|
786
|
-
const names = exports.map((item) => item.n).filter((name) => isValidEsmExportName(name));
|
|
787
|
-
const regexNames = getNamedExportsViaRegex(source, entryPath);
|
|
788
|
-
const filteredNames = names.filter((name) => name !== "type" || regexNames.includes(name));
|
|
789
|
-
if (filteredNames.length > 0) return Array.from(new Set([...filteredNames, ...regexNames]));
|
|
790
|
-
return regexNames;
|
|
797
|
+
return getNamedExportsViaRegex(readFileSync(entryPath, "utf-8"), entryPath);
|
|
791
798
|
} catch {
|
|
792
|
-
return
|
|
799
|
+
return [];
|
|
793
800
|
}
|
|
794
801
|
}
|
|
795
802
|
function getEsmNamedExports(pkg) {
|
|
796
803
|
return getEsmNamedExportsFromFile(getPackageEsmEntryPath(pkg));
|
|
797
804
|
}
|
|
798
805
|
function resolveConfiguredImportPath(importSource) {
|
|
799
|
-
if (path.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
|
|
806
|
+
if (path$1.isAbsolute(importSource)) return resolveFileLikeModule(importSource);
|
|
800
807
|
const projectRoot = getPackageDetectionCwd();
|
|
801
|
-
if (importSource.startsWith(".")) return resolveFileLikeModule(path.resolve(projectRoot, importSource));
|
|
808
|
+
if (importSource.startsWith(".")) return resolveFileLikeModule(path$1.resolve(projectRoot, importSource));
|
|
802
809
|
const esmEntry = getInstalledPackageEntry(importSource, {
|
|
803
810
|
conditions: [
|
|
804
811
|
"browser",
|
|
@@ -810,7 +817,7 @@ function resolveConfiguredImportPath(importSource) {
|
|
|
810
817
|
});
|
|
811
818
|
if (esmEntry) return esmEntry;
|
|
812
819
|
try {
|
|
813
|
-
return createRequire(
|
|
820
|
+
return createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(importSource);
|
|
814
821
|
} catch {
|
|
815
822
|
return;
|
|
816
823
|
}
|
|
@@ -830,13 +837,13 @@ function resolveFileLikeModule(filePath) {
|
|
|
830
837
|
if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
|
|
831
838
|
}
|
|
832
839
|
for (const ext of extensions) {
|
|
833
|
-
const candidate = path.join(filePath, "index" + ext);
|
|
840
|
+
const candidate = path$1.join(filePath, "index" + ext);
|
|
834
841
|
if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
|
|
835
842
|
}
|
|
836
843
|
}
|
|
837
844
|
function resolveRelativeModule(filePath, specifier) {
|
|
838
|
-
const dir = path.dirname(filePath);
|
|
839
|
-
const exact = path.resolve(dir, specifier);
|
|
845
|
+
const dir = path$1.dirname(filePath);
|
|
846
|
+
const exact = path$1.resolve(dir, specifier);
|
|
840
847
|
if (existsSync(exact) && !statSync(exact).isDirectory()) return exact;
|
|
841
848
|
const extensions = [
|
|
842
849
|
".ts",
|
|
@@ -847,12 +854,12 @@ function resolveRelativeModule(filePath, specifier) {
|
|
|
847
854
|
".mts"
|
|
848
855
|
];
|
|
849
856
|
for (const ext of extensions) {
|
|
850
|
-
const candidate = path.resolve(dir, specifier + ext);
|
|
857
|
+
const candidate = path$1.resolve(dir, specifier + ext);
|
|
851
858
|
if (existsSync(candidate) && !statSync(candidate).isDirectory()) return candidate;
|
|
852
859
|
}
|
|
853
|
-
const resolved = path.resolve(dir, specifier);
|
|
860
|
+
const resolved = path$1.resolve(dir, specifier);
|
|
854
861
|
for (const ext of extensions) {
|
|
855
|
-
const candidate = path.join(resolved, "index" + ext);
|
|
862
|
+
const candidate = path$1.join(resolved, "index" + ext);
|
|
856
863
|
if (existsSync(candidate)) return candidate;
|
|
857
864
|
}
|
|
858
865
|
}
|
|
@@ -893,6 +900,8 @@ function getNamedExportsViaRegex(source, filePath, visited) {
|
|
|
893
900
|
if (isValidEsmExportName(name)) names.add(name);
|
|
894
901
|
}
|
|
895
902
|
}
|
|
903
|
+
const namespaceReExportRegex = new RegExp(`export\\s+\\*\\s+as\\s+(${JS_IDENTIFIER_PATTERN})\\s+from\\s+['"][^'"]+['"]`, "gu");
|
|
904
|
+
while ((match = namespaceReExportRegex.exec(source)) !== null) if (isValidEsmExportName(match[1])) names.add(match[1]);
|
|
896
905
|
if (filePath) {
|
|
897
906
|
const starExportRegex = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g;
|
|
898
907
|
while ((match = starExportRegex.exec(source)) !== null) {
|
|
@@ -910,7 +919,7 @@ function getNamedExportsViaRegex(source, filePath, visited) {
|
|
|
910
919
|
}
|
|
911
920
|
function getPackageNamedExports(pkg) {
|
|
912
921
|
try {
|
|
913
|
-
const mod = createRequire(
|
|
922
|
+
const mod = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json")))(pkg);
|
|
914
923
|
return Object.keys(mod).filter((k) => isValidEsmExportName(k));
|
|
915
924
|
} catch {
|
|
916
925
|
return getEsmNamedExports(pkg);
|
|
@@ -926,7 +935,7 @@ function getSharedNamedExports(pkg, shareItem) {
|
|
|
926
935
|
}
|
|
927
936
|
function getLocalProviderImportPath(pkg) {
|
|
928
937
|
try {
|
|
929
|
-
const resolved = createRequire(
|
|
938
|
+
const resolved = createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
|
|
930
939
|
return isWorkspaceFilePath(resolved) ? resolved : void 0;
|
|
931
940
|
} catch {
|
|
932
941
|
const resolved = getInstalledPackageEntry(pkg, {
|
|
@@ -947,7 +956,7 @@ function getProjectResolvedImportPath(pkg) {
|
|
|
947
956
|
if (esmEntry) return esmEntry;
|
|
948
957
|
}
|
|
949
958
|
try {
|
|
950
|
-
return createRequire(
|
|
959
|
+
return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(pkg);
|
|
951
960
|
} catch {
|
|
952
961
|
return;
|
|
953
962
|
}
|
|
@@ -961,7 +970,7 @@ function isWorkspaceFilePath(resolved) {
|
|
|
961
970
|
return !realResolved.includes("/node_modules/") && !realResolved.includes("\\node_modules\\");
|
|
962
971
|
}
|
|
963
972
|
function isWorkspacePackageEntry(pkg, resolved) {
|
|
964
|
-
if (!resolved || !path.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
|
|
973
|
+
if (!resolved || !path$1.isAbsolute(resolved) || !isWorkspaceFilePath(resolved)) return false;
|
|
965
974
|
return !!getInstalledPackageJson(pkg, {
|
|
966
975
|
packageName: getPackageName(pkg),
|
|
967
976
|
fromResolvedEntry: resolved
|
|
@@ -969,7 +978,7 @@ function isWorkspacePackageEntry(pkg, resolved) {
|
|
|
969
978
|
}
|
|
970
979
|
function tryResolveImportFromPackageRoot(pkg, root) {
|
|
971
980
|
try {
|
|
972
|
-
return createRequire(
|
|
981
|
+
return createRequire$1(pathToFileURL(path$1.join(root, "package.json"))).resolve(pkg);
|
|
973
982
|
} catch {
|
|
974
983
|
return;
|
|
975
984
|
}
|
|
@@ -979,11 +988,11 @@ function getConcreteSharedImportSource(pkg, shareItem) {
|
|
|
979
988
|
if (typeof configuredImport === "string") return configuredImport;
|
|
980
989
|
const projectRoot = getPackageDetectionCwd();
|
|
981
990
|
if (tryResolveImportFromPackageRoot(pkg, projectRoot)) return;
|
|
982
|
-
let currentDir = path.dirname(projectRoot);
|
|
983
|
-
while (currentDir !== path.dirname(currentDir)) {
|
|
991
|
+
let currentDir = path$1.dirname(projectRoot);
|
|
992
|
+
while (currentDir !== path$1.dirname(currentDir)) {
|
|
984
993
|
const resolved = tryResolveImportFromPackageRoot(pkg, currentDir);
|
|
985
994
|
if (resolved) return resolved;
|
|
986
|
-
currentDir = path.dirname(currentDir);
|
|
995
|
+
currentDir = path$1.dirname(currentDir);
|
|
987
996
|
}
|
|
988
997
|
return tryResolveImportFromPackageRoot(pkg, currentDir);
|
|
989
998
|
}
|
|
@@ -1064,7 +1073,7 @@ function getSharedImportSource(pkg, shareItem) {
|
|
|
1064
1073
|
const LOAD_SHARE_TAG = "__loadShare__";
|
|
1065
1074
|
const loadShareCacheMap = {};
|
|
1066
1075
|
function getLoadShareImportId(pkg, _isRolldown) {
|
|
1067
|
-
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".
|
|
1076
|
+
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
|
|
1068
1077
|
return loadShareCacheMap[pkg].getImportId();
|
|
1069
1078
|
}
|
|
1070
1079
|
function getLoadShareModulePath(pkg, isRolldown) {
|
|
@@ -1092,6 +1101,33 @@ function materializeCachedLoadShareModule(options) {
|
|
|
1092
1101
|
options.addUsedShares(pkg);
|
|
1093
1102
|
options.writeLocalSharedImportMap();
|
|
1094
1103
|
}
|
|
1104
|
+
function generateLazyWorkspaceSingletonExports(namedExports, importSource, cacheKey, eagerLocalFallback) {
|
|
1105
|
+
const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
|
|
1106
|
+
const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
|
|
1107
|
+
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;";
|
|
1108
|
+
const namedExportLine = namedExports.length > 0 ? `\n export { ${namedExports.map((name, i) => `${namedExportVars[i]} as ${name}`).join(", ")} };` : "";
|
|
1109
|
+
const body = `${declarations}
|
|
1110
|
+
const __mfApplyLazyShareExports = (mod) => {
|
|
1111
|
+
${assignments}
|
|
1112
|
+
};
|
|
1113
|
+
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}];
|
|
1114
|
+
if (exportModule === undefined) {
|
|
1115
|
+
${eagerLocalFallback ? `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
1116
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
|
|
1117
|
+
__mfApplyLazyShareExports(exportModule);` : `initPromise.then(() =>
|
|
1118
|
+
import(${escapeGeneratedStringLiteral(importSource)}).then((mod) => {
|
|
1119
|
+
exportModule = __mfNormalizeShareModule(mod);
|
|
1120
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;
|
|
1121
|
+
__mfApplyLazyShareExports(exportModule);
|
|
1122
|
+
})
|
|
1123
|
+
);`}
|
|
1124
|
+
} else {
|
|
1125
|
+
__mfApplyLazyShareExports(exportModule);
|
|
1126
|
+
}
|
|
1127
|
+
export { __mf_default as default };${namedExportLine}`;
|
|
1128
|
+
return eagerLocalFallback ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(importSource)};
|
|
1129
|
+
${body}` : body;
|
|
1130
|
+
}
|
|
1095
1131
|
function generateDeferredHostProvidedExports(namedExports, pkg, cacheKey) {
|
|
1096
1132
|
const namedExportVars = namedExports.map((_name, i) => `__mf_${i}`);
|
|
1097
1133
|
const declarations = ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ");
|
|
@@ -1133,8 +1169,8 @@ const normalizeLocalShareModuleCode = `const __mfNormalizeShareModule = (mod) =>
|
|
|
1133
1169
|
})}
|
|
1134
1170
|
};`;
|
|
1135
1171
|
function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
1136
|
-
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".
|
|
1137
|
-
|
|
1172
|
+
if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
|
|
1173
|
+
let importLine = getRuntimeModuleCacheBootstrapCode();
|
|
1138
1174
|
const cacheKey = getSharedCacheKey(pkg, shareItem);
|
|
1139
1175
|
if (shareItem.shareConfig.import === false) {
|
|
1140
1176
|
const namedExports = getPackageNamedExports(pkg);
|
|
@@ -1161,7 +1197,11 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
|
1161
1197
|
const usesLazyLocalFallback = isWorkspacePackage && shareItem.shareConfig.singleton === true;
|
|
1162
1198
|
const namedExports = getSharedNamedExports(pkg, shareItem);
|
|
1163
1199
|
let exportLine;
|
|
1164
|
-
|
|
1200
|
+
let initBlock = "";
|
|
1201
|
+
if (usesLazyLocalFallback) {
|
|
1202
|
+
importLine = `${getRuntimeInitPromiseBootstrapCode()}\n ${importLine}`;
|
|
1203
|
+
exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheKey, command !== "build");
|
|
1204
|
+
} else if (namedExports.length > 0) {
|
|
1165
1205
|
const destructure = `const { ${namedExports.map((name, i) => `${name}: __mf_${i}`).join(", ")} } = exportModule;`;
|
|
1166
1206
|
const namedExportLine = `export { ${namedExports.map((name, i) => `__mf_${i} as ${name}`).join(", ")} };`;
|
|
1167
1207
|
exportLine = `const __mfDefaultExport = (() => {
|
|
@@ -1174,23 +1214,33 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown) {
|
|
|
1174
1214
|
export default __mfDefaultExport;
|
|
1175
1215
|
${destructure}
|
|
1176
1216
|
${namedExportLine}`;
|
|
1177
|
-
|
|
1178
|
-
|
|
1217
|
+
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
1218
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
|
|
1219
|
+
} else {
|
|
1220
|
+
exportLine = `export default exportModule.default ?? exportModule\n export * from ${escapeGeneratedStringLiteral(sharedImportSource)}`;
|
|
1221
|
+
initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
1222
|
+
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`;
|
|
1223
|
+
}
|
|
1179
1224
|
const prebuildImportLine = usesLazyLocalFallback || isWorkspacePackage && command !== "build" ? "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
|
|
1180
1225
|
const devDynamicImportLine = isWorkspacePackage ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
|
|
1181
|
-
|
|
1226
|
+
const moduleBody = usesLazyLocalFallback ? `
|
|
1227
|
+
${prebuildImportLine}
|
|
1228
|
+
${devDynamicImportLine}
|
|
1229
|
+
${importLine}
|
|
1230
|
+
${normalizeLocalShareModuleCode}
|
|
1231
|
+
${exportLine}
|
|
1232
|
+
` : `
|
|
1182
1233
|
${prebuildImportLine}
|
|
1183
1234
|
${devDynamicImportLine}
|
|
1184
1235
|
${importLine}
|
|
1185
1236
|
${normalizeLocalShareModuleCode}
|
|
1186
1237
|
let exportModule = __mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}]
|
|
1187
1238
|
if (exportModule === undefined) {
|
|
1188
|
-
${
|
|
1189
|
-
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;` : `exportModule = __mfNormalizeShareModule(__mfLocalShare);
|
|
1190
|
-
__mfModuleCache.share[${escapeGeneratedStringLiteral(cacheKey)}] = exportModule;`}
|
|
1239
|
+
${initBlock}
|
|
1191
1240
|
}
|
|
1192
1241
|
${exportLine}
|
|
1193
|
-
|
|
1242
|
+
`;
|
|
1243
|
+
loadShareCacheMap[pkg].writeSync(moduleBody, true);
|
|
1194
1244
|
}
|
|
1195
1245
|
//#endregion
|
|
1196
1246
|
//#region src/virtualModules/virtualRemoteEntry.ts
|
|
@@ -1618,11 +1668,12 @@ function getHostAutoInitPath() {
|
|
|
1618
1668
|
//#region src/virtualModules/virtualRemotes.ts
|
|
1619
1669
|
const cacheRemoteMap = {};
|
|
1620
1670
|
const LOAD_REMOTE_TAG = "__loadRemote__";
|
|
1621
|
-
function getRemoteVirtualModule(remote, command, enableSsrInit = false) {
|
|
1622
|
-
const
|
|
1671
|
+
function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer = "unified") {
|
|
1672
|
+
const { shareStrategy } = getNormalizeModuleFederationOptions();
|
|
1673
|
+
const cacheKey = `${remote}__${command}__${shareStrategy}__${consumer}__${enableSsrInit ? "ssr-init" : "no-ssr-init"}`;
|
|
1623
1674
|
if (!cacheRemoteMap[cacheKey]) {
|
|
1624
|
-
cacheRemoteMap[cacheKey] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".
|
|
1625
|
-
cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit));
|
|
1675
|
+
cacheRemoteMap[cacheKey] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
|
|
1676
|
+
cacheRemoteMap[cacheKey].writeSync(generateRemotes(remote, command, enableSsrInit, consumer));
|
|
1626
1677
|
}
|
|
1627
1678
|
return cacheRemoteMap[cacheKey];
|
|
1628
1679
|
}
|
|
@@ -1638,131 +1689,89 @@ function getRemoteFromId(id, remotes) {
|
|
|
1638
1689
|
const remoteName = Object.keys(remotes).filter((name) => id === name || id.startsWith(name + "/")).sort((a, b) => b.length - a.length)[0];
|
|
1639
1690
|
return remoteName ? remotes[remoteName] : void 0;
|
|
1640
1691
|
}
|
|
1641
|
-
function
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
|
|
1647
|
-
entryGlobalName: remote.entryGlobalName,
|
|
1648
|
-
name: remote.name,
|
|
1649
|
-
type: remote.type,
|
|
1650
|
-
entry: remote.entry,
|
|
1651
|
-
shareScope: remote.shareScope ?? "default"
|
|
1652
|
-
})}]);` : "";
|
|
1653
|
-
const reactImportLine = useReactProxy ? `import __mfReactDefault from "react";
|
|
1654
|
-
import * as __mfReactNamespace from "react";
|
|
1655
|
-
const __mfReact = __mfReactDefault ?? __mfReactNamespace.default ?? __mfReactNamespace;` : "";
|
|
1656
|
-
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
|
|
1657
|
-
import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${getRuntimeInitBootstrapCode(enableSsrInit)}
|
|
1658
|
-
const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];
|
|
1659
|
-
if (typeof window !== "undefined") {
|
|
1660
|
-
import(${JSON.stringify(getHostAutoInitPath())})
|
|
1661
|
-
.then((mod) => mod.hostInitPromise)
|
|
1662
|
-
.then(initResolve, initReject);
|
|
1663
|
-
}`;
|
|
1664
|
-
const exportLine = command === "serve" ? `if (__mfRemotePending) {
|
|
1665
|
-
__mfRemotePending = __mfRemotePending.then((mod) => {
|
|
1666
|
-
if (mod !== undefined) exportModule = mod;
|
|
1667
|
-
return exportModule;
|
|
1668
|
-
});
|
|
1692
|
+
function resolveRemoteInitMode(shareStrategy, consumer) {
|
|
1693
|
+
if (shareStrategy !== "loaded-first") return "eager";
|
|
1694
|
+
if (consumer === "server") return "loaded-first-ssr";
|
|
1695
|
+
if (consumer === "client") return "loaded-first-client";
|
|
1696
|
+
return "loaded-first-unified";
|
|
1669
1697
|
}
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?.__esModule ? exportModule.default : exportModule.default ?? exportModule` : command === "build" ? `if (__mfRemotePending) {
|
|
1673
|
-
__mfRemotePending = __mfRemotePending.then((mod) => {
|
|
1674
|
-
if (mod !== undefined) exportModule = mod;
|
|
1675
|
-
return exportModule;
|
|
1676
|
-
});
|
|
1698
|
+
function shouldDeferRemoteLoad(initMode) {
|
|
1699
|
+
return initMode === "loaded-first-client" || initMode === "loaded-first-unified";
|
|
1677
1700
|
}
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1701
|
+
/** Dev SSR only — build/preview client graphs must keep deferred proxies for static imports. */
|
|
1702
|
+
function clientNeedsRealRemoteForHydration(command, enableSsrInit) {
|
|
1703
|
+
return enableSsrInit && command === "serve";
|
|
1704
|
+
}
|
|
1705
|
+
function shouldIncludeDeferredProxy(initMode, consumer, clientNeedsRealRemote, deferRemoteLoad) {
|
|
1706
|
+
if (initMode === "eager") return consumer !== "server" && (consumer === "unified" || !clientNeedsRealRemote);
|
|
1707
|
+
if (consumer === "client" && clientNeedsRealRemote) return false;
|
|
1708
|
+
return deferRemoteLoad || consumer !== "server";
|
|
1709
|
+
}
|
|
1710
|
+
/** Codegen shared by every remote virtual module (no top-level await). */
|
|
1711
|
+
function getRemoteModuleRuntimeHelpers() {
|
|
1688
1712
|
return `
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
return runtime.loadRemote(${JSON.stringify(id)});
|
|
1700
|
-
})
|
|
1701
|
-
.then((mod) => {
|
|
1702
|
-
__mfModuleCache.remote[${JSON.stringify(id)}] = mod;
|
|
1703
|
-
delete __mfModuleCache.remote[pendingKey];
|
|
1704
|
-
return mod;
|
|
1705
|
-
})
|
|
1706
|
-
${remoteLoadFailureHandler};
|
|
1707
|
-
}
|
|
1708
|
-
return __mfModuleCache.remote[pendingKey];`}
|
|
1713
|
+
function __mfUnwrapRemoteDefault(mod) {
|
|
1714
|
+
if (mod == null) return mod;
|
|
1715
|
+
if (mod.__esModule && mod.default != null) return mod.default;
|
|
1716
|
+
return mod.default ?? mod;
|
|
1717
|
+
}
|
|
1718
|
+
let __mfDefaultExport;
|
|
1719
|
+
function __mfSyncDefaultExport() {
|
|
1720
|
+
__mfDefaultExport = exportModule?.__mf_is_remote_proxy
|
|
1721
|
+
? exportModule
|
|
1722
|
+
: __mfUnwrapRemoteDefault(exportModule);
|
|
1709
1723
|
}
|
|
1710
|
-
function
|
|
1711
|
-
|
|
1724
|
+
function __mfAssignRemoteModule(mod) {
|
|
1725
|
+
if (mod !== undefined) exportModule = mod;
|
|
1726
|
+
__mfSyncDefaultExport();
|
|
1727
|
+
return exportModule;
|
|
1728
|
+
}`;
|
|
1729
|
+
}
|
|
1730
|
+
function getDeferredProxyHelper(remoteId) {
|
|
1731
|
+
return `
|
|
1732
|
+
function __mfCreateDeferredRemoteProxy() {
|
|
1733
|
+
let pendingPromise;
|
|
1712
1734
|
const ensurePending = () => {
|
|
1713
1735
|
pendingPromise ||= __mfStartRemoteLoad();
|
|
1714
|
-
pendingPromise?.finally(() => {
|
|
1715
|
-
for (const listener of listeners) listener();
|
|
1716
|
-
});
|
|
1717
1736
|
return pendingPromise;
|
|
1718
1737
|
};
|
|
1719
|
-
const getModule = () => __mfModuleCache.remote[${JSON.stringify(
|
|
1738
|
+
const getModule = () => __mfModuleCache.remote[${JSON.stringify(remoteId)}];
|
|
1720
1739
|
const proxyTarget = function (...args) {
|
|
1721
|
-
|
|
1722
|
-
__mfReact.useEffect(() => {
|
|
1723
|
-
ensurePending();
|
|
1724
|
-
const listener = () => setVersion((value) => value + 1);
|
|
1725
|
-
listeners.add(listener);
|
|
1726
|
-
if (getModule()) listener();
|
|
1727
|
-
return () => listeners.delete(listener);
|
|
1728
|
-
}, []);` : ""}
|
|
1740
|
+
pendingPromise ||= __mfStartRemoteLoad();
|
|
1729
1741
|
const mod = getModule();
|
|
1730
1742
|
const fn = mod && (mod.default ?? mod);
|
|
1731
1743
|
if (fn !== undefined && fn !== null) {
|
|
1732
|
-
|
|
1744
|
+
return fn.apply(this, args);
|
|
1733
1745
|
}
|
|
1734
|
-
|
|
1746
|
+
return null;
|
|
1735
1747
|
};
|
|
1736
1748
|
return new Proxy(proxyTarget, {
|
|
1737
1749
|
get(_target, prop) {
|
|
1738
1750
|
if (prop === "__mf_is_remote_proxy") return true;
|
|
1739
1751
|
if (prop === "__esModule") return true;
|
|
1740
1752
|
if (prop === "then") return undefined;
|
|
1741
|
-
// Allow React's dev-mode console.warn to stringify the proxy without
|
|
1742
|
-
// throwing "Cannot convert object to primitive value".
|
|
1743
1753
|
if (prop === Symbol.toPrimitive || prop === "toString")
|
|
1744
|
-
return () => "[MF remote
|
|
1754
|
+
return () => "[MF remote: pending]";
|
|
1745
1755
|
const mod = getModule();
|
|
1746
1756
|
if (mod) {
|
|
1747
1757
|
return prop in mod ? mod[prop] : mod.default?.[prop];
|
|
1748
1758
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
${useReactProxy ? `if (prop === "default") return proxyTarget;
|
|
1753
|
-
return undefined;` : `throw ensurePending();`}
|
|
1759
|
+
pendingPromise ||= __mfStartRemoteLoad();
|
|
1760
|
+
if (prop === "default") return proxyTarget;
|
|
1761
|
+
throw ensurePending();
|
|
1754
1762
|
},
|
|
1755
1763
|
has(_target, prop) {
|
|
1756
1764
|
const mod = getModule();
|
|
1757
1765
|
if (mod) return prop in mod;
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1766
|
+
return (
|
|
1767
|
+
prop === "default" ||
|
|
1768
|
+
prop === "__esModule" ||
|
|
1769
|
+
prop === "__mf_is_remote_proxy"
|
|
1770
|
+
);
|
|
1761
1771
|
},
|
|
1762
1772
|
ownKeys() {
|
|
1763
1773
|
const mod = getModule();
|
|
1764
1774
|
const keys = new Set(mod ? Reflect.ownKeys(mod) : []);
|
|
1765
|
-
// Proxy invariant: must include non-configurable target own keys
|
|
1766
1775
|
for (const k of Reflect.ownKeys(proxyTarget)) {
|
|
1767
1776
|
const d = Object.getOwnPropertyDescriptor(proxyTarget, k);
|
|
1768
1777
|
if (d && !d.configurable) keys.add(k);
|
|
@@ -1770,7 +1779,6 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
|
|
|
1770
1779
|
return Array.from(keys);
|
|
1771
1780
|
},
|
|
1772
1781
|
getOwnPropertyDescriptor(_target, prop) {
|
|
1773
|
-
// Proxy invariant: non-configurable target props must be reported accurately
|
|
1774
1782
|
const targetDesc = Object.getOwnPropertyDescriptor(proxyTarget, prop);
|
|
1775
1783
|
if (targetDesc && !targetDesc.configurable) return targetDesc;
|
|
1776
1784
|
const mod = getModule();
|
|
@@ -1785,14 +1793,118 @@ export default exportModule?.__mf_is_remote_proxy ? exportModule : exportModule?
|
|
|
1785
1793
|
return target.apply(thisArg, args);
|
|
1786
1794
|
}
|
|
1787
1795
|
});
|
|
1788
|
-
}
|
|
1796
|
+
}`;
|
|
1797
|
+
}
|
|
1798
|
+
function getLazyRemotePendingExport() {
|
|
1799
|
+
return `export const __mf_remote_pending = __mfRemotePending ?? {
|
|
1800
|
+
then(onFulfilled, onRejected) {
|
|
1801
|
+
return (__mfRemotePending ??= __mfStartRemoteLoad().then(__mfAssignRemoteModule)).then(onFulfilled, onRejected);
|
|
1802
|
+
},
|
|
1803
|
+
};`;
|
|
1804
|
+
}
|
|
1805
|
+
function getEagerRemotePendingExport() {
|
|
1806
|
+
return `export const __mf_remote_pending =
|
|
1807
|
+
__mfRemotePending ??
|
|
1808
|
+
__mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
|
|
1809
|
+
}
|
|
1810
|
+
function getServerThenExport() {
|
|
1811
|
+
return `export function then(onFulfilled, onRejected) {
|
|
1812
|
+
return (__mfRemotePending ?? Promise.resolve(exportModule))
|
|
1813
|
+
.then(__mfAssignRemoteModule)
|
|
1814
|
+
.then(() => {
|
|
1815
|
+
__mfSyncDefaultExport();
|
|
1816
|
+
return {
|
|
1817
|
+
...exportModule,
|
|
1818
|
+
default: __mfDefaultExport,
|
|
1819
|
+
__moduleExports: exportModule,
|
|
1820
|
+
__mf_remote_pending: __mfRemotePending,
|
|
1821
|
+
};
|
|
1822
|
+
})
|
|
1823
|
+
.then(onFulfilled, onRejected);
|
|
1824
|
+
}`;
|
|
1825
|
+
}
|
|
1826
|
+
function getRemoteExportBlock(command, deferRemoteLoad, consumer) {
|
|
1827
|
+
if (command !== "serve" && command !== "build") return `__mfSyncDefaultExport();
|
|
1828
|
+
export { __mfDefaultExport as default };`;
|
|
1829
|
+
return `__mfSyncDefaultExport();
|
|
1830
|
+
__mfRemotePending?.then(__mfSyncDefaultExport);
|
|
1831
|
+
export { exportModule as __moduleExports };
|
|
1832
|
+
${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()}
|
|
1833
|
+
${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
|
|
1834
|
+
export { __mfDefaultExport as default };`;
|
|
1835
|
+
}
|
|
1836
|
+
function generateRemotes(id, command, enableSsrInit = false, consumer = "unified") {
|
|
1837
|
+
const options = getNormalizeModuleFederationOptions();
|
|
1838
|
+
const isLoadedFirst = options.shareStrategy === "loaded-first";
|
|
1839
|
+
const initMode = resolveRemoteInitMode(options.shareStrategy, consumer);
|
|
1840
|
+
const deferRemoteLoad = shouldDeferRemoteLoad(initMode);
|
|
1841
|
+
const remote = getRemoteFromId(id, options.remotes);
|
|
1842
|
+
const registerRemoteCode = isLoadedFirst && remote ? `runtime.registerRemotes([${JSON.stringify({
|
|
1843
|
+
entryGlobalName: remote.entryGlobalName,
|
|
1844
|
+
name: remote.name,
|
|
1845
|
+
type: remote.type,
|
|
1846
|
+
entry: remote.entry,
|
|
1847
|
+
shareScope: remote.shareScope ?? "default"
|
|
1848
|
+
})}]);` : "";
|
|
1849
|
+
const browserHostInitCode = `import(${JSON.stringify(getHostAutoInitPath())})
|
|
1850
|
+
.then((mod) => mod.hostInitPromise)
|
|
1851
|
+
.then(initResolve, initReject);`;
|
|
1852
|
+
const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getHostAutoInitPath())}
|
|
1853
|
+
const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
|
|
1854
|
+
const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
|
|
1855
|
+
import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(getHostAutoInitPath())};` : `${devRuntimeBootstrap}
|
|
1856
|
+
${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
|
|
1857
|
+
const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
|
|
1858
|
+
const remoteLoadFailureHandler = command === "build" ? `.catch((error) => {
|
|
1859
|
+
delete __mfModuleCache.remote[pendingKey];
|
|
1860
|
+
throw error;
|
|
1861
|
+
})` : `.catch(() => {
|
|
1862
|
+
delete __mfModuleCache.remote[pendingKey];
|
|
1863
|
+
})`;
|
|
1864
|
+
const remoteLoadCode = `
|
|
1865
|
+
function __mfStartRemoteLoad() {
|
|
1866
|
+
${`
|
|
1867
|
+
const pendingKey = ${JSON.stringify(`__mf_pending__${id}`)};
|
|
1868
|
+
if (!__mfModuleCache.remote[pendingKey]) {
|
|
1869
|
+
__mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
|
|
1870
|
+
.then((runtime) => {
|
|
1871
|
+
${registerRemoteCode}
|
|
1872
|
+
return runtime.loadRemote(${JSON.stringify(id)});
|
|
1873
|
+
})
|
|
1874
|
+
.then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
|
|
1875
|
+
.then((mod) => {
|
|
1876
|
+
__mfModuleCache.remote[${JSON.stringify(id)}] = mod;
|
|
1877
|
+
delete __mfModuleCache.remote[pendingKey];
|
|
1878
|
+
return mod;
|
|
1879
|
+
})
|
|
1880
|
+
${remoteLoadFailureHandler};
|
|
1881
|
+
}
|
|
1882
|
+
return __mfModuleCache.remote[pendingKey];`}
|
|
1883
|
+
}`;
|
|
1884
|
+
const realRemoteInit = `__mfRemotePending = __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
|
|
1885
|
+
const deferredClientInit = `exportModule = __mfCreateDeferredRemoteProxy();`;
|
|
1886
|
+
const clientNeedsRealRemote = clientNeedsRealRemoteForHydration(command, enableSsrInit);
|
|
1887
|
+
const eagerClientInit = clientNeedsRealRemote ? realRemoteInit : deferredClientInit;
|
|
1888
|
+
const loadedFirstClientInit = clientNeedsRealRemote ? realRemoteInit : deferredClientInit;
|
|
1889
|
+
const environmentSplitInit = (clientInit, serverInit) => consumer === "client" ? clientInit : consumer === "server" ? serverInit : `if (typeof window === "undefined") {
|
|
1890
|
+
${serverInit}
|
|
1891
|
+
} else {
|
|
1892
|
+
${clientInit}
|
|
1893
|
+
}`;
|
|
1894
|
+
const initExportModule = initMode === "eager" ? environmentSplitInit(eagerClientInit, realRemoteInit) : environmentSplitInit(loadedFirstClientInit, realRemoteInit);
|
|
1895
|
+
const includeProxyHelper = shouldIncludeDeferredProxy(initMode, consumer, clientNeedsRealRemote, deferRemoteLoad);
|
|
1896
|
+
const deferredProxyCode = getDeferredProxyHelper(id);
|
|
1897
|
+
return `
|
|
1898
|
+
${importLine}
|
|
1899
|
+
${remoteLoadCode}
|
|
1900
|
+
${includeProxyHelper ? deferredProxyCode : ""}
|
|
1901
|
+
${getRemoteModuleRuntimeHelpers()}
|
|
1789
1902
|
let __mfRemotePending;
|
|
1790
1903
|
let exportModule = __mfModuleCache.remote[${JSON.stringify(id)}]
|
|
1791
1904
|
if (exportModule === undefined) {
|
|
1792
|
-
|
|
1793
|
-
exportModule = __mfCreateRemoteProxy(__mfRemotePending);
|
|
1905
|
+
${initExportModule}
|
|
1794
1906
|
}
|
|
1795
|
-
${
|
|
1907
|
+
${getRemoteExportBlock(command, deferRemoteLoad, consumer)}
|
|
1796
1908
|
`;
|
|
1797
1909
|
}
|
|
1798
1910
|
//#endregion
|
|
@@ -1846,6 +1958,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1846
1958
|
let clientInjected = forceClientInjected ?? false;
|
|
1847
1959
|
let emittedFileName;
|
|
1848
1960
|
let skipTransformIds = /* @__PURE__ */ new Set();
|
|
1961
|
+
let bootstrapDir = "";
|
|
1849
1962
|
function skipSvelteKitSsrBuild() {
|
|
1850
1963
|
return (_command === "build" || viteConfig?.command === "build") && viteConfig?.build?.ssr && hasPackageDependency("@sveltejs/kit");
|
|
1851
1964
|
}
|
|
@@ -1858,6 +1971,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1858
1971
|
function rewriteSvelteKitInlineStart(html, initPath) {
|
|
1859
1972
|
return html.replace(/<script>([\s\S]*?)<\/script>/gi, (scriptTag, body) => {
|
|
1860
1973
|
if (!body.includes("kit.start(app, element);") || !body.includes("Promise.all([")) return scriptTag;
|
|
1974
|
+
if (body.includes("initHost")) return scriptTag;
|
|
1861
1975
|
const blockStart = body.indexOf("{");
|
|
1862
1976
|
const blockEnd = body.lastIndexOf("}");
|
|
1863
1977
|
if (blockStart === -1 || blockEnd <= blockStart) return scriptTag;
|
|
@@ -1881,7 +1995,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1881
1995
|
return walkFiles(dir, (fileName) => fileName.endsWith(".html"));
|
|
1882
1996
|
}
|
|
1883
1997
|
function toRelativeImport(fromFile, targetFile) {
|
|
1884
|
-
const relative = path$1.relative(path$1.dirname(fromFile), targetFile)
|
|
1998
|
+
const relative = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), targetFile));
|
|
1885
1999
|
return relative.startsWith(".") ? relative : `./${relative}`;
|
|
1886
2000
|
}
|
|
1887
2001
|
function patchSvelteKitStaticHtml() {
|
|
@@ -1903,14 +2017,14 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
1903
2017
|
}
|
|
1904
2018
|
return patched;
|
|
1905
2019
|
}
|
|
1906
|
-
function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false) {
|
|
2020
|
+
function getBootstrapSource(initSrc, entrySrc, useSystemImportFallback = false, options) {
|
|
1907
2021
|
const importHelper = useSystemImportFallback ? `const __mfImport = (src) =>
|
|
1908
2022
|
globalThis.System && typeof globalThis.System.import === 'function'
|
|
1909
2023
|
? globalThis.System.import(src)
|
|
1910
2024
|
: import(src);
|
|
1911
2025
|
` : "";
|
|
1912
2026
|
const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
|
|
1913
|
-
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(",") : "";
|
|
2027
|
+
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(",") : "";
|
|
1914
2028
|
const preloadBlock = remotePreloads ? `
|
|
1915
2029
|
const runtime = await initHost();
|
|
1916
2030
|
const __mfPreloadRemote = (remote) => {
|
|
@@ -2099,6 +2213,8 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
2099
2213
|
if (htmlFileNames.length === 0) return;
|
|
2100
2214
|
const file = this.getFileName(emitFileId);
|
|
2101
2215
|
emittedFileName = file;
|
|
2216
|
+
const lastSlash = file.lastIndexOf("/");
|
|
2217
|
+
bootstrapDir = lastSlash !== -1 ? file.slice(0, lastSlash + 1) : "";
|
|
2102
2218
|
const resolvePath = (htmlFileName) => {
|
|
2103
2219
|
if (!viteConfig.experimental?.renderBuiltUrl) return viteConfig.base + file;
|
|
2104
2220
|
const result = viteConfig.experimental.renderBuiltUrl(file, {
|
|
@@ -2117,6 +2233,8 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
2117
2233
|
}
|
|
2118
2234
|
return viteConfig.base + file;
|
|
2119
2235
|
};
|
|
2236
|
+
const basePrefix = viteConfig.base?.replace(/\/$/, "") ?? "";
|
|
2237
|
+
const stripBase = (p) => basePrefix && p.startsWith(basePrefix + "/") ? p.slice(basePrefix.length) : p;
|
|
2120
2238
|
let bootstrapIndex = 0;
|
|
2121
2239
|
for (const fileName of htmlFileNames) {
|
|
2122
2240
|
let htmlAsset = bundle[fileName];
|
|
@@ -2127,9 +2245,11 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
2127
2245
|
let rewritten = false;
|
|
2128
2246
|
htmlContent = htmlContent.replace(scriptRegex, (scriptTag, entrySrc) => {
|
|
2129
2247
|
rewritten = true;
|
|
2130
|
-
const
|
|
2248
|
+
const strippedInit = stripBase(initPath);
|
|
2249
|
+
const strippedEntry = stripBase(entrySrc);
|
|
2250
|
+
const bootstrapSource = getSystemBootstrapSource(bootstrapDir ? rebaseImport(strippedInit, bootstrapDir) : initPath, bootstrapDir ? rebaseImport(strippedEntry, bootstrapDir) : entrySrc);
|
|
2131
2251
|
const bootstrapHash = createHash("sha256").update(bootstrapSource).digest("hex").slice(0, 8);
|
|
2132
|
-
const bootstrapFileName =
|
|
2252
|
+
const bootstrapFileName = `${bootstrapDir}mf-entry-bootstrap-${bootstrapIndex++}-${bootstrapHash}.js`;
|
|
2133
2253
|
const bootstrapRef = this.emitFile({
|
|
2134
2254
|
type: "asset",
|
|
2135
2255
|
fileName: bootstrapFileName,
|
|
@@ -2192,12 +2312,13 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
|
|
|
2192
2312
|
return mapCodeToCodeWithSourcemap(code.replace("vueApp.mount(vueAppRootContainer);", `${injection}vueApp.mount(vueAppRootContainer);`));
|
|
2193
2313
|
}
|
|
2194
2314
|
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);
|
|
2195
|
-
const
|
|
2196
|
-
|
|
2315
|
+
const isNuxtEntryAsyncModule = /(?:^|\/)nuxt\/dist\/app\/entry\.async\.js(?:\?|$)/.test(id) && code.includes("entry();");
|
|
2316
|
+
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);
|
|
2317
|
+
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)) {
|
|
2197
2318
|
clientInjected = true;
|
|
2198
2319
|
if (!waitsForInit || _command === "serve" && inject === "entry" && isHydrationEntryFallback) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
|
|
2199
2320
|
const entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
|
|
2200
|
-
return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc));
|
|
2321
|
+
return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
|
|
2201
2322
|
}
|
|
2202
2323
|
}
|
|
2203
2324
|
}];
|
|
@@ -2248,17 +2369,35 @@ function checkAliasConflicts(options) {
|
|
|
2248
2369
|
}
|
|
2249
2370
|
//#endregion
|
|
2250
2371
|
//#region src/plugins/hmr/react.ts
|
|
2372
|
+
const REACT_REFRESH_PATH = "/@react-refresh";
|
|
2373
|
+
const LOCAL_REACT_REFRESH_PATH = "/@mf-react-refresh-local";
|
|
2374
|
+
function stripQuery(url) {
|
|
2375
|
+
return url?.replace(/\?.*$/, "");
|
|
2376
|
+
}
|
|
2377
|
+
function resolveReactRefreshRuntime(root) {
|
|
2378
|
+
const reactPluginEntry = createRequire(pathToFileURL$1(path.join(root, "package.json"))).resolve("@vitejs/plugin-react");
|
|
2379
|
+
const requireFromReactPlugin = createRequire(reactPluginEntry);
|
|
2380
|
+
const reactPluginRoot = path.dirname(reactPluginEntry);
|
|
2381
|
+
const runtimePath = path.join(reactPluginRoot, "refresh-runtime.js");
|
|
2382
|
+
const refreshUtilsPath = path.join(reactPluginRoot, "refreshUtils.js");
|
|
2383
|
+
if (existsSync$1(runtimePath)) return readFileSync$1(runtimePath, "utf-8");
|
|
2384
|
+
const reactRefreshDir = path.dirname(requireFromReactPlugin.resolve("react-refresh/package.json"));
|
|
2385
|
+
return [
|
|
2386
|
+
"const exports = {}",
|
|
2387
|
+
readFileSync$1(path.join(reactRefreshDir, "cjs/react-refresh-runtime.development.js"), "utf-8"),
|
|
2388
|
+
readFileSync$1(refreshUtilsPath, "utf-8"),
|
|
2389
|
+
"export default exports"
|
|
2390
|
+
].join("\n");
|
|
2391
|
+
}
|
|
2251
2392
|
/**
|
|
2252
2393
|
* Proxy module served for `/@react-refresh` on MF remote dev servers.
|
|
2253
|
-
* Delegates to the host page's RefreshRuntime
|
|
2254
|
-
*
|
|
2255
|
-
* across federation boundaries. A `configureServer` middleware is used
|
|
2256
|
-
* instead of `resolveId` because `@vitejs/plugin-react`'s
|
|
2257
|
-
* `vite:react-refresh` sub-plugin uses `enforce: 'pre'` and typically
|
|
2258
|
-
* wins the `resolveId` race.
|
|
2394
|
+
* Delegates to the host page's RefreshRuntime when consumed by a host, but
|
|
2395
|
+
* falls back to this remote's local runtime when the remote is opened directly.
|
|
2259
2396
|
*/
|
|
2260
2397
|
const REACT_REFRESH_PROXY_MODULE = [
|
|
2261
|
-
`const
|
|
2398
|
+
`const __remoteOrigin = new URL(import.meta.url).origin;`,
|
|
2399
|
+
`const __target = window.location.origin === __remoteOrigin ? '${LOCAL_REACT_REFRESH_PATH}' : window.location.origin + '${REACT_REFRESH_PATH}';`,
|
|
2400
|
+
`const __rt = await import(__target);`,
|
|
2262
2401
|
`export const injectIntoGlobalHook = __rt.injectIntoGlobalHook;`,
|
|
2263
2402
|
`export const register = __rt.register;`,
|
|
2264
2403
|
`export const createSignatureFunctionForTransform = __rt.createSignatureFunctionForTransform;`,
|
|
@@ -2271,8 +2410,17 @@ const reactAdapter = {
|
|
|
2271
2410
|
name: "react",
|
|
2272
2411
|
pluginNames: ["vite:react-refresh", "vite:react-swc:refresh"],
|
|
2273
2412
|
remote: { configureServer({ server }) {
|
|
2413
|
+
let reactRefreshRuntime;
|
|
2274
2414
|
server.middlewares.use((req, res, next) => {
|
|
2275
|
-
|
|
2415
|
+
const url = stripQuery(req.url);
|
|
2416
|
+
if (url === LOCAL_REACT_REFRESH_PATH) {
|
|
2417
|
+
reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
|
|
2418
|
+
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
2419
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
2420
|
+
res.end(reactRefreshRuntime);
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
if (url !== REACT_REFRESH_PATH) return next();
|
|
2276
2424
|
res.setHeader("Content-Type", "application/javascript; charset=utf-8");
|
|
2277
2425
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
2278
2426
|
res.end(REACT_REFRESH_PROXY_MODULE);
|
|
@@ -2697,7 +2845,7 @@ function pluginDevRemoteHmr(options) {
|
|
|
2697
2845
|
function initVirtualModules(command, remoteEntryId, enableSsrInit = false) {
|
|
2698
2846
|
writeLocalSharedImportMap();
|
|
2699
2847
|
writeHostAutoInit(remoteEntryId, command);
|
|
2700
|
-
writeRuntimeInitStatus(command, enableSsrInit);
|
|
2848
|
+
writeRuntimeInitStatus(command, enableSsrInit, getHostAutoInitPath());
|
|
2701
2849
|
}
|
|
2702
2850
|
//#endregion
|
|
2703
2851
|
//#region src/utils/bundleHelpers.ts
|
|
@@ -2963,11 +3111,11 @@ const processModuleAssets = (bundle, filesMap, moduleMatcher, options = {}) => {
|
|
|
2963
3111
|
if (fileData.type !== "chunk") continue;
|
|
2964
3112
|
if (!fileData.modules) continue;
|
|
2965
3113
|
for (const modulePath of Object.keys(fileData.modules)) {
|
|
2966
|
-
const comparableModulePath = options.root ? path.resolve(options.root, modulePath) : modulePath;
|
|
3114
|
+
const comparableModulePath = options.root ? path$1.resolve(options.root, modulePath) : modulePath;
|
|
2967
3115
|
const comparableModulePaths = [comparableModulePath];
|
|
2968
3116
|
if (options.stripKnownJsExtensions) {
|
|
2969
|
-
const ext = path.extname(comparableModulePath);
|
|
2970
|
-
if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path.join(path.dirname(comparableModulePath), path.basename(comparableModulePath, ext)));
|
|
3117
|
+
const ext = path$1.extname(comparableModulePath);
|
|
3118
|
+
if (JS_EXTENSIONS.includes(ext)) comparableModulePaths.push(path$1.join(path$1.dirname(comparableModulePath), path$1.basename(comparableModulePath, ext)));
|
|
2971
3119
|
}
|
|
2972
3120
|
const matchKey = comparableModulePaths.map(moduleMatcher).find(Boolean);
|
|
2973
3121
|
if (!matchKey) continue;
|
|
@@ -3260,41 +3408,44 @@ const Manifest = () => {
|
|
|
3260
3408
|
if (req.url?.replace(/\?.*/, "") === (viteConfig.base + mfManifestName).replace(/^\/?/, "/")) {
|
|
3261
3409
|
res.setHeader("Content-Type", "application/json");
|
|
3262
3410
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
metaData: {
|
|
3411
|
+
(async () => {
|
|
3412
|
+
const manifest = await applyManifestAdditionalData({
|
|
3413
|
+
...generateMFManifest({}, disableAssetsAnalyze),
|
|
3414
|
+
id: name,
|
|
3268
3415
|
name,
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3416
|
+
metaData: {
|
|
3417
|
+
name,
|
|
3418
|
+
type: "app",
|
|
3419
|
+
buildInfo: {
|
|
3420
|
+
buildVersion: getBuildVersion(),
|
|
3421
|
+
buildName: name
|
|
3422
|
+
},
|
|
3423
|
+
remoteEntry: {
|
|
3424
|
+
name: filename,
|
|
3425
|
+
path: "",
|
|
3426
|
+
type: "module"
|
|
3427
|
+
},
|
|
3428
|
+
ssrRemoteEntry: {
|
|
3429
|
+
name: getSsrRemoteEntryFileName(filename),
|
|
3430
|
+
path: "/__mf_ssr__/",
|
|
3431
|
+
type: "module"
|
|
3432
|
+
},
|
|
3433
|
+
varRemoteEntry: varFilename ? {
|
|
3434
|
+
name: varFilename,
|
|
3435
|
+
path: "",
|
|
3436
|
+
type: "var"
|
|
3437
|
+
} : void 0,
|
|
3438
|
+
types: {
|
|
3439
|
+
path: "",
|
|
3440
|
+
name: ""
|
|
3441
|
+
},
|
|
3442
|
+
globalName: name,
|
|
3443
|
+
pluginVersion: "0.2.5",
|
|
3444
|
+
publicPath
|
|
3445
|
+
}
|
|
3446
|
+
});
|
|
3447
|
+
res.end(JSON.stringify(manifest));
|
|
3448
|
+
})().catch(next);
|
|
3298
3449
|
} else next();
|
|
3299
3450
|
});
|
|
3300
3451
|
}
|
|
@@ -3339,16 +3490,20 @@ const Manifest = () => {
|
|
|
3339
3490
|
if (mfOptions.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
|
|
3340
3491
|
filesMap = deduplicateAssets(filesMap);
|
|
3341
3492
|
}
|
|
3493
|
+
const manifest = await applyManifestAdditionalData(generateMFManifest(filesMap, disableAssetsAnalyze), void 0);
|
|
3342
3494
|
this.emitFile({
|
|
3343
3495
|
type: "asset",
|
|
3344
3496
|
fileName: mfManifestName,
|
|
3345
|
-
source: JSON.stringify(
|
|
3346
|
-
});
|
|
3347
|
-
if (mfManifestStatsName) this.emitFile({
|
|
3348
|
-
type: "asset",
|
|
3349
|
-
fileName: mfManifestStatsName,
|
|
3350
|
-
source: JSON.stringify(generateMFStats(filesMap, bundle, disableAssetsAnalyze))
|
|
3497
|
+
source: JSON.stringify(manifest)
|
|
3351
3498
|
});
|
|
3499
|
+
if (mfManifestStatsName) {
|
|
3500
|
+
const stats = await applyManifestAdditionalData(generateMFStats(manifest, filesMap, bundle, disableAssetsAnalyze), manifest);
|
|
3501
|
+
this.emitFile({
|
|
3502
|
+
type: "asset",
|
|
3503
|
+
fileName: mfManifestStatsName,
|
|
3504
|
+
source: JSON.stringify(stats)
|
|
3505
|
+
});
|
|
3506
|
+
}
|
|
3352
3507
|
}
|
|
3353
3508
|
}];
|
|
3354
3509
|
/**
|
|
@@ -3447,8 +3602,7 @@ const Manifest = () => {
|
|
|
3447
3602
|
...disableAssetsAnalyze ? {} : { exposes }
|
|
3448
3603
|
};
|
|
3449
3604
|
}
|
|
3450
|
-
function generateMFStats(preloadMap, bundle, disableAssetsAnalyze = false) {
|
|
3451
|
-
const baseManifest = generateMFManifest(preloadMap, disableAssetsAnalyze);
|
|
3605
|
+
function generateMFStats(manifest, preloadMap, bundle, disableAssetsAnalyze = false) {
|
|
3452
3606
|
const bundleSummary = Object.entries(bundle).map(([fileName, chunkOrAsset]) => ({
|
|
3453
3607
|
fileName,
|
|
3454
3608
|
type: chunkOrAsset.type,
|
|
@@ -3456,11 +3610,22 @@ const Manifest = () => {
|
|
|
3456
3610
|
size: typeof chunkOrAsset.code === "string" ? chunkOrAsset.code.length : chunkOrAsset.source?.length || void 0
|
|
3457
3611
|
}));
|
|
3458
3612
|
return {
|
|
3459
|
-
...
|
|
3613
|
+
...manifest,
|
|
3460
3614
|
buildOutput: bundleSummary,
|
|
3461
3615
|
...disableAssetsAnalyze ? {} : { assetAnalysis: preloadMap }
|
|
3462
3616
|
};
|
|
3463
3617
|
}
|
|
3618
|
+
async function applyManifestAdditionalData(stats, manifest) {
|
|
3619
|
+
if (typeof manifestOptions !== "object" || typeof manifestOptions.additionalData !== "function") return stats;
|
|
3620
|
+
return await manifestOptions.additionalData({
|
|
3621
|
+
stats,
|
|
3622
|
+
manifest,
|
|
3623
|
+
pluginOptions: mfOptions,
|
|
3624
|
+
compiler: void 0,
|
|
3625
|
+
compilation: void 0,
|
|
3626
|
+
bundler: "vite"
|
|
3627
|
+
}) || stats;
|
|
3628
|
+
}
|
|
3464
3629
|
};
|
|
3465
3630
|
function getStatsFileName(manifestFileName) {
|
|
3466
3631
|
const parsed = path$1.parse(manifestFileName);
|
|
@@ -3626,7 +3791,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
3626
3791
|
});
|
|
3627
3792
|
if (options.bundleAllCSS) addCssAssetsToAllExports(filesMap, allCssAssets);
|
|
3628
3793
|
const ensureRelativeImportPath = (fromFile, toFile) => {
|
|
3629
|
-
let relativePath = path$1.relative(path$1.dirname(fromFile), toFile);
|
|
3794
|
+
let relativePath = normalizePathForImport(path$1.relative(path$1.dirname(fromFile), toFile));
|
|
3630
3795
|
if (!relativePath.startsWith(".")) relativePath = `./${relativePath}`;
|
|
3631
3796
|
return relativePath;
|
|
3632
3797
|
};
|
|
@@ -3649,6 +3814,40 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
|
|
|
3649
3814
|
};
|
|
3650
3815
|
}
|
|
3651
3816
|
//#endregion
|
|
3817
|
+
//#region src/utils/remoteConsumerTarget.ts
|
|
3818
|
+
function getPluginEnvironmentName(ctx) {
|
|
3819
|
+
if (ctx == null || typeof ctx !== "object") return void 0;
|
|
3820
|
+
const environment = ctx["environment"];
|
|
3821
|
+
if (environment == null || typeof environment !== "object") return void 0;
|
|
3822
|
+
const name = environment["name"];
|
|
3823
|
+
return typeof name === "string" ? name : void 0;
|
|
3824
|
+
}
|
|
3825
|
+
function resolveRemoteConsumer(ctx, hasMultiEnvironment) {
|
|
3826
|
+
if (!hasMultiEnvironment) return "unified";
|
|
3827
|
+
const envName = getPluginEnvironmentName(ctx);
|
|
3828
|
+
if (!envName || envName === "client") return "client";
|
|
3829
|
+
return "server";
|
|
3830
|
+
}
|
|
3831
|
+
//#endregion
|
|
3832
|
+
//#region src/utils/ssrCapabilities.ts
|
|
3833
|
+
/**
|
|
3834
|
+
* Single source of truth for SSR-related feature gates.
|
|
3835
|
+
*
|
|
3836
|
+
* - Vite 8+ dev: ModuleRunner + FetchableDevEnvironment for `/__mf_ssr__/` entries.
|
|
3837
|
+
* - Any Vite major on build/preview: HTTP fetch + temp-file import via ssrEntryLoader.
|
|
3838
|
+
*/
|
|
3839
|
+
function getSsrCapabilities(viteMajor, command, hasRemotes) {
|
|
3840
|
+
if (!hasRemotes) return {
|
|
3841
|
+
enableSsrInitBootstrap: false,
|
|
3842
|
+
injectSsrEntryLoader: false
|
|
3843
|
+
};
|
|
3844
|
+
const supported = command === "build" || command === "serve" && viteMajor >= 8;
|
|
3845
|
+
return {
|
|
3846
|
+
enableSsrInitBootstrap: supported,
|
|
3847
|
+
injectSsrEntryLoader: supported
|
|
3848
|
+
};
|
|
3849
|
+
}
|
|
3850
|
+
//#endregion
|
|
3652
3851
|
//#region src/plugins/pluginProxyRemotes.ts
|
|
3653
3852
|
function isNodeModulesImporter(importer) {
|
|
3654
3853
|
return importer?.includes("/node_modules/") || importer?.includes("\\node_modules\\");
|
|
@@ -3673,13 +3872,15 @@ function pluginProxyRemotes_default(options) {
|
|
|
3673
3872
|
let command;
|
|
3674
3873
|
let root = process.cwd();
|
|
3675
3874
|
let enableSsrInit = false;
|
|
3875
|
+
let hasMultiEnvironment = false;
|
|
3676
3876
|
const { remotes } = options;
|
|
3677
|
-
function resolveRemoteId(source, importer, remoteName) {
|
|
3877
|
+
function resolveRemoteId(pluginContext, source, importer, remoteName) {
|
|
3678
3878
|
if (source === remoteName) {
|
|
3679
3879
|
const installedPackageEntry = getInstalledPackageEntry(source, { cwd: root });
|
|
3680
3880
|
if (installedPackageEntry && (importer === void 0 || isNodeModulesImporter(importer))) return installedPackageEntry;
|
|
3681
3881
|
}
|
|
3682
|
-
const
|
|
3882
|
+
const consumer = resolveRemoteConsumer(pluginContext, hasMultiEnvironment);
|
|
3883
|
+
const remoteModule = getRemoteVirtualModule(source, command, enableSsrInit, consumer);
|
|
3683
3884
|
addUsedRemote(remoteName, source);
|
|
3684
3885
|
refreshHostAutoInit();
|
|
3685
3886
|
return remoteModule.getImportId();
|
|
@@ -3687,6 +3888,9 @@ function pluginProxyRemotes_default(options) {
|
|
|
3687
3888
|
return {
|
|
3688
3889
|
name: "proxyRemotes",
|
|
3689
3890
|
enforce: "pre",
|
|
3891
|
+
applyToEnvironment() {
|
|
3892
|
+
return true;
|
|
3893
|
+
},
|
|
3690
3894
|
config(config, { command: _command }) {
|
|
3691
3895
|
command = _command;
|
|
3692
3896
|
root = config.root || process.cwd();
|
|
@@ -3698,14 +3902,15 @@ function pluginProxyRemotes_default(options) {
|
|
|
3698
3902
|
});
|
|
3699
3903
|
});
|
|
3700
3904
|
},
|
|
3701
|
-
configResolved() {
|
|
3702
|
-
|
|
3905
|
+
configResolved(config) {
|
|
3906
|
+
hasMultiEnvironment = Boolean(config.environments?.ssr);
|
|
3907
|
+
enableSsrInit = getSsrCapabilities(parseInt(version, 10), command, Object.keys(remotes).length > 0).enableSsrInitBootstrap;
|
|
3703
3908
|
},
|
|
3704
3909
|
resolveId(source, importer) {
|
|
3705
3910
|
if (!filterId(source)) return;
|
|
3706
3911
|
for (const remote of Object.values(remotes)) {
|
|
3707
3912
|
if (source !== remote.name && !source.startsWith(`${remote.name}/`)) continue;
|
|
3708
|
-
return resolveRemoteId(source, importer, remote.name);
|
|
3913
|
+
return resolveRemoteId(this, source, importer, remote.name);
|
|
3709
3914
|
}
|
|
3710
3915
|
}
|
|
3711
3916
|
};
|
|
@@ -3747,11 +3952,11 @@ function getPrebuildResolutionSource(pkgName, shareItem) {
|
|
|
3747
3952
|
return getConcreteSharedImportSource(pkgName, shareItem) || pkgName;
|
|
3748
3953
|
}
|
|
3749
3954
|
function tryResolveFromProjectRoot(source) {
|
|
3750
|
-
if (path.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
|
|
3955
|
+
if (path$1.isAbsolute(source) || source.startsWith(".") || source.startsWith("/")) return source;
|
|
3751
3956
|
const browserEntry = getInstalledPackageEntry(source, { cwd: getPackageDetectionCwd() });
|
|
3752
3957
|
if (browserEntry) return browserEntry;
|
|
3753
3958
|
try {
|
|
3754
|
-
return createRequire(
|
|
3959
|
+
return createRequire$1(pathToFileURL(path$1.join(getPackageDetectionCwd(), "package.json"))).resolve(source);
|
|
3755
3960
|
} catch {
|
|
3756
3961
|
return;
|
|
3757
3962
|
}
|
|
@@ -3939,36 +4144,28 @@ function proxySharedModule(options) {
|
|
|
3939
4144
|
];
|
|
3940
4145
|
}
|
|
3941
4146
|
//#endregion
|
|
3942
|
-
//#region src/utils/loadWalk.ts
|
|
3943
|
-
let walkPromise = null;
|
|
3944
|
-
function loadWalk() {
|
|
3945
|
-
walkPromise ||= import("estree-walker").then(({ walk }) => walk);
|
|
3946
|
-
return walkPromise;
|
|
3947
|
-
}
|
|
3948
|
-
//#endregion
|
|
3949
4147
|
//#region src/plugins/pluginRemoteNamedExports.ts
|
|
3950
|
-
/**
|
|
3951
|
-
* Transforms consumer-side imports of remote modules so that named exports
|
|
3952
|
-
* are accessible even when the bundler does not support syntheticNamedExports
|
|
3953
|
-
* (Rolldown / Vite 8+).
|
|
3954
|
-
*
|
|
3955
|
-
* The remote proxy module exports:
|
|
3956
|
-
* export const __moduleExports = exportModule; // full namespace
|
|
3957
|
-
* export default exportModule.default ?? exportModule; // unwrapped default
|
|
3958
|
-
*
|
|
3959
|
-
* This plugin rewrites consumer code:
|
|
3960
|
-
* import { foo } from "remote/xxx"
|
|
3961
|
-
* → import { __moduleExports as __mf_ns_0 } from "remote/xxx"; const { foo } = __mf_ns_0;
|
|
3962
|
-
*
|
|
3963
|
-
* import("remote/xxx")
|
|
3964
|
-
* → import("remote/xxx").then(…) // spreads __moduleExports into namespace
|
|
3965
|
-
*
|
|
3966
|
-
* NOTE: `export * from "remote/xxx"` is not supported — Rolldown cannot
|
|
3967
|
-
* statically resolve the set of exported names from a federated remote at
|
|
3968
|
-
* build time. Use explicit named re-exports instead.
|
|
3969
|
-
*/
|
|
3970
4148
|
const JS_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?|vue|svelte)(?:\?|$)/;
|
|
3971
4149
|
const REGEX_FALLBACK_EXTENSIONS_RE = /\.(?:[mc]?[jt]sx?)(?:\?|$)/;
|
|
4150
|
+
function isAstNode(value) {
|
|
4151
|
+
return !!value && typeof value === "object" && typeof value.type === "string";
|
|
4152
|
+
}
|
|
4153
|
+
function walkAST(root, visitor) {
|
|
4154
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
4155
|
+
function visit(node) {
|
|
4156
|
+
if (!isAstNode(node)) return;
|
|
4157
|
+
if (seen.has(node)) return;
|
|
4158
|
+
seen.add(node);
|
|
4159
|
+
let skipped = false;
|
|
4160
|
+
visitor.enter.call({ skip() {
|
|
4161
|
+
skipped = true;
|
|
4162
|
+
} }, node);
|
|
4163
|
+
if (skipped) return;
|
|
4164
|
+
for (const value of Object.values(node)) if (Array.isArray(value)) for (const item of value) visit(item);
|
|
4165
|
+
else visit(value);
|
|
4166
|
+
}
|
|
4167
|
+
visit(root);
|
|
4168
|
+
}
|
|
3972
4169
|
function parseNamedSpecifiers(specifiersRaw, kind) {
|
|
3973
4170
|
return specifiersRaw.split(",").map((s) => s.trim()).filter((s) => s.length > 0 && !s.startsWith("type ")).map((s) => {
|
|
3974
4171
|
const asMatch = s.match(/^(\w+)\s+as\s+(\w+)$/);
|
|
@@ -3984,7 +4181,7 @@ function parseNamedSpecifiers(specifiersRaw, kind) {
|
|
|
3984
4181
|
});
|
|
3985
4182
|
}
|
|
3986
4183
|
function wrapDynamicImport(original) {
|
|
3987
|
-
return `${original}.then(function(__mf_m__) {\n var
|
|
4184
|
+
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})`;
|
|
3988
4185
|
}
|
|
3989
4186
|
function applyRewrites(code, imports, id) {
|
|
3990
4187
|
if (imports.length === 0) return;
|
|
@@ -3992,6 +4189,7 @@ function applyRewrites(code, imports, id) {
|
|
|
3992
4189
|
let changed = false;
|
|
3993
4190
|
let counter = 0;
|
|
3994
4191
|
let namedProxyHelperDeclared = false;
|
|
4192
|
+
const dependencyPendingIds = [];
|
|
3995
4193
|
const namedProxyHelper = `function __mfCreateNamedRemoteProxy(ns, key) {
|
|
3996
4194
|
const target = function (...args) {
|
|
3997
4195
|
const value = ns[key];
|
|
@@ -4013,12 +4211,18 @@ function applyRewrites(code, imports, id) {
|
|
|
4013
4211
|
for (const imp of imports) switch (imp.kind) {
|
|
4014
4212
|
case "static": {
|
|
4015
4213
|
const src = JSON.stringify(imp.source);
|
|
4016
|
-
if (imp.namespaceLocal && !imp.defaultLocal && imp.named.length === 0)
|
|
4017
|
-
|
|
4214
|
+
if (imp.namespaceLocal && !imp.defaultLocal && imp.named.length === 0) {
|
|
4215
|
+
const pendingId = `${imp.namespaceLocal}__mf_pending`;
|
|
4216
|
+
dependencyPendingIds.push(pendingId);
|
|
4217
|
+
ms.overwrite(imp.start, imp.end, `import { __moduleExports as ${imp.namespaceLocal}, __mf_remote_pending as ${pendingId} } from ${src};`);
|
|
4218
|
+
} else {
|
|
4018
4219
|
const nsId = `__mf_ns_${counter++}`;
|
|
4220
|
+
const pendingId = `${nsId}_pending`;
|
|
4221
|
+
dependencyPendingIds.push(pendingId);
|
|
4019
4222
|
const importParts = [];
|
|
4020
4223
|
if (imp.defaultLocal) importParts.push(`default as ${imp.defaultLocal}`);
|
|
4021
4224
|
importParts.push(`__moduleExports as ${nsId}`);
|
|
4225
|
+
importParts.push(`__mf_remote_pending as ${pendingId}`);
|
|
4022
4226
|
let rewrite = `import { ${importParts.join(", ")} } from ${src};`;
|
|
4023
4227
|
if (imp.named.length > 0) {
|
|
4024
4228
|
const isProxyId = `__mf_is_proxy_${counter++}`;
|
|
@@ -4044,6 +4248,8 @@ function applyRewrites(code, imports, id) {
|
|
|
4044
4248
|
case "reexport": {
|
|
4045
4249
|
const src = JSON.stringify(imp.source);
|
|
4046
4250
|
const nsId = `__mf_ns_${counter++}`;
|
|
4251
|
+
const pendingId = `${nsId}_pending`;
|
|
4252
|
+
dependencyPendingIds.push(pendingId);
|
|
4047
4253
|
const vars = imp.specifiers.map((s) => {
|
|
4048
4254
|
const tmp = `__mf_re_${counter++}`;
|
|
4049
4255
|
return {
|
|
@@ -4051,10 +4257,11 @@ function applyRewrites(code, imports, id) {
|
|
|
4051
4257
|
tmp
|
|
4052
4258
|
};
|
|
4053
4259
|
});
|
|
4054
|
-
const importLine = `import { __moduleExports as ${nsId} } from ${src};`;
|
|
4055
|
-
const varLines = vars.map((v) => `
|
|
4260
|
+
const importLine = `import { __moduleExports as ${nsId}, __mf_remote_pending as ${pendingId} } from ${src};`;
|
|
4261
|
+
const varLines = vars.map((v) => `let ${v.tmp} = ${nsId}[${JSON.stringify(v.local)}];`).join("\n");
|
|
4262
|
+
const syncLine = `${pendingId}.then(() => {\n${vars.map((v) => `${v.tmp} = ${nsId}[${JSON.stringify(v.local)}];`).join("\n")}\n});`;
|
|
4056
4263
|
const exportLine = `export { ${vars.map((v) => `${v.tmp} as ${v.exported}`).join(", ")} };`;
|
|
4057
|
-
ms.overwrite(imp.start, imp.end, `${importLine}\n${varLines}\n${exportLine}`);
|
|
4264
|
+
ms.overwrite(imp.start, imp.end, `${importLine}\n${varLines}\n${syncLine}\n${exportLine}`);
|
|
4058
4265
|
changed = true;
|
|
4059
4266
|
break;
|
|
4060
4267
|
}
|
|
@@ -4067,15 +4274,15 @@ function applyRewrites(code, imports, id) {
|
|
|
4067
4274
|
break;
|
|
4068
4275
|
}
|
|
4069
4276
|
if (!changed) return;
|
|
4277
|
+
if (dependencyPendingIds.length > 0) ms.overwrite(code.length, code.length, `\nexport const __mf_remote_dependency_pending = Promise.all([${dependencyPendingIds.join(", ")}]);`);
|
|
4070
4278
|
return {
|
|
4071
4279
|
code: ms.toString(),
|
|
4072
4280
|
map: ms.generateMap(id)
|
|
4073
4281
|
};
|
|
4074
4282
|
}
|
|
4075
4283
|
async function collectFromAST(ast, code, isRemoteImport) {
|
|
4076
|
-
const walk = await loadWalk();
|
|
4077
4284
|
const result = [];
|
|
4078
|
-
|
|
4285
|
+
walkAST(ast, { enter(node) {
|
|
4079
4286
|
if (node.type === "ImportDeclaration" && node.source?.value) {
|
|
4080
4287
|
if (!isRemoteImport(node.source.value)) return;
|
|
4081
4288
|
const specifiers = node.specifiers || [];
|
|
@@ -4134,86 +4341,11 @@ async function collectFromAST(ast, code, isRemoteImport) {
|
|
|
4134
4341
|
} });
|
|
4135
4342
|
return result;
|
|
4136
4343
|
}
|
|
4137
|
-
async function collectFromEsLexer(code, isRemoteImport) {
|
|
4138
|
-
await init;
|
|
4139
|
-
let imports;
|
|
4140
|
-
try {
|
|
4141
|
-
[imports] = parse(code);
|
|
4142
|
-
} catch {
|
|
4143
|
-
return;
|
|
4144
|
-
}
|
|
4145
|
-
const result = [];
|
|
4146
|
-
for (const imp of imports) {
|
|
4147
|
-
if (imp.d === -2) continue;
|
|
4148
|
-
if (!imp.n || !isRemoteImport(imp.n)) continue;
|
|
4149
|
-
const stmtText = code.slice(imp.ss, imp.se);
|
|
4150
|
-
if (imp.d >= 0) {
|
|
4151
|
-
result.push({
|
|
4152
|
-
kind: "dynamic",
|
|
4153
|
-
start: imp.ss,
|
|
4154
|
-
end: imp.se,
|
|
4155
|
-
originalText: stmtText
|
|
4156
|
-
});
|
|
4157
|
-
continue;
|
|
4158
|
-
}
|
|
4159
|
-
if (/^\s*export\s*\*\s/.test(stmtText)) {
|
|
4160
|
-
result.push({
|
|
4161
|
-
kind: "export-all",
|
|
4162
|
-
source: imp.n,
|
|
4163
|
-
start: imp.ss,
|
|
4164
|
-
end: imp.se
|
|
4165
|
-
});
|
|
4166
|
-
continue;
|
|
4167
|
-
}
|
|
4168
|
-
if (/^\s*export\s/.test(stmtText)) {
|
|
4169
|
-
const braceMatch = stmtText.match(/\{([^}]*)\}/);
|
|
4170
|
-
if (!braceMatch) continue;
|
|
4171
|
-
const specifiers = parseNamedSpecifiers(braceMatch[1], "export");
|
|
4172
|
-
if (specifiers.length === 0) continue;
|
|
4173
|
-
result.push({
|
|
4174
|
-
kind: "reexport",
|
|
4175
|
-
source: imp.n,
|
|
4176
|
-
start: imp.ss,
|
|
4177
|
-
end: imp.se,
|
|
4178
|
-
specifiers
|
|
4179
|
-
});
|
|
4180
|
-
continue;
|
|
4181
|
-
}
|
|
4182
|
-
const importMatch = stmtText.match(/^import\s+([\s\S]*?)\s+from\s/);
|
|
4183
|
-
if (!importMatch) continue;
|
|
4184
|
-
const specifiersPart = importMatch[1].trim();
|
|
4185
|
-
if (/^type\s/.test(specifiersPart)) continue;
|
|
4186
|
-
const nsMatch = specifiersPart.match(/^\*\s+as\s+(\w+)$/);
|
|
4187
|
-
if (nsMatch) {
|
|
4188
|
-
result.push({
|
|
4189
|
-
kind: "static",
|
|
4190
|
-
source: imp.n,
|
|
4191
|
-
start: imp.ss,
|
|
4192
|
-
end: imp.se,
|
|
4193
|
-
named: [],
|
|
4194
|
-
namespaceLocal: nsMatch[1]
|
|
4195
|
-
});
|
|
4196
|
-
continue;
|
|
4197
|
-
}
|
|
4198
|
-
const braceMatch = specifiersPart.match(/\{([^}]*)\}/);
|
|
4199
|
-
if (!braceMatch) continue;
|
|
4200
|
-
const named = parseNamedSpecifiers(braceMatch[1], "import");
|
|
4201
|
-
if (named.length === 0) continue;
|
|
4202
|
-
const defaultMatch = specifiersPart.match(/^(\w+)\s*,/);
|
|
4203
|
-
result.push({
|
|
4204
|
-
kind: "static",
|
|
4205
|
-
source: imp.n,
|
|
4206
|
-
start: imp.ss,
|
|
4207
|
-
end: imp.se,
|
|
4208
|
-
named,
|
|
4209
|
-
defaultLocal: defaultMatch?.[1]
|
|
4210
|
-
});
|
|
4211
|
-
}
|
|
4212
|
-
return result;
|
|
4213
|
-
}
|
|
4214
4344
|
function collectFromRegex(code, isRemoteImport) {
|
|
4215
4345
|
const result = [];
|
|
4216
|
-
|
|
4346
|
+
const importAttributes = String.raw`(?:\s+(?:with|assert)\s+\{[^;]*\})?`;
|
|
4347
|
+
const staticRe = new RegExp(String.raw`^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
|
|
4348
|
+
for (const match of code.matchAll(staticRe)) {
|
|
4217
4349
|
const [full, specifiersPartRaw, , source] = match;
|
|
4218
4350
|
if (!isRemoteImport(source)) continue;
|
|
4219
4351
|
const specifiersPart = specifiersPartRaw.trim();
|
|
@@ -4244,7 +4376,8 @@ function collectFromRegex(code, isRemoteImport) {
|
|
|
4244
4376
|
defaultLocal: defaultMatch?.[1]
|
|
4245
4377
|
});
|
|
4246
4378
|
}
|
|
4247
|
-
|
|
4379
|
+
const reexportRe = new RegExp(String.raw`^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`, "gm");
|
|
4380
|
+
for (const match of code.matchAll(reexportRe)) {
|
|
4248
4381
|
const [full, specifiersRaw, , source] = match;
|
|
4249
4382
|
if (!isRemoteImport(source)) continue;
|
|
4250
4383
|
const specifiers = parseNamedSpecifiers(specifiersRaw, "export");
|
|
@@ -4257,7 +4390,8 @@ function collectFromRegex(code, isRemoteImport) {
|
|
|
4257
4390
|
specifiers
|
|
4258
4391
|
});
|
|
4259
4392
|
}
|
|
4260
|
-
|
|
4393
|
+
const exportAllRe = new RegExp(String.raw`^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1${importAttributes}\s*;?`, "gm");
|
|
4394
|
+
for (const match of code.matchAll(exportAllRe)) {
|
|
4261
4395
|
const [full, , source] = match;
|
|
4262
4396
|
if (!isRemoteImport(source)) continue;
|
|
4263
4397
|
result.push({
|
|
@@ -4267,7 +4401,7 @@ function collectFromRegex(code, isRemoteImport) {
|
|
|
4267
4401
|
end: match.index + full.length
|
|
4268
4402
|
});
|
|
4269
4403
|
}
|
|
4270
|
-
for (const match of code.matchAll(/import\(\s*(['"])([^'"]+)\1\s*\)/g)) {
|
|
4404
|
+
for (const match of code.matchAll(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])([^'"]+)\1\s*\)/g)) {
|
|
4271
4405
|
const [full, , source] = match;
|
|
4272
4406
|
if (!isRemoteImport(source)) continue;
|
|
4273
4407
|
result.push({
|
|
@@ -4302,7 +4436,8 @@ function pluginRemoteNamedExports(options) {
|
|
|
4302
4436
|
try {
|
|
4303
4437
|
imports = await collectFromAST(this.parse(code), code, matchesRemoteImport);
|
|
4304
4438
|
} catch {
|
|
4305
|
-
|
|
4439
|
+
if ((id.includes(".vue") || id.includes(".svelte")) && /^\s*</.test(code)) return;
|
|
4440
|
+
imports = collectFromRegex(code, matchesRemoteImport);
|
|
4306
4441
|
}
|
|
4307
4442
|
if ((!imports || imports.length === 0) && REGEX_FALLBACK_EXTENSIONS_RE.test(id)) imports = collectFromRegex(code, matchesRemoteImport);
|
|
4308
4443
|
if (!imports) return;
|
|
@@ -4437,10 +4572,10 @@ function pluginSSRRemoteEntry(options) {
|
|
|
4437
4572
|
const bareId = decodeViteId(id);
|
|
4438
4573
|
try {
|
|
4439
4574
|
const { createRequire } = await import("module");
|
|
4440
|
-
const
|
|
4575
|
+
const path = await import("path");
|
|
4441
4576
|
const { pathToFileURL } = await import("url");
|
|
4442
4577
|
result = {
|
|
4443
|
-
externalize: pathToFileURL(
|
|
4578
|
+
externalize: pathToFileURL(createRequire(pathToFileURL(path.join(server.config.root, "package.json"))).resolve(bareId.replace(/^\0/, ""))).href,
|
|
4444
4579
|
type: "module"
|
|
4445
4580
|
};
|
|
4446
4581
|
} catch {
|
|
@@ -4462,6 +4597,12 @@ function pluginSSRRemoteEntry(options) {
|
|
|
4462
4597
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
4463
4598
|
res.end(code);
|
|
4464
4599
|
});
|
|
4600
|
+
const exposesPath = `${base}/${options.filename.replace(/\.[^.]+$/, "")}.exposes.js`;
|
|
4601
|
+
server.middlewares.use(exposesPath, (_req, res) => {
|
|
4602
|
+
res.setHeader("Content-Type", "application/javascript");
|
|
4603
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
4604
|
+
res.end(generateExposesSSR(options));
|
|
4605
|
+
});
|
|
4465
4606
|
},
|
|
4466
4607
|
resolveId(id) {
|
|
4467
4608
|
if (id === remoteEntrySSRId || id.startsWith(remoteEntrySSRId)) return id;
|
|
@@ -4754,13 +4895,13 @@ function escapeUnsafeJsSourceChars(str) {
|
|
|
4754
4895
|
});
|
|
4755
4896
|
}
|
|
4756
4897
|
function isFederationHtmlPreloadDependency(dep, includeSharedRuntime = false) {
|
|
4757
|
-
const file = path.basename(dep);
|
|
4898
|
+
const file = path$1.basename(dep);
|
|
4758
4899
|
if (file.includes("__mfe_internal__") || file.includes("virtual_mf-") || file.includes("virtualExposes") || file.includes("localSharedImportMap") || file.includes("hostInit")) return true;
|
|
4759
4900
|
return includeSharedRuntime && (file.includes("preload-helper") || file.includes("rolldown-runtime") || file.startsWith("dist-"));
|
|
4760
4901
|
}
|
|
4761
4902
|
function canResolveSharedSubpath(subpath, projectRoot) {
|
|
4762
4903
|
try {
|
|
4763
|
-
createRequire(
|
|
4904
|
+
createRequire$1(pathToFileURL(path$1.join(projectRoot, "package.json"))).resolve(subpath);
|
|
4764
4905
|
return true;
|
|
4765
4906
|
} catch {
|
|
4766
4907
|
return false;
|
|
@@ -4895,7 +5036,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4895
5036
|
const optimizeDeps = config.optimizeDeps ??= {};
|
|
4896
5037
|
optimizeDeps.include ??= [];
|
|
4897
5038
|
optimizeDeps.exclude ??= [];
|
|
4898
|
-
if (isLitShare(key)) optimizeDeps.exclude.push(key);
|
|
5039
|
+
if (isLitShare(key) || key === "react" && hasPackageDependency("react-redux", root)) optimizeDeps.exclude.push(key);
|
|
4899
5040
|
else optimizeDeps.include.push(key);
|
|
4900
5041
|
for (const subpath of getCommonSharedSubpaths(key)) {
|
|
4901
5042
|
getLoadShareModulePath(subpath, isRolldown);
|
|
@@ -4911,13 +5052,13 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4911
5052
|
}
|
|
4912
5053
|
},
|
|
4913
5054
|
configResolved(config) {
|
|
4914
|
-
|
|
4915
|
-
|
|
5055
|
+
const viteMajor = parseInt(version, 10);
|
|
5056
|
+
const hasRemotes = Object.keys(options.remotes).length > 0;
|
|
5057
|
+
if (!getSsrCapabilities(viteMajor, config.command, hasRemotes).injectSsrEntryLoader) return;
|
|
4916
5058
|
if (options.runtimePlugins.some((p) => {
|
|
4917
5059
|
return (typeof p === "string" ? p : p[0]) === "@module-federation/vite/ssrEntryLoader";
|
|
4918
5060
|
})) return;
|
|
4919
|
-
const
|
|
4920
|
-
const projectRequire = createRequire(new URL(`file://${config.root}/package.json`));
|
|
5061
|
+
const projectRequire = createRequire$1(pathToFileURL(path$1.join(config.root, "package.json")));
|
|
4921
5062
|
const sharedKeys = Object.keys(options.shared ?? {});
|
|
4922
5063
|
const commonSharedPkgs = [
|
|
4923
5064
|
"react",
|
|
@@ -4934,12 +5075,12 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4934
5075
|
resolvedShared[pkg] = projectRequire.resolve(pkg);
|
|
4935
5076
|
} catch {
|
|
4936
5077
|
try {
|
|
4937
|
-
resolvedShared[pkg] =
|
|
5078
|
+
resolvedShared[pkg] = resolveImportPath(pkg);
|
|
4938
5079
|
} catch {}
|
|
4939
5080
|
}
|
|
4940
5081
|
const ssrEntryLoaderSpecifier = "@module-federation/vite/ssrEntryLoader";
|
|
4941
5082
|
try {
|
|
4942
|
-
|
|
5083
|
+
resolveImportPath(ssrEntryLoaderSpecifier);
|
|
4943
5084
|
options.runtimePlugins.push([ssrEntryLoaderSpecifier, { resolvedShared }]);
|
|
4944
5085
|
} catch {}
|
|
4945
5086
|
}
|
|
@@ -4948,7 +5089,7 @@ export default __mfShared.default ?? __mfShared;`
|
|
|
4948
5089
|
const SSR_ONLY_PLUGINS = new Set(["@module-federation/vite/ssrEntryLoader"]);
|
|
4949
5090
|
function loadPluginDts(options) {
|
|
4950
5091
|
if (options.dts === false) return [];
|
|
4951
|
-
return [import("./pluginDts-
|
|
5092
|
+
return [import("./pluginDts-BaVhdR6i.js").then(({ default: pluginDts }) => pluginDts(options))];
|
|
4952
5093
|
}
|
|
4953
5094
|
function federation(mfUserOptions) {
|
|
4954
5095
|
if (isTestEnv()) return [];
|
|
@@ -5003,8 +5144,8 @@ function federation(mfUserOptions) {
|
|
|
5003
5144
|
const environmentName = this.environment?.name;
|
|
5004
5145
|
if (!environmentName || environmentName === "client") return;
|
|
5005
5146
|
const target = reactServerEntryMap[id];
|
|
5006
|
-
const reactPackageJson = createRequire(
|
|
5007
|
-
return path.join(path.dirname(reactPackageJson), target.replace(/^react\//, ""));
|
|
5147
|
+
const reactPackageJson = createRequire$1(pathToFileURL(path$1.join(process.cwd(), "package.json"))).resolve("react/package.json");
|
|
5148
|
+
return path$1.join(path$1.dirname(reactPackageJson), target.replace(/^react\//, ""));
|
|
5008
5149
|
}
|
|
5009
5150
|
}] : [],
|
|
5010
5151
|
{
|
|
@@ -5014,7 +5155,8 @@ function federation(mfUserOptions) {
|
|
|
5014
5155
|
command = env.command;
|
|
5015
5156
|
},
|
|
5016
5157
|
configResolved() {
|
|
5017
|
-
|
|
5158
|
+
const ssrCapabilities = getSsrCapabilities(parseInt(version, 10), command, Object.keys(options.remotes).length > 0);
|
|
5159
|
+
initVirtualModules(command, remoteEntryId, ssrCapabilities.enableSsrInitBootstrap);
|
|
5018
5160
|
}
|
|
5019
5161
|
},
|
|
5020
5162
|
aliasToArrayPlugin_default,
|
|
@@ -5079,7 +5221,7 @@ function federation(mfUserOptions) {
|
|
|
5079
5221
|
...currentModulePreload,
|
|
5080
5222
|
resolveDependencies(filename, deps, context) {
|
|
5081
5223
|
const resolvedDeps = existingResolveDependencies ? existingResolveDependencies(filename, deps, context) : deps;
|
|
5082
|
-
const hostFile = path.basename(context.hostId);
|
|
5224
|
+
const hostFile = path$1.basename(context.hostId);
|
|
5083
5225
|
if (context.hostType === "js" && (hostFile === options.filename || hostFile.includes("hostInit") || hostFile.includes("virtualExposes") || hostFile.includes("localSharedImportMap"))) return [];
|
|
5084
5226
|
const hasFederationHtmlDeps = context.hostType === "html" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
|
|
5085
5227
|
const hasFederationJsDeps = context.hostType === "js" && resolvedDeps.some((dep) => isFederationHtmlPreloadDependency(dep));
|
|
@@ -5193,23 +5335,7 @@ function federation(mfUserOptions) {
|
|
|
5193
5335
|
let code = VirtualModule.findById(id)?.code ?? readFileSync(id, "utf-8");
|
|
5194
5336
|
code = code.replace(/import\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
|
|
5195
5337
|
code = code.replace(/export\s+\*\s+from\s+["'][^"']*__prebuild__[^"']*["']\s*;?/g, "");
|
|
5196
|
-
|
|
5197
|
-
* Shared/remote shims only have `export default exportModule`.
|
|
5198
|
-
*
|
|
5199
|
-
* We add a second named export (__moduleExports) that holds the full
|
|
5200
|
-
* module namespace and point syntheticNamedExports at it. This lets
|
|
5201
|
-
* Rollup resolve named imports (e.g. `import { useState } from 'react'`)
|
|
5202
|
-
* from the namespace while still applying its normal default-export
|
|
5203
|
-
* interop — which is needed for libraries like @emotion/styled where
|
|
5204
|
-
* `import styled from '@emotion/styled'` must receive the .default
|
|
5205
|
-
* function, not the raw namespace object.
|
|
5206
|
-
*
|
|
5207
|
-
* Using 'default' as the syntheticNamedExports key would skip the
|
|
5208
|
-
* interop and break default imports.
|
|
5209
|
-
*
|
|
5210
|
-
* @see https://rollupjs.org/plugin-development/#synthetic-named-exports
|
|
5211
|
-
*/
|
|
5212
|
-
if (!/\bexport\s+const\s+__moduleExports\b/.test(code) && !/\bexport\s*\{[^}]*__moduleExports/.test(code)) {
|
|
5338
|
+
if (!(/\b(?:var|let|const)\s+__moduleExports\b/.test(code) || /\bexport\s+const\s+__moduleExports\b/.test(code) || /\bexport\s*\{[^}]*__moduleExports/.test(code))) {
|
|
5213
5339
|
const nextCode = code.replace("export default exportModule", "export const __moduleExports = exportModule;\nexport default exportModule.__esModule ? exportModule.default : exportModule");
|
|
5214
5340
|
code = nextCode === code ? `${code}\nexport const __moduleExports = exportModule;\n` : nextCode;
|
|
5215
5341
|
}
|
|
@@ -5257,7 +5383,7 @@ function federation(mfUserOptions) {
|
|
|
5257
5383
|
for (const chunk of Object.values(bundle)) {
|
|
5258
5384
|
if (!isOutputChunk(chunk)) continue;
|
|
5259
5385
|
if (!isFederationControlChunk(chunk.fileName, filename)) continue;
|
|
5260
|
-
const outputPath = path.join(outputOptions.dir, chunk.fileName);
|
|
5386
|
+
const outputPath = path$1.join(outputOptions.dir, chunk.fileName);
|
|
5261
5387
|
writeFileSync(outputPath, sanitizeFederationControlChunk(readFileSync(outputPath, "utf-8"), chunk.fileName, filename));
|
|
5262
5388
|
}
|
|
5263
5389
|
}
|
|
@@ -5268,11 +5394,9 @@ function federation(mfUserOptions) {
|
|
|
5268
5394
|
_options: options,
|
|
5269
5395
|
config(config, { command: _command }) {
|
|
5270
5396
|
const isRolldown = getIsRolldown(this);
|
|
5271
|
-
let implementation = options.implementation;
|
|
5272
|
-
if (isRolldown) implementation = implementation.replace(/\.cjs(\.js)?$/, ".js");
|
|
5273
5397
|
appendResolveAlias(config, {
|
|
5274
5398
|
find: "@module-federation/runtime",
|
|
5275
|
-
replacement: implementation
|
|
5399
|
+
replacement: options.implementation
|
|
5276
5400
|
});
|
|
5277
5401
|
config.build ||= {};
|
|
5278
5402
|
config.build.commonjsOptions ||= {};
|
|
@@ -5354,8 +5478,8 @@ function federation(mfUserOptions) {
|
|
|
5354
5478
|
for (const chunk of Object.values(bundle)) {
|
|
5355
5479
|
if (!isOutputChunk(chunk)) continue;
|
|
5356
5480
|
if (!chunk.code.includes("modulepreload")) continue;
|
|
5357
|
-
const chunkDir = path.dirname(chunk.fileName);
|
|
5358
|
-
const prefixToRoot = chunkDir === "." ? "" : `${path.relative(chunkDir, ".")}/`;
|
|
5481
|
+
const chunkDir = path$1.dirname(chunk.fileName);
|
|
5482
|
+
const prefixToRoot = chunkDir === "." ? "" : `${normalizePathForImport(path$1.relative(chunkDir, "."))}/`;
|
|
5359
5483
|
const replacementExpr = prefixToRoot ? `${escapeUnsafeJsSourceChars(JSON.stringify(prefixToRoot))}+$1` : "$1";
|
|
5360
5484
|
const replacement = `=function($1){return new URL(${replacementExpr},import.meta.url).href}`;
|
|
5361
5485
|
const replaced = chunk.code.replace(/=\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/, replacement);
|