Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react-server): generate mapping of server route to client assets #331

Merged
merged 1 commit into from
Jun 4, 2024
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
1 change: 1 addition & 0 deletions packages/react-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"dependencies": {
"@hiogawa/transforms": "workspace:*",
"@tanstack/history": "^1.15.13",
"fast-glob": "^3.3.2",
"use-sync-external-store": "^1.2.0"
},
"devDependencies": {
Expand Down
110 changes: 110 additions & 0 deletions packages/react-server/src/features/router/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import path from "node:path";
import { objectMapValues, tinyassert, uniq } from "@hiogawa/utils";
import FastGlob from "fast-glob";
import type { Plugin, Rollup } from "vite";
import type { PluginStateManager } from "../../plugin";
import { type CustomModuleMeta, createVirtualPlugin } from "../../plugin/utils";

export function routeManifestPluginServer({
manager,
}: { manager: PluginStateManager }): Plugin[] {
return [
{
name: "server-route-manifest",
apply: "build",
async buildEnd() {
if (manager.buildType === "rsc") {
const routeFiles = await FastGlob(
"./src/routes/**/(page|layout|error).(js|jsx|ts|tsx)",
);
for (const routeFile of routeFiles) {
const absFile = path.join(manager.config.root, routeFile);
const deps = collectModuleDeps(absFile, this);
let ids: string[] = [];
for (const id of deps) {
const info = this.getModuleInfo(id);
tinyassert(info);
const meta = info.meta as CustomModuleMeta;
if (meta.$$rsc?.type === "client") {
ids.push(id);
}
}
manager.routeToClientReferences[routeFile] = ids;
}
}
},
},
];
}

export function routeManifestPluginClient({
manager,
}: { manager: PluginStateManager }): Plugin[] {
return [
{
name: routeManifestPluginClient.name + ":bundle",
apply: "build",
generateBundle(_options, bundle) {
if (manager.buildType === "client") {
const facadeModuleDeps: Record<string, string[]> = {};
for (const [k, v] of Object.entries(bundle)) {
if (v.type === "chunk" && v.facadeModuleId) {
facadeModuleDeps[v.facadeModuleId] = collectAssetDeps(k, bundle);
}
}
manager.routeToClientAssets = objectMapValues(
manager.routeToClientReferences,
(ids) =>
uniq(
ids.flatMap((id) => {
const deps = facadeModuleDeps[id];
tinyassert(deps);
return deps;
}),
),
);
console.log(manager.routeToClientAssets);
}
},
},
createVirtualPlugin("route-manifest", () => {
return `export default "todo"`;
}),
];
}

function collectModuleDeps(id: string, ctx: Rollup.PluginContext) {
const visited = new Set<string>();
const recurse = (id: string) => {
if (visited.has(id)) {
return;
}
visited.add(id);
const info = ctx.getModuleInfo(id);
tinyassert(info);
for (const imported of info.importedIds) {
recurse(imported);
}
};
recurse(id);
return [...visited];
}

function collectAssetDeps(fileName: string, bundle: Rollup.OutputBundle) {
const visited = new Set<string>();

function recurse(k: string) {
if (visited.has(k)) return;
visited.add(k);
const v = bundle[k];
tinyassert(v);
if (v.type === "chunk") {
for (const k2 of v.imports) {
recurse(k2);
}
}
}

recurse(fileName);
return [...visited];
}
14 changes: 12 additions & 2 deletions packages/react-server/src/features/use-client/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
} from "vite";
import type { PluginStateManager } from "../../plugin";
import {
type CustomModuleMeta,
USE_CLIENT,
USE_CLIENT_RE,
createVirtualPlugin,
Expand Down Expand Up @@ -147,10 +148,19 @@ export function vitePluginServerUseClient({
);
manager.rscUseClientIds.add(id);
if (manager.buildType === "scan") {
// only collect references without transform during the scan
// to discover server references imported only by client
// we keep code as is and continue crawling
return;
}
return { code: output.toString(), map: output.generateMap() };
return {
code: output.toString(),
map: output.generateMap(),
meta: {
$$rsc: {
type: "client",
},
} satisfies CustomModuleMeta,
};
},

/**
Expand Down
16 changes: 16 additions & 0 deletions packages/react-server/src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type InlineConfig,
type Plugin,
type PluginOption,
type ResolvedConfig,
type ViteDevServer,
build,
createLogger,
Expand All @@ -14,6 +15,10 @@ import {
SERVER_CSS_PROXY,
vitePluginServerAssets,
} from "../features/assets/plugin";
import {
routeManifestPluginClient,
routeManifestPluginServer,
} from "../features/router/plugin";
import {
vitePluginClientUseServer,
vitePluginServerUseServer,
Expand Down Expand Up @@ -51,10 +56,14 @@ export type { PluginStateManager };

class PluginStateManager {
server?: ViteDevServer;
config!: ResolvedConfig;
configEnv!: ConfigEnv;

buildType?: "scan" | "rsc" | "client" | "ssr";

routeToClientReferences: Record<string, string[]> = {};
routeToClientAssets: Record<string, string[]> = {};

// expose "use client" node modules to client via virtual modules
// to avoid dual package due to deps optimization hash during dev
nodeModules = {
Expand Down Expand Up @@ -134,6 +143,8 @@ export function vitePluginReactServer(options?: {
runtimePath: RUNTIME_REACT_SERVER_PATH,
}),

routeManifestPluginServer({ manager }),

// this virtual is not necessary anymore but has been used in the past
// to extend user's react-server entry like ENTRY_CLIENT_WRAPPER
createVirtualPlugin(
Expand Down Expand Up @@ -219,6 +230,9 @@ export function vitePluginReactServer(options?: {
},
};
},
configResolved(config) {
manager.config = config;
},
async configureServer(server) {
manager.server = server;
},
Expand Down Expand Up @@ -285,6 +299,7 @@ export function vitePluginReactServer(options?: {
await build(reactServerViteConfig);
console.log("▶▶▶ REACT SERVER BUILD (server) [2/4]");
manager.buildType = "rsc";
manager.rscUseClientIds.clear();
await build(reactServerViteConfig);
console.log("▶▶▶ REACT SERVER BUILD (browser) [3/4]");
manager.buildType = "client";
Expand Down Expand Up @@ -315,6 +330,7 @@ export function vitePluginReactServer(options?: {
}),
...vitePluginClientUseClient({ manager }),
...vitePluginServerAssets({ manager }),
...routeManifestPluginClient({ manager }),
createVirtualPlugin(ENTRY_CLIENT_WRAPPER.slice("virtual:".length), () => {
// dev
if (!manager.buildType) {
Expand Down
7 changes: 7 additions & 0 deletions packages/react-server/src/plugin/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ export function invalidateModule(server: ViteDevServer, id: string) {
}
}

// cf. https://github.com/vercel/next.js/blob/5ae286ffd664e5c76841ed64f6e2da85a0835922/packages/next/src/build/webpack/loaders/get-module-build-info.ts#L8
export type CustomModuleMeta = {
$$rsc?: {
type: "client";
};
};

// TODO: configurable?
export const ENTRY_CLIENT = "/src/entry-client";
export const ENTRY_REACT_SERVER = "/src/entry-react-server";
Expand Down
21 changes: 3 additions & 18 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.