@rangojs/router 0.0.0-experimental.fb4fdc18 → 0.0.0-experimental.fce7fbd1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/bin/rango.js +147 -57
- package/dist/testing/vitest.js +48 -0
- package/dist/vite/index.js +914 -485
- package/package.json +55 -11
- package/skills/bundle-analysis/SKILL.md +159 -0
- package/skills/cache-guide/SKILL.md +220 -30
- package/skills/caching/SKILL.md +116 -8
- package/skills/composability/SKILL.md +27 -2
- package/skills/document-cache/SKILL.md +78 -55
- package/skills/handler-use/SKILL.md +3 -1
- package/skills/hooks/SKILL.md +214 -18
- package/skills/host-router/SKILL.md +45 -20
- package/skills/intercept/SKILL.md +26 -4
- package/skills/layout/SKILL.md +6 -7
- package/skills/links/SKILL.md +173 -17
- package/skills/loader/SKILL.md +149 -6
- package/skills/middleware/SKILL.md +13 -9
- package/skills/migrate-nextjs/SKILL.md +1 -1
- package/skills/mime-routes/SKILL.md +27 -0
- package/skills/observability/SKILL.md +137 -0
- package/skills/parallel/SKILL.md +5 -6
- package/skills/prerender/SKILL.md +14 -33
- package/skills/rango/SKILL.md +242 -26
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +58 -9
- package/skills/route/SKILL.md +13 -4
- package/skills/router-setup/SKILL.md +3 -3
- package/skills/server-actions/SKILL.md +53 -41
- package/skills/testing/SKILL.md +599 -0
- package/skills/typesafety/SKILL.md +310 -26
- package/skills/use-cache/SKILL.md +34 -5
- package/skills/view-transitions/SKILL.md +294 -0
- package/src/__augment-tests__/augment.ts +81 -0
- package/src/__augment-tests__/augmented.check.ts +117 -0
- package/src/browser/action-coordinator.ts +53 -36
- package/src/browser/event-controller.ts +42 -66
- package/src/browser/history-state.ts +21 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/navigation-bridge.ts +6 -6
- package/src/browser/navigation-client.ts +12 -15
- package/src/browser/navigation-store.ts +7 -8
- package/src/browser/navigation-transaction.ts +10 -28
- package/src/browser/partial-update.ts +9 -19
- package/src/browser/react/NavigationProvider.tsx +29 -40
- package/src/browser/react/index.ts +3 -0
- package/src/browser/react/location-state-shared.ts +175 -4
- package/src/browser/react/location-state.ts +39 -13
- package/src/browser/react/use-handle.ts +17 -9
- package/src/browser/react/use-params.ts +3 -4
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +14 -1
- package/src/browser/response-adapter.ts +25 -0
- package/src/browser/rsc-router.tsx +30 -16
- package/src/browser/scroll-restoration.ts +22 -14
- package/src/browser/segment-structure-assert.ts +2 -2
- package/src/browser/server-action-bridge.ts +23 -30
- package/src/browser/types.ts +2 -0
- package/src/build/collect-fallback-refs.ts +107 -0
- package/src/build/generate-manifest.ts +60 -35
- package/src/build/generate-route-types.ts +2 -0
- package/src/build/index.ts +2 -0
- package/src/build/route-types/codegen.ts +4 -4
- package/src/build/route-types/include-resolution.ts +1 -1
- package/src/build/route-types/per-module-writer.ts +7 -4
- package/src/build/route-types/router-processing.ts +55 -14
- package/src/build/route-types/scan-filter.ts +1 -1
- package/src/build/route-types/source-scan.ts +118 -0
- package/src/build/runtime-discovery.ts +9 -20
- package/src/cache/cache-scope.ts +28 -42
- package/src/cache/cf/cf-cache-store.ts +49 -6
- package/src/client.rsc.tsx +3 -0
- package/src/client.tsx +10 -8
- package/src/context-var.ts +5 -5
- package/src/decode-loader-results.ts +36 -0
- package/src/errors.ts +30 -1
- package/src/handle.ts +26 -13
- package/src/host/index.ts +2 -2
- package/src/host/router.ts +129 -57
- package/src/host/types.ts +31 -2
- package/src/host/utils.ts +1 -1
- package/src/href-client.ts +140 -20
- package/src/index.rsc.ts +6 -4
- package/src/index.ts +13 -6
- package/src/loader-store.ts +500 -0
- package/src/loader.rsc.ts +2 -5
- package/src/loader.ts +3 -10
- package/src/missing-id-error.ts +68 -0
- package/src/prerender.ts +4 -4
- package/src/response-utils.ts +9 -0
- package/src/reverse.ts +65 -41
- package/src/route-content-wrapper.tsx +6 -28
- package/src/route-definition/dsl-helpers.ts +238 -263
- package/src/route-definition/helper-factories.ts +29 -139
- package/src/route-definition/helpers-types.ts +37 -14
- package/src/route-definition/use-item-types.ts +32 -0
- package/src/route-types.ts +19 -41
- package/src/router/basename.ts +14 -0
- package/src/router/content-negotiation.ts +15 -2
- package/src/router/error-handling.ts +1 -1
- package/src/router/handler-context.ts +4 -42
- package/src/router/intercept-resolution.ts +4 -18
- package/src/router/lazy-includes.ts +2 -2
- package/src/router/loader-resolution.ts +16 -2
- package/src/router/match-handlers.ts +62 -20
- package/src/router/match-middleware/cache-lookup.ts +44 -91
- package/src/router/match-middleware/cache-store.ts +3 -2
- package/src/router/match-result.ts +32 -30
- package/src/router/metrics.ts +1 -1
- package/src/router/middleware-types.ts +1 -1
- package/src/router/middleware.ts +46 -78
- package/src/router/prerender-match.ts +1 -1
- package/src/router/preview-match.ts +3 -1
- package/src/router/request-classification.ts +4 -28
- package/src/router/revalidation.ts +43 -1
- package/src/router/router-interfaces.ts +45 -28
- package/src/router/router-options.ts +40 -1
- package/src/router/router-registry.ts +2 -5
- package/src/router/segment-resolution/fresh.ts +19 -6
- package/src/router/segment-resolution/revalidation.ts +19 -6
- package/src/router/segment-resolution/view-transition-default.ts +36 -0
- package/src/router/substitute-pattern-params.ts +56 -0
- package/src/router/telemetry.ts +99 -0
- package/src/router/types.ts +8 -0
- package/src/router.ts +37 -21
- package/src/rsc/handler-context.ts +2 -2
- package/src/rsc/handler.ts +20 -65
- package/src/rsc/helpers.ts +22 -2
- package/src/rsc/index.ts +1 -1
- package/src/rsc/origin-guard.ts +28 -10
- package/src/rsc/response-route-handler.ts +32 -52
- package/src/rsc/rsc-rendering.ts +27 -53
- package/src/rsc/runtime-warnings.ts +9 -10
- package/src/rsc/server-action.ts +13 -37
- package/src/rsc/ssr-setup.ts +16 -0
- package/src/rsc/types.ts +2 -2
- package/src/search-params.ts +4 -4
- package/src/segment-system.tsx +121 -65
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +118 -51
- package/src/server/cookie-store.ts +28 -4
- package/src/server/request-context.ts +10 -0
- package/src/static-handler.ts +1 -1
- package/src/testing/cache-status.ts +166 -0
- package/src/testing/collect-handle.ts +63 -0
- package/src/testing/dispatch.ts +440 -0
- package/src/testing/dom.entry.ts +22 -0
- package/src/testing/e2e/fixture.ts +154 -0
- package/src/testing/e2e/index.ts +149 -0
- package/src/testing/e2e/matchers.ts +51 -0
- package/src/testing/e2e/page-helpers.ts +272 -0
- package/src/testing/e2e/parity.ts +306 -0
- package/src/testing/e2e/server.ts +183 -0
- package/src/testing/flight-matchers.ts +104 -0
- package/src/testing/flight-runtime.d.ts +21 -0
- package/src/testing/flight.entry.ts +22 -0
- package/src/testing/flight.ts +182 -0
- package/src/testing/generated-routes.ts +223 -0
- package/src/testing/index.ts +105 -0
- package/src/testing/internal/context.ts +193 -0
- package/src/testing/render-route.tsx +536 -0
- package/src/testing/run-loader.ts +296 -0
- package/src/testing/run-middleware.ts +170 -0
- package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
- package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
- package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
- package/src/testing/vitest-stubs/version.ts +5 -0
- package/src/testing/vitest.ts +183 -0
- package/src/types/global-namespace.ts +39 -26
- package/src/types/handler-context.ts +56 -11
- package/src/types/index.ts +1 -0
- package/src/types/segments.ts +18 -1
- package/src/urls/include-helper.ts +10 -53
- package/src/urls/index.ts +0 -3
- package/src/urls/path-helper-types.ts +11 -3
- package/src/urls/path-helper.ts +17 -52
- package/src/urls/pattern-types.ts +36 -19
- package/src/urls/response-types.ts +20 -19
- package/src/urls/type-extraction.ts +26 -116
- package/src/urls/urls-function.ts +1 -5
- package/src/use-loader.tsx +413 -42
- package/src/vite/debug.ts +1 -0
- package/src/vite/discovery/bundle-postprocess.ts +6 -6
- package/src/vite/discovery/discover-routers.ts +70 -48
- package/src/vite/discovery/discovery-errors.ts +194 -0
- package/src/vite/discovery/prerender-collection.ts +19 -25
- package/src/vite/discovery/route-types-writer.ts +40 -84
- package/src/vite/discovery/state.ts +33 -0
- package/src/vite/discovery/virtual-module-codegen.ts +13 -23
- package/src/vite/index.ts +2 -0
- package/src/vite/plugin-types.ts +67 -0
- package/src/vite/plugins/cjs-to-esm.ts +3 -7
- package/src/vite/plugins/client-ref-hashing.ts +12 -1
- package/src/vite/plugins/cloudflare-protocol-stub.ts +1 -1
- package/src/vite/plugins/expose-action-id.ts +2 -2
- package/src/vite/plugins/expose-id-utils.ts +12 -8
- package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
- package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
- package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
- package/src/vite/plugins/expose-internal-ids.ts +47 -67
- package/src/vite/plugins/performance-tracks.ts +12 -16
- package/src/vite/plugins/use-cache-transform.ts +13 -11
- package/src/vite/plugins/version-injector.ts +2 -12
- package/src/vite/plugins/version-plugin.ts +59 -2
- package/src/vite/plugins/virtual-entries.ts +2 -2
- package/src/vite/rango.ts +67 -15
- package/src/vite/router-discovery.ts +208 -63
- package/src/vite/utils/ast-handler-extract.ts +15 -15
- package/src/vite/utils/bundle-analysis.ts +4 -2
- package/src/vite/utils/client-chunks.ts +190 -0
- package/src/vite/utils/forward-user-plugins.ts +193 -0
- package/src/vite/utils/manifest-utils.ts +21 -5
- package/src/vite/utils/shared-utils.ts +107 -26
- package/src/browser/action-response-classifier.ts +0 -99
package/skills/caching/SKILL.md
CHANGED
|
@@ -8,6 +8,46 @@ argument-hint: [setup]
|
|
|
8
8
|
|
|
9
9
|
@rangojs/router supports segment-level caching with stale-while-revalidate (SWR) for optimal performance.
|
|
10
10
|
|
|
11
|
+
> SWR support is store-specific. `CFCacheStore` revalidates segment, response,
|
|
12
|
+
> and `"use cache"` entries in the background. `MemorySegmentCacheStore`
|
|
13
|
+
> supports SWR for response and `"use cache"` item entries, but its
|
|
14
|
+
> route-segment entries expire at TTL with no background revalidation — use
|
|
15
|
+
> `CFCacheStore` for real segment SWR. See `/cache-guide`.
|
|
16
|
+
|
|
17
|
+
## cache() is Partial Prerendering (PPR)
|
|
18
|
+
|
|
19
|
+
`cache()` caches **everything except loaders**. On a cache hit, the cached
|
|
20
|
+
segments (layouts, route components, parallels — including any resolved
|
|
21
|
+
Suspense) are served from the store, and **loaders re-run fresh on every
|
|
22
|
+
request**, streaming their results into the same response. Loaders are the
|
|
23
|
+
dynamic "holes" of an otherwise-cached tree.
|
|
24
|
+
|
|
25
|
+
This means a `cache()` boundary at the document root **is** whole-document
|
|
26
|
+
Partial Prerendering: the static shell is cached and served instantly while
|
|
27
|
+
per-request/per-user data stays live — in one streamed response, no extra round
|
|
28
|
+
trip. The browser cannot tell the shell came from cache.
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
cache({ ttl: 60, swr: 300 }, () => [
|
|
32
|
+
layout(<RootLayout />), // cached shell
|
|
33
|
+
path("/dashboard", Dashboard, { name: "dashboard" }, () => [
|
|
34
|
+
loader(StatsLoader), // DYNAMIC HOLE — re-runs every request
|
|
35
|
+
]),
|
|
36
|
+
]);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The consumer rule: **want it cached? render it inline. want it dynamic? put it
|
|
40
|
+
in a loader and read it with `useLoader()` in a client component.** Anything
|
|
41
|
+
read with `cookies()`, `headers()`, or a non-cacheable variable belongs in a
|
|
42
|
+
loader (loaders always run fresh). Reading it directly in a cached handler
|
|
43
|
+
throws; awaiting it with `ctx.use()` and rendering the result in a cached
|
|
44
|
+
handler silently bakes per-request data into the shared shell (see "Cache purity
|
|
45
|
+
& tainted objects" below).
|
|
46
|
+
|
|
47
|
+
Pre-rendering (`/prerender`) is the build-time twin: it caches the same shell at
|
|
48
|
+
build time instead of on first request. Both feed the segment system
|
|
49
|
+
identically, and loaders always run fresh at request time.
|
|
50
|
+
|
|
11
51
|
## Route-Level Caching with cache()
|
|
12
52
|
|
|
13
53
|
Use the `cache()` DSL function to cache routes:
|
|
@@ -116,7 +156,6 @@ import { MemorySegmentCacheStore } from "@rangojs/router/cache";
|
|
|
116
156
|
|
|
117
157
|
const store = new MemorySegmentCacheStore({
|
|
118
158
|
defaults: { ttl: 60, swr: 300 },
|
|
119
|
-
maxSize: 1000, // Max entries
|
|
120
159
|
});
|
|
121
160
|
```
|
|
122
161
|
|
|
@@ -173,13 +212,82 @@ const router = createRouter<AppBindings>({
|
|
|
173
212
|
KV entries require `expirationTtl >= 60s`. Short-lived entries (< 60s total TTL)
|
|
174
213
|
are only cached in L1.
|
|
175
214
|
|
|
176
|
-
##
|
|
215
|
+
## Cache purity & tainted objects
|
|
216
|
+
|
|
217
|
+
A `cache()` boundary caches everything except loaders, so anything read inside a
|
|
218
|
+
cached handler is **frozen into the shared cache entry** and served to every
|
|
219
|
+
subsequent visitor. To stop one user's request-scoped data from leaking to
|
|
220
|
+
another, request-scoped APIs are guarded inside a cache scope:
|
|
221
|
+
|
|
222
|
+
| Inside a `cache()` boundary | Behavior |
|
|
223
|
+
| --------------------------------------------------------------- | --------------------------------------------------- |
|
|
224
|
+
| `cookies()` / `headers()` (read or write) | **throws** — request-scoped, would poison the entry |
|
|
225
|
+
| `ctx.header()` / `setCookie()` / `setStatus()` / `onResponse()` | **throws** — response side effects lost on a hit |
|
|
226
|
+
| `ctx.get(var)` where the var is `{ cache: false }` | **throws** on read |
|
|
227
|
+
| `ctx.set(var, value)` for a cacheable var | allowed (children are cached too) |
|
|
228
|
+
| Any of the above **inside a loader** | **allowed** — loaders always run fresh |
|
|
229
|
+
|
|
230
|
+
**Tainted objects.** Request-scoped objects (`ctx`, `env`, `request`) carry an
|
|
231
|
+
internal taint symbol so they are excluded from `"use cache"` cache keys, and
|
|
232
|
+
the cache scope is tracked via async-local state. Two flags back the guards:
|
|
233
|
+
`INSIDE_CACHE_EXEC` (set while a `"use cache"` function runs) and the `cache()`
|
|
234
|
+
DSL scope (`isInsideCacheScope()`). `isInsideCacheScope()` deliberately returns
|
|
235
|
+
`false` inside loaders — which is exactly why loaders are the dynamic holes:
|
|
236
|
+
they may read `cookies()`/`headers()` and re-run on every request.
|
|
237
|
+
|
|
238
|
+
The fix for "I need request data in a cached route": register a `loader()` and
|
|
239
|
+
**consume it with `useLoader()` in a client component**. The loader is the
|
|
240
|
+
dynamic hole — its data rides the fresh (never-cached) loader segment and is
|
|
241
|
+
rendered in the client component, so it never lands in the cached shell.
|
|
242
|
+
|
|
243
|
+
This is NOT the same as awaiting the loader in the handler. A cached handler
|
|
244
|
+
that does `await ctx.use(Loader)` and renders the result bakes that per-request
|
|
245
|
+
data straight into the shared cached segment — the loader running "fresh" does
|
|
246
|
+
not help, because its output was inlined into the cached parent, and `ctx.use()`
|
|
247
|
+
is **not** guarded. `ctx.use()` is a server-side escape hatch for non-rendered
|
|
248
|
+
uses (set a ctx var, make a routing decision); never render its result inside a
|
|
249
|
+
cached handler.
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
// WRONG — throws: cookies() read directly in a cached handler
|
|
253
|
+
cache({ ttl: 60 }, () => [
|
|
254
|
+
path("/me", () => <Profile id={cookies().get("uid")?.value} />),
|
|
255
|
+
]);
|
|
256
|
+
|
|
257
|
+
// ALSO WRONG (unguarded, but leaks) — the awaited loader data is rendered into
|
|
258
|
+
// the cached handler, so the user's data is frozen into the shared shell.
|
|
259
|
+
cache({ ttl: 60 }, () => [
|
|
260
|
+
path(
|
|
261
|
+
"/me",
|
|
262
|
+
async (ctx) => {
|
|
263
|
+
const { user } = await ctx.use(MeLoader); // runs fresh…
|
|
264
|
+
return <Profile user={user} />; // …but inlined into the CACHED segment → leak
|
|
265
|
+
},
|
|
266
|
+
{ name: "me" },
|
|
267
|
+
() => [loader(MeLoader)],
|
|
268
|
+
),
|
|
269
|
+
]);
|
|
270
|
+
|
|
271
|
+
// RIGHT — consume the loader in a CLIENT component via useLoader(). The cached
|
|
272
|
+
// route segment holds only the <Profile/> reference; the user data rides the
|
|
273
|
+
// fresh loader segment and renders client-side.
|
|
274
|
+
|
|
275
|
+
// profile.tsx (client component)
|
|
276
|
+
"use client";
|
|
277
|
+
import { useLoader } from "@rangojs/router/client";
|
|
278
|
+
|
|
279
|
+
export function Profile() {
|
|
280
|
+
const { user } = useLoader(MeLoader); // fresh per request; never cached
|
|
281
|
+
return <span>{user.name}</span>;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// urls — register the loader; MeLoader reads cookies() inside the loader (allowed)
|
|
285
|
+
cache({ ttl: 60 }, () => [
|
|
286
|
+
path("/me", () => <Profile />, { name: "me" }, () => [loader(MeLoader)]),
|
|
287
|
+
]);
|
|
288
|
+
```
|
|
177
289
|
|
|
178
|
-
|
|
179
|
-
written inside `cache()` scopes. Variables marked with `{ cache: false }` (at
|
|
180
|
-
the var level or write level) throw when read inside a cache scope. Response
|
|
181
|
-
side effects (`ctx.header()`, `ctx.cookie()`) always throw inside cache
|
|
182
|
-
boundaries. See `/cache-guide` for the full cache safety table.
|
|
290
|
+
See `/cache-guide` for the full decision guide and the `cache()` vs `"use cache"` comparison.
|
|
183
291
|
|
|
184
292
|
## Nested Cache Boundaries
|
|
185
293
|
|
|
@@ -245,7 +353,7 @@ export const urlpatterns = urls(({ path, layout, cache, loader, revalidate }) =>
|
|
|
245
353
|
path("/shop/product/:slug", ProductPage, { name: "product" }, () => [
|
|
246
354
|
loader(ProductLoader, () => [cache({ ttl: 120 })]),
|
|
247
355
|
loader(CartLoader, () => [
|
|
248
|
-
revalidate(({ actionId }) => actionId?.includes("Cart")
|
|
356
|
+
revalidate(({ actionId }) => actionId?.includes("Cart") || undefined),
|
|
249
357
|
]),
|
|
250
358
|
]),
|
|
251
359
|
]),
|
|
@@ -55,7 +55,9 @@ import { cache, revalidate, loading, errorBoundary, middleware } from "@rangojs/
|
|
|
55
55
|
// Shared caching configuration
|
|
56
56
|
const withCaching = () => [
|
|
57
57
|
cache({ ttl: 600_000 }),
|
|
58
|
-
|
|
58
|
+
// Defer on navigation (|| undefined) so each route keeps its own param/search
|
|
59
|
+
// revalidation default; only force a re-run when an action ran.
|
|
60
|
+
revalidate(({ actionId }) => (actionId ? true : undefined)),
|
|
59
61
|
];
|
|
60
62
|
|
|
61
63
|
// Shared loading and error handling
|
|
@@ -71,6 +73,29 @@ const withAuth = () => [
|
|
|
71
73
|
];
|
|
72
74
|
```
|
|
73
75
|
|
|
76
|
+
> **Factories compose logic, not just values.** A `revalidate()` predicate in a
|
|
77
|
+
> shared factory applies its logic to _every_ route that composes it, so a
|
|
78
|
+
> footgun here is amplified across the app. Two rules:
|
|
79
|
+
>
|
|
80
|
+
> 1. Use `|| undefined` (defer), not `?? false` (hard short-circuit), in shared
|
|
81
|
+
> predicates — a hard `false` ends the chain and overrides each consuming
|
|
82
|
+
> route's own default, and a downstream revalidator never runs. See `/loader`
|
|
83
|
+
> → "`|| undefined` (defer) vs `?? false` (hard)".
|
|
84
|
+
> 2. Match actions with `ctx.isAction(Action)`, not an inline
|
|
85
|
+
> `actionId.includes("…")` buried in a factory: it resolves the action from an
|
|
86
|
+
> imported reference, so a rename is a compile error in one place instead of
|
|
87
|
+
> silent drift across every consumer.
|
|
88
|
+
>
|
|
89
|
+
> Remember the axis: a factory's `revalidate()` controls client-update
|
|
90
|
+
> selection, while its `cache()` controls stored-value freshness. They are
|
|
91
|
+
> independent even when bundled in the same factory (`/cache-guide` → "Two axes").
|
|
92
|
+
|
|
93
|
+
> **Keep factories small and intention-named.** The anti-pattern that kills
|
|
94
|
+
> readability is over-bundling — a `withDefaults()` that secretly adds five
|
|
95
|
+
> things — and factory-of-factories nesting (leaning on `.flat(3)`). Surprising
|
|
96
|
+
> config stays inline; extract only the boring, repeated parts; compose by
|
|
97
|
+
> _naming concerns_ (`withAuth()`, `withCaching()`), not by hiding them.
|
|
98
|
+
|
|
74
99
|
## Using Factories in Routes
|
|
75
100
|
|
|
76
101
|
Place factory calls inside `path()` or `layout()` use callbacks. The returned arrays are flattened automatically (up to 3 levels):
|
|
@@ -107,7 +132,7 @@ import { authMiddleware } from "./middleware/auth";
|
|
|
107
132
|
|
|
108
133
|
export const withPublicDefaults = () => [
|
|
109
134
|
cache({ ttl: 300 }),
|
|
110
|
-
revalidate(({ actionId }) =>
|
|
135
|
+
revalidate(({ actionId }) => (actionId ? true : undefined)),
|
|
111
136
|
];
|
|
112
137
|
|
|
113
138
|
export const withProtectedDefaults = () => [
|
|
@@ -10,73 +10,82 @@ Caches complete HTTP responses (HTML/RSC) at the edge based on Cache-Control hea
|
|
|
10
10
|
|
|
11
11
|
## Setup
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Document caching is a middleware. Add `createDocumentCacheMiddleware()` to the
|
|
14
|
+
router with `.use()`. The cache store it reads from is the app-level store you
|
|
15
|
+
configure on `createRouter({ cache })` (available on the request context as
|
|
16
|
+
`requestCtx._cacheStore`), not a store passed to the middleware.
|
|
14
17
|
|
|
15
18
|
```typescript
|
|
16
19
|
import { createRouter } from "@rangojs/router";
|
|
17
|
-
import {
|
|
20
|
+
import {
|
|
21
|
+
createDocumentCacheMiddleware,
|
|
22
|
+
CFCacheStore,
|
|
23
|
+
} from "@rangojs/router/cache";
|
|
18
24
|
import { urlpatterns } from "./urls";
|
|
19
25
|
|
|
20
26
|
const router = createRouter<AppBindings>({
|
|
21
27
|
document: Document,
|
|
22
28
|
urls: urlpatterns,
|
|
23
|
-
|
|
24
|
-
|
|
29
|
+
// App-level cache store. The document cache middleware uses this store's
|
|
30
|
+
// getResponse/putResponse methods.
|
|
31
|
+
cache: (_env, ctx) => new CFCacheStore({ ctx: ctx! }),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
router.use(
|
|
35
|
+
createDocumentCacheMiddleware({
|
|
25
36
|
skipPaths: ["/api", "/admin"],
|
|
26
37
|
debug: process.env.NODE_ENV === "development",
|
|
27
38
|
}),
|
|
28
|
-
|
|
39
|
+
);
|
|
29
40
|
|
|
30
41
|
export default router;
|
|
31
42
|
```
|
|
32
43
|
|
|
33
|
-
## Route Opt-In with
|
|
44
|
+
## Route Opt-In with Cache-Control
|
|
34
45
|
|
|
35
|
-
Routes opt-in to document caching
|
|
46
|
+
Routes opt-in to document caching by setting a `Cache-Control` response header
|
|
47
|
+
with `s-maxage`. The middleware caches responses whose `Cache-Control` includes
|
|
48
|
+
`s-maxage`; `stale-while-revalidate` enables background revalidation (SWR).
|
|
36
49
|
|
|
37
50
|
```typescript
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
// No cache for dashboard (no documentCache option)
|
|
52
|
-
path("/dashboard", Dashboard, { name: "dashboard" }),
|
|
53
|
-
]);
|
|
51
|
+
// Cache full page for 5 min, serve stale for 1 hour
|
|
52
|
+
function BlogIndexHandler(ctx) {
|
|
53
|
+
ctx.headers.set("Cache-Control", "s-maxage=300, stale-while-revalidate=3600");
|
|
54
|
+
return <BlogIndex />;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Long cache for individual posts
|
|
58
|
+
function BlogPostHandler(ctx) {
|
|
59
|
+
ctx.headers.set("Cache-Control", "s-maxage=3600, stale-while-revalidate=86400");
|
|
60
|
+
return <BlogPost />;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Dashboard sets no Cache-Control header, so it is never document-cached.
|
|
54
64
|
```
|
|
55
65
|
|
|
56
66
|
## Document Cache Options
|
|
57
67
|
|
|
58
|
-
|
|
59
|
-
createRouter({
|
|
60
|
-
// ...
|
|
61
|
-
documentCache: (_env, ctx) => ({
|
|
62
|
-
// Cache store (required)
|
|
63
|
-
store: new CFCacheStore({ ctx: ctx! }),
|
|
68
|
+
`createDocumentCacheMiddleware(options?)` accepts:
|
|
64
69
|
|
|
65
|
-
|
|
66
|
-
|
|
70
|
+
```typescript
|
|
71
|
+
createDocumentCacheMiddleware({
|
|
72
|
+
// Skip specific paths (matched by pathname prefix)
|
|
73
|
+
skipPaths: ["/api", "/admin"],
|
|
67
74
|
|
|
68
|
-
|
|
69
|
-
|
|
75
|
+
// Custom cache key generator
|
|
76
|
+
keyGenerator: (url) => url.pathname,
|
|
70
77
|
|
|
71
|
-
|
|
72
|
-
|
|
78
|
+
// Conditional caching, evaluated per request
|
|
79
|
+
isEnabled: (ctx) => !ctx.request.headers.has("x-preview"),
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}),
|
|
81
|
+
// Debug logging (HIT, MISS, STALE, REVALIDATED)
|
|
82
|
+
debug: true,
|
|
77
83
|
});
|
|
78
84
|
```
|
|
79
85
|
|
|
86
|
+
The cache store is not a middleware option — it comes from the app-level
|
|
87
|
+
`createRouter({ cache })` store.
|
|
88
|
+
|
|
80
89
|
## How It Works
|
|
81
90
|
|
|
82
91
|
```
|
|
@@ -89,7 +98,7 @@ Request → Check Cache
|
|
|
89
98
|
↓ ↓
|
|
90
99
|
Fresh? Run handler
|
|
91
100
|
│ │
|
|
92
|
-
Yes → Return Has
|
|
101
|
+
Yes → Return Has s-maxage?
|
|
93
102
|
│ │
|
|
94
103
|
No (stale) Yes → Cache + Return
|
|
95
104
|
│ │
|
|
@@ -120,13 +129,14 @@ Segment hash ensures different cached responses for navigations from different s
|
|
|
120
129
|
|
|
121
130
|
- Full HTML responses (document requests)
|
|
122
131
|
- RSC payloads (client navigation)
|
|
123
|
-
- Only 200 OK responses
|
|
132
|
+
- Only 200 OK responses whose `Cache-Control` includes `s-maxage`
|
|
124
133
|
|
|
125
134
|
## What's NOT Cached
|
|
126
135
|
|
|
127
136
|
- Server actions (`_rsc_action`)
|
|
128
137
|
- Loader requests (`_rsc_loader`)
|
|
129
|
-
-
|
|
138
|
+
- Non-GET requests
|
|
139
|
+
- Responses without an `s-maxage` `Cache-Control` directive
|
|
130
140
|
- Non-200 responses
|
|
131
141
|
|
|
132
142
|
## Complete Example
|
|
@@ -134,40 +144,53 @@ Segment hash ensures different cached responses for navigations from different s
|
|
|
134
144
|
```typescript
|
|
135
145
|
// router.tsx
|
|
136
146
|
import { createRouter } from "@rangojs/router";
|
|
137
|
-
import { CFCacheStore } from "@rangojs/router/cache";
|
|
147
|
+
import { createDocumentCacheMiddleware, CFCacheStore } from "@rangojs/router/cache";
|
|
138
148
|
import { urlpatterns } from "./urls";
|
|
139
149
|
|
|
140
150
|
const router = createRouter<AppBindings>({
|
|
141
151
|
document: Document,
|
|
142
152
|
urls: urlpatterns,
|
|
143
|
-
|
|
144
|
-
|
|
153
|
+
cache: (_env, ctx) => new CFCacheStore({ ctx: ctx! }),
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
router.use(
|
|
157
|
+
createDocumentCacheMiddleware({
|
|
145
158
|
skipPaths: ["/api"],
|
|
146
159
|
debug: process.env.NODE_ENV === "development",
|
|
147
160
|
}),
|
|
148
|
-
|
|
161
|
+
);
|
|
149
162
|
|
|
150
163
|
export default router;
|
|
151
164
|
|
|
152
165
|
// urls.tsx
|
|
153
166
|
import { urls } from "@rangojs/router";
|
|
154
167
|
|
|
155
|
-
export const urlpatterns = urls(({ path, layout,
|
|
156
|
-
// Blog
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
]),
|
|
168
|
+
export const urlpatterns = urls(({ path, layout, loader }) => [
|
|
169
|
+
// Blog pages opt into document caching via Cache-Control headers set in
|
|
170
|
+
// their handlers (see BlogIndex / BlogPost below).
|
|
171
|
+
layout(<BlogLayout />, () => [
|
|
172
|
+
path("/blog", BlogIndex, { name: "blog" }),
|
|
173
|
+
path("/blog/:slug", BlogPost, { name: "blogPost" }, () => [
|
|
174
|
+
loader(BlogPostLoader),
|
|
163
175
|
]),
|
|
164
176
|
]),
|
|
165
177
|
|
|
166
|
-
// Dashboard
|
|
178
|
+
// Dashboard sets no Cache-Control header, so it is never document-cached.
|
|
167
179
|
layout(<DashboardLayout />, () => [
|
|
168
180
|
path("/dashboard", Dashboard, { name: "dashboard" }),
|
|
169
181
|
]),
|
|
170
182
|
]);
|
|
183
|
+
|
|
184
|
+
// Blog handlers set s-maxage to opt into the document cache.
|
|
185
|
+
function BlogIndex(ctx) {
|
|
186
|
+
ctx.headers.set("Cache-Control", "s-maxage=300, stale-while-revalidate=3600");
|
|
187
|
+
return <BlogIndexPage />;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function BlogPost(ctx) {
|
|
191
|
+
ctx.headers.set("Cache-Control", "s-maxage=300, stale-while-revalidate=3600");
|
|
192
|
+
return <BlogPostPage />;
|
|
193
|
+
}
|
|
171
194
|
```
|
|
172
195
|
|
|
173
196
|
## Document Cache vs Segment Cache
|
|
@@ -175,7 +198,7 @@ export const urlpatterns = urls(({ path, layout, cache, loader }) => [
|
|
|
175
198
|
| Feature | Document Cache | Segment Cache |
|
|
176
199
|
| ------------ | -------------------------- | --------------------- |
|
|
177
200
|
| Granularity | Full response | Individual segments |
|
|
178
|
-
| Opt-in | `
|
|
201
|
+
| Opt-in | `Cache-Control` `s-maxage` | `cache({ ttl, swr })` |
|
|
179
202
|
| Use case | Static pages | Dynamic compositions |
|
|
180
203
|
| Key includes | URL + segment hash | Route params |
|
|
181
204
|
|
|
@@ -59,6 +59,8 @@ Now `ProductPage` carries its loader, loading state, and response-header middlew
|
|
|
59
59
|
| `intercept()` | `middleware`, `revalidate`, `loader`, `loading`, `errorBoundary`, `notFoundBoundary`, `layout`, `route`, `when`, `transition` |
|
|
60
60
|
| Response routes (`path.json()`, `path.text()`, …) | `middleware`, `cache` |
|
|
61
61
|
|
|
62
|
+
For per-item semantics see the dedicated skills: [middleware](../middleware/SKILL.md), [loader](../loader/SKILL.md), [parallel](../parallel/SKILL.md), [intercept](../intercept/SKILL.md), [layout](../layout/SKILL.md), [view-transitions](../view-transitions/SKILL.md).
|
|
63
|
+
|
|
62
64
|
If `handler.use()` returns a disallowed item for a mount site, registration throws:
|
|
63
65
|
|
|
64
66
|
```
|
|
@@ -295,7 +297,7 @@ QuickViewModal.use = () => [
|
|
|
295
297
|
|
|
296
298
|
## `loading()` is a single-assignment item — scope it correctly
|
|
297
299
|
|
|
298
|
-
Most `use` items accumulate when merged: `handler.use` `middleware()` runs _and_ explicit `middleware()` runs; both `loader()` registrations apply. `loading()` is different — it mutates `entry.loading` directly, last call wins ([dsl-helpers.ts `
|
|
300
|
+
Most `use` items accumulate when merged: `handler.use` `middleware()` runs _and_ explicit `middleware()` runs; both `loader()` registrations apply. `loading()` is different — it mutates `entry.loading` directly, last call wins ([dsl-helpers.ts `loading`](../../src/route-definition/dsl-helpers.ts)).
|
|
299
301
|
|
|
300
302
|
For pages, layouts, and intercepts that's straightforward: explicit `loading()` at the mount site replaces any `loading()` from `handler.use`. The merge order is `handler.use → explicit`, so the explicit one is the last writer and wins.
|
|
301
303
|
|