Skip to content

Commit 7f42803

Browse files
authored
fix(router): handler-invoked loaders under cache() throw on header writes (#725 gap) + drop removed __debug_manifest docs (#730)
* fix(router): handler-invoked loaders under cache() throw on header writes (closes #725 gap) The cached-scope header guard (#725) exempted every loader body under a cache() boundary via isInsideAnyLoaderScope(). That let a handler-invoked loader — await ctx.use(Loader) from a handler, never registered with loader() — write a cookie/header on the MISS. On a HIT the handler is skipped and only DSL-registered loaders re-run, so that loader never executes and its write silently vanishes — the exact MISS/HIT divergence #725 was built to eliminate. Narrow the exemption to isInsideLoaderScope() (DSL scope only): registered loaders re-run on every HIT and merge into every response, so their writes stay allowed; a handler-invoked loader now throws deterministically like a handler write. The DSL scope ALS survives nested ctx.use bodies, so a handler-invoked loader nested under a DSL loader stays exempt (its parent re-runs it every HIT). The broad predicate is deferred to the throw path for the error label so the PPR handler-invoked-loader message stays "loader", and the throw reason keys on scope.kind so the cache() case explains the handler-skip cause. Re-ground the neighbouring read-purity guard comment, which this change makes contradictory: reads stay on the broad predicate under the consumption-lane baked-copy tradeoff (#672/#674), only writes narrow to DSL scope. Unit (cached-header-guard.test.ts): DSL-allowed pin, handler-invoked-throws pin (red before this change, green after), nested-under-DSL-allowed pin. E2e (cache-scope-guard, dev + production): /handler-loader-cookie-blocked asserts the error boundary renders and the cookie never reaches the wire; the DSL /loader-cookie-allowed control stays green in both modes. * docs: drop the removed __debug_manifest browser endpoint from the skill and guide #728 deleted the ?__debug_manifest HTTP endpoint and its routeAncestry data, but the debug-manifest skill and docs guide still told users to open http://localhost:PORT/?__debug_manifest and documented the deleted { routerId, routeManifest, routeAncestry, routeTrie, precomputedEntries } shape. Remove both browser-endpoint sections; both files already carry the correct router.debugManifest() programmatic path ({ routes, layouts, totalRoutes, totalLayouts }), now the primary documented route.
1 parent 4d80289 commit 7f42803

10 files changed

Lines changed: 178 additions & 40 deletions

File tree

‎apps/docs/content/docs/rango/guides/debug-manifest.mdx‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,9 @@ type: guide
66

77
A path resolves to the wrong handler, a layout isn't wrapping its children, or an intercept never fires. The debug manifest shows you the route tree Rango actually built — parent relationships, shortCodes, and per-route flags — so you can verify structure instead of guessing.
88

9-
## Quick look in the browser
10-
11-
In development, visit:
12-
13-
```bash
14-
open "http://localhost:PORT/?__debug_manifest"
15-
```
16-
17-
You get formatted JSON with the shape `{ routerId, routeManifest, routeAncestry, routeTrie, precomputedEntries }`.
18-
199
## Programmatic access
2010

21-
The programmatic API returns a different, summarized shape — `{ routes, layouts, totalRoutes, totalLayouts }`:
11+
Call `router.debugManifest()` in development — an `async` method that returns a summarized `{ routes, layouts, totalRoutes, totalLayouts }` shape:
2212

2313
```ts
2414
import { router } from "./router.js";

‎packages/rangojs-router/docs/design/ppr-shell-resume.md‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,10 +1015,29 @@ at TTFB before any loader settles, so loader writes are dead letters on HITs
10151015
by physics. Middleware is THE header lane: it wraps the commit point, runs on
10161016
every request including HITs, and its stub-response writes merge into every
10171017
response (`createResponseWithMergedHeaders` -> `applyStubHeaders`,
1018-
`src/rsc/helpers.ts`). One deliberate asymmetry survives: loader writes inside
1019-
a plain `cache()` boundary stay ALLOWED — those loaders re-run and merge into
1020-
every response (no divergence exists; pinned by the cache-scope-guard e2e and
1021-
vite-rsc-demo's shop cart), while ppr loader writes throw.
1018+
`src/rsc/helpers.ts`). One deliberate asymmetry survives, and it is loader-KIND
1019+
specific (#725): a DSL (registered) loader's writes inside a plain `cache()`
1020+
boundary stay ALLOWED — a registered loader re-runs on every HIT
1021+
(`runInsideLoaderScope` in `fresh.ts` -> `resolveLoadersOnly` on the cache-hit
1022+
path) and merges into every response, so no divergence exists (pinned by the
1023+
`/loader-cookie-allowed` cache-scope-guard e2e and vite-rsc-demo's shop cart).
1024+
A **handler-invoked** loader body (`await ctx.use(Loader)` from a handler,
1025+
never registered with `loader()`) does NOT get the exemption: on a HIT the
1026+
handler is skipped, so that loader never re-runs and its Set-Cookie/header
1027+
would land only on the MISS — it throws exactly like a handler write. The
1028+
discriminator is `isInsideLoaderScope()` (DSL scope only, `loaderScopeALS`),
1029+
not `isInsideAnyLoaderScope()` (which also sees the handler-invoked
1030+
`loaderBodyScopeALS`); because the DSL scope ALS survives nested `ctx.use`
1031+
bodies, a handler-invoked loader nested under a DSL loader stays exempt (its
1032+
DSL parent re-invokes it every HIT). ppr loader writes throw regardless — the
1033+
shell prelude flushes before any loader settles.
1034+
1035+
Note this is a WRITE-only narrowing. The request-scoped READ guard
1036+
(`isInsideCacheScope`, `src/server/context.ts`) deliberately stays on the
1037+
BROAD predicate (`isInsideAnyLoaderScope()`): a handler-invoked loader's read
1038+
under `cache()` bakes a shared copy into the cached artifact — the accepted
1039+
consumption-lane tradeoff (#672/#674) — whereas a write has no baked-copy
1040+
semantics on a HIT, so only writes narrow to DSL scope.
10221041
10231042
Mechanics (the invariants the code comments point at):
10241043

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
212212
- SWR background revalidation re-establishes the request-context ALS (so a cached body reading `getRequestContext()` resolves off the request's I/O context on workerd); profile opt-in `foregroundOnAction` re-executes a stale entry in the foreground during a server action's revalidation render (fresh action response) instead of serving stale + background-revalidating
213213
- Tag-based invalidation: `cacheTag()` (runtime) + `cache({ tags })` (static/dynamic); `updateTag()` (awaitable, read-your-own-writes) and `revalidateTag()` (background, non-blocking — both hard-purge; the only difference is awaitability) fan out to the store-level `invalidateTags()` (the whole tag batch in one call). `cacheTag()` is render-callable: outside a `"use cache"` scope but during a request render it records onto the request's document artifact (`_requestTags`) instead of throwing, so a plain server component tags the PPR shell / document it renders into — PPR's DERIVATIVE invalidation, no first-class ppr tag API (`cacheTag`/`cache-tag.ts`). Built-in stores index tags; the CF store keeps markers in its own KV (single-store, no companion tag store), and the tag-marker reads inherit the L1/L2 latency budgets and fail open. Explicit `cache({ store })` stores are registered for invalidation via a handler-owned, LRU-bounded registry. Document-cache and PPR shell entries are tagged with the request's tag union so they are tag-invalidatable too.
214214
- PPR shell caching (the `ppr` path option; `PartialPrerenderProps` exported from the root) — an opt-in second render axis, integral to the router (no middleware). It caches the rendered HTML shell (React `prerender`'s prelude bytes plus the `postponed` resume state, one coupled `ShellCacheEntry`) and, on a hit, commits the composed response after the WHOLE middleware chain: prelude bytes flush first, then fizz resumes only the holes; the browser sees one ordinary streamed document. Holes are render-defined — `loading()` subtrees (structural; loaders masked at capture), pending promises in handed-over data under the consumer's Suspense (physics), everything else shell (top-level pushed handle promises are awaited pre-SSR and baked; the capture gate holds for that await, bounded by `ppr.captureTimeout` — default 15s; expiry with pushes pending refuses the capture, so a partial head snapshot is never stored). The background capture is mixed-chain (cached segments replay, uncached handlers execute — the cookies()/headers() capture guard is load-bearing) and never re-runs middleware (the derived context inherits post-middleware state). Backed by the optional `getShell`/`putShell` store family (memory/CF/Vercel), reactVersion+buildVersion-gated (isValidShellHit; a redeploy invalidates like a React upgrade, hasIntactShellPayload rejects corrupt payloads pre-commit, a failed HIT tail schedules a healing recapture) and tag-invalidatable. Shell/payload PARITY on a HIT is guaranteed by the CAPTURE DATA SNAPSHOT (`cache/shell-snapshot.ts`, internal): a pre-render write barrier settles the foreground's deferred cache writes so the capture replays the foreground's cache generation (never clobbers it); the capture render records its cache-store read-hits + writes (`RecordingShellStore`, excluding the shell family; `captureAndStoreShell` fires the capture's isolated `onResponse` so the ring-3 segment write runs and is recorded), stores them on `ShellCacheEntry.snapshot` (carried through the CF/Vercel envelopes), and `serveShellHit`'s tail render replays them AS FRESH (`SeededShellStore`) so a shell-baked cached value that DRIFTED (shorter-ttl `cache()`, tag-invalidated item) still matches the frozen prelude — parity beats freshness inside the shell; freshness comes from holes, the shell ttl/swr, and `ppr.tags`. Actions, progressive enhancement, per-request nonce, and `streamMode: "allReady"` (the SEO/bot story) always take axis 1. On a HIT the tail's hydration payload is FRAGMENT-SPLICED (#700): replayed segments carry their STORED per-segment Flight strings verbatim (`__rangoFragment` envelopes, `src/segment-fragments.ts`) instead of being deserialized and re-serialized per request; the SSR resume pass and browser hydration expand them through their own Flight deserializers, so the browser still can't tell. Operability (issue #651): `PartialPrerenderProps.maxSnapshotBytes` (default 8 MiB) skips an over-cap snapshot (shell still stored; once-per-key report; documented drift on later HITs); the `debugShellCapture` router option (`ShellCaptureDebug`/`ShellCaptureDebugEvent`, exported) emits one structured event per capture attempt/skip — outcome, barrier/write-settle waits, prelude/snapshot bytes, backoff state — and in dev the terminal event mirrors into the NEXT ppr GET's Server-Timing (`ppr-capture;desc="…"`, plus a `ppr:shell-read` metric); a KV-less `CFCacheStore` warns once per isolate that its shell family is inert. See [PPR shell caching design](../design/ppr-shell-resume.md).
215-
- Cached-scope header doctrine (#713): ppr is a document-scoped `cache()` — in any cached scenario only MIDDLEWARE writes response headers. One unified guard (`assertCachedHeaderWriteAllowed`, `server/context.ts`) refuses handler header/cookie/status/theme writes inside a `cache()` boundary AND on any render of a `ppr` route (latched at the segment funnels: positional for `cache()`, whole-funnel for ppr — leaf-entry check, same `isPprEntry` + input as the serve path's `resolvePprConfig`; the intercept funnels carry a defense-in-depth latch off the target route), plus loader writes on ppr routes (headers flush with the shell before loaders settle). Enforced at ONE choke point: a guarded Headers proxy shadowed onto the request context's stub `Response`, so `ctx.header`/`setCookie`/`deleteCookie`/`setTheme`, the handler `ctx.headers` proxy, and raw `ctx.res.headers` mutations all hit the guard at the mutation itself (`setStatus`/`onResponse` stay enumerated; internal serve writers are exempt via the raw Headers). Deterministic first-render throw, dev and prod, one message family naming route + layer + the fix ("set response headers in route middleware"). Deliberate asymmetry: loader writes inside plain `cache()` stay allowed (they re-run and merge per request — pinned by cache-scope-guard e2e + vite-rsc-demo shop cart). Middleware headers/cookies merge into every response including shell HITs (`createResponseWithMergedHeaders`/`applyStubHeaders`, `rsc/helpers.ts`). See the header doctrine section in [PPR shell caching design](../design/ppr-shell-resume.md).
215+
- Cached-scope header doctrine (#713): ppr is a document-scoped `cache()` — in any cached scenario only MIDDLEWARE writes response headers. One unified guard (`assertCachedHeaderWriteAllowed`, `server/context.ts`) refuses handler header/cookie/status/theme writes inside a `cache()` boundary AND on any render of a `ppr` route (latched at the segment funnels: positional for `cache()`, whole-funnel for ppr — leaf-entry check, same `isPprEntry` + input as the serve path's `resolvePprConfig`; the intercept funnels carry a defense-in-depth latch off the target route), plus loader writes on ppr routes (headers flush with the shell before loaders settle). Enforced at ONE choke point: a guarded Headers proxy shadowed onto the request context's stub `Response`, so `ctx.header`/`setCookie`/`deleteCookie`/`setTheme`, the handler `ctx.headers` proxy, and raw `ctx.res.headers` mutations all hit the guard at the mutation itself (`setStatus`/`onResponse` stay enumerated; internal serve writers are exempt via the raw Headers). Deterministic first-render throw, dev and prod, one message family naming route + layer + the fix ("set response headers in route middleware"). Deliberate asymmetry: DSL (registered) loader writes inside plain `cache()` stay allowed (they re-run and merge per request — pinned by the `/loader-cookie-allowed` cache-scope-guard e2e + vite-rsc-demo shop cart); a handler-invoked loader body (`ctx.use` from a handler, never registered with `loader()`) throws under `cache()` because it is skipped with its handler on a HIT and its write would land only on the MISS (#725; discriminator `isInsideLoaderScope()` vs `isInsideAnyLoaderScope()`; pinned by the `/handler-loader-cookie-blocked` e2e). Middleware headers/cookies merge into every response including shell HITs (`createResponseWithMergedHeaders`/`applyStubHeaders`, `rsc/helpers.ts`). See the header doctrine section in [PPR shell caching design](../design/ppr-shell-resume.md).
216216
- Build-time PPR shells (producer B, #699): a `Prerender` route that also declares `ppr` gets its complete `ShellCacheEntry` produced at `vite build` and served from the FIRST request after deploy (`x-rango-shell: HIT`, zero runtime capture) — one entry format, two producers, one consumer. The build's shell prerender phase (buildApp post; the prelude embeds the BUILT client bootstrap URL) reuses the discovery temp server and runs producer A's capture core over the just-collected prerender payloads; entries stage as `__ps-*.js` assets + a lazy `__shell-manifest.js` (pathname-only keys) read through on a shell-store MISS. `ppr.ttl` is staleness-only (recapture = the SWR upgrade path); the buildVersion gate retires entries per deploy; `updateTag` evicts by tag-marker comparison (`isTagsInvalidatedSince`, new optional store method on all three stores) against the entry's build-time `createdAt` — no tombstones. Dev parity: the read-through fetches the `/__rsc_shell` dev endpoint (on-demand capture, memoized per HMR generation) for trie `pr`-flagged routes. See prerender-api-design.md (Build-time PPR shells).
217217

218218
### Error and Control Flow

‎packages/rangojs-router/e2e/cache-scope-guard.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,27 @@ test.describe("cache-scope-guard", () => {
161161
);
162162
});
163163

164+
test("handler-invoked loader writing a cookie inside cache() should throw (#725)", async ({
165+
page,
166+
}) => {
167+
const response = await page.goto(
168+
f.url("/cache-scope-guard/handler-loader-cookie-blocked"),
169+
);
170+
await waitForHydration(page);
171+
172+
await expect(page.getByTestId("csg-error-page")).toBeVisible();
173+
await expect(page.getByTestId("csg-error-message")).toContainText(
174+
"cache() boundary",
175+
);
176+
await expect(page.getByTestId("csg-error-message")).toContainText(
177+
"from a loader",
178+
);
179+
// Divergence pin: the MISS-only Set-Cookie never reaches the wire.
180+
expect(response?.headers()["set-cookie"] ?? "").not.toContain(
181+
"csg-hil-cookie",
182+
);
183+
});
184+
164185
test("ctx.headers.set() inside cache() should throw (SSR)", async ({
165186
request,
166187
}) => {
@@ -341,6 +362,22 @@ test.describe("cache-scope-guard (production)", () => {
341362
);
342363
});
343364

365+
test("handler-invoked loader writing a cookie inside cache() should render error boundary (#725)", async ({
366+
page,
367+
}) => {
368+
// Production redacts the error message, so assert the boundary rendered and
369+
// pin the divergence: the MISS-only Set-Cookie never reaches the wire.
370+
const response = await page.goto(
371+
f.url("/cache-scope-guard/handler-loader-cookie-blocked"),
372+
);
373+
await waitForHydration(page);
374+
375+
await expect(page.getByTestId("csg-error-page")).toBeVisible();
376+
expect(response?.headers()["set-cookie"] ?? "").not.toContain(
377+
"csg-hil-cookie",
378+
);
379+
});
380+
344381
test("getRequestContext().get(nonCacheable) inside cache() should render error boundary", async ({
345382
page,
346383
}) => {

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export const NamedRoutes = {
3232
"cacheIsolation.queryVariant": "/cache-isolation/query-variant",
3333
"cacheScopeGuard.asyncLoaderReadAllowed": "/cache-scope-guard/async-loader-read-allowed",
3434
"cacheScopeGuard.cookiesReadBlocked": "/cache-scope-guard/cookies-read-blocked",
35+
"cacheScopeGuard.handlerLoaderCookieBlocked": "/cache-scope-guard/handler-loader-cookie-blocked",
3536
"cacheScopeGuard.headerBlocked": "/cache-scope-guard/header-blocked",
3637
"cacheScopeGuard.headersReadBlocked": "/cache-scope-guard/headers-read-blocked",
3738
"cacheScopeGuard.index": "/cache-scope-guard",

‎packages/rangojs-router/e2e/test-app/src/urls/cache-scope-guard-loader.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,16 @@ export const CookieReaderLoader = createLoader(async () => {
3838
const session = cookies().get("csg-session")?.value;
3939
return { session: session ?? "no-cookie" };
4040
});
41+
42+
// Writes a cookie, but is consumed ONLY via ctx.use from a handler — never
43+
// registered with loader() in the route config. Under cache() this must THROW
44+
// (#725): a handler-invoked loader runs on the MISS but is skipped with its
45+
// handler on a HIT, so the Set-Cookie would land only on the MISS and vanish on
46+
// hits. Contrast CookieWriterLoader (DSL-registered, re-runs every hit,
47+
// ALLOWED).
48+
export const HandlerInvokedCookieWriterLoader = createLoader(async () => {
49+
"use server";
50+
await new Promise((resolve) => setTimeout(resolve, 10));
51+
cookies().set("csg-hil-cookie", "written-by-handler-loader", { path: "/" });
52+
return { wrote: true };
53+
});

‎packages/rangojs-router/e2e/test-app/src/urls/cache-scope-guard.tsx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
AsyncNonCacheableReaderLoader,
1414
CookieWriterLoader,
1515
CookieReaderLoader,
16+
HandlerInvokedCookieWriterLoader,
1617
} from "./cache-scope-guard-loader.js";
1718
import { CacheScopeGuardCookieReader } from "../components/CacheScopeGuardCookieReader.js";
1819

@@ -355,6 +356,28 @@ export const cacheScopeGuardPatterns = urls(
355356
),
356357
]),
357358

359+
// Handler-invoked loader (NOT registered via loader()) calling
360+
// cookies().set() inside cache() — BLOCKED (#725). Unlike
361+
// /loader-cookie-allowed above, the loader is consumed only via ctx.use
362+
// and is never re-run on a HIT (the handler is skipped), so its
363+
// Set-Cookie would land only on the MISS and vanish on hits. The guard
364+
// throws deterministically on the first render instead.
365+
cache({ ttl: 600 }, () => [
366+
errorBoundary((props) => (
367+
<div data-testid="csg-error-page">
368+
<span data-testid="csg-error-message">{props.error.message}</span>
369+
</div>
370+
)),
371+
path(
372+
"/handler-loader-cookie-blocked",
373+
async (ctx) => {
374+
await ctx.use(HandlerInvokedCookieWriterLoader);
375+
return <div>Should not render</div>;
376+
},
377+
{ name: "handlerLoaderCookieBlocked" },
378+
),
379+
]),
380+
358381
// cookies() read inside cache() — BLOCKED (read-purity guard)
359382
cache({ ttl: 600 }, () => [
360383
errorBoundary((props) => (

‎packages/rangojs-router/skills/debug-manifest/SKILL.md‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,10 @@ argument-hint:
88

99
Inspect the route manifest to verify parent relationships, shortCodes, and route structure.
1010

11-
## Quick Access
12-
13-
In development, visit:
14-
15-
```
16-
http://localhost:PORT/?__debug_manifest
17-
```
18-
19-
Returns formatted JSON. The HTTP endpoint shape is `{ routerId, routeManifest, routeAncestry, routeTrie, precomputedEntries }` (see below for the programmatic API shape).
20-
2111
## Programmatic Access
2212

13+
Call `router.debugManifest()` — an `async` method on the router instance:
14+
2315
```typescript
2416
import { router } from "./router.js";
2517

0 commit comments

Comments
 (0)