@module-federation/vite 1.20.3 → 1.20.4

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,5 +1,5 @@
1
1
  import { n as normalizePathForImport, r as rebaseImport } from "./buildPaths-BkaQHrd2.js";
2
- import { a as getMatchingNodeModuleSubpath, c as isNuxtClientBase, d as resolvePublicPath, i as getCommonSharedSubpaths, l as isViteOptimizableEntry, n as getBasePath$2, o as isAssetLikeImport, r as getCommonSharedSubpathFromNodeModulePath, s as isNodeModulePath, t as filterId, u as normalizeNodeModulePath } from "./pathNormalization-CLDIcf9-.js";
2
+ import { a as getCommonSharedSubpaths, c as isNodeModulePath, d as normalizeNodeModulePath, f as resolvePublicPath, i as getCommonSharedSubpathFromNodeModulePath, l as isNuxtClientBase, n as filterId, o as getMatchingNodeModuleSubpath, r as getBasePath$2, s as isAssetLikeImport, t as ensureTrailingSlash, u as isViteOptimizableEntry } from "./pathNormalization-DvgU8LIp.js";
3
3
  import { createRequire } from "node:module";
4
4
  import * as fs$2 from "fs";
5
5
  import fs, { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
@@ -1074,6 +1074,7 @@ function normalizeModuleFederationOptions(options) {
1074
1074
  moduleParseIdleTimeout: options.moduleParseIdleTimeout,
1075
1075
  varFilename: options.varFilename,
1076
1076
  target: options.target,
1077
+ ssrExternals: options.ssrExternals,
1077
1078
  disableRemote: options.disableRemote,
1078
1079
  disableShared: options.disableShared,
1079
1080
  disableSnapshot: options.disableSnapshot,
@@ -1752,6 +1753,24 @@ ${exportStatement}
1752
1753
  `);
1753
1754
  }
1754
1755
  //#endregion
1756
+ //#region src/plugins/pluginReactMixedModeGuard.ts
1757
+ function createReactMixedModeRuntimeGuard() {
1758
+ return `const __mfReactInternals = mod["__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE"];
1759
+ if (__mfReactInternals && "A" in __mfReactInternals) {
1760
+ let __mfReactDispatcher = __mfReactInternals.A;
1761
+ Object.defineProperty(__mfReactInternals, "A", {
1762
+ configurable: true,
1763
+ enumerable: true,
1764
+ get: () => __mfReactDispatcher,
1765
+ set: (next) => {
1766
+ if (next && typeof next.getOwner !== "function") next.getOwner = () => null;
1767
+ __mfReactDispatcher = next;
1768
+ },
1769
+ });
1770
+ __mfReactInternals.A = __mfReactDispatcher;
1771
+ }`;
1772
+ }
1773
+ //#endregion
1755
1774
  //#region src/utils/treeShaking.ts
1756
1775
  function shouldAnalyzeSharedExports(shareItem) {
1757
1776
  return !!(shareItem && (shareItem.shareConfig.treeShaking || shareItem.shareConfig.import === false));
@@ -3249,12 +3268,13 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
3249
3268
  const hasCompleteExportCoverage = detectedNamedExports !== void 0;
3250
3269
  const isWorkspaceSingleton = isWorkspacePackage && shareItem.shareConfig.singleton === true;
3251
3270
  const isDefaultShareScope = shareItem.scope === void 0 || shareItem.scope === "default" || Array.isArray(shareItem.scope) && shareItem.scope[0] === "default";
3252
- const usesDeferredSingletonFallback = hasCompleteExportCoverage && (isWorkspaceSingleton || command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true || command === "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true && !isDefaultShareScope);
3271
+ const usesDeferredSingletonFallback = hasCompleteExportCoverage && (isWorkspacePackage || command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true || command === "build" && isRemoteOnlyContainer(resolvedOptions) && (shareItem.shareConfig.singleton === true ? !isDefaultShareScope : isDefaultShareScope));
3253
3272
  const servesRemoteSingletonFallback = command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true;
3254
3273
  const isConsumedByPeerSingleton = isSharedSingletonConsumedByPeer(pkg, resolvedOptions);
3255
3274
  const usesEntryInjectedRemoteFallback = hasCompleteExportCoverage && command !== "build" && !isWorkspaceSingleton && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true && resolvedOptions.hostInitInjectLocation === "entry" && isConsumedByPeerSingleton;
3256
- const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && isConsumedByPeerSingleton;
3275
+ const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
3257
3276
  const usesDeferredTreeShakingFallback = hasCompleteExportCoverage && Boolean(treeShakingConsumer);
3277
+ const reactMixedModeGuard = pkg === "react" ? createReactMixedModeRuntimeGuard() : "";
3258
3278
  let exportLine;
3259
3279
  let initBlock = "";
3260
3280
  if (usesDeferredTreeShakingFallback) {
@@ -3280,13 +3300,17 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
3280
3300
  const namedExportVars = copiedNamedExports.map((_name, i) => `__mf_${i}`);
3281
3301
  exportLine = `${["let __mfDefaultExport;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ")}
3282
3302
  const __mfApplySharedExports = (mod) => {
3283
- ${[...copiedNamedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`), `__mfDefaultExport = (() => {
3303
+ ${[
3304
+ ...reactMixedModeGuard ? [reactMixedModeGuard] : [],
3305
+ ...copiedNamedExports.map((name, i) => `${namedExportVars[i]} = mod[${escapeGeneratedStringLiteral(name)}];`),
3306
+ `__mfDefaultExport = (() => {
3284
3307
  ${generateShareModuleUnwrapCode({
3285
- source: "mod",
3286
- preserveNamedExports: false,
3287
- stopWithReturn: "defaultExport ?? current"
3288
- })}
3289
- })();`].join("\n ")}
3308
+ source: "mod",
3309
+ preserveNamedExports: false,
3310
+ stopWithReturn: "defaultExport ?? current"
3311
+ })}
3312
+ })();`
3313
+ ].join("\n ")}
3290
3314
  };
3291
3315
  __mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplySharedExports);
3292
3316
  __mfApplySharedExports(exportModule);
@@ -3314,6 +3338,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
3314
3338
  } else if (shareItem.shareConfig.singleton === true) {
3315
3339
  exportLine = `let __mfDefaultExport;
3316
3340
  const __mfApplySharedDefaultExport = (mod) => {
3341
+ ${reactMixedModeGuard}
3317
3342
  __mfDefaultExport = mod.default ?? mod;
3318
3343
  };
3319
3344
  __mfSubscribeSharedCache(__mfModuleCache.share, ${cacheDescriptor}, __mfApplySharedDefaultExport);
@@ -3856,7 +3881,6 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy) {
3856
3881
  : __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor);
3857
3882
  if (cachedShare !== undefined) return false;
3858
3883
  if (share.treeShaking || share.shareConfig?.import === false) return true;
3859
- if (!share.shareConfig?.singleton) return false;
3860
3884
  if (typeof __mfSelectExternalSharedProvider !== 'function') return false;
3861
3885
  return Boolean(__mfSelectExternalSharedProvider(
3862
3886
  initialShared[pkg],
@@ -4595,6 +4619,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
4595
4619
  if (!providerEntry) return;
4596
4620
  const selectedLocalProvider = __mfMatchesSharedProvider(selectedRuntimeProvider, usedShare);
4597
4621
  const { version } = providerEntry;
4622
+ if (!usedShare.shareConfig?.singleton && version !== usedShare.version) return;
4598
4623
  const passedProvider = passedVersionMap?.[version];
4599
4624
  const resolvedExternalProvider = __mfResolveExternalSharedProvider(
4600
4625
  federationInstances,
@@ -4612,10 +4637,6 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
4612
4637
  provider: selectedRuntimeProvider,
4613
4638
  scopeRootProvider: undefined
4614
4639
  };
4615
- // Non-singleton proxies may have already snapshotted their local exports while
4616
- // seeding shared dependencies. Late cache replacement is safe only for the
4617
- // live-bound singleton proxies.
4618
- if (!usedShare.shareConfig?.singleton) return;
4619
4640
  if (usedShare.canLiveRebind === false) return;
4620
4641
  // Preserve a singleton already selected by another container. The bridge may
4621
4642
  // only replace the provisional local fallback seeded by this container.
@@ -7878,6 +7899,11 @@ function resolveDevHashEntryFileName(fileName) {
7878
7899
  const baseName = path$1.basename(normalized);
7879
7900
  return path$1.extname(baseName) ? normalized : `${normalized}.js`;
7880
7901
  }
7902
+ function resolveAbsoluteDevRemoteEntryUrl(publicPath, fileName) {
7903
+ const base = new URL(publicPath);
7904
+ base.pathname = ensureTrailingSlash(base.pathname);
7905
+ return new URL(fileName, base).href;
7906
+ }
7881
7907
  function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposesId, getParsePromise = () => Promise.resolve() }) {
7882
7908
  let viteConfig, _command, root, originalConfigBase;
7883
7909
  let exposeRemoteDependencies = {};
@@ -8007,12 +8033,15 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
8007
8033
  if (_command === "serve") {
8008
8034
  const host = typeof viteConfig.server?.host === "string" && viteConfig.server.host !== "0.0.0.0" ? viteConfig.server.host : "localhost";
8009
8035
  const resolvedPublicPath = resolvePublicPath(options, viteConfig.base, originalConfigBase);
8010
- const publicPath = JSON.stringify((resolvedPublicPath === "auto" ? "/" : resolvedPublicPath) + resolveDevHashEntryFileName(options.filename));
8036
+ const devPublicPath = resolvedPublicPath === "auto" ? "/" : resolvedPublicPath;
8037
+ const remoteEntryFileName = resolveDevHashEntryFileName(options.filename);
8038
+ const isAbsolutePublicPath = /^https?:\/\//i.test(devPublicPath);
8039
+ const remoteEntryUrl = JSON.stringify(isAbsolutePublicPath ? resolveAbsoluteDevRemoteEntryUrl(devPublicPath, remoteEntryFileName) : `${ensureTrailingSlash(devPublicPath)}${remoteEntryFileName}`);
8011
8040
  const fallbackOrigin = `//${host}:${viteConfig.server?.port}`;
8012
8041
  const ssrRemoteEntry = "data:text/javascript," + encodeURIComponent("export async function init(){return {loadRemote:async()=>({}),loadShare:async()=>({})}}");
8013
8042
  return `
8014
8043
  const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
8015
- const remoteEntryImport = typeof window !== 'undefined' ? origin + ${publicPath} : ${JSON.stringify(ssrRemoteEntry)};
8044
+ const remoteEntryImport = typeof window !== 'undefined' ? ${isAbsolutePublicPath ? remoteEntryUrl : `origin + ${remoteEntryUrl}`} : ${JSON.stringify(ssrRemoteEntry)};
8016
8045
  ${generateHostAutoInitCode("remoteEntryImport", "serve", options)}
8017
8046
  `;
8018
8047
  }
@@ -8155,41 +8184,6 @@ function pluginProxyRemotes_default(options) {
8155
8184
  };
8156
8185
  }
8157
8186
  //#endregion
8158
- //#region src/plugins/pluginReactMixedModeGuard.ts
8159
- const REACT_DEVELOPMENT_RUNTIME = /[\\/]react[\\/]cjs[\\/]react(?:-jsx-(?:dev-)?runtime)?\.development\.js$/;
8160
- const UNSAFE_GET_OWNER = "return null === dispatcher ? null : dispatcher.getOwner();";
8161
- const SAFE_GET_OWNER = "return typeof dispatcher?.getOwner === \"function\" ? dispatcher.getOwner() : null;";
8162
- const REACT_MIXED_MODE_ROLLDOWN_PLUGIN = "module-federation:react-mixed-mode-rolldown";
8163
- const REACT_MIXED_MODE_ESBUILD_PLUGIN = "module-federation:react-mixed-mode-esbuild";
8164
- function patchReactDevelopmentRuntime(code, id) {
8165
- if (!REACT_DEVELOPMENT_RUNTIME.test(id)) return;
8166
- const patched = code.replaceAll(UNSAFE_GET_OWNER, SAFE_GET_OWNER);
8167
- return patched === code ? void 0 : patched;
8168
- }
8169
- function createRolldownReactMixedModeGuard() {
8170
- return {
8171
- name: REACT_MIXED_MODE_ROLLDOWN_PLUGIN,
8172
- transform(code, id) {
8173
- return patchReactDevelopmentRuntime(code, id);
8174
- }
8175
- };
8176
- }
8177
- function createEsbuildReactMixedModeGuard() {
8178
- return {
8179
- name: REACT_MIXED_MODE_ESBUILD_PLUGIN,
8180
- setup(build) {
8181
- build.onLoad({ filter: REACT_DEVELOPMENT_RUNTIME }, (args) => {
8182
- const patched = patchReactDevelopmentRuntime(readFileSync$1(args.path, "utf8"), args.path);
8183
- if (patched === void 0) return;
8184
- return {
8185
- contents: patched,
8186
- loader: "js"
8187
- };
8188
- });
8189
- }
8190
- };
8191
- }
8192
- //#endregion
8193
8187
  //#region src/utils/PromiseStore.ts
8194
8188
  /**
8195
8189
  * example:
@@ -9116,12 +9110,8 @@ function pluginSSRRemoteEntry(options) {
9116
9110
  ssrOutputFilename = getSsrRemoteEntryFileName(options.filename);
9117
9111
  const environmentName = this.environment?.name;
9118
9112
  const hasSsrEnvironment = Boolean(viteConfig?.environments?.ssr);
9119
- const isLegacySsrBuild = Boolean(this.environment?.config?.build?.ssr);
9120
- if (hasSsrEnvironment) {
9121
- if (isNuxtProject) {
9122
- if (environmentName === "ssr") return;
9123
- } else if (environmentName !== "ssr") return;
9124
- } else if (isLegacySsrBuild) {} else if (environmentName && environmentName !== "client") return;
9113
+ const isLegacySsrBuild = Boolean(this.environment?.config?.build?.ssr ?? viteConfig?.build?.ssr);
9114
+ if (hasSsrEnvironment && environmentName !== "ssr" || !hasSsrEnvironment && !isLegacySsrBuild) return;
9125
9115
  if (Object.keys(options.exposes).length === 0) return;
9126
9116
  if (isRolldown) this.emitFile({
9127
9117
  type: "chunk",
@@ -9661,7 +9651,6 @@ function includeLinkedSharedEntries(optimizeDeps, shared, projectRoot, exposes,
9661
9651
  function createEarlyVirtualModulesPlugin(options) {
9662
9652
  const { shared, remotes } = options;
9663
9653
  const isLitShare = (pkg) => pkg === "lit" || pkg.startsWith("lit/");
9664
- const shouldGuardReactMixedMode = Object.keys(remotes ?? {}).length > 0 && shared?.react?.shareConfig.singleton === true;
9665
9654
  return {
9666
9655
  name: "vite:module-federation-early-init",
9667
9656
  enforce: "pre",
@@ -9689,7 +9678,6 @@ function createEarlyVirtualModulesPlugin(options) {
9689
9678
  if (isRolldown) {
9690
9679
  optimizeDeps.rolldownOptions ??= {};
9691
9680
  optimizeDeps.rolldownOptions.plugins ??= [];
9692
- if (shouldGuardReactMixedMode) optimizeDeps.rolldownOptions.plugins.push(createRolldownReactMixedModeGuard());
9693
9681
  optimizeDeps.rolldownOptions.plugins.push({
9694
9682
  name: "module-federation:optimize-shared-resolver",
9695
9683
  load(id) {
@@ -9734,7 +9722,6 @@ function createEarlyVirtualModulesPlugin(options) {
9734
9722
  } else {
9735
9723
  optimizeDeps.esbuildOptions ??= {};
9736
9724
  optimizeDeps.esbuildOptions.plugins ??= [];
9737
- if (shouldGuardReactMixedMode) optimizeDeps.esbuildOptions.plugins.push(createEsbuildReactMixedModeGuard());
9738
9725
  optimizeDeps.esbuildOptions.plugins.push({
9739
9726
  name: "module-federation:optimize-shared-proxy",
9740
9727
  setup(build) {
@@ -10163,6 +10150,7 @@ function federation(mfUserOptions) {
10163
10150
  patchedManualChunks.add(mfChunkName);
10164
10151
  if (!useCodeSplitting) {
10165
10152
  const mfManualChunks = function(id) {
10153
+ if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
10166
10154
  return mfChunkName(id) ?? void 0;
10167
10155
  };
10168
10156
  patchedManualChunks.add(mfManualChunks);
@@ -116,4 +116,4 @@ function resolvePublicPath(options, viteBase, originalBase) {
116
116
  return "auto";
117
117
  }
118
118
  //#endregion
119
- export { getMatchingNodeModuleSubpath as a, isNuxtClientBase as c, resolvePublicPath as d, getCommonSharedSubpaths as i, isViteOptimizableEntry as l, getBasePath as n, isAssetLikeImport as o, getCommonSharedSubpathFromNodeModulePath as r, isNodeModulePath as s, filterId as t, normalizeNodeModulePath as u };
119
+ export { getCommonSharedSubpaths as a, isNodeModulePath as c, normalizeNodeModulePath as d, resolvePublicPath as f, getCommonSharedSubpathFromNodeModulePath as i, isNuxtClientBase as l, filterId as n, getMatchingNodeModuleSubpath as o, getBasePath as r, isAssetLikeImport as s, ensureTrailingSlash as t, isViteOptimizableEntry as u };
@@ -603,7 +603,7 @@ async function importTempModule(filePath, versionKey) {
603
603
  }
604
604
  let warnedVmUnavailable = false;
605
605
  async function tryVmStrategy(ssrEntry, options) {
606
- const { loadViaVmStrategy, isVmStrategyAvailable } = await import("./ssrVmStrategy-BkEp3YIv.js");
606
+ const { loadViaVmStrategy, isVmStrategyAvailable } = await import("./ssrVmStrategy-DTJITp2Z.js");
607
607
  if (!await isVmStrategyAvailable()) {
608
608
  if (!warnedVmUnavailable) {
609
609
  warnedVmUnavailable = true;
@@ -1,5 +1,5 @@
1
- import { i as getCommonSharedSubpaths } from "./pathNormalization-CLDIcf9-.js";
2
- import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-7v0Do_g5.js";
1
+ import { a as getCommonSharedSubpaths } from "./pathNormalization-DvgU8LIp.js";
2
+ import { c as readResponseTextBounded, n as neutralizeBrowserPreloadHelpers, s as fetchWithTimeout, t as SsrEntryHttpError } from "./ssrEntryLoader-Ccr0zMrr.js";
3
3
  //#region src/utils/ssrVmStrategy.ts
4
4
  /**
5
5
  * vm.SourceTextModule strategy for loading remote SSR entries.
@@ -1,3 +1,4 @@
1
+ import runtimePackage from "@module-federation/runtime/package.json" with { type: "json" };
1
2
  import * as runtimeCore from "@module-federation/runtime/core";
2
3
  //#region src/utils/injectExternalRuntimeCorePlugin.ts
3
4
  /**
@@ -8,8 +9,7 @@ import * as runtimeCore from "@module-federation/runtime/core";
8
9
  * Mirrors `@module-federation/inject-external-runtime-core-plugin` without
9
10
  * adding that package (or `runtime-tools`) as a dependency of this plugin.
10
11
  */
11
- /** Keep in sync with the `@module-federation/runtime` dependency version. */
12
- const PLUGIN_VERSION = "2.8.0";
12
+ const PLUGIN_VERSION = runtimePackage.version;
13
13
  function getFederationGlobal() {
14
14
  const globalRef = runtimeCore.Global;
15
15
  if (!globalRef || typeof globalRef !== "object") return void 0;
@@ -1,2 +1,2 @@
1
- import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-7v0Do_g5.js";
1
+ import { i as ssrEntryLoaderPlugin, n as neutralizeBrowserPreloadHelpers, r as revalidate, t as SsrEntryHttpError } from "../ssrEntryLoader-Ccr0zMrr.js";
2
2
  export { SsrEntryHttpError, ssrEntryLoaderPlugin as default, neutralizeBrowserPreloadHelpers, revalidate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.20.3",
3
+ "version": "1.20.4",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -77,9 +77,9 @@
77
77
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
78
78
  },
79
79
  "dependencies": {
80
- "@module-federation/dts-plugin": "2.8.1",
81
- "@module-federation/runtime": "2.8.1",
82
- "@module-federation/sdk": "2.8.1"
80
+ "@module-federation/dts-plugin": "2.8.2",
81
+ "@module-federation/runtime": "2.8.2",
82
+ "@module-federation/sdk": "2.8.2"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@playwright/test": "1.62.0",