@rangojs/router 0.0.0-experimental.d7eeaa75 → 0.0.0-experimental.dc2bd2b4
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 +120 -25
- package/dist/bin/rango.js +147 -57
- package/dist/testing/vitest.js +48 -0
- package/dist/vite/index.js +2151 -846
- package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/package.json +57 -11
- package/skills/breadcrumbs/SKILL.md +3 -1
- 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 +364 -0
- package/skills/hooks/SKILL.md +229 -20
- package/skills/host-router/SKILL.md +45 -20
- package/skills/i18n/SKILL.md +276 -0
- package/skills/intercept/SKILL.md +46 -4
- package/skills/layout/SKILL.md +28 -7
- package/skills/links/SKILL.md +247 -17
- package/skills/loader/SKILL.md +219 -9
- package/skills/middleware/SKILL.md +47 -12
- package/skills/migrate-nextjs/SKILL.md +562 -0
- package/skills/migrate-react-router/SKILL.md +769 -0
- package/skills/mime-routes/SKILL.md +27 -0
- package/skills/observability/SKILL.md +137 -0
- package/skills/parallel/SKILL.md +71 -6
- package/skills/prerender/SKILL.md +14 -33
- package/skills/rango/SKILL.md +242 -22
- package/skills/react-compiler/SKILL.md +168 -0
- package/skills/response-routes/SKILL.md +66 -9
- package/skills/route/SKILL.md +57 -4
- package/skills/router-setup/SKILL.md +3 -3
- package/skills/server-actions/SKILL.md +751 -0
- package/skills/streams-and-websockets/SKILL.md +283 -0
- package/skills/testing/SKILL.md +647 -0
- package/skills/typesafety/SKILL.md +319 -27
- 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/app-shell.ts +52 -0
- package/src/browser/event-controller.ts +86 -70
- package/src/browser/history-state.ts +21 -0
- package/src/browser/index.ts +3 -3
- package/src/browser/navigation-bridge.ts +84 -11
- package/src/browser/navigation-client.ts +76 -28
- package/src/browser/navigation-store.ts +32 -9
- package/src/browser/navigation-transaction.ts +10 -28
- package/src/browser/partial-update.ts +64 -26
- package/src/browser/prefetch/cache.ts +129 -21
- package/src/browser/prefetch/fetch.ts +148 -16
- package/src/browser/prefetch/queue.ts +36 -5
- package/src/browser/rango-state.ts +53 -13
- package/src/browser/react/Link.tsx +30 -2
- package/src/browser/react/NavigationProvider.tsx +72 -31
- package/src/browser/react/filter-segment-order.ts +51 -7
- 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-navigation.ts +22 -2
- package/src/browser/react/use-params.ts +20 -8
- package/src/browser/react/use-reverse.ts +106 -0
- package/src/browser/react/use-router.ts +22 -2
- package/src/browser/react/use-segments.ts +11 -8
- package/src/browser/response-adapter.ts +25 -0
- package/src/browser/rsc-router.tsx +64 -22
- package/src/browser/scroll-restoration.ts +22 -14
- package/src/browser/segment-reconciler.ts +36 -14
- package/src/browser/segment-structure-assert.ts +2 -2
- package/src/browser/server-action-bridge.ts +23 -30
- package/src/browser/types.ts +21 -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-trie.ts +52 -25
- 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 +54 -13
- package/src/client.rsc.tsx +3 -0
- package/src/client.tsx +92 -182
- 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 +9 -4
- package/src/index.ts +53 -15
- 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/outlet-context.ts +1 -1
- package/src/prerender.ts +4 -4
- package/src/response-utils.ts +37 -0
- package/src/reverse.ts +65 -36
- package/src/route-content-wrapper.tsx +6 -28
- package/src/route-definition/dsl-helpers.ts +384 -257
- package/src/route-definition/helper-factories.ts +29 -139
- package/src/route-definition/helpers-types.ts +100 -28
- package/src/route-definition/resolve-handler-use.ts +6 -0
- package/src/route-definition/use-item-types.ts +32 -0
- package/src/route-types.ts +26 -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 +21 -38
- package/src/router/intercept-resolution.ts +4 -18
- package/src/router/lazy-includes.ts +8 -8
- package/src/router/loader-resolution.ts +19 -2
- package/src/router/manifest.ts +22 -13
- package/src/router/match-api.ts +4 -3
- package/src/router/match-handlers.ts +63 -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 +53 -32
- package/src/router/metrics.ts +1 -1
- package/src/router/middleware-types.ts +15 -26
- package/src/router/middleware.ts +99 -84
- package/src/router/pattern-matching.ts +101 -17
- 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 +58 -2
- 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 +27 -6
- package/src/router/segment-resolution/revalidation.ts +147 -106
- 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/trie-matching.ts +18 -13
- package/src/router/types.ts +8 -0
- package/src/router/url-params.ts +49 -0
- package/src/router.ts +38 -23
- package/src/rsc/handler-context.ts +2 -2
- package/src/rsc/handler.ts +28 -69
- package/src/rsc/helpers.ts +91 -43
- package/src/rsc/index.ts +1 -1
- package/src/rsc/origin-guard.ts +28 -10
- package/src/rsc/progressive-enhancement.ts +4 -0
- package/src/rsc/response-route-handler.ts +46 -53
- package/src/rsc/rsc-rendering.ts +35 -51
- package/src/rsc/runtime-warnings.ts +9 -10
- package/src/rsc/server-action.ts +17 -37
- package/src/rsc/ssr-setup.ts +16 -0
- package/src/rsc/types.ts +8 -2
- package/src/search-params.ts +4 -4
- package/src/segment-content-promise.ts +67 -0
- package/src/segment-loader-promise.ts +122 -0
- package/src/segment-system.tsx +132 -116
- package/src/serialize.ts +243 -0
- package/src/server/context.ts +143 -53
- package/src/server/cookie-store.ts +28 -4
- package/src/server/request-context.ts +20 -42
- package/src/ssr/index.tsx +5 -1
- 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 +68 -50
- package/src/types/index.ts +1 -0
- package/src/types/loader-types.ts +5 -6
- package/src/types/request-scope.ts +126 -0
- package/src/types/route-entry.ts +11 -0
- package/src/types/segments.ts +35 -2
- package/src/urls/include-helper.ts +34 -67
- package/src/urls/index.ts +0 -3
- package/src/urls/path-helper-types.ts +41 -7
- package/src/urls/path-helper.ts +17 -52
- package/src/urls/pattern-types.ts +36 -19
- package/src/urls/response-types.ts +22 -29
- 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 +185 -0
- package/src/vite/discovery/bundle-postprocess.ts +6 -6
- package/src/vite/discovery/discover-routers.ts +101 -51
- package/src/vite/discovery/discovery-errors.ts +194 -0
- package/src/vite/discovery/gate-state.ts +171 -0
- package/src/vite/discovery/prerender-collection.ts +67 -26
- package/src/vite/discovery/route-types-writer.ts +40 -84
- package/src/vite/discovery/self-gen-tracking.ts +27 -1
- 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 +8 -7
- package/src/vite/plugins/client-ref-dedup.ts +16 -0
- package/src/vite/plugins/client-ref-hashing.ts +28 -5
- package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
- package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
- package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
- package/src/vite/plugins/expose-action-id.ts +54 -30
- 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-ids/router-transform.ts +20 -3
- package/src/vite/plugins/expose-internal-ids.ts +496 -486
- package/src/vite/plugins/performance-tracks.ts +29 -25
- package/src/vite/plugins/use-cache-transform.ts +65 -50
- package/src/vite/plugins/version-injector.ts +39 -23
- package/src/vite/plugins/version-plugin.ts +59 -2
- package/src/vite/plugins/virtual-entries.ts +2 -2
- package/src/vite/rango.ts +116 -29
- package/src/vite/router-discovery.ts +750 -100
- package/src/vite/utils/ast-handler-extract.ts +15 -15
- package/src/vite/utils/banner.ts +1 -1
- 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/package-resolution.ts +41 -1
- package/src/vite/utils/prerender-utils.ts +21 -6
- package/src/vite/utils/shared-utils.ts +107 -26
- package/src/browser/action-response-classifier.ts +0 -99
|
@@ -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
|
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: handler-use
|
|
3
|
+
description: Attach default loaders, middleware, parallels, and other use items directly to handlers via handler.use, and compose them with explicit use() at mount sites
|
|
4
|
+
argument-hint: "[handler]"
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Handler-Attached `.use`
|
|
8
|
+
|
|
9
|
+
A handler function (or branded `Static`/`Prerender`/`Passthrough` definition) can carry its own defaults via a `.use` callback that returns an array of `use` items (loader, middleware, parallel, intercept, layout, loading, etc.). The mount-site DSL (`path()`, `layout()`, `parallel()`, `intercept()`) merges those defaults with any explicit `use()` callback supplied at the registration site.
|
|
10
|
+
|
|
11
|
+
This lets handlers be **self-contained, reusable units** — a page brings its own loader, a layout brings its own middleware, a parallel slot brings its own data + skeleton — without forcing every caller to wire the same items at every mount site.
|
|
12
|
+
|
|
13
|
+
Canonical implementation reference:
|
|
14
|
+
[src/route-definition/resolve-handler-use.ts](../../src/route-definition/resolve-handler-use.ts)
|
|
15
|
+
|
|
16
|
+
## Defining a handler with `.use`
|
|
17
|
+
|
|
18
|
+
Attach `.use` to the function (or to the branded definition for `Static()`/`Prerender()`/`Passthrough()`):
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import {
|
|
22
|
+
loader,
|
|
23
|
+
middleware,
|
|
24
|
+
loading,
|
|
25
|
+
createLoader,
|
|
26
|
+
type Handler,
|
|
27
|
+
} from "@rangojs/router";
|
|
28
|
+
|
|
29
|
+
export const ProductLoader = createLoader(async (ctx) =>
|
|
30
|
+
fetchProduct(ctx.params.slug),
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
const ProductPage: Handler<"/product/:slug"> = async (ctx) => {
|
|
34
|
+
const product = await ctx.use(ProductLoader);
|
|
35
|
+
return <ProductView product={product} />;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
ProductPage.use = () => [
|
|
39
|
+
loader(ProductLoader),
|
|
40
|
+
loading(<ProductSkeleton />),
|
|
41
|
+
middleware(async (ctx, next) => {
|
|
42
|
+
await next();
|
|
43
|
+
ctx.header("Cache-Control", "private, max-age=60");
|
|
44
|
+
}),
|
|
45
|
+
];
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Now `ProductPage` carries its loader, loading state, and response-header middleware regardless of where it is mounted.
|
|
49
|
+
|
|
50
|
+
## Allowed items per mount site
|
|
51
|
+
|
|
52
|
+
`handler.use()` is the same callback shape regardless of where the handler runs, but the runtime validates that the items it returns are valid for the mount site. Driven by `MOUNT_SITE_ALLOWED_TYPES` in [resolve-handler-use.ts](../../src/route-definition/resolve-handler-use.ts):
|
|
53
|
+
|
|
54
|
+
| Mount site | Allowed item types |
|
|
55
|
+
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
56
|
+
| `path()` / `route()` | `layout`, `parallel`, `intercept`, `middleware`, `revalidate`, `loader`, `loading`, `errorBoundary`, `notFoundBoundary`, `cache`, `transition` |
|
|
57
|
+
| `layout()` | All of the above, plus `route`, `include` |
|
|
58
|
+
| `parallel()` (per slot) | `revalidate`, `loader`, `loading`, `errorBoundary`, `notFoundBoundary`, `transition` |
|
|
59
|
+
| `intercept()` | `middleware`, `revalidate`, `loader`, `loading`, `errorBoundary`, `notFoundBoundary`, `layout`, `route`, `when`, `transition` |
|
|
60
|
+
| Response routes (`path.json()`, `path.text()`, …) | `middleware`, `cache` |
|
|
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
|
+
|
|
64
|
+
If `handler.use()` returns a disallowed item for a mount site, registration throws:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
handler.use() returned middleware() which is not valid inside parallel().
|
|
68
|
+
Allowed types: revalidate, loader, loading, errorBoundary, notFoundBoundary, transition.
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The narrowest contract is `parallel()` — slots cannot bring their own middleware or layout; only data, loading, error/notFound boundaries, revalidation, and transitions.
|
|
72
|
+
|
|
73
|
+
## Composition with explicit `use()`
|
|
74
|
+
|
|
75
|
+
Every mount site that takes a `use` callback merges in this order:
|
|
76
|
+
|
|
77
|
+
1. **`handler.use()` items first** — the handler's defaults.
|
|
78
|
+
2. **Explicit `use()` items second** — overrides specified at the mount site.
|
|
79
|
+
|
|
80
|
+
Items of the same kind from the explicit `use()` follow the existing override rules of that item type. The most important ones for composition:
|
|
81
|
+
|
|
82
|
+
- **`loading()`** — last definition wins, so explicit `loading()` replaces the handler's default.
|
|
83
|
+
- **`parallel({ "@slot": … })`** — the last `parallel()` call wins per slot name. Other slots from earlier calls are preserved (see `skills/parallel`).
|
|
84
|
+
- **`loader()`, `middleware()`, etc.** — accumulate; both the handler's and the explicit ones run.
|
|
85
|
+
|
|
86
|
+
Skip the boilerplate: if neither `handler.use` nor explicit `use()` is provided, no merge happens.
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
// Handler brings a loader + a (placeholder) loading; explicit use replaces loading.
|
|
90
|
+
const SidebarSlot: Handler = async (ctx) => {
|
|
91
|
+
const data = await ctx.use(SidebarLoader);
|
|
92
|
+
return <Sidebar data={data} />;
|
|
93
|
+
};
|
|
94
|
+
SidebarSlot.use = () => [
|
|
95
|
+
loader(SidebarLoader),
|
|
96
|
+
loading(<DefaultSidebarSkeleton />),
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
parallel({ "@sidebar": SidebarSlot }, () => [
|
|
100
|
+
// Replaces the default skeleton; SidebarLoader from handler.use still runs.
|
|
101
|
+
loading(<SiteSpecificSidebarSkeleton />),
|
|
102
|
+
]);
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Composable parallel slots (the main pay-off)
|
|
106
|
+
|
|
107
|
+
The parallel slot site is where `handler.use` shines. A slot handler that owns its data/loading lets a layout declare **just** the slot names — every loader, skeleton, and revalidation contract travels with the slot itself.
|
|
108
|
+
|
|
109
|
+
### Without `handler.use` (every caller wires it up)
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
layout(<DashboardLayout />, () => [
|
|
113
|
+
parallel({ "@cart": CartSummary }, () => [
|
|
114
|
+
loader(CartLoader),
|
|
115
|
+
loading(<CartSkeleton />),
|
|
116
|
+
revalidate(revalidateCartData),
|
|
117
|
+
]),
|
|
118
|
+
parallel({ "@notifs": NotificationPanel }, () => [
|
|
119
|
+
loader(NotificationsLoader),
|
|
120
|
+
loading(<NotifsSkeleton />),
|
|
121
|
+
revalidate(revalidateNotifs),
|
|
122
|
+
]),
|
|
123
|
+
path("/dashboard", DashboardIndex, { name: "dashboard.index" }),
|
|
124
|
+
]);
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Every layout that wants `@cart` must repeat the same loader/loading/revalidate triplet.
|
|
128
|
+
|
|
129
|
+
### With `handler.use` (slot owns its dependencies)
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
const CartSummary: Handler = async (ctx) => {
|
|
133
|
+
const cart = await ctx.use(CartLoader);
|
|
134
|
+
return <CartSummaryView cart={cart} />;
|
|
135
|
+
};
|
|
136
|
+
CartSummary.use = () => [
|
|
137
|
+
loader(CartLoader),
|
|
138
|
+
loading(<CartSkeleton />),
|
|
139
|
+
revalidate(revalidateCartData),
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
const NotificationPanel: Handler = async (ctx) => {
|
|
143
|
+
const items = await ctx.use(NotificationsLoader);
|
|
144
|
+
return <NotificationsView items={items} />;
|
|
145
|
+
};
|
|
146
|
+
NotificationPanel.use = () => [
|
|
147
|
+
loader(NotificationsLoader),
|
|
148
|
+
loading(<NotifsSkeleton />),
|
|
149
|
+
revalidate(revalidateNotifs),
|
|
150
|
+
];
|
|
151
|
+
|
|
152
|
+
// Mount sites become declarative — no per-call data wiring.
|
|
153
|
+
layout(<DashboardLayout />, () => [
|
|
154
|
+
parallel({ "@cart": CartSummary, "@notifs": NotificationPanel }),
|
|
155
|
+
path("/dashboard", DashboardIndex, { name: "dashboard.index" }),
|
|
156
|
+
]);
|
|
157
|
+
|
|
158
|
+
layout(<AccountLayout />, () => [
|
|
159
|
+
// Same slot, same defaults, zero re-wiring.
|
|
160
|
+
parallel({ "@cart": CartSummary }),
|
|
161
|
+
path("/account", AccountIndex, { name: "account.index" }),
|
|
162
|
+
]);
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Each slot handler is now a portable, self-contained unit. Different layouts can use the same slot without copying data plumbing.
|
|
166
|
+
|
|
167
|
+
### Streaming behavior is per-slot
|
|
168
|
+
|
|
169
|
+
A slot's `loading()` (whether from `handler.use` or explicit) makes that slot an independent streaming unit — its loader does not block the parent layout. Two slot handlers with their own loading skeletons stream independently.
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
parallel({
|
|
173
|
+
"@cart": CartSummary, // handler.use loading() → streams independently
|
|
174
|
+
"@cartBadge": CartBadge, // no loading() anywhere → awaited before paint
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Two scopes for explicit `use` at the mount site: shared (broadcast) and slot-local
|
|
179
|
+
|
|
180
|
+
`parallel()` accepts an explicit `use()` callback that **broadcasts** to every slot in the call ([dsl-helpers.ts](../../src/route-definition/dsl-helpers.ts)). That's the right behavior for the items the parallel allow-list permits and that accumulate (`loader`, `revalidate`, `errorBoundary`, `notFoundBoundary`, `transition`) — every slot gets them. (Note: `middleware` is not allowed inside `parallel()`; see the allowed-types table above.)
|
|
181
|
+
|
|
182
|
+
For single-assignment items like `loading()`, broadcasting overwrites every slot's `handler.use` default. Pass a **slot descriptor** `{ handler, use }` instead: items in the descriptor's `use` apply only to that slot.
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
parallel({
|
|
186
|
+
"@meta": MetaSlot,
|
|
187
|
+
"@sidebar": {
|
|
188
|
+
handler: SidebarSlot,
|
|
189
|
+
use: () => [loading(<SidebarSkeleton />)], // ← only @sidebar
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Per-slot merge order is **handler.use → shared use → slot-local use** (narrowest scope wins for last-write-wins items like `loading()`):
|
|
195
|
+
|
|
196
|
+
```typescript
|
|
197
|
+
parallel(
|
|
198
|
+
{
|
|
199
|
+
"@cart": {
|
|
200
|
+
handler: Cart,
|
|
201
|
+
use: () => [loading(<CartSkeleton />)], // wins for @cart
|
|
202
|
+
},
|
|
203
|
+
"@notifs": Notifs, // gets <BroadcastSkeleton />
|
|
204
|
+
},
|
|
205
|
+
() => [
|
|
206
|
+
loader(SharedAnalyticsLoader), // accumulates on every slot
|
|
207
|
+
loading(<BroadcastSkeleton />), // applies to slots without slot-local
|
|
208
|
+
],
|
|
209
|
+
);
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Use the descriptor's `use` for `loading(false)` too — opting one slot out of streaming without affecting siblings:
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
parallel(
|
|
216
|
+
{
|
|
217
|
+
"@cart": { handler: Cart, use: () => [loading(false)] }, // @cart awaits
|
|
218
|
+
"@notifs": Notifs, // @notifs still streams with broadcast skeleton
|
|
219
|
+
},
|
|
220
|
+
() => [loading(<BroadcastSkeleton />)],
|
|
221
|
+
);
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Rule of thumb: shared `use` is for items that legitimately apply to every slot. Slot-local `use` is for per-slot precision — especially `loading()` and `loading(false)`.
|
|
225
|
+
|
|
226
|
+
### Replacing a whole slot from a parent's `handler.use`
|
|
227
|
+
|
|
228
|
+
A handler can publish a default `parallel({...})` set via its `.use`, and the mount site can replace any individual slot by re-declaring it. Last `parallel()` per slot name wins (see `skills/parallel` § Slot Override Semantics).
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
const ProductPage: Handler<"/product/:slug"> = (ctx) => (
|
|
232
|
+
<article>
|
|
233
|
+
<ProductHero slug={ctx.params.slug} />
|
|
234
|
+
<ParallelOutlet name="@related" />
|
|
235
|
+
<ParallelOutlet name="@reviews" />
|
|
236
|
+
</article>
|
|
237
|
+
);
|
|
238
|
+
ProductPage.use = () => [
|
|
239
|
+
parallel({
|
|
240
|
+
"@related": DefaultRelatedProducts,
|
|
241
|
+
"@reviews": DefaultReviews,
|
|
242
|
+
}),
|
|
243
|
+
];
|
|
244
|
+
|
|
245
|
+
path("/product/:slug", ProductPage, { name: "product" }, () => [
|
|
246
|
+
// Override @related only; @reviews keeps the default from handler.use.
|
|
247
|
+
parallel({ "@related": SiteSpecificRelated }),
|
|
248
|
+
]);
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Other mount sites
|
|
252
|
+
|
|
253
|
+
### Pages (`path()`)
|
|
254
|
+
|
|
255
|
+
Page handlers can carry middleware, loaders, error boundaries, parallel slots, etc. — anything from the `path` row of the table above.
|
|
256
|
+
|
|
257
|
+
```typescript
|
|
258
|
+
const CheckoutPage: Handler<"/checkout"> = async (ctx) => { /* … */ };
|
|
259
|
+
CheckoutPage.use = () => [
|
|
260
|
+
middleware(requireAuth),
|
|
261
|
+
loader(CartLoader),
|
|
262
|
+
errorBoundary(<CheckoutError />),
|
|
263
|
+
notFoundBoundary(<CheckoutNotFound />),
|
|
264
|
+
];
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Layouts (`layout()`)
|
|
268
|
+
|
|
269
|
+
Layout handlers can carry middleware that runs for every child route, plus default parallels, includes, etc.
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
const AdminLayout: Handler = (ctx) => {
|
|
273
|
+
const user = ctx.get(CurrentUser);
|
|
274
|
+
return <Admin user={user} />;
|
|
275
|
+
};
|
|
276
|
+
AdminLayout.use = () => [
|
|
277
|
+
middleware(requireAdmin),
|
|
278
|
+
parallel({ "@adminNotifs": AdminNotifsSlot }),
|
|
279
|
+
];
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Intercepts (`intercept()`)
|
|
283
|
+
|
|
284
|
+
Intercept handlers can carry their own middleware chain, loaders, and even nested layouts/routes for the modal shell.
|
|
285
|
+
|
|
286
|
+
```typescript
|
|
287
|
+
const QuickViewModal: Handler = async (ctx) => {
|
|
288
|
+
const product = await ctx.use(ProductLoader);
|
|
289
|
+
return <QuickView product={product} />;
|
|
290
|
+
};
|
|
291
|
+
QuickViewModal.use = () => [
|
|
292
|
+
loader(ProductLoader),
|
|
293
|
+
loading(<QuickViewSkeleton />),
|
|
294
|
+
layout(<ModalChrome />),
|
|
295
|
+
];
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
## `loading()` is a single-assignment item — scope it correctly
|
|
299
|
+
|
|
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)).
|
|
301
|
+
|
|
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.
|
|
303
|
+
|
|
304
|
+
For parallel slots, the shared `parallel(..., () => [...])` callback is **broadcast** to every slot in the call. A single `loading()` placed there lands on every slot, overwriting each slot's `handler.use` default. To scope `loading()` to one slot, use the **slot descriptor** form:
|
|
305
|
+
|
|
306
|
+
```typescript
|
|
307
|
+
const Cart: Handler = async (ctx) => { /* … */ };
|
|
308
|
+
Cart.use = () => [loader(CartLoader), loading(<CartSkeleton />)];
|
|
309
|
+
|
|
310
|
+
const Notifs: Handler = async (ctx) => { /* … */ };
|
|
311
|
+
Notifs.use = () => [loader(NotifsLoader), loading(<NotifsSkeleton />)];
|
|
312
|
+
|
|
313
|
+
// ✅ @cart gets a custom skeleton; @notifs keeps its handler.use default.
|
|
314
|
+
parallel({
|
|
315
|
+
"@cart": {
|
|
316
|
+
handler: Cart,
|
|
317
|
+
use: () => [loading(<CustomCartSkeleton />)],
|
|
318
|
+
},
|
|
319
|
+
"@notifs": Notifs,
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
// ✅ Opt one slot out of streaming while siblings still stream the broadcast.
|
|
323
|
+
parallel(
|
|
324
|
+
{
|
|
325
|
+
"@cart": { handler: Cart, use: () => [loading(false)] },
|
|
326
|
+
"@notifs": Notifs,
|
|
327
|
+
},
|
|
328
|
+
() => [loading(<BroadcastSkeleton />)],
|
|
329
|
+
);
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Per-slot merge order is **handler.use → shared use → slot-local use**. Slot-local is the narrowest scope, so it wins for last-write-wins items like `loading()`. Items that accumulate within the parallel allow-list (`loader`, `revalidate`, `errorBoundary`, `notFoundBoundary`, `transition`) compose across all three layers regardless.
|
|
333
|
+
|
|
334
|
+
Other things to keep in mind about `loading()`:
|
|
335
|
+
|
|
336
|
+
- Any `loading()` (regardless of source) makes the segment a streaming unit. A handler that includes `loading()` in its `.use` opts every mount site into streaming by default. To opt back out, pass `loading(false)` at the mount site (`loading: false` handling in [match-middleware/segment-resolution.ts](../../src/router/match-middleware/segment-resolution.ts)) — use the slot descriptor form for parallel slots so the opt-out doesn't broadcast.
|
|
337
|
+
|
|
338
|
+
Rule of thumb: only put `loading()` in `handler.use` if you genuinely want every mount site to stream by default. Use the slot descriptor's `use` for any per-slot intent at a `parallel()` call.
|
|
339
|
+
|
|
340
|
+
## Edge cases & gotchas
|
|
341
|
+
|
|
342
|
+
- **ReactNode handlers cannot have `.use`.** A bare JSX element passed as a handler (e.g., `path("/about", <About />)`) has no function to attach properties to. Pass a function or branded definition instead.
|
|
343
|
+
- **Branded handlers** — `Static()`, `Prerender()`, and `Passthrough()` are positional constructors (not object-arg). Construct first, then attach `.use` to the returned definition:
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
const ProductPage = Prerender(async (ctx) => {
|
|
347
|
+
const product = await fetchProduct(ctx.params.slug);
|
|
348
|
+
return <ProductView product={product} />;
|
|
349
|
+
});
|
|
350
|
+
ProductPage.use = () => [loader(ProductLoader)];
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
- **Items can be flat or nested arrays.** `handler.use()` results are flattened with `.flat(3)` before validation, so factory helpers that return arrays inline work the same as in regular `use()` callbacks.
|
|
354
|
+
- **Validation runs at registration / first match**, not at handler definition. A handler doesn't know its mount site at definition time — the same handler used in a `path()` and an `intercept()` is validated against each mount's allowed-types set when registered.
|
|
355
|
+
- **No silent shadowing.** If a disallowed item slips through (e.g., a layout factory returning `cache()` from a slot's `handler.use`), the runtime throws with the offending type and mount site named.
|
|
356
|
+
|
|
357
|
+
## Cross-references
|
|
358
|
+
|
|
359
|
+
- `skills/route` — `path()` mount site basics
|
|
360
|
+
- `skills/layout` — `layout()` mount site basics
|
|
361
|
+
- `skills/parallel` — parallel slot semantics, slot override rules, streaming behavior
|
|
362
|
+
- `skills/intercept` — intercept mount site basics
|
|
363
|
+
- `skills/loader` — defining `createLoader` and reading via `ctx.use()`
|
|
364
|
+
- `skills/middleware` — middleware semantics and ordering
|