Skip to content
Draft
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
112 changes: 112 additions & 0 deletions packages/vinext/src/build/layout-classification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* Layout classification — determines whether each layout in an App Router
* route tree is static or dynamic via two complementary detection layers:
*
* Layer 1: Segment config (`export const dynamic`, `export const revalidate`)
* Layer 2: Module graph traversal (checks for transitive dynamic shim imports)
*
* Layer 3 (probe-based runtime detection) is handled separately in
* `app-page-execution.ts` at request time.
*/

import { classifyLayoutSegmentConfig } from "./report.js";
import { createAppPageTreePath } from "../server/app-page-route-wiring.js";

export type ModuleGraphClassification = "static" | "needs-probe";
export type LayoutClassificationResult = "static" | "dynamic" | "needs-probe";

export type ModuleInfoProvider = {
getModuleInfo(id: string): {
importedIds: string[];
dynamicImportedIds: string[];
} | null;
};

type RouteForClassification = {
layouts: string[];
layoutTreePositions: number[];
routeSegments: string[];
layoutSegmentConfigs?: ReadonlyArray<{ code: string } | null>;
};

/**
* BFS traversal of a layout's dependency tree. If any transitive import
* resolves to a dynamic shim path (headers, cache, server), the layout
* cannot be proven static at build time and needs a runtime probe.
*/
export function classifyLayoutByModuleGraph(
layoutModuleId: string,
dynamicShimPaths: ReadonlySet<string>,
moduleInfo: ModuleInfoProvider,
): ModuleGraphClassification {
const visited = new Set<string>();
const queue: string[] = [layoutModuleId];
let head = 0;

while (head < queue.length) {
const currentId = queue[head++]!;

if (visited.has(currentId)) continue;
visited.add(currentId);

if (dynamicShimPaths.has(currentId)) return "needs-probe";

const info = moduleInfo.getModuleInfo(currentId);
if (!info) continue;

for (const importedId of info.importedIds) {
if (!visited.has(importedId)) queue.push(importedId);
}
for (const dynamicId of info.dynamicImportedIds) {
if (!visited.has(dynamicId)) queue.push(dynamicId);
}
}

return "static";
}

/**
* Classifies all layouts across all routes using a two-layer strategy:
*
* 1. Segment config (Layer 1) — short-circuits to "static" or "dynamic"
* 2. Module graph (Layer 2) — BFS for dynamic shim imports → "static" or "needs-probe"
*
* Shared layouts (same file appearing in multiple routes) are classified once
* and deduplicated by layout ID.
*/
export function classifyAllRouteLayouts(
routes: readonly RouteForClassification[],
dynamicShimPaths: ReadonlySet<string>,
moduleInfo: ModuleInfoProvider,
): Map<string, LayoutClassificationResult> {
const result = new Map<string, LayoutClassificationResult>();

for (const route of routes) {
for (let i = 0; i < route.layouts.length; i++) {
const treePosition = route.layoutTreePositions[i] ?? 0;
const layoutId = `layout:${createAppPageTreePath(route.routeSegments, treePosition)}`;

if (result.has(layoutId)) continue;

// Layer 1: segment config
const segmentConfig = route.layoutSegmentConfigs?.[i];
if (segmentConfig) {
const configResult = classifyLayoutSegmentConfig(segmentConfig.code);
if (configResult !== null) {
result.set(layoutId, configResult);
continue;
}
}

// Layer 2: module graph
const graphResult = classifyLayoutByModuleGraph(
route.layouts[i],
dynamicShimPaths,
moduleInfo,
);
result.set(layoutId, graphResult);
}
}

return result;
}
31 changes: 31 additions & 0 deletions packages/vinext/src/build/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,37 @@ function findMatchingToken(
return -1;
}

// ─── Layout segment config classification ────────────────────────────────────

/**
* Classification result for layout segment config analysis.
* "static" means the layout is confirmed static via segment config.
* "dynamic" means the layout is confirmed dynamic via segment config.
*/
export type LayoutClassification = "static" | "dynamic";

/**
* Classifies a layout file by its segment config exports (`dynamic`, `revalidate`).
*
* Returns `"static"` or `"dynamic"` when the config is decisive, or `null`
* when no segment config is present (deferring to module graph analysis).
*
* Unlike page classification, positive `revalidate` values are not meaningful
* for layout skip decisions — ISR is a page-level concept. Only the extremes
* (`revalidate = 0` → dynamic, `revalidate = Infinity` → static) are decisive.
*/
export function classifyLayoutSegmentConfig(code: string): LayoutClassification | null {
const dynamicValue = extractExportConstString(code, "dynamic");
if (dynamicValue === "force-dynamic") return "dynamic";
if (dynamicValue === "force-static" || dynamicValue === "error") return "static";

const revalidateValue = extractExportConstNumber(code, "revalidate");
if (revalidateValue === Infinity) return "static";
if (revalidateValue === 0) return "dynamic";

return null;
}

// ─── Route classification ─────────────────────────────────────────────────────

/**
Expand Down
23 changes: 23 additions & 0 deletions packages/vinext/src/entries/app-rsc-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,8 @@ import {
import {
APP_INTERCEPTION_CONTEXT_KEY as __APP_INTERCEPTION_CONTEXT_KEY,
createAppPayloadRouteId as __createAppPayloadRouteId,
parseSkipHeader as __parseSkipHeader,
X_VINEXT_ROUTER_SKIP_HEADER as __X_VINEXT_ROUTER_SKIP_HEADER,
} from ${JSON.stringify(appElementsPath)};
import {
buildAppPageElements as __buildAppPageElements,
Expand Down Expand Up @@ -1412,6 +1414,9 @@ async function _handleRequest(request, __reqCtx, _mwCtx) {
}

const isRscRequest = pathname.endsWith(".rsc") || request.headers.get("accept")?.includes("text/x-component");
const __skipLayoutIds = isRscRequest
? __parseSkipHeader(request.headers.get(__X_VINEXT_ROUTER_SKIP_HEADER))
: new Set();
const interceptionContextHeader = request.headers.get("X-Vinext-Interception-Context")?.replaceAll("\0", "") || null;
let cleanPathname = pathname.replace(/\\.rsc$/, "");

Expand Down Expand Up @@ -2422,8 +2427,26 @@ async function _handleRequest(request, __reqCtx, _mwCtx) {
const _asyncSearchParams = makeThenableParams(_probeSearchObj);
return PageComponent({ params: _asyncLayoutParams, searchParams: _asyncSearchParams });
},
classification: {
getLayoutId(index) {
const tp = route.layoutTreePositions?.[index] ?? 0;
return "layout:" + __createAppPageTreePath(route.routeSegments, tp);
},
buildTimeClassifications: null, // Future: embed from Vite build plugin codegen
async runWithIsolatedDynamicScope(fn) {
const priorDynamic = consumeDynamicUsage();
try {
const result = await fn();
const dynamicDetected = consumeDynamicUsage();
return { result, dynamicDetected };
} finally {
if (priorDynamic) markDynamicUsage();
}
},
},
revalidateSeconds,
mountedSlotsHeader: __mountedSlotsHeader,
requestedSkipLayoutIds: __skipLayoutIds,
renderErrorBoundaryResponse(renderErr) {
return renderErrorBoundaryPage(route, renderErr, isRscRequest, request, params, _scriptNonce);
},
Expand Down
26 changes: 21 additions & 5 deletions packages/vinext/src/server/app-browser-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,16 @@ import {
getVinextBrowserGlobal,
} from "./app-browser-stream.js";
import {
buildSkipHeaderValue,
createAppPayloadCacheKey,
getMountedSlotIdsHeader,
normalizeAppElements,
readAppElementsMetadata,
resolveVisitedResponseInterceptionContext,
X_VINEXT_ROUTER_SKIP_HEADER,
type AppElements,
type AppWireElements,
type LayoutFlags,
} from "./app-elements.js";
import {
createHistoryStateWithPreviousNextUrl,
Expand Down Expand Up @@ -366,11 +369,18 @@ function getRequestState(
}
}

function createRscRequestHeaders(interceptionContext: string | null): Headers {
function createRscRequestHeaders(
interceptionContext: string | null,
layoutFlags: LayoutFlags,
): Headers {
const headers = new Headers({ Accept: "text/x-component" });
if (interceptionContext !== null) {
headers.set("X-Vinext-Interception-Context", interceptionContext);
}
const skipValue = buildSkipHeaderValue(layoutFlags);
if (skipValue !== null) {
headers.set(X_VINEXT_ROUTER_SKIP_HEADER, skipValue);
}
return headers;
}

Expand Down Expand Up @@ -458,6 +468,7 @@ async function commitSameUrlNavigatePayload(
pending.action.renderId,
"navigate",
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down Expand Up @@ -491,6 +502,7 @@ function BrowserRoot({
const [treeState, dispatchTreeState] = useReducer(routerReducer, {
elements: resolvedElements,
interceptionContext: initialMetadata.interceptionContext,
layoutFlags: initialMetadata.layoutFlags,
navigationSnapshot: initialNavigationSnapshot,
previousNextUrl: null,
renderId: 0,
Expand Down Expand Up @@ -570,6 +582,7 @@ function dispatchBrowserTree(
renderId: number,
actionType: "navigate" | "replace" | "traverse",
interceptionContext: string | null,
layoutFlags: LayoutFlags,
previousNextUrl: string | null,
routeId: string,
rootLayoutTreePath: string | null,
Expand All @@ -581,6 +594,7 @@ function dispatchBrowserTree(
dispatch({
elements,
interceptionContext,
layoutFlags,
navigationSnapshot,
previousNextUrl,
renderId,
Expand Down Expand Up @@ -662,6 +676,7 @@ async function renderNavigationPayload(
renderId,
actionType,
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down Expand Up @@ -968,10 +983,10 @@ async function main(): Promise<void> {
}

if (!navResponse) {
const requestHeaders = createRscRequestHeaders(requestInterceptionContext);
if (mountedSlotsHeader) {
requestHeaders.set("X-Vinext-Mounted-Slots", mountedSlotsHeader);
}
const requestHeaders = createRscRequestHeaders(
requestInterceptionContext,
getBrowserRouterState().layoutFlags,
);
navResponse = await fetch(rscUrl, {
headers: requestHeaders,
credentials: "include",
Expand Down Expand Up @@ -1146,6 +1161,7 @@ async function main(): Promise<void> {
pending.action.renderId,
"replace",
pending.interceptionContext,
pending.action.layoutFlags,
pending.previousNextUrl,
pending.routeId,
pending.rootLayoutTreePath,
Expand Down
7 changes: 6 additions & 1 deletion packages/vinext/src/server/app-browser-state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mergeElements } from "../shims/slot.js";
import { stripBasePath } from "../utils/base-path.js";
import { readAppElementsMetadata, type AppElements } from "./app-elements.js";
import { readAppElementsMetadata, type AppElements, type LayoutFlags } from "./app-elements.js";
import type { ClientNavigationRenderSnapshot } from "../shims/navigation.js";

const VINEXT_PREVIOUS_NEXT_URL_HISTORY_STATE_KEY = "__vinext_previousNextUrl";
Expand All @@ -12,6 +12,7 @@ type HistoryStateRecord = {
export type AppRouterState = {
elements: AppElements;
interceptionContext: string | null;
layoutFlags: LayoutFlags;
previousNextUrl: string | null;
renderId: number;
navigationSnapshot: ClientNavigationRenderSnapshot;
Expand All @@ -22,6 +23,7 @@ export type AppRouterState = {
export type AppRouterAction = {
elements: AppElements;
interceptionContext: string | null;
layoutFlags: LayoutFlags;
navigationSnapshot: ClientNavigationRenderSnapshot;
previousNextUrl: string | null;
renderId: number;
Expand Down Expand Up @@ -95,6 +97,7 @@ export function routerReducer(state: AppRouterState, action: AppRouterAction): A
return {
elements: mergeElements(state.elements, action.elements, action.type === "traverse"),
interceptionContext: action.interceptionContext,
layoutFlags: { ...state.layoutFlags, ...action.layoutFlags },
navigationSnapshot: action.navigationSnapshot,
previousNextUrl: action.previousNextUrl,
renderId: action.renderId,
Expand All @@ -105,6 +108,7 @@ export function routerReducer(state: AppRouterState, action: AppRouterAction): A
return {
elements: action.elements,
interceptionContext: action.interceptionContext,
layoutFlags: action.layoutFlags,
navigationSnapshot: action.navigationSnapshot,
previousNextUrl: action.previousNextUrl,
renderId: action.renderId,
Expand Down Expand Up @@ -168,6 +172,7 @@ export async function createPendingNavigationCommit(options: {
action: {
elements,
interceptionContext: metadata.interceptionContext,
layoutFlags: metadata.layoutFlags,
navigationSnapshot: options.navigationSnapshot,
previousNextUrl,
renderId: options.renderId,
Expand Down
Loading
Loading