Files
cloudflare__vinext/tests/route-classification-manifest.test.ts
Divanshu Chauhan (divkix) b4c829d6a2 feat(interception): sibling-style interception routes (#1364 Part C) (#1804)
* test(interception): add failing sibling-interception graph tests

* feat(routing): discover sibling-style interception markers

* feat(routing): emit sibling interception manifest facts

* feat(app-router): serialize sibling intercepts in route manifest

* feat(app-router): match sibling intercepts in route matcher

* feat(app-router): render sibling intercept as full page response

* test: add siblingIntercepts field to AppRoute test fixtures

* test(interception): add sibling interception fixtures

* fix(app-router): emit null proof for sibling intercepts to bypass slot-validation

* test(interception): add sibling interception e2e specs

* fix(interception): correct (...)→(..)(..) marker in interception-from-root fixture

* fix(interception): resolve sourceRouteIndex to slot-owner route in intercept lookup

When a route inherits a @slot from an ancestor via discoverInheritedParallelSlots,
the inherited slot's interceptingRoutes are copied from the ancestor. Previously,
createInterceptLookup used routeIndex (the inheriting descendant's index) as
sourceRouteIndex, causing resolveAppPageInterceptState to see sourceRoute ===
currentRoute → kind='current-route' instead of kind='source-route'.

Fix: build a patternToIndex map and resolve sourceRouteIndex via the intercept's
sourceMatchPattern (which names the actual slot-owner route), falling back to
routeIndex only when no match is found.

* fix(interception): use locale-prefixed href so middleware interception fires correctly

* fix(interception): address codex review issues in sibling intercept implementation

- Pass effectiveParams to resolveAppPageHead so generateMetadata/generateViewport
  sees the intercepted route's params instead of the source route's params
- Rename SIBLING_INTERCEPT_SLOT_NAME from __page to __vinext_sibling_intercept
  to prevent collision with a user @__page parallel route directory
- Restore middleware-rewrite fixture link without locale prefix so the
  interception-dynamic-segment-middleware spec exercises the intended
  middleware rewrite path

* fix(test): update slotId assertions and restore locale-prefixed fixture link

- Update test assertions from slot:__page to slot:__vinext_sibling_intercept
  following the rename in commit 2248b8fe
- Restore locale-prefixed href in interception-mw fixture so the
  interception-dynamic-segment-middleware E2E tests pass (reverts the
  accidental revert from 2248b8fe back to the working state from 02e80c26)

* fix(interception): address review findings on sibling interception PR

- Restore locale-less href in interception-mw fixture and fix the
  underlying middleware-rewrite interception gap: add a Referer-based
  fallback in app-rsc-handler so interception fires when middleware
  rewrites the URL before the server matches it (the client-side manifest
  check sees the pre-rewrite target and skips setting the interception
  context header; the Referer carries the source page the server needs)
- Apply interceptLayouts for sibling intercepts in buildPageElements so
  a layout.tsx under the interception marker dir wraps the intercepting
  page, matching Next.js segment-layout wrapping behaviour; add fixture
  layout and E2E assertion
- Add unit test proving findOwnerRouteForDir ancestor walk attaches a
  sibling intercept to the nearest ancestor route when the marker's
  parent dir has no page.tsx (not dropped silently)

* fix(interception): send current pathname as fallback interception context

The client-side manifest check compares the pre-middleware target URL
against declared interception patterns. When middleware rewrites the URL
(e.g. /foo/p/1 → /en/foo/p/1), the pre-rewrite URL has fewer segments
and doesn't match the pattern, so no X-Vinext-Interception-Context
header is sent and the server cannot fire interception.

Fix: when the manifest check yields no match and there is no prior
intercepted navigation in browser state, fall back to sending the
current page pathname as the interception context. This mirrors Next.js
sending Next-URL on every RSC navigation. The server's findIntercept is
double-gated on both source and target matching, so false positives
cannot occur. The previousNextUrl is also populated so back/forward
traversal can restore intercepted state.

Revert the Referer-based server-side fallback (unreliable across
environments) in favour of this explicit browser-side fix.

* fix(interception): gate middleware-rewrite fallback on declared source pattern

The previous fix sent window.location.pathname as fallback interception
context on every unmatched navigation, which broke prefetch cache reuse:
a prefetch stored with null context wouldn't be found when the navigation
used a non-null context key.

Refine the fallback to only fire when the current page URL matches at
least one sourcePatternParts declared in the route manifest — i.e., the
current page is a known interception source. This preserves prefetch
cache reuse for ordinary navigations while still enabling middleware-
rewrite interception for pages that declare an interception relationship.

* fix(interception): support middleware-rewrite targets in fallback context and planner

The previous fallback-context gate only checked whether the current page
is a declared interception source; it did not verify the target URL
could plausibly be a middleware-rewritten version of the declared target
pattern.  This meant the client sent interception context when it
shouldn't (pre-middleware target had no static anchors in common with the
pattern) and the planner hard-navigated when the proof target matched
only after the rewrite.

Three coordinated fixes:

1. Client fallback gate (app-browser-entry / app-browser-interception-context):
   replace the broad source-only check with matchRoutePatternWithOptionalDynamicSegments
   on the target side — the pre-middleware URL must still share every
   static anchor of the declared target pattern, in order, while allowing
   dynamic segments to be absent.

2. Planner interception proof (navigation-planner):
   findRouteManifestInterceptionForProof now accepts a proof whose target
   matched URL equals the pre-rewrite canonical pathname (shorter than the
   full pattern) when matchRoutePatternWithOptionalDynamicSegments passes.
   Exact pattern match still skips the targetRouteId guard; the relaxed
   path skips it too so the middleware-added locale segment does not
   invalidate an otherwise valid proof.

3. displayPathname threading (app-rsc-handler / app-rsc-entry / app-page-element-builder):
   the handler now passes canonicalPathname as displayPathname separately
   from cleanPathname.  buildPageElements uses cleanPathname for all
   internal routing work (slot param extraction, slot overrides) and
   displayPathname only for render identity — keeping the browser-visible
   URL in RSC metadata without affecting internal matching.

* fix(interception): guard siblingInterceptElement construction and document reserved slot name

* fix(interception): surface missing default export on sibling intercept pages

A sibling-style interception whose intercepting page module is missing
its `default` export previously fell back to the source route's page
component (`effectivePageModule?.default ?? PageComponent`), silently
rendering a *different* page than the one requested.

Resolve the effective component from the intercepting page only and
extend the existing no-default-export guard to cover sibling intercepts,
so a missing export surfaces the same explicit "Page has no default
export" error the source/slot paths already produce. For a normal
request this is identical to the previous behavior since
`effectivePageModule === pageModule`.

Addresses bonk review feedback on #1804.

* test(app-router): guard canonical pathname commit on soft-nav config rewrites

The `displayPathname = canonicalPathname` change feeds the RSC payload
identity the client planner uses to commit a navigation, so it affects
every rewritten route, not just interceptions. Existing coverage
(nextjs-compat/hooks.test.ts) only exercises the hard-nav (SSR) path.

Add an e2e that soft-navigates (client-side) to an afterFiles-rewritten
route and asserts the committed URL and `usePathname()` stay canonical
(pre-rewrite), with a marker check proving no full page reload occurred.

Addresses bonk review feedback on #1804.

* fix(interception): restore __pageLoader on slot intercept lookup entries

The main merge auto-resolved incorrectly: it moved the `__pageLoader`
field that #1738 added to the *slot* intercept push block onto the new
*sibling* push block instead (the two `interceptLookup.push({...})` calls
are textually similar). As a result slot intercept lookup entries lost
`__pageLoader`, so resolveAppPageInterceptState never loaded the lazy
intercepting page (`page` stayed null) and the modal slot fell back to
default.tsx — breaking every slot interception.

Restore `__pageLoader: intercept.__pageLoader` on the slot push block.
The sibling block already carries it (see merge commit), and both
intercept types declare the optional field.

Fixes the app-router-dev-server intercept tests and the interception
e2e suites that regressed after merging main.

---------

Co-authored-by: James Anderson <james@eli.cx>
2026-06-08 19:01:29 +01:00

402 lines
14 KiB
TypeScript

/**
* Tests for the build-time layout classification manifest helpers.
*
* These helpers bridge the classifier (src/build/layout-classification.ts)
* with the RSC entry codegen so that the per-layout static/dynamic
* classifications computed at build time actually reach the runtime probe in
* app-page-execution.ts.
*/
import fsp from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import vm from "node:vm";
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
import {
buildClassificationReplacement,
buildReasonsReplacement,
collectRouteClassificationManifest,
} from "../packages/vinext/src/build/route-classification-manifest.js";
import type { ClassificationReason } from "../packages/vinext/src/build/layout-classification-types.js";
type MinimalAppRoute = {
pattern: string;
pagePath: string | null;
routePath: string | null;
layouts: string[];
templates: string[];
parallelSlots: [];
siblingIntercepts: [];
loadingPath: null;
errorPath: null;
layoutErrorPaths: (string | null)[];
notFoundPath: null;
notFoundPaths: (string | null)[];
forbiddenPaths: (string | null)[];
forbiddenPath: null;
unauthorizedPaths: (string | null)[];
unauthorizedPath: null;
routeSegments: string[];
layoutTreePositions: number[];
isDynamic: boolean;
params: string[];
patternParts: string[];
};
function makeRoute(partial: Partial<MinimalAppRoute> & { layouts: string[] }): MinimalAppRoute {
return {
pattern: "/",
pagePath: null,
routePath: null,
templates: [],
parallelSlots: [],
siblingIntercepts: [],
loadingPath: null,
errorPath: null,
layoutErrorPaths: partial.layouts.map(() => null),
notFoundPath: null,
notFoundPaths: partial.layouts.map(() => null),
forbiddenPaths: partial.layouts.map(() => null),
forbiddenPath: null,
unauthorizedPaths: partial.layouts.map(() => null),
unauthorizedPath: null,
routeSegments: [],
layoutTreePositions: partial.layouts.map((_, idx) => idx),
isDynamic: false,
params: [],
patternParts: [],
...partial,
};
}
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "vinext-classification-manifest-"));
});
afterEach(async () => {
await fsp.rm(tmpDir, { recursive: true, force: true });
});
async function writeLayout(name: string, source: string): Promise<string> {
const file = path.join(tmpDir, name);
await fsp.writeFile(file, source, "utf8");
return file;
}
describe("collectRouteClassificationManifest", () => {
it("reads force-dynamic layouts as dynamic", async () => {
const layout = await writeLayout(
"layout-dyn.tsx",
`export const dynamic = "force-dynamic";\nexport default function L({children}){return children;}`,
);
const routes = [makeRoute({ pattern: "/", layouts: [layout] })];
const manifest = collectRouteClassificationManifest(routes);
expect(manifest.routes[0].layer1.get(0)).toBe("dynamic");
expect(manifest.routes[0].layer1Reasons.get(0)).toEqual({
layer: "segment-config",
key: "dynamic",
value: "force-dynamic",
});
});
it("reads force-static layouts as static", async () => {
const layout = await writeLayout(
"layout-static.tsx",
`export const dynamic = "force-static";\nexport default function L({children}){return children;}`,
);
const routes = [makeRoute({ pattern: "/", layouts: [layout] })];
const manifest = collectRouteClassificationManifest(routes);
expect(manifest.routes[0].layer1.get(0)).toBe("static");
});
it("leaves layouts without segment config unclassified", async () => {
const layout = await writeLayout(
"layout-plain.tsx",
`export default function L({children}){return <div>{children}</div>;}`,
);
const routes = [makeRoute({ pattern: "/", layouts: [layout] })];
const manifest = collectRouteClassificationManifest(routes);
expect(manifest.routes[0].layer1.has(0)).toBe(false);
});
it("reads revalidate = 0 as dynamic", async () => {
const layout = await writeLayout(
"layout-reval0.tsx",
`export const revalidate = 0;\nexport default function L({children}){return children;}`,
);
const routes = [makeRoute({ pattern: "/", layouts: [layout] })];
const manifest = collectRouteClassificationManifest(routes);
expect(manifest.routes[0].layer1.get(0)).toBe("dynamic");
});
it("throws when a layout file is missing, naming the route and path", () => {
const missingPath = path.join(tmpDir, "nonexistent", "layout.tsx");
const routes = [makeRoute({ pattern: "/blog", layouts: [missingPath] })];
expect(() => collectRouteClassificationManifest(routes)).toThrow(/\/blog/);
expect(() => collectRouteClassificationManifest(routes)).toThrow(/nonexistent/);
});
});
describe("buildClassificationReplacement", () => {
function evalDispatch(source: string): (routeIdx: number) => unknown {
// The helper returns a function expression suitable for:
// function __VINEXT_CLASS(routeIdx) { return (<replacement>)(routeIdx); }
// Use vm.runInThisContext so the resulting Map instances share their
// prototype with the test process — `instanceof Map` would otherwise
// fail across v8 contexts.
const fn: unknown = vm.runInThisContext(`(${source})`);
if (typeof fn !== "function") {
throw new Error("buildClassificationReplacement did not produce a function expression");
}
return (routeIdx: number) => Reflect.apply(fn, null, [routeIdx]);
}
function makeManifest(
entries: Array<{ layer1?: Array<[number, "static" | "dynamic"]> }>,
): Parameters<typeof buildClassificationReplacement>[0] {
return {
routes: entries.map((e, idx) => {
const layer1 = new Map(e.layer1 ?? []);
const layer1Reasons = new Map<number, ClassificationReason>();
for (const [layoutIdx, kind] of layer1) {
layer1Reasons.set(layoutIdx, {
layer: "segment-config",
key: "dynamic",
value: kind === "dynamic" ? "force-dynamic" : "force-static",
});
}
return {
pattern: `/route-${idx}`,
layoutPaths: [],
layer1,
layer1Reasons,
};
}),
};
}
it("returns a function expression that evaluates to a dispatch function", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
const replacement = buildClassificationReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
expect(typeof dispatch).toBe("function");
const result = dispatch(0);
expect(result).toBeInstanceOf(Map);
});
function asMap(value: unknown): Map<unknown, unknown> {
if (!(value instanceof Map)) {
throw new Error(`Expected Map, got ${String(value)}`);
}
return value;
}
it("merges Layer 1 and Layer 2 into the dispatch function's Map", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
const layer2: Parameters<typeof buildClassificationReplacement>[1] = new Map([
[0, new Map([[1, { layer: "module-graph", result: "static" }]])],
]);
const replacement = buildClassificationReplacement(manifest, layer2);
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
expect(result.get(0)).toBe("dynamic");
expect(result.get(1)).toBe("static");
});
it("preserves Layer 1 priority over Layer 2 for the same layout index", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
// Layer 2 proves "static" for index 0 — but Layer 1 said "dynamic", so
// Layer 1 must win. This guards against the classifier silently demoting
// a force-dynamic layout because the module graph happened to be clean.
const layer2: Parameters<typeof buildClassificationReplacement>[1] = new Map([
[0, new Map([[0, { layer: "module-graph", result: "static" }]])],
]);
const replacement = buildClassificationReplacement(manifest, layer2);
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
expect(result.get(0)).toBe("dynamic");
});
it("returns null from dispatch for unknown route indices", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
const replacement = buildClassificationReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
expect(dispatch(999)).toBeNull();
});
it("returns null from dispatch for routes with no classifications", () => {
// Route 0 has Layer 1 data; route 1 has nothing in Layer 1 or Layer 2.
// A route with no merged entries should fall through to the default case.
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }, { layer1: [] }]);
const replacement = buildClassificationReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
expect(dispatch(0)).toBeInstanceOf(Map);
expect(dispatch(1)).toBeNull();
});
it("throws when layer1 and layer1Reasons are out of sync", () => {
// This invariant is enforced in mergeLayersForRoute: every entry in layer1
// must have a corresponding entry in layer1Reasons. collectRouteClassificationManifest
// always populates them in lockstep, but callers constructing RouteManifestEntry
// manually could violate this.
const brokenManifest: Parameters<typeof buildClassificationReplacement>[0] = {
routes: [
{
pattern: "/broken",
layoutPaths: [],
layer1: new Map([[0, "dynamic"]]),
layer1Reasons: new Map(), // missing reason for layoutIdx 0
},
],
};
expect(() => buildClassificationReplacement(brokenManifest, new Map())).toThrow(
/Layer 1 decision without a reason/,
);
});
});
describe("buildReasonsReplacement", () => {
function evalDispatch(source: string): (routeIdx: number) => unknown {
const fn: unknown = vm.runInThisContext(`(${source})`);
if (typeof fn !== "function") {
throw new Error("buildReasonsReplacement did not produce a function expression");
}
return (routeIdx: number) => Reflect.apply(fn, null, [routeIdx]);
}
function asMap(value: unknown): Map<unknown, unknown> {
if (!(value instanceof Map)) {
throw new Error(`Expected Map, got ${String(value)}`);
}
return value;
}
function makeManifest(
entries: Array<{ layer1?: Array<[number, "static" | "dynamic"]> }>,
): Parameters<typeof buildReasonsReplacement>[0] {
return {
routes: entries.map((e, idx) => {
const layer1 = new Map(e.layer1 ?? []);
const layer1Reasons = new Map<number, ClassificationReason>();
for (const [layoutIdx, kind] of layer1) {
layer1Reasons.set(layoutIdx, {
layer: "segment-config",
key: "dynamic",
value: kind === "dynamic" ? "force-dynamic" : "force-static",
});
}
return {
pattern: `/route-${idx}`,
layoutPaths: [],
layer1,
layer1Reasons,
};
}),
};
}
it("returns segment-config reasons for Layer 1 decisions", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
const replacement = buildReasonsReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
expect(result.get(0)).toEqual({
layer: "segment-config",
key: "dynamic",
value: "force-dynamic",
});
});
it("preserves Infinity in segment-config reasons", () => {
const manifest = {
routes: [
{
pattern: "/route-0",
layoutPaths: [],
layer1: new Map<number, "static" | "dynamic">([[0, "static"]]),
layer1Reasons: new Map<number, ClassificationReason>([
[0, { layer: "segment-config", key: "revalidate", value: Infinity }],
]),
},
],
};
const replacement = buildReasonsReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
expect(result.get(0)).toEqual({
layer: "segment-config",
key: "revalidate",
value: Infinity,
});
});
it("returns module-graph reasons for Layer 2 static decisions", () => {
const manifest = makeManifest([{ layer1: [] }]);
const layer2: Parameters<typeof buildReasonsReplacement>[1] = new Map([
[0, new Map([[3, { layer: "module-graph", result: "static" }]])],
]);
const replacement = buildReasonsReplacement(manifest, layer2);
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
expect(result.get(3)).toEqual({
layer: "module-graph",
result: "static",
});
});
it("preserves Layer 1 reason priority over Layer 2 for the same layout index", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }]);
const layer2: Parameters<typeof buildReasonsReplacement>[1] = new Map([
[0, new Map([[0, { layer: "module-graph", result: "static" }]])],
]);
const replacement = buildReasonsReplacement(manifest, layer2);
const dispatch = evalDispatch(replacement);
const result = asMap(dispatch(0));
// Layer 1 wins — the reason carried must be the segment-config reason,
// not the module-graph reason.
expect(result.get(0)).toEqual({
layer: "segment-config",
key: "dynamic",
value: "force-dynamic",
});
});
it("returns null for routes with no classifications", () => {
const manifest = makeManifest([{ layer1: [[0, "dynamic"]] }, { layer1: [] }]);
const replacement = buildReasonsReplacement(manifest, new Map());
const dispatch = evalDispatch(replacement);
expect(dispatch(1)).toBeNull();
});
});