Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions apps/rsbuild-ssr-host/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { getRemoteStylesheets, lazyRemote } from "@module-federation/tanstack/runtime";
import {
dedupeRemoteStylesheets,
getRemoteStylesheets,
lazyRemote,
} from "@module-federation/tanstack/runtime";
import { createFileRoute } from "@tanstack/react-router";
import { RemoteBoundary } from "../components/RemoteBoundary";
import { ServerAnswers } from "../components/ServerAnswers";
Expand All @@ -9,12 +13,6 @@ const RsbuildStatusCard = lazyRemote(() => import("tanstack_rsbuild_ssr_remote/S
const ViteStatusCard = lazyRemote(() => import("tanstack_vite_remote/StatusCard"));
const ViteRouterCard = lazyRemote(() => import("tanstack_vite_remote/RouterCard"));

// Manifests of the remotes this route renders on the server.
const serverRenderedManifests = [
"http://127.0.0.1:3004/mf-manifest.json",
"http://127.0.0.1:3001/mf-manifest.json",
];

// Calls the Rsbuild SSR remote's server functions on the server: the remote's container
// sends them to the remote's server, so the answers are in the initial HTML. The POST call
// carries this host's name in its body.
Expand All @@ -33,10 +31,14 @@ export const Route = createFileRoute("/")({
loader: async () => {
const [stylesheets, remoteAnswer] = await Promise.all([
Promise.all(
serverRenderedManifests.map((manifest) =>
getRemoteStylesheets(manifest, "./StatusCard").catch(() => []),
["tanstack_rsbuild_ssr_remote/StatusCard", "tanstack_vite_remote/StatusCard"].map(
(specifier) =>
getRemoteStylesheets(specifier, {
onError: (error) =>
console.error(`Failed to resolve stylesheets for ${specifier}`, error),
}).catch(() => []),
),
).then((lists) => lists.flat()),
).then((lists) => dedupeRemoteStylesheets(...lists)),
askRemoteServer(),
RsbuildStatusCard.preload().catch(() => null),
ViteStatusCard.preload().catch(() => null),
Expand Down
22 changes: 12 additions & 10 deletions apps/vite-host/src/routes/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { getRemoteStylesheets, lazyRemote } from "@module-federation/tanstack/runtime";
import {
dedupeRemoteStylesheets,
getRemoteStylesheets,
lazyRemote,
} from "@module-federation/tanstack/runtime";
import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { RemoteBoundary } from "../components/RemoteBoundary";
Expand All @@ -11,12 +15,6 @@ const RemoteRouterCard = lazyRemote(() => import("tanstack_vite_remote/RouterCar
const RsbuildStatusCard = lazyRemote(() => import("tanstack_rsbuild_remote/StatusCard"));
const RsbuildSsrStatusCard = lazyRemote(() => import("tanstack_rsbuild_ssr_remote/StatusCard"));

// Manifests of the remotes this route renders on the server.
const serverRenderedManifests = [
"http://127.0.0.1:3001/mf-manifest.json",
"http://127.0.0.1:3004/mf-manifest.json",
];

// Calls the Rsbuild SSR remote's server functions on the server: the remote's container
// sends them to the remote's server, so the answers are in the initial HTML. The POST call
// carries this host's name in its body.
Expand All @@ -35,10 +33,14 @@ export const Route = createFileRoute("/")({
loader: async () => {
const [stylesheets, remoteAnswer] = await Promise.all([
Promise.all(
serverRenderedManifests.map((manifest) =>
getRemoteStylesheets(manifest, "./StatusCard").catch(() => []),
["tanstack_vite_remote/StatusCard", "tanstack_rsbuild_ssr_remote/StatusCard"].map(
(specifier) =>
getRemoteStylesheets(specifier, {
onError: (error) =>
console.error(`Failed to resolve stylesheets for ${specifier}`, error),
}).catch(() => []),
),
).then((lists) => lists.flat()),
).then((lists) => dedupeRemoteStylesheets(...lists)),
askRemoteServer(),
RemoteStatusCard.preload().catch(() => null),
RemoteRouterCard.preload().catch(() => null),
Expand Down
2 changes: 1 addition & 1 deletion apps/vite-host/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default defineConfig({
tanstack_vite_remote: {
type: "module",
name: "tanstack_vite_remote",
entry: "http://127.0.0.1:3001/remoteEntry.js",
entry: "http://127.0.0.1:3001/mf-manifest.json",
},
tanstack_rsbuild_remote: {
type: "global",
Expand Down
30 changes: 23 additions & 7 deletions packages/tanstack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,9 @@ export const Route = createFileRoute("/")({
// response. Catch route-loader failures so an unavailable remote does not fail the route.
loader: async () => {
const [stylesheets] = await Promise.all([
getRemoteStylesheets("https://remote.test/mf-manifest.json", "./StatusCard").catch(() => []),
getRemoteStylesheets("remote/StatusCard", {
onError: (error) => console.error("Remote stylesheet lookup failed", error),
}).catch(() => []),
StatusCard.preload().catch(() => null),
]);
return { stylesheets };
Expand Down Expand Up @@ -299,12 +301,26 @@ rendering or hydration recovery instead.
its fallback. The import itself loads again after a failure too: `@module-federation/vite`
1.23.3+ retries failed server loads, and the Rsbuild adapter removes a failed
remote module from Rspack's module cache.
- **`getRemoteStylesheets(manifestUrl, expose, { maxAgeMs })`** lists the
stylesheets the remote's manifest declares for an expose, as absolute URLs. A
remote's CSS otherwise loads with its JavaScript, after the HTML, so the
server-rendered markup would be unstyled until then. It works in the browser
and on the server, reuses a fetched manifest for 30 seconds (`maxAgeMs`), and
rejects when the manifest is unreachable or does not list the expose.
- **`getRemoteStylesheets("remote/Expose", options)`** resolves a configured Vite or
Rsbuild remote through the adapter and lists the stylesheets its manifest declares,
as absolute URLs. A remote's CSS otherwise loads with its JavaScript, after the HTML,
so the server-rendered markup would be unstyled until then. It works in the browser
and on the server, reuses a fetched manifest for 30 seconds (`maxAgeMs`), reports
failures through `onError`, and still rejects when the manifest is unreachable or does
not list the expose. The explicit `getRemoteStylesheets(manifestUrl, expose, options)`
form remains available when the manifest boundary is known by the caller.

The adapter resolver matches a remote by its configured key, `name`, or `alias`, and
reads the manifest from the remote's entry: an entry that is already a `.json` manifest
is used as is, and any other entry, such as `remoteEntry.js`, maps to `mf-manifest.json`
in the same directory. A remote configured with several entries uses the first one. For
a different layout, build a resolver with
`createRemoteStylesheetResolver(remotes, { resolveManifestUrl })` and pass it as the
`resolveRemote` option. Without an adapter, such as in a unit test, the `remote/Expose`
form rejects with `RemoteStylesheetResolutionError` unless `resolveRemote` is passed.

- **`dedupeRemoteStylesheets(...groups)`** removes duplicate stylesheet URLs while
preserving their first declaration order.

Remote manifest fetches throw `RemoteFetchError` from the `runtime` entry. Its
`code` distinguishes network, timeout, HTTP, response-size, and JSON parse
Expand Down
10 changes: 10 additions & 0 deletions packages/tanstack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@
"default": "./dist/runtime.cjs"
}
},
"./remote-stylesheet-resolver": {
"import": {
"types": "./dist/remote-stylesheet-resolver.d.ts",
"default": "./dist/remote-stylesheet-resolver.js"
},
"require": {
"types": "./dist/remote-stylesheet-resolver.d.cts",
"default": "./dist/remote-stylesheet-resolver.cjs"
}
},
"./server-container-rpc": {
"import": {
"types": "./dist/server-container-rpc.d.ts",
Expand Down
3 changes: 3 additions & 0 deletions packages/tanstack/rslib.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const entry = {
"node-entry-loader": "./src/node-entry-loader.ts",
"remote-errors": "./src/remote-errors.ts",
"remote-fetch": "./src/remote-fetch.ts",
"remote-stylesheet-adapter": "./src/remote-stylesheet-adapter.ts",
"remote-stylesheet-remotes": "./src/remote-stylesheet-remotes.ts",
"remote-stylesheet-resolver": "./src/remote-stylesheet-resolver.ts",
rsbuild: "./src/rsbuild.ts",
runtime: "./src/runtime.ts",
"server-container": "./src/server-container.ts",
Expand Down
28 changes: 28 additions & 0 deletions packages/tanstack/src/remote-stylesheet-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { normalizeRemoteStylesheetRemotes } from "./remote-stylesheet-remotes";

export const REMOTE_STYLESHEET_RESOLVER_MODULE =
"@module-federation/tanstack/remote-stylesheet-resolver";

export const RESOLVED_REMOTE_STYLESHEET_RESOLVER_MODULE = `\0${REMOTE_STYLESHEET_RESOLVER_MODULE}`;

/**
* Generates the adapter-owned resolver module. The remote configuration is serialized at
* build time so server and browser bundles use the same manifest identity policy without a
* process-global federation runtime singleton.
*
* Only each remote's identity is serialized: its configured key, name, alias, and entry.
*/
export function createRemoteStylesheetResolverModule(remotes: unknown): string {
// A keyed remote stays keyed, so the key keeps resolving next to the name and alias.
const serializedRemotes = JSON.stringify(
normalizeRemoteStylesheetRemotes(remotes).map(({ info, key }) =>
key === undefined ? info : { [key]: info },
),
);

return `import { createRemoteStylesheetResolver } from "@module-federation/tanstack/runtime";

export const resolveRemoteStylesheet = createRemoteStylesheetResolver(${serializedRemotes});
export default resolveRemoteStylesheet;
`;
}
135 changes: 135 additions & 0 deletions packages/tanstack/src/remote-stylesheet-remotes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
export type RemoteStylesheetRemoteConfig = {
entry?: string;
name?: string;
alias?: string;
external?: string | readonly string[];
type?: string;
internalName?: string;
entryGlobalName?: string;
shareScope?: string | string[];
[key: string]: unknown;
};

export type RemoteStylesheetRemoteValue = string | readonly string[] | RemoteStylesheetRemoteConfig;

export type RemoteStylesheetRemotes =
| Record<string, RemoteStylesheetRemoteValue>
| readonly (
| string
| RemoteStylesheetRemoteConfig
| Record<string, RemoteStylesheetRemoteValue>
)[];

export type RemoteStylesheetRemoteInfo = {
entry: string;
name: string;
alias?: string;
};

export type NormalizedRemote = {
/** Every name a `remote/Expose` specifier can use for this remote. */
aliases: string[];
info: RemoteStylesheetRemoteInfo;
/** The key the remote was configured under, when it had one. */
key?: string;
};

const UNSUPPORTED_SHAPE = "Remote stylesheet remotes must use a supported Module Federation shape.";

/**
* Normalizes the remote shapes Vite and Rspack accept: `name@entry` strings, `{ entry }`
* and `{ external }` objects, entry lists, and arrays of any of them. The adapters and the
* runtime resolver share this, so a build-time remote resolves the same way at run time.
*
* A remote with several entries resolves stylesheets from the first one: the others are
* fallbacks for loading the container, and a manifest is fetched from a single location.
*/
export function normalizeRemoteStylesheetRemotes(remotes: unknown): NormalizedRemote[] {
if (remotes == null) return [];
if (Array.isArray(remotes)) {
return remotes.flatMap((remote) => {
if (typeof remote === "string" || isRemoteConfig(remote)) {
return [normalizeRemote(undefined, remote)];
}
if (isRecord(remote)) return normalizeRecord(remote);
throw new TypeError(UNSUPPORTED_SHAPE);
});
}
if (!isRecord(remotes)) throw new TypeError(UNSUPPORTED_SHAPE);
return normalizeRecord(remotes);
}

function normalizeRecord(remotes: Record<string, unknown>): NormalizedRemote[] {
return Object.entries(remotes).map(([key, remote]) => normalizeRemote(key, remote));
}

function normalizeRemote(key: string | undefined, remote: unknown): NormalizedRemote {
if (typeof remote === "string") {
const parsed = parseNamedRemote(remote);
const name = parsed?.name ?? key;
if (!name) throw new TypeError(`A remote string must include a name: ${remote}`);
return {
aliases: uniqueStrings([key, name]),
info: { alias: aliasFromKey(key, name), entry: parsed?.entry ?? remote, name },
key,
};
}

if (Array.isArray(remote)) {
const first = firstString(remote);
if (!first) throw new TypeError(`Remote "${key ?? "unknown"}" must define an entry.`);
return normalizeRemote(key, first);
}

if (!isRecord(remote)) throw new TypeError(UNSUPPORTED_SHAPE);

const source = typeof remote.entry === "string" ? remote.entry : firstString(remote.external);
const parsed = source ? parseNamedRemote(source) : undefined;
const name = (typeof remote.name === "string" ? remote.name : parsed?.name) ?? key;
if (!name) throw new TypeError("A configured remote must have a name.");
const entry = parsed?.entry ?? source;
if (!entry) throw new TypeError(`Remote "${name}" must define an entry or external URL.`);
const alias = typeof remote.alias === "string" ? remote.alias : undefined;
return {
aliases: uniqueStrings([key, name, parsed?.name, alias]),
info: { alias: alias ?? aliasFromKey(key, name), entry, name },
key,
};
}

function aliasFromKey(key: string | undefined, name: string): string | undefined {
return key !== name ? key : undefined;
}

function isRemoteConfig(value: unknown): value is RemoteStylesheetRemoteConfig {
if (!isRecord(value)) return false;
return (
typeof value.entry === "string" ||
typeof value.external === "string" ||
Array.isArray(value.external) ||
typeof value.name === "string" ||
typeof value.alias === "string"
);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}

function firstString(value: unknown): string | undefined {
if (typeof value === "string") return value;
if (!Array.isArray(value)) return undefined;
return value.find((item): item is string => typeof item === "string" && item !== "");
}

function parseNamedRemote(remote: string): { entry: string; name: string } | undefined {
const match = /^([^/@]+)@(.+)$/.exec(remote);
const name = match?.[1];
const entry = match?.[2];
if (!name || !entry || (!entry.includes("://") && !entry.startsWith("/"))) return undefined;
return { entry, name };
}

function uniqueStrings(values: (string | undefined)[]): string[] {
return [...new Set(values.filter((value): value is string => Boolean(value)))];
}
9 changes: 9 additions & 0 deletions packages/tanstack/src/remote-stylesheet-resolver-module.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* Type declaration for the package self-reference used as the adapter replacement point.
* The bundler replaces this module with the resolver generated from its remote configuration.
*/
declare module "@module-federation/tanstack/remote-stylesheet-resolver" {
export const resolveRemoteStylesheet: import("./runtime").RemoteStylesheetResolver;
const defaultResolver: import("./runtime").RemoteStylesheetResolver;
export default defaultResolver;
}
17 changes: 17 additions & 0 deletions packages/tanstack/src/remote-stylesheet-resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { RemoteStylesheetResolutionError, type RemoteStylesheetResolver } from "./runtime";

/**
* Resolves a `remote/Expose` specifier through the active federation adapter.
*
* Vite and Rsbuild replace this module at build time with a resolver created from the
* adapter's configured remotes. The fallback keeps the package import type-safe and fails
* explicitly when the federation adapter is not installed in the bundler configuration.
*/
export const resolveRemoteStylesheet: RemoteStylesheetResolver = async (specifier) => {
throw new RemoteStylesheetResolutionError(
`No Module Federation adapter resolver is available for "${specifier}".`,
specifier,
);
};

export default resolveRemoteStylesheet;
Loading