@module-federation/vite 1.23.2 → 1.23.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,6 +1,6 @@
1
1
  import { _ as resolvePublicPath, a as matchesSharedSource, c as filterId, d as getNodeModulesSuffix, f as isAssetLikeImport, g as normalizeNodeModulePath, h as isViteOptimizableEntry, i as invalidateSharedKeyMatcher, l as getBasePath$1, m as isNuxtClientBase, n as getSharedRequest, p as isNodeModulePath, r as getSharedRuntimeKey, s as ensureTrailingSlash, t as findSharedKey, u as getCommonSharedSubpaths, v as stripQueryAndHash, y as stripViteFsPrefix } from "./sharedKeyMatcher-Od_nYxJA.js";
2
2
  import { a as CodeRewriter, c as isAbsoluteUrl, d as resolveHashPlaceholderFileName, i as createCodePositionMap, l as normalizePathForImport, o as createSourceMap, r as mfWarn, t as createModuleFederationError, u as rebaseImport } from "./logger-DOwfTlw5.js";
3
- import { C as isReactCoreShare, S as REACT_DOM_CLIENT_SHARE, _ as resolveModulePath, a as getIsRolldown, b as supportsCodeSplittingGroupDebugName, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as isPackageExportAvailable, g as resolveImportPath, h as packageNameEncode, i as getInstalledPackageJson, l as getSharedCacheDescriptor, m as packageNameDecode, n as getDependencyNames, o as getPackageDetectionCwd, p as isPackageInstalled, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as setPackageDetectionCwd, x as REACT_CLIENT_INTERNALS_KEY, y as sharedCacheHelperCode } from "./dtsConstants-r5OfegUr.js";
3
+ import { C as isReactCoreShare, S as REACT_DOM_CLIENT_SHARE, _ as resolveModulePath, a as getIsRolldown, b as supportsCodeSplittingGroupDebugName, c as getPackageNameFromNodeModulePath, d as isNuxtProjectRoot, f as isPackageExportAvailable, g as resolveImportPath, h as packageNameEncode, i as getInstalledPackageJson, l as getSharedCacheDescriptor, m as packageNameDecode, n as getDependencyNames, o as getPackageDetectionCwd, p as isPackageInstalled, r as getInstalledPackageEntry, s as getPackageName, u as hasPackageDependency, v as setPackageDetectionCwd, x as REACT_CLIENT_INTERNALS_KEY, y as sharedCacheHelperCode } from "./dtsConstants-DSTzyKSG.js";
4
4
  import { createRequire } from "node:module";
5
5
  import * as fs$2 from "fs";
6
6
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "fs";
@@ -281,9 +281,17 @@ function isClientEnvironment(ctx) {
281
281
  * the legacy root `build.ssr` flag.
282
282
  */
283
283
  function isServerBuildContext(ctx, config) {
284
+ return isServerContext(ctx, Boolean(config?.build?.ssr));
285
+ }
286
+ /**
287
+ * Whether a hook runs for a server graph. Hooks without an environment context
288
+ * (Vite 5) use `legacySsr`, such as the root `build.ssr` flag or the load
289
+ * hook's `ssr` option.
290
+ */
291
+ function isServerContext(ctx, legacySsr) {
284
292
  const target = resolveEnvironmentConsumerTarget(ctx);
285
293
  if (target) return target === "server";
286
- return Boolean(config?.build?.ssr);
294
+ return legacySsr;
287
295
  }
288
296
  function resolveRemoteConsumer(ctx, hasMultiEnvironment) {
289
297
  if (!hasMultiEnvironment) return "unified";
@@ -730,9 +738,13 @@ function normalizeExperiments(experiments) {
730
738
  };
731
739
  }
732
740
  function normalizeSsrEntryLoader(ssrEntryLoader) {
733
- const strategy = ssrEntryLoader?.strategy;
734
- if (strategy !== "temp-file" && strategy !== "vm") return void 0;
735
- return { strategy };
741
+ if (!ssrEntryLoader) return void 0;
742
+ const normalized = {};
743
+ if (ssrEntryLoader.strategy === "temp-file" || ssrEntryLoader.strategy === "vm") normalized.strategy = ssrEntryLoader.strategy;
744
+ if (Number.isFinite(ssrEntryLoader.maxAgeMs)) normalized.maxAgeMs = ssrEntryLoader.maxAgeMs;
745
+ if (Number.isFinite(ssrEntryLoader.fetchTimeoutMs)) normalized.fetchTimeoutMs = ssrEntryLoader.fetchTimeoutMs;
746
+ if (Number.isFinite(ssrEntryLoader.fetchMaxBytes)) normalized.fetchMaxBytes = ssrEntryLoader.fetchMaxBytes;
747
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
736
748
  }
737
749
  let config;
738
750
  let explicitSharedKeys = /* @__PURE__ */ new Set();
@@ -3300,7 +3312,7 @@ function generateEagerWorkspaceSingletonExports(edges, namedExports, importSourc
3300
3312
  __mfApplyEagerShareExportsWhenReady(exportModule);
3301
3313
  export { __mf_default as default };${namedExportLine}${mutableExportLine}`;
3302
3314
  }
3303
- function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = [], deferredEntryFallback = false) {
3315
+ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource, cacheDescriptor, cacheOwner, treeShakingConsumer, serveLocalFallback = false, mutableExports = [], deferredEntryFallback = false, ssrLocalFallback = true) {
3304
3316
  const copiedExports = namedExports.filter((name) => !mutableExports.includes(name));
3305
3317
  const namedExportVars = copiedExports.map((_name, i) => `__mf_${i}`);
3306
3318
  const declarations = namedExports.length > 0 ? ["let __mf_default;", ...namedExportVars.map((name) => `let ${name};`)].join("\n ") : "let __mf_default;";
@@ -3340,7 +3352,7 @@ function generateLazyWorkspaceSingletonExports(edges, namedExports, importSource
3340
3352
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});
3341
3353
  });
3342
3354
  })`;
3343
- const synchronousFallbackConditions = [...deferredEntryFallback ? [] : ["import.meta.env.SSR"], ...serveLocalFallback ? ["(import.meta.env.DEV && typeof __mfLocalShare !== 'undefined')"] : []];
3355
+ const synchronousFallbackConditions = [...ssrLocalFallback ? ["import.meta.env.SSR"] : [], ...serveLocalFallback ? ["(import.meta.env.DEV && typeof __mfLocalShare !== 'undefined')"] : []];
3344
3356
  const trackPendingLoad = `__mfTrackPendingShareLoad(${deferredEntryFallback ? deferredEntryLoad : deferredInitLoad});`;
3345
3357
  return `${declarations}
3346
3358
  const __mfApplyLazyShareExports = (mod) => {
@@ -3546,7 +3558,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
3546
3558
  exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
3547
3559
  } else if (usesDeferredEntryInjectedSingletonFallback) {
3548
3560
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
3549
- exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, false, liveNamedExports, true);
3561
+ exportLine = generateLazyWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, false, liveNamedExports, true, pkg !== REACT_DOM_CLIENT_SHARE);
3550
3562
  } else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(edges, namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
3551
3563
  else if (usesDeferredSingletonFallback) {
3552
3564
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
@@ -3795,7 +3807,7 @@ function generateLocalSharedImportMap(options) {
3795
3807
  return pkg;`}
3796
3808
  }
3797
3809
  `;
3798
- }).join(",")}
3810
+ }).filter(Boolean).join(",")}
3799
3811
  }
3800
3812
  const usedShared = {
3801
3813
  ${orderedShares.map((key) => {
@@ -4396,7 +4408,14 @@ function generateRuntimeSharedCacheSeedCode(shareStrategy, options, command = "b
4396
4408
  );
4397
4409
  return;
4398
4410
  }
4399
- if (typeof isWebpackProvider === 'function' && isWebpackProvider(externalProvider)) return;
4411
+ // Leave an unloaded webpack provider to the late bridge, which only takes a
4412
+ // non-singleton of this share's own version; any other version seeds locally.
4413
+ if (
4414
+ typeof isWebpackProvider === 'function' &&
4415
+ isWebpackProvider(externalProvider) &&
4416
+ (share.shareConfig?.singleton ||
4417
+ __mfFindSharedProviderEntry(initialShared[pkg], externalProvider)?.version === share.version)
4418
+ ) return;
4400
4419
  }
4401
4420
  const providerKey = cacheDescriptor.canonical;
4402
4421
  const resolved = await __mfInitializeProviderOnce(providerKey, async () => {
@@ -5772,7 +5791,8 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
5772
5791
  const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
5773
5792
  if (
5774
5793
  __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined &&
5775
- ${_command === "serve" ? `__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined` : `(
5794
+ ${_command === "serve" ? `__mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined &&
5795
+ !(share.shareConfig?.singleton && __mfHasAlternativeSharedVersion(pkg, share))` : `(
5776
5796
  (!share.shareConfig?.singleton && __mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) === ${cacheOwner}) ||
5777
5797
  (share.shareConfig?.singleton && !__mfHasAlternativeSharedVersion(pkg, share))
5778
5798
  )`}
@@ -6221,9 +6241,23 @@ function getLazyRemotePendingExport() {
6221
6241
  };`;
6222
6242
  }
6223
6243
  function getEagerRemotePendingExport() {
6224
- return `export const __mf_remote_pending =
6244
+ return `export let __mf_remote_pending =
6225
6245
  __mfRemotePending ??
6226
- __mfStartRemoteLoad().then(__mfAssignRemoteModule);`;
6246
+ __mfStartRemoteLoad().then(__mfAssignRemoteModule);
6247
+ __mf_remote_pending.then(undefined, () => {
6248
+ let attempt;
6249
+ const retry = {
6250
+ then(onFulfilled, onRejected) {
6251
+ attempt ||= __mfStartRemoteLoad().then(__mfAssignRemoteModule, (error) => {
6252
+ attempt = undefined;
6253
+ throw error;
6254
+ });
6255
+ return attempt.then(onFulfilled, onRejected);
6256
+ },
6257
+ };
6258
+ if (__mfRemotePending) __mfRemotePending = retry;
6259
+ __mf_remote_pending = retry;
6260
+ });`;
6227
6261
  }
6228
6262
  function getServerThenExport() {
6229
6263
  return `export function then(onFulfilled, onRejected) {
@@ -6237,7 +6271,15 @@ function getServerThenExport() {
6237
6271
  __moduleExports: exportModule,
6238
6272
  __mf_remote_pending: __mfRemotePending,
6239
6273
  };
6240
- })
6274
+ }, () => ({
6275
+ get default() {
6276
+ return __mfDefaultExport;
6277
+ },
6278
+ get __moduleExports() {
6279
+ return exportModule;
6280
+ },
6281
+ __mf_remote_pending: { then: (resolve, reject) => __mf_remote_pending.then(resolve, reject) },
6282
+ }))
6241
6283
  .then(onFulfilled, onRejected);
6242
6284
  }`;
6243
6285
  }
@@ -6462,6 +6504,27 @@ function patchHashEntryFileNames(config, entryName, fileName) {
6462
6504
  patchBundlerOutput(config.build.rolldownOptions);
6463
6505
  Object.values(config.environments ?? {}).forEach((environment) => patchHashEntryFileNames(environment, entryName, fileName));
6464
6506
  }
6507
+ const ROLLDOWN_RUNTIME_GLOBAL = "__rolldown_runtime__";
6508
+ /**
6509
+ * Rolldown's dev runtime lives on `globalThis.__rolldown_runtime__`, and its
6510
+ * module registry is keyed by cwd-relative ids (`src/App.jsx`). A bundledDev
6511
+ * remote loaded into a bundledDev host would share the host's runtime, so the
6512
+ * remote's modules, hot contexts and HMR factories would collide with the
6513
+ * host's. Give each remote its own same-length global (sourcemaps stay valid)
6514
+ * in every chunk and HMR patch it serves.
6515
+ */
6516
+ function renameBundledDevRuntime(req, res, remoteName) {
6517
+ if (!req.url || !stripQueryAndHash(req.url).endsWith(".js")) return;
6518
+ const runtimeGlobal = `__mf_rt_${createHash("sha256").update(remoteName).digest("hex").slice(0, 10)}__`;
6519
+ const end = res.end;
6520
+ res.end = function(chunk, ...args) {
6521
+ if (typeof chunk === "string" || chunk instanceof Uint8Array) {
6522
+ const code = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
6523
+ if (code.includes(ROLLDOWN_RUNTIME_GLOBAL)) chunk = code.replace(/\b__rolldown_runtime__\b/g, runtimeGlobal);
6524
+ }
6525
+ return end.call(this, chunk, ...args);
6526
+ };
6527
+ }
6465
6528
  const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClientInjected, skipTransformFor = [], federationOptions }) => {
6466
6529
  const DEV_HTML_PROXY_PREFIX = "virtual:mf-html-entry-proxy?";
6467
6530
  const ENTRY_BOOTSTRAP_PARAM = "mf-entry-bootstrap";
@@ -6481,8 +6544,12 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
6481
6544
  let emittedFileName;
6482
6545
  let skipTransformIds = /* @__PURE__ */ new Set();
6483
6546
  let injectedTransformIds = /* @__PURE__ */ new Set();
6547
+ const virtualEntryCode = /* @__PURE__ */ new Map();
6484
6548
  const ignoredHtmlScriptSources = /* @__PURE__ */ new Set();
6485
6549
  let bootstrapDir = "";
6550
+ let isBundledDevRemote = false;
6551
+ let bundledDevRemoteEntryCode;
6552
+ let resolveBundledDevRemoteEntryCode;
6486
6553
  function skipSvelteKitSsrBuild() {
6487
6554
  return (_command === "build" || viteConfig?.command === "build") && viteConfig?.build?.ssr && hasPackageDependency("@sveltejs/kit");
6488
6555
  }
@@ -6581,7 +6648,7 @@ const __mfCurrentScript = document.currentScript;
6581
6648
  : import(src);
6582
6649
  ` : "";
6583
6650
  const importExpression = (src) => useSystemImportFallback ? `__mfImport(${JSON.stringify(src)})` : `import(${JSON.stringify(src)})`;
6584
- const isEncodedVirtualEntry = entrySrc.startsWith(VITE_ENCODED_NULL_BYTE_PREFIX);
6651
+ const isEncodedVirtualEntry = !options?.isBundled && entrySrc.startsWith(VITE_ENCODED_NULL_BYTE_PREFIX);
6585
6652
  const entryImportDeclaration = isEncodedVirtualEntry ? `const __mfEntryUrl = ${JSON.stringify(entrySrc)};
6586
6653
  ` : "";
6587
6654
  const entryImportExpression = isEncodedVirtualEntry ? "import(/* @vite-ignore */ __mfEntryUrl)" : importExpression(entrySrc);
@@ -6603,10 +6670,11 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6603
6670
  const shareItem = getNormalizeShareItem(pkg, federationOptions);
6604
6671
  const isExplicitShare = Object.hasOwn(federationOptions.shared, pkg);
6605
6672
  return shareItem?.shareConfig?.singleton === true && shareItem?.shareConfig?.import !== false && !shareItem?.shareConfig?.treeShaking && (isExplicitShare || typeof shareItem?.shareConfig?.import === "string" || Boolean(getProjectResolvedImportPath(pkg)));
6606
- }).map((pkg) => toViteEncodedId(getLoadShareModulePath(pkg, false, federationOptions))) : [];
6607
- const sharedPreloadBlock = sharedPreloadSources.length > 0 ? `
6608
- const __mfSharedPreloadUrls = ${JSON.stringify(sharedPreloadSources)};
6609
- await Promise.all(__mfSharedPreloadUrls.map((src) => import(/* @vite-ignore */ src).catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));` : "";
6673
+ }).map((pkg) => getLoadShareModulePath(pkg, false, federationOptions)) : [];
6674
+ const sharedPreloadBlock = sharedPreloadSources.length === 0 ? "" : options?.isBundled ? `
6675
+ await Promise.all([${sharedPreloadSources.map((src) => `[${JSON.stringify(src)}, import(${JSON.stringify(src)})]`).join(", ")}].map(([src, load]) => load.catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));` : `
6676
+ const __mfSharedPreloadUrls = ${JSON.stringify(sharedPreloadSources.map(toViteEncodedId))};
6677
+ await Promise.all(__mfSharedPreloadUrls.map((src) => import(/* @vite-ignore */ src).catch((err) => console.warn("[module-federation] shared preload failed:", src, err))));`;
6610
6678
  const remoteCachePrefix = getRuntimeRemoteCachePrefix(federationOptions);
6611
6679
  const preloadBlock = remotePreloads ? `
6612
6680
  const runtime = await initHost();
@@ -6733,19 +6801,6 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6733
6801
  apply: "serve",
6734
6802
  config(_config, { command }) {
6735
6803
  _command = command;
6736
- const isRemoteEntry = entryName === "remoteEntry" && federationOptions !== void 0 && isRemoteContainer(federationOptions);
6737
- if (command === "serve" && _config.experimental?.bundledDev && isRemoteEntry) {
6738
- _config.experimental = {
6739
- ..._config.experimental,
6740
- bundledDev: false
6741
- };
6742
- _config.environments ??= {};
6743
- _config.environments.client ??= {};
6744
- if (_config.environments.client.isBundled !== false) {
6745
- _config.environments.client.isBundled = false;
6746
- mfWarn("Vite bundledDev is disabled for the client environment of a Module Federation remote container so its remoteEntry keeps the standard init/get contract.");
6747
- }
6748
- }
6749
6804
  },
6750
6805
  configResolved(config) {
6751
6806
  viteConfig = config;
@@ -6758,6 +6813,10 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6758
6813
  devEntryPath = config.base + relativePath.replace(/^\//, "");
6759
6814
  }
6760
6815
  skipTransformIds = new Set(skipTransformFor.map(resolveProjectId));
6816
+ isBundledDevRemote = config.command === "serve" && entryName === "remoteEntry" && federationOptions !== void 0 && isRemoteContainer(federationOptions) && (config.environments?.client)?.isBundled === true;
6817
+ if (isBundledDevRemote) bundledDevRemoteEntryCode = new Promise((resolve) => {
6818
+ resolveBundledDevRemoteEntryCode = resolve;
6819
+ });
6761
6820
  },
6762
6821
  configureServer(server) {
6763
6822
  devServer = server;
@@ -6785,7 +6844,18 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6785
6844
  }
6786
6845
  const devFileName = resolveHashPlaceholderFileName(fileName);
6787
6846
  if (devFileName !== fileName && req.url?.startsWith((viteConfig.base + devFileName).replace(/^\/?/, "/"))) req.url = req.url.replace(devFileName, fileName);
6847
+ if (isBundledDevRemote) renameBundledDevRuntime(req, res, federationOptions.name);
6788
6848
  if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, "/"))) {
6849
+ if (isBundledDevRemote) {
6850
+ const bundledDev = (server.environments?.client)?.bundledDev;
6851
+ Promise.all([bundledDevRemoteEntryCode, bundledDev?.waitForInitialBuildFinish?.()]).then(([code]) => {
6852
+ if (code === void 0) return next();
6853
+ res.setHeader("Content-Type", "text/javascript");
6854
+ res.setHeader("Cache-Control", "no-cache");
6855
+ res.end(code);
6856
+ }, next);
6857
+ return;
6858
+ }
6789
6859
  req.url = devEntryPath;
6790
6860
  req.headers["sec-fetch-dest"] = "script";
6791
6861
  }
@@ -6823,7 +6893,7 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6823
6893
  const initSrc = params.get("init");
6824
6894
  const entrySrc = params.get("entry");
6825
6895
  if (!initSrc || !entrySrc) return;
6826
- const source = getBootstrapSource(initSrc, entrySrc);
6896
+ const source = getBootstrapSource(initSrc, entrySrc, false, { isBundled: this.environment?.config?.isBundled === true });
6827
6897
  return warmupDevEntryGraph(entrySrc).then(() => source);
6828
6898
  },
6829
6899
  transform(code, id) {
@@ -6866,7 +6936,30 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6866
6936
  }
6867
6937
  if (htmlFilePath) addHtmlScriptEntries(htmlFilePath);
6868
6938
  },
6869
- buildStart() {
6939
+ options(inputOptions) {
6940
+ if (!isBundledDevRemote || !isClientEnvironment(this)) return;
6941
+ const input = inputOptions.input;
6942
+ if (typeof input === "object" && input !== null && !Array.isArray(input)) return {
6943
+ ...inputOptions,
6944
+ input: {
6945
+ ...input,
6946
+ [entryName]: getEntryPath()
6947
+ }
6948
+ };
6949
+ return {
6950
+ ...inputOptions,
6951
+ input: [...input === void 0 ? [] : [input].flat(), getEntryPath()]
6952
+ };
6953
+ },
6954
+ buildEnd(error) {
6955
+ if (error && isBundledDevRemote) resolveBundledDevRemoteEntryCode?.(void 0);
6956
+ },
6957
+ async buildStart() {
6958
+ if (inject === "entry" && waitsForInit && isClientEnvironment(this)) for (const entry of [...entryFiles]) {
6959
+ if (path$1.isAbsolute(entry)) continue;
6960
+ const resolved = await this.resolve(entry, void 0, { skipSelf: true }).catch(() => null);
6961
+ if (resolved && !resolved.external && (_command === "serve" || !resolved.id.startsWith("\0"))) addEntryFile(resolveProjectId(resolved.id));
6962
+ }
6870
6963
  if (_command === "serve") return;
6871
6964
  if (skipSvelteKitSsrBuild()) return;
6872
6965
  if (this.environment?.name === "ssr") return;
@@ -6888,6 +6981,15 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6888
6981
  if (htmlFilePath) addHtmlScriptEntries(htmlFilePath);
6889
6982
  },
6890
6983
  generateBundle(_options, bundle) {
6984
+ if (isBundledDevRemote && _command === "serve") {
6985
+ const remoteEntryChunk = Object.values(bundle).find((output) => output.type === "chunk" && output.isEntry && output.facadeModuleId === getEntryPath());
6986
+ if (remoteEntryChunk?.type === "chunk") {
6987
+ const code = `export { ${remoteEntryChunk.exports.join(", ")} } from ${JSON.stringify(`./${remoteEntryChunk.fileName}`)};\n`;
6988
+ bundledDevRemoteEntryCode = Promise.resolve(code);
6989
+ resolveBundledDevRemoteEntryCode?.(code);
6990
+ }
6991
+ return;
6992
+ }
6891
6993
  if (skipSvelteKitSsrBuild()) return;
6892
6994
  if (entryName === "remoteEntry" && emitFileId && fileName && !viteConfig?.build?.ssr && _options?.format === "es" && viteConfig?.build?.modulePreload !== false) {
6893
6995
  const remoteEntryFile = findRemoteEntryFile(fileName, bundle);
@@ -6972,11 +7074,18 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
6972
7074
  };
6973
7075
  setTimeout(retry, 0);
6974
7076
  },
7077
+ load(id) {
7078
+ return virtualEntryCode.get(id);
7079
+ },
6975
7080
  transform(code, id) {
6976
7081
  if (skipSvelteKitSsrBuild()) return;
6977
7082
  if (viteConfig?.command === "build" && !waitsForInit) return;
6978
7083
  if (isSvelteKitServerModule(id)) return;
6979
- if (hasEntryBootstrapParam(id)) return;
7084
+ if (hasEntryBootstrapParam(id)) return {
7085
+ code,
7086
+ map: null,
7087
+ moduleSideEffects: true
7088
+ };
6980
7089
  if (normalizeModuleId(id).endsWith(".html")) return;
6981
7090
  const projectId = resolveProjectId(id);
6982
7091
  if (skipTransformIds.has(projectId)) return;
@@ -7010,8 +7119,15 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
7010
7119
  clientInjected = true;
7011
7120
  injectedTransformIds.add(projectId);
7012
7121
  if (!waitsForInit) return mapCodeToCodeWithSourcemap(`import ${JSON.stringify(getEntryPath())};\n` + code);
7013
- const entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
7014
- return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, { skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule }));
7122
+ let entrySrc = id.includes("?") ? `${id}&${ENTRY_BOOTSTRAP_QUERY.slice(1)}` : `${id}${ENTRY_BOOTSTRAP_QUERY}`;
7123
+ if (entrySrc.startsWith("\0")) {
7124
+ virtualEntryCode.set(entrySrc, code);
7125
+ entrySrc = toViteEncodedId(entrySrc.slice(1));
7126
+ }
7127
+ return mapCodeToCodeWithSourcemap(getBootstrapSource(getEntryPath(), entrySrc, false, {
7128
+ skipRemotePreload: _command === "serve" && isNuxtEntryAsyncModule,
7129
+ isBundled: _command === "serve" && this.environment?.config?.isBundled === true
7130
+ }));
7015
7131
  }
7016
7132
  }
7017
7133
  }];
@@ -7073,6 +7189,16 @@ function checkAliasConflicts(options) {
7073
7189
  const REACT_REFRESH_PATH = "/@react-refresh";
7074
7190
  const LOCAL_REACT_REFRESH_PATH = "/@mf-react-refresh-local";
7075
7191
  const HOST_REACT_REFRESH_URL = "__MF_REACT_REFRESH_URL__";
7192
+ const HOST_REACT_REFRESH_RUNTIME = "__MF_REACT_REFRESH_RUNTIME__";
7193
+ const LOCAL_REACT_REFRESH_ID = "virtual:mf-react-refresh-local";
7194
+ const REACT_REFRESH_EXPORTS = [
7195
+ "injectIntoGlobalHook",
7196
+ "register",
7197
+ "getRefreshReg",
7198
+ "createSignatureFunctionForTransform",
7199
+ "registerExportsForReactRefresh",
7200
+ "validateRefreshBoundaryAndEnqueueUpdate"
7201
+ ];
7076
7202
  function stripQuery(url) {
7077
7203
  return url?.replace(/\?.*$/, "");
7078
7204
  }
@@ -7098,8 +7224,9 @@ function resolveReactRefreshRuntime(root) {
7098
7224
  */
7099
7225
  const REACT_REFRESH_PROXY_MODULE = [
7100
7226
  `const __remoteUrl = new URL(import.meta.url);`,
7101
- `const __target = window.location.origin === __remoteUrl.origin ? new URL('.${LOCAL_REACT_REFRESH_PATH}', __remoteUrl).href : globalThis.${HOST_REACT_REFRESH_URL} || window.location.origin + '${REACT_REFRESH_PATH}';`,
7102
- `const __rt = await import(__target);`,
7227
+ `const __isHost = window.location.origin !== __remoteUrl.origin;`,
7228
+ `const __target = __isHost ? globalThis.${HOST_REACT_REFRESH_URL} || window.location.origin + '${REACT_REFRESH_PATH}' : new URL('.${LOCAL_REACT_REFRESH_PATH}', __remoteUrl).href;`,
7229
+ `const __rt = (__isHost && globalThis.${HOST_REACT_REFRESH_RUNTIME}) || await import(__target);`,
7103
7230
  `export const injectIntoGlobalHook = __rt.injectIntoGlobalHook;`,
7104
7231
  `export const register = __rt.register;`,
7105
7232
  `export const getRefreshReg = __rt.getRefreshReg;`,
@@ -7109,34 +7236,64 @@ const REACT_REFRESH_PROXY_MODULE = [
7109
7236
  `export const __hmr_import = __rt.__hmr_import;`,
7110
7237
  `export default __rt.default || __rt;`
7111
7238
  ].join("\n");
7239
+ /**
7240
+ * `/@react-refresh` for a bundledDev remote. The bundle cannot fetch the
7241
+ * host's runtime by URL, so it binds lazily to the runtime the host page
7242
+ * publishes on a global and falls back to its own copy when opened directly.
7243
+ * Both share one component registry with the host's React.
7244
+ */
7245
+ const BUNDLED_REACT_REFRESH_MODULE = [
7246
+ `import * as __local from '${LOCAL_REACT_REFRESH_ID}';`,
7247
+ `const __rt = () => globalThis.${HOST_REACT_REFRESH_RUNTIME} || __local;`,
7248
+ ...REACT_REFRESH_EXPORTS.map((name) => `export function ${name}(...args) { return __rt().${name}(...args); }`),
7249
+ `export const __hmr_import = __local.__hmr_import;`,
7250
+ `export const __mfLocalRuntime = __local;`,
7251
+ `export default { injectIntoGlobalHook };`
7252
+ ].join("\n");
7112
7253
  const reactAdapter = {
7113
7254
  name: "react",
7114
7255
  pluginNames: ["vite:react-refresh", "vite:react-swc"],
7115
7256
  host: { transformIndexHtml({ server }) {
7116
7257
  const refreshPath = `${server.config.base.replace(/\/$/, "")}${REACT_REFRESH_PATH}`;
7258
+ const isBundled = server.config.experimental?.bundledDev === true;
7117
7259
  return [{
7118
7260
  tag: "script",
7119
7261
  children: `globalThis.${HOST_REACT_REFRESH_URL} = new URL(${JSON.stringify(refreshPath)}, window.location.origin).href;`,
7120
7262
  injectTo: "head-prepend"
7263
+ }, {
7264
+ tag: "script",
7265
+ attrs: { type: "module" },
7266
+ children: `import * as rt from ${JSON.stringify(isBundled ? REACT_REFRESH_PATH : refreshPath)};\nglobalThis.${HOST_REACT_REFRESH_RUNTIME} ??= rt.__mfLocalRuntime || rt;`,
7267
+ injectTo: "head-prepend"
7121
7268
  }];
7122
7269
  } },
7123
- remote: { configureServer({ server }) {
7124
- let reactRefreshRuntime;
7125
- server.middlewares.use((req, res, next) => {
7126
- const url = stripQuery(req.url);
7127
- if (url?.endsWith(LOCAL_REACT_REFRESH_PATH)) {
7128
- reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
7270
+ remote: {
7271
+ configureServer({ server }) {
7272
+ let reactRefreshRuntime;
7273
+ server.middlewares.use((req, res, next) => {
7274
+ const url = stripQuery(req.url);
7275
+ if (url?.endsWith(LOCAL_REACT_REFRESH_PATH)) {
7276
+ reactRefreshRuntime ??= resolveReactRefreshRuntime(server.config.root);
7277
+ res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7278
+ res.setHeader("Access-Control-Allow-Origin", "*");
7279
+ res.end(reactRefreshRuntime);
7280
+ return;
7281
+ }
7282
+ if (!url?.endsWith(REACT_REFRESH_PATH)) return next();
7129
7283
  res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7130
7284
  res.setHeader("Access-Control-Allow-Origin", "*");
7131
- res.end(reactRefreshRuntime);
7132
- return;
7133
- }
7134
- if (!url?.endsWith(REACT_REFRESH_PATH)) return next();
7135
- res.setHeader("Content-Type", "application/javascript; charset=utf-8");
7136
- res.setHeader("Access-Control-Allow-Origin", "*");
7137
- res.end(REACT_REFRESH_PROXY_MODULE);
7138
- });
7139
- } }
7285
+ res.end(REACT_REFRESH_PROXY_MODULE);
7286
+ });
7287
+ },
7288
+ resolveId(id) {
7289
+ if (id === LOCAL_REACT_REFRESH_ID) return `\0${LOCAL_REACT_REFRESH_ID}`;
7290
+ },
7291
+ load(id, { root, isBundled }) {
7292
+ if (!isBundled) return;
7293
+ if (id === REACT_REFRESH_PATH) return BUNDLED_REACT_REFRESH_MODULE;
7294
+ if (id === `\0${LOCAL_REACT_REFRESH_ID}`) return resolveReactRefreshRuntime(root);
7295
+ }
7296
+ }
7140
7297
  };
7141
7298
  //#endregion
7142
7299
  //#region src/plugins/hmr/vue.ts
@@ -7523,14 +7680,18 @@ function pluginDevRemoteHmr(options) {
7523
7680
  const isRemote = Object.keys(options.exposes).length > 0;
7524
7681
  let adapters = [];
7525
7682
  let strategy = "full-reload";
7683
+ let root;
7684
+ let devServer;
7526
7685
  return {
7527
7686
  name: "module-federation-dev-remote-hmr",
7528
7687
  apply: "serve",
7529
7688
  configResolved(config) {
7689
+ root = config.root;
7530
7690
  adapters = resolveAdapters(config.plugins);
7531
7691
  strategy = resolveHmrStrategy(options.dev, config.plugins);
7532
7692
  },
7533
7693
  configureServer(server) {
7694
+ devServer = server;
7534
7695
  if (!isRemoteHmrEnabled(options.dev)) return;
7535
7696
  if (isRemote) {
7536
7697
  for (const adapter of adapters) adapter.remote?.configureServer?.({
@@ -7548,6 +7709,27 @@ function pluginDevRemoteHmr(options) {
7548
7709
  if (strategy === "full-reload") setupHostFullReloadRelay(server, options);
7549
7710
  }
7550
7711
  },
7712
+ resolveId(id) {
7713
+ if (!isRemote || !isRemoteHmrEnabled(options.dev)) return;
7714
+ for (const adapter of adapters) {
7715
+ const resolved = adapter.remote?.resolveId?.(id);
7716
+ if (resolved) return resolved;
7717
+ }
7718
+ },
7719
+ load: {
7720
+ order: "pre",
7721
+ handler(id) {
7722
+ if (!isRemote || !isRemoteHmrEnabled(options.dev) || !root) return;
7723
+ const isBundled = this.environment?.config?.isBundled === true;
7724
+ for (const adapter of adapters) {
7725
+ const code = adapter.remote?.load?.(id, {
7726
+ root,
7727
+ isBundled
7728
+ });
7729
+ if (code !== void 0) return code;
7730
+ }
7731
+ }
7732
+ },
7551
7733
  transform: {
7552
7734
  order: "post",
7553
7735
  handler(code, id) {
@@ -7566,8 +7748,9 @@ function pluginDevRemoteHmr(options) {
7566
7748
  order: "pre",
7567
7749
  handler(_html, ctx) {
7568
7750
  if (!isRemoteHmrEnabled(options.dev)) return;
7569
- if (!isHost || !ctx.server) return;
7570
- return collectHostTags(ctx.server, options, adapters);
7751
+ const server = ctx.server ?? devServer;
7752
+ if (!isHost || !server) return;
7753
+ return collectHostTags(server, options, adapters);
7571
7754
  }
7572
7755
  }
7573
7756
  };
@@ -8083,7 +8266,7 @@ function ${helperName}(names) {
8083
8266
  }
8084
8267
  //#endregion
8085
8268
  //#region package.json
8086
- var version$1 = "1.23.2";
8269
+ var version$1 = "1.23.4";
8087
8270
  //#endregion
8088
8271
  //#region src/virtualModules/virtualExposesSSR.ts
8089
8272
  /**
@@ -10486,6 +10669,8 @@ function pluginSSRRemoteEntry(options) {
10486
10669
  return exposeKeys.every((key) => code.includes(JSON.stringify(key)));
10487
10670
  })?.fileName;
10488
10671
  };
10672
+ const isNuxtLike = () => isNuxtProject || isNuxtClientBase(getBasePath$1(viteConfig?.base));
10673
+ const findEmittedExposesChunk = (bundle) => Object.values(bundle).find((file) => file.type === "chunk" && file.facadeModuleId === virtualExposesSSRId)?.fileName;
10489
10674
  return [{
10490
10675
  name: "mf:ssr-remote-entry:pre",
10491
10676
  enforce: "pre",
@@ -10528,7 +10713,7 @@ function pluginSSRRemoteEntry(options) {
10528
10713
  const base = "/__mf_ssr__";
10529
10714
  const basePath = getBasePath$1(viteConfig?.base);
10530
10715
  const ssrEntryFileName = getSsrRemoteEntryFileName(options);
10531
- if (isNuxtProject || isNuxtClientBase(basePath)) server.middlewares.use((req, _res, next) => {
10716
+ if (isNuxtLike()) server.middlewares.use((req, _res, next) => {
10532
10717
  if (req.url?.replace(/\?.*/, "") === `${basePath}/${ssrEntryFileName}`) req.url = `${basePath}/__mf_ssr__/${ssrEntryFileName}`;
10533
10718
  next();
10534
10719
  });
@@ -10615,16 +10800,26 @@ function pluginSSRRemoteEntry(options) {
10615
10800
  fileName: ssrOutputFilename,
10616
10801
  preserveSignature: "strict"
10617
10802
  });
10803
+ else if (Object.keys(options.exposes).length > 0 && !isNuxtLike()) this.emitFile({
10804
+ type: "chunk",
10805
+ id: virtualExposesSSRId,
10806
+ name: "ssrExposes",
10807
+ preserveSignature: "strict"
10808
+ });
10618
10809
  },
10619
10810
  generateBundle: {
10620
10811
  order: "post",
10621
10812
  handler(_options, bundle) {
10622
10813
  const isRolldown = getIsRolldown(this);
10623
10814
  const environment = this.environment;
10624
- const exposesChunk = findNuxtExposesChunk(bundle);
10815
+ const exposesChunk = findNuxtExposesChunk(bundle) ?? findEmittedExposesChunk(bundle);
10625
10816
  if (!isRolldown && isSsrRemoteEntryBuild(environment)) {
10626
10817
  let source = getSsrRemoteEntrySource();
10627
- if (exposesChunk) source = source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g, `import("./${exposesChunk}")`);
10818
+ if (exposesChunk) {
10819
+ let exposesImport = path$1.posix.relative(path$1.posix.dirname(ssrOutputFilename), exposesChunk);
10820
+ if (!exposesImport.startsWith(".")) exposesImport = `./${exposesImport}`;
10821
+ source = source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g, `import("${exposesImport}")`);
10822
+ }
10628
10823
  this.emitFile({
10629
10824
  type: "asset",
10630
10825
  fileName: ssrOutputFilename,
@@ -10743,6 +10938,7 @@ const VarRemoteEntry = (providedOptions) => {
10743
10938
  */
10744
10939
  async generateBundle(_options, bundle) {
10745
10940
  if (!varFilename) return;
10941
+ if (viteConfig?.command === "serve") return;
10746
10942
  if (!isValidVarName(name)) mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);
10747
10943
  const remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
10748
10944
  if (!remoteEntryFile) throw createModuleFederationError(`Couldn't find a remoteEntry chunk file for ${mfOptions.filename}, can't generate varRemoteEntry file`);
@@ -11366,6 +11562,15 @@ const PRELOAD_HELPER_CHUNK = "vite-preload-helper";
11366
11562
  const PRELOAD_HELPER_TEST = /\0?vite\/preload-helper/;
11367
11563
  const MF_GROUP_PRIORITY = 1e6;
11368
11564
  const USER_GROUP_MAX_PRIORITY = MF_GROUP_PRIORITY - 1;
11565
+ function getBundledDevHtmlPreambleChunk(id, ctx) {
11566
+ let importers;
11567
+ try {
11568
+ importers = ctx.getModuleInfo(id)?.importers;
11569
+ } catch {
11570
+ return null;
11571
+ }
11572
+ return importers?.some((importer) => importer.includes("?html-proxy")) ? "mf-html-preamble" : null;
11573
+ }
11369
11574
  function normalizeVinextRscPreloadHints(code) {
11370
11575
  return code.replace(/(:HL\[[^\]\n]*?,)"stylesheet"/g, "$1\"style\"").replace(/(:HL\[[^\]\n]*?,)\\"stylesheet\\"/g, "$1\\\"style\\\"");
11371
11576
  }
@@ -11898,7 +12103,7 @@ export default __mfShared.default ?? __mfShared;`
11898
12103
  resolveImportPath(ssrEntryLoaderSpecifier);
11899
12104
  options.runtimePlugins.push([ssrEntryLoaderSpecifier, {
11900
12105
  resolvedShared,
11901
- ...options.ssrEntryLoader?.strategy ? { strategy: options.ssrEntryLoader.strategy } : {}
12106
+ ...options.ssrEntryLoader
11902
12107
  }]);
11903
12108
  } catch {}
11904
12109
  }
@@ -11927,7 +12132,7 @@ function withoutDynamicRemoteTypeHints(options) {
11927
12132
  }
11928
12133
  function loadPluginDts(options) {
11929
12134
  if (options.dts === false) return [];
11930
- return [import("./pluginDts-DnEX3cp_.js").then(({ default: pluginDts }) => pluginDts(options))];
12135
+ return [import("./pluginDts-CVyHPAEq.js").then(({ default: pluginDts }) => pluginDts(options))];
11931
12136
  }
11932
12137
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
11933
12138
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -12037,6 +12242,124 @@ function federation(mfUserOptions) {
12037
12242
  return getSharedExportUsage(pkg, shared[key], key, options);
12038
12243
  });
12039
12244
  };
12245
+ function applyFederationChunking(config, ctx, snapshotOutput) {
12246
+ const runtimeInitId = getRuntimeInitStatusImportId(options);
12247
+ config.build = config.build || {};
12248
+ let warnedAboutCodeSplitting = false;
12249
+ const ensureCodeSplitting = (output) => {
12250
+ if (output?.codeSplitting !== false) return;
12251
+ delete output.codeSplitting;
12252
+ if (warnedAboutCodeSplitting) return;
12253
+ warnedAboutCodeSplitting = true;
12254
+ mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
12255
+ };
12256
+ const isFederationGroup = (group) => typeof group === "object" && group !== null && federationGroups.has(group);
12257
+ let warnedAboutGroupPriority = false;
12258
+ const clampUserGroup = (group) => {
12259
+ const candidate = group;
12260
+ if (typeof candidate?.priority !== "number") return group;
12261
+ if (candidate.priority <= USER_GROUP_MAX_PRIORITY) return group;
12262
+ if (!warnedAboutGroupPriority) {
12263
+ warnedAboutGroupPriority = true;
12264
+ mfWarn(`Clamping \`output.codeSplitting.groups\` priority to ${USER_GROUP_MAX_PRIORITY} — module federation groups must keep the highest priority so shared dependency init wrappers stay isolated in their own chunks.`);
12265
+ }
12266
+ return {
12267
+ ...candidate,
12268
+ priority: USER_GROUP_MAX_PRIORITY
12269
+ };
12270
+ };
12271
+ const federationGroupDebugName = supportsCodeSplittingGroupDebugName(ctx) ? { debugName: "module-federation" } : {};
12272
+ let warnedAboutManualChunks = false;
12273
+ let warnedAboutObjectManualChunks = false;
12274
+ const applyManualChunks = (output, useCodeSplitting) => {
12275
+ ensureCodeSplitting(output);
12276
+ const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
12277
+ const mfChunkName = function(id) {
12278
+ if (id.includes(runtimeInitId) || id.includes("__mf_v__runtimeInit__mf_v__")) return "runtimeInit";
12279
+ if (isSharedCacheHelpersId(id)) return getSharedChunkName(id);
12280
+ if (id.includes("__loadShare__")) {
12281
+ const pkg = getCachedLoadSharePkg(id);
12282
+ const key = pkg && findSharedKey(pkg, shared);
12283
+ if (key && shared[key].shareConfig.eager === true) return "loadShare-eager";
12284
+ if (key && shared[key].shareConfig.import === false) return null;
12285
+ if (pkg && !id.includes("commonjs-proxy") && isCoalescableLoadShareWrapper(pkg, options, id)) return getSharedChunkName(id);
12286
+ const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
12287
+ return match ? match[1] : "loadShare";
12288
+ }
12289
+ return null;
12290
+ };
12291
+ patchedManualChunks.add(mfChunkName);
12292
+ if (!useCodeSplitting) {
12293
+ if (isPatchedByPlugin) return;
12294
+ const userManualChunks = output.manualChunks;
12295
+ if (userManualChunks && typeof userManualChunks !== "function" && !warnedAboutObjectManualChunks) {
12296
+ warnedAboutObjectManualChunks = true;
12297
+ mfWarn("Ignoring the object form of `output.manualChunks` because module federation cannot safely compose with it. Use the function form instead: federation modules are claimed first and your function runs for everything else.");
12298
+ }
12299
+ const mfManualChunks = function(id, ...rest) {
12300
+ if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
12301
+ const mfChunk = mfChunkName(id);
12302
+ if (mfChunk) return mfChunk;
12303
+ if (typeof userManualChunks === "function") return userManualChunks(id, ...rest) ?? void 0;
12304
+ };
12305
+ patchedManualChunks.add(mfManualChunks);
12306
+ output.manualChunks = mfManualChunks;
12307
+ return;
12308
+ }
12309
+ if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
12310
+ warnedAboutManualChunks = true;
12311
+ mfWarn("Ignoring `output.manualChunks` for the Rolldown build because module federation manages chunking with `output.codeSplitting.groups`. Move your grouping there — user groups are kept below the federation groups.");
12312
+ }
12313
+ const existingGroups = output.codeSplitting && typeof output.codeSplitting === "object" ? output.codeSplitting.groups : void 0;
12314
+ const userGroups = Array.isArray(existingGroups) ? existingGroups.filter((group) => !isFederationGroup(group)).map(clampUserGroup) : [];
12315
+ const mfPreloadGroup = {
12316
+ name: PRELOAD_HELPER_CHUNK,
12317
+ test: PRELOAD_HELPER_TEST,
12318
+ priority: 1000001
12319
+ };
12320
+ const mfNameGroup = {
12321
+ name: mfChunkName,
12322
+ priority: MF_GROUP_PRIORITY,
12323
+ ...federationGroupDebugName
12324
+ };
12325
+ federationGroups.add(mfPreloadGroup);
12326
+ federationGroups.add(mfNameGroup);
12327
+ const groups = [mfPreloadGroup, mfNameGroup];
12328
+ if (!snapshotOutput) {
12329
+ const htmlPreambleGroup = {
12330
+ name: getBundledDevHtmlPreambleChunk,
12331
+ priority: 1000002
12332
+ };
12333
+ federationGroups.add(htmlPreambleGroup);
12334
+ groups.push(htmlPreambleGroup);
12335
+ }
12336
+ groups.push(...userGroups);
12337
+ output.codeSplitting = {
12338
+ ...output.codeSplitting || {},
12339
+ groups
12340
+ };
12341
+ delete output.manualChunks;
12342
+ };
12343
+ config.build.rollupOptions = config.build.rollupOptions || {};
12344
+ const rollupOutput = config.build.rollupOptions.output;
12345
+ if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output, false));
12346
+ else applyManualChunks(config.build.rollupOptions.output ||= {}, false);
12347
+ const buildWithRolldown = config.build;
12348
+ buildWithRolldown.rolldownOptions = buildWithRolldown.rolldownOptions || {};
12349
+ const rolldownOutput = buildWithRolldown.rolldownOptions.output;
12350
+ const snapshotRolldownOutput = (output) => ({
12351
+ entryFileNames: output.entryFileNames,
12352
+ chunkFileNames: output.chunkFileNames,
12353
+ assetFileNames: output.assetFileNames
12354
+ });
12355
+ if (Array.isArray(rolldownOutput)) {
12356
+ rolldownOutput.forEach((output) => applyManualChunks(output, true));
12357
+ if (snapshotOutput) desiredRolldownOutput = rolldownOutput.map((output) => snapshotRolldownOutput(output));
12358
+ } else {
12359
+ applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {}, true);
12360
+ if (snapshotOutput) desiredRolldownOutput = [snapshotRolldownOutput(buildWithRolldown.rolldownOptions.output)];
12361
+ }
12362
+ }
12040
12363
  return [
12041
12364
  {
12042
12365
  name: "vite:module-federation-virtual-modules",
@@ -12077,7 +12400,11 @@ function federation(mfUserOptions) {
12077
12400
  const virtualModule = VirtualModule.findById(id);
12078
12401
  if (!virtualModule) return;
12079
12402
  if (command === "build" && (id.includes("__loadShare__") || id.includes("__loadRemote__"))) return;
12080
- return virtualModule.code;
12403
+ const code = virtualModule.code;
12404
+ if (code && id.includes("__loadShare__")) {
12405
+ if (isServerContext(this, loadOptions?.ssr === true)) return prependWorkspaceSingletonSsrImport(code);
12406
+ }
12407
+ return code;
12081
12408
  }
12082
12409
  },
12083
12410
  ...options.experiments.externalRuntime ? [pluginExternalRuntimeCore()] : [],
@@ -12162,13 +12489,20 @@ function federation(mfUserOptions) {
12162
12489
  getParsePromise: () => moduleParseController.parsePromise
12163
12490
  }),
12164
12491
  pluginLazyConsumeOnlyShares(options),
12492
+ {
12493
+ name: "module-federation-bundled-dev-chunks",
12494
+ apply: "serve",
12495
+ config(config) {
12496
+ if (!config.experimental?.bundledDev) return;
12497
+ applyFederationChunking(config, this, false);
12498
+ }
12499
+ },
12165
12500
  {
12166
12501
  name: "module-federation-esm-shims",
12167
12502
  enforce: "pre",
12168
12503
  apply: "build",
12169
12504
  config(config) {
12170
12505
  isSsrBuild = Boolean(config.build?.ssr);
12171
- const runtimeInitId = getRuntimeInitStatusImportId(options);
12172
12506
  config.build = config.build || {};
12173
12507
  if (config.build.modulePreload !== false) {
12174
12508
  const remoteEntryBasename = path$1.posix.basename(options.filename);
@@ -12190,115 +12524,7 @@ function federation(mfUserOptions) {
12190
12524
  }
12191
12525
  };
12192
12526
  }
12193
- let warnedAboutCodeSplitting = false;
12194
- const ensureCodeSplitting = (output) => {
12195
- if (output?.codeSplitting !== false) return;
12196
- delete output.codeSplitting;
12197
- if (warnedAboutCodeSplitting) return;
12198
- warnedAboutCodeSplitting = true;
12199
- mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
12200
- };
12201
- const isFederationGroup = (group) => typeof group === "object" && group !== null && federationGroups.has(group);
12202
- let warnedAboutGroupPriority = false;
12203
- const clampUserGroup = (group) => {
12204
- const candidate = group;
12205
- if (typeof candidate?.priority !== "number") return group;
12206
- if (candidate.priority <= USER_GROUP_MAX_PRIORITY) return group;
12207
- if (!warnedAboutGroupPriority) {
12208
- warnedAboutGroupPriority = true;
12209
- mfWarn(`Clamping \`output.codeSplitting.groups\` priority to ${USER_GROUP_MAX_PRIORITY} — module federation groups must keep the highest priority so shared dependency init wrappers stay isolated in their own chunks.`);
12210
- }
12211
- return {
12212
- ...candidate,
12213
- priority: USER_GROUP_MAX_PRIORITY
12214
- };
12215
- };
12216
- const federationGroupDebugName = supportsCodeSplittingGroupDebugName(this) ? { debugName: "module-federation" } : {};
12217
- let warnedAboutManualChunks = false;
12218
- let warnedAboutObjectManualChunks = false;
12219
- const applyManualChunks = (output, useCodeSplitting) => {
12220
- ensureCodeSplitting(output);
12221
- const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
12222
- const mfChunkName = function(id) {
12223
- if (id.includes(runtimeInitId) || id.includes("__mf_v__runtimeInit__mf_v__")) return "runtimeInit";
12224
- if (isSharedCacheHelpersId(id)) return getSharedChunkName(id);
12225
- if (id.includes("__loadShare__")) {
12226
- const pkg = getCachedLoadSharePkg(id);
12227
- const key = pkg && findSharedKey(pkg, shared);
12228
- if (key && shared[key].shareConfig.eager === true) return "loadShare-eager";
12229
- if (key && shared[key].shareConfig.import === false) return null;
12230
- if (pkg && !id.includes("commonjs-proxy") && isCoalescableLoadShareWrapper(pkg, options, id)) return getSharedChunkName(id);
12231
- const match = id.match(/([^/\\]+__loadShare__[^/\\]+)/);
12232
- return match ? match[1] : "loadShare";
12233
- }
12234
- return null;
12235
- };
12236
- patchedManualChunks.add(mfChunkName);
12237
- if (!useCodeSplitting) {
12238
- if (isPatchedByPlugin) return;
12239
- const userManualChunks = output.manualChunks;
12240
- if (userManualChunks && typeof userManualChunks !== "function" && !warnedAboutObjectManualChunks) {
12241
- warnedAboutObjectManualChunks = true;
12242
- mfWarn("Ignoring the object form of `output.manualChunks` because module federation cannot safely compose with it. Use the function form instead: federation modules are claimed first and your function runs for everything else.");
12243
- }
12244
- const mfManualChunks = function(id, ...rest) {
12245
- if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
12246
- const mfChunk = mfChunkName(id);
12247
- if (mfChunk) return mfChunk;
12248
- if (typeof userManualChunks === "function") return userManualChunks(id, ...rest) ?? void 0;
12249
- };
12250
- patchedManualChunks.add(mfManualChunks);
12251
- output.manualChunks = mfManualChunks;
12252
- return;
12253
- }
12254
- if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
12255
- warnedAboutManualChunks = true;
12256
- mfWarn("Ignoring `output.manualChunks` for the Rolldown build because module federation manages chunking with `output.codeSplitting.groups`. Move your grouping there — user groups are kept below the federation groups.");
12257
- }
12258
- const existingGroups = output.codeSplitting && typeof output.codeSplitting === "object" ? output.codeSplitting.groups : void 0;
12259
- const userGroups = Array.isArray(existingGroups) ? existingGroups.filter((group) => !isFederationGroup(group)).map(clampUserGroup) : [];
12260
- const mfPreloadGroup = {
12261
- name: PRELOAD_HELPER_CHUNK,
12262
- test: PRELOAD_HELPER_TEST,
12263
- priority: 1000001
12264
- };
12265
- const mfNameGroup = {
12266
- name: mfChunkName,
12267
- priority: MF_GROUP_PRIORITY,
12268
- ...federationGroupDebugName
12269
- };
12270
- federationGroups.add(mfPreloadGroup);
12271
- federationGroups.add(mfNameGroup);
12272
- const groups = [
12273
- mfPreloadGroup,
12274
- mfNameGroup,
12275
- ...userGroups
12276
- ];
12277
- output.codeSplitting = {
12278
- ...output.codeSplitting || {},
12279
- groups
12280
- };
12281
- delete output.manualChunks;
12282
- };
12283
- config.build.rollupOptions = config.build.rollupOptions || {};
12284
- const rollupOutput = config.build.rollupOptions.output;
12285
- if (Array.isArray(rollupOutput)) rollupOutput.forEach((output) => applyManualChunks(output, false));
12286
- else applyManualChunks(config.build.rollupOptions.output ||= {}, false);
12287
- const buildWithRolldown = config.build;
12288
- buildWithRolldown.rolldownOptions = buildWithRolldown.rolldownOptions || {};
12289
- const rolldownOutput = buildWithRolldown.rolldownOptions.output;
12290
- const snapshotRolldownOutput = (output) => ({
12291
- entryFileNames: output.entryFileNames,
12292
- chunkFileNames: output.chunkFileNames,
12293
- assetFileNames: output.assetFileNames
12294
- });
12295
- if (Array.isArray(rolldownOutput)) {
12296
- rolldownOutput.forEach((output) => applyManualChunks(output, true));
12297
- desiredRolldownOutput = rolldownOutput.map((output) => snapshotRolldownOutput(output));
12298
- } else {
12299
- applyManualChunks(buildWithRolldown.rolldownOptions.output ||= {}, true);
12300
- desiredRolldownOutput = [snapshotRolldownOutput(buildWithRolldown.rolldownOptions.output)];
12301
- }
12527
+ applyFederationChunking(config, this, true);
12302
12528
  },
12303
12529
  async buildApp(builder) {
12304
12530
  const desiredOutput = desiredRolldownOutput;
@@ -12337,8 +12563,7 @@ function federation(mfUserOptions) {
12337
12563
  const virtualModule = VirtualModule.findById(id);
12338
12564
  if (!virtualModule?.code) return null;
12339
12565
  let code = virtualModule.code;
12340
- const consumerTarget = resolveEnvironmentConsumerTarget(this);
12341
- if (consumerTarget === "server" || !consumerTarget && isSsrBuild) {
12566
+ if (isServerContext(this, isSsrBuild)) {
12342
12567
  const withSsrImport = prependWorkspaceSingletonSsrImport(code);
12343
12568
  if (withSsrImport !== code) {
12344
12569
  const pkg = getCachedLoadSharePkg(id);