@rangojs/router 0.0.0-experimental.fa8a383a → 0.0.0-experimental.fad716ff

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.
Files changed (118) hide show
  1. package/README.md +76 -18
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +526 -168
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/package.json +2 -2
  6. package/skills/cache-guide/SKILL.md +32 -0
  7. package/skills/caching/SKILL.md +8 -0
  8. package/skills/links/SKILL.md +3 -1
  9. package/skills/loader/SKILL.md +53 -43
  10. package/skills/middleware/SKILL.md +2 -0
  11. package/skills/parallel/SKILL.md +67 -0
  12. package/skills/prerender/SKILL.md +110 -68
  13. package/skills/route/SKILL.md +31 -0
  14. package/skills/router-setup/SKILL.md +87 -2
  15. package/skills/typesafety/SKILL.md +10 -0
  16. package/src/__internal.ts +1 -1
  17. package/src/browser/app-version.ts +14 -0
  18. package/src/browser/navigation-bridge.ts +16 -3
  19. package/src/browser/navigation-client.ts +64 -40
  20. package/src/browser/navigation-store.ts +43 -8
  21. package/src/browser/partial-update.ts +37 -4
  22. package/src/browser/prefetch/fetch.ts +8 -2
  23. package/src/browser/prefetch/queue.ts +61 -29
  24. package/src/browser/prefetch/resource-ready.ts +77 -0
  25. package/src/browser/react/Link.tsx +44 -8
  26. package/src/browser/react/NavigationProvider.tsx +13 -4
  27. package/src/browser/react/context.ts +7 -2
  28. package/src/browser/react/use-handle.ts +9 -58
  29. package/src/browser/react/use-router.ts +21 -8
  30. package/src/browser/rsc-router.tsx +26 -3
  31. package/src/browser/scroll-restoration.ts +10 -8
  32. package/src/browser/server-action-bridge.ts +8 -6
  33. package/src/browser/types.ts +27 -5
  34. package/src/build/generate-manifest.ts +6 -6
  35. package/src/build/generate-route-types.ts +3 -0
  36. package/src/build/route-types/include-resolution.ts +8 -1
  37. package/src/build/route-types/router-processing.ts +211 -72
  38. package/src/build/route-types/scan-filter.ts +8 -1
  39. package/src/cache/cache-runtime.ts +15 -11
  40. package/src/cache/cache-scope.ts +46 -5
  41. package/src/cache/taint.ts +55 -0
  42. package/src/client.tsx +2 -56
  43. package/src/context-var.ts +72 -2
  44. package/src/handle.ts +40 -0
  45. package/src/index.rsc.ts +3 -1
  46. package/src/index.ts +12 -0
  47. package/src/prerender/store.ts +5 -4
  48. package/src/prerender.ts +138 -77
  49. package/src/reverse.ts +22 -1
  50. package/src/route-definition/dsl-helpers.ts +42 -19
  51. package/src/route-definition/helpers-types.ts +10 -6
  52. package/src/route-definition/index.ts +3 -0
  53. package/src/route-definition/redirect.ts +9 -1
  54. package/src/route-definition/resolve-handler-use.ts +149 -0
  55. package/src/route-types.ts +11 -0
  56. package/src/router/content-negotiation.ts +100 -1
  57. package/src/router/handler-context.ts +79 -23
  58. package/src/router/intercept-resolution.ts +9 -4
  59. package/src/router/loader-resolution.ts +156 -21
  60. package/src/router/match-api.ts +124 -189
  61. package/src/router/match-middleware/background-revalidation.ts +12 -1
  62. package/src/router/match-middleware/cache-lookup.ts +72 -13
  63. package/src/router/match-middleware/cache-store.ts +21 -4
  64. package/src/router/match-middleware/segment-resolution.ts +53 -0
  65. package/src/router/match-result.ts +11 -5
  66. package/src/router/metrics.ts +6 -1
  67. package/src/router/middleware-types.ts +6 -8
  68. package/src/router/middleware.ts +2 -5
  69. package/src/router/navigation-snapshot.ts +182 -0
  70. package/src/router/prerender-match.ts +110 -10
  71. package/src/router/preview-match.ts +30 -102
  72. package/src/router/request-classification.ts +310 -0
  73. package/src/router/route-snapshot.ts +245 -0
  74. package/src/router/router-context.ts +1 -0
  75. package/src/router/router-interfaces.ts +36 -4
  76. package/src/router/router-options.ts +37 -11
  77. package/src/router/segment-resolution/fresh.ts +101 -18
  78. package/src/router/segment-resolution/helpers.ts +29 -24
  79. package/src/router/segment-resolution/revalidation.ts +122 -26
  80. package/src/router/types.ts +1 -0
  81. package/src/router.ts +54 -5
  82. package/src/rsc/handler.ts +464 -377
  83. package/src/rsc/loader-fetch.ts +23 -3
  84. package/src/rsc/manifest-init.ts +5 -1
  85. package/src/rsc/progressive-enhancement.ts +14 -2
  86. package/src/rsc/rsc-rendering.ts +10 -1
  87. package/src/rsc/server-action.ts +8 -0
  88. package/src/rsc/ssr-setup.ts +2 -2
  89. package/src/rsc/types.ts +9 -1
  90. package/src/server/context.ts +50 -1
  91. package/src/server/handle-store.ts +19 -0
  92. package/src/server/loader-registry.ts +9 -8
  93. package/src/server/request-context.ts +175 -15
  94. package/src/ssr/index.tsx +3 -0
  95. package/src/static-handler.ts +18 -6
  96. package/src/types/cache-types.ts +4 -4
  97. package/src/types/handler-context.ts +137 -33
  98. package/src/types/loader-types.ts +36 -9
  99. package/src/types/route-entry.ts +1 -1
  100. package/src/urls/path-helper-types.ts +9 -2
  101. package/src/urls/path-helper.ts +47 -12
  102. package/src/urls/pattern-types.ts +12 -0
  103. package/src/urls/response-types.ts +16 -6
  104. package/src/use-loader.tsx +73 -4
  105. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  106. package/src/vite/discovery/discover-routers.ts +5 -1
  107. package/src/vite/discovery/prerender-collection.ts +14 -1
  108. package/src/vite/discovery/state.ts +13 -4
  109. package/src/vite/index.ts +4 -0
  110. package/src/vite/plugin-types.ts +60 -5
  111. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  112. package/src/vite/plugins/expose-internal-ids.ts +118 -39
  113. package/src/vite/plugins/performance-tracks.ts +88 -0
  114. package/src/vite/plugins/refresh-cmd.ts +88 -26
  115. package/src/vite/rango.ts +19 -2
  116. package/src/vite/router-discovery.ts +178 -37
  117. package/src/vite/utils/prerender-utils.ts +18 -0
  118. package/src/vite/utils/shared-utils.ts +3 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangojs/router",
3
- "version": "0.0.0-experimental.fa8a383a",
3
+ "version": "0.0.0-experimental.fad716ff",
4
4
  "description": "Django-inspired RSC router with composable URL patterns",
5
5
  "keywords": [
6
6
  "react",
@@ -142,7 +142,7 @@
142
142
  "test:unit:watch": "vitest"
143
143
  },
144
144
  "dependencies": {
145
- "@vitejs/plugin-rsc": "^0.5.14",
145
+ "@vitejs/plugin-rsc": "^0.5.19",
146
146
  "magic-string": "^0.30.17",
147
147
  "picomatch": "^4.0.3",
148
148
  "rsc-html-stream": "^0.0.7"
@@ -162,6 +162,38 @@ middleware(async (ctx, next) => {
162
162
  });
163
163
  ```
164
164
 
165
+ ## Context Variable Cache Safety
166
+
167
+ Context variables created with `createVar()` are cacheable by default and can
168
+ be read freely inside `cache()` and `"use cache"` scopes. Non-cacheable vars
169
+ throw at read time to prevent request-specific data from being captured.
170
+
171
+ There are two ways to mark a value as non-cacheable:
172
+
173
+ ```typescript
174
+ // Var-level policy — inherently request-specific data
175
+ const Session = createVar<SessionData>({ cache: false });
176
+
177
+ // Write-level escalation — this specific write is non-cacheable
178
+ ctx.set(Theme, derivedTheme, { cache: false });
179
+ ```
180
+
181
+ "Least cacheable wins": if either the var definition or the `ctx.set()` call
182
+ specifies `cache: false`, the value is non-cacheable.
183
+
184
+ **Behavior inside cache scopes:**
185
+
186
+ | Operation | Inside `cache()` / `"use cache"` |
187
+ | ----------------------------------- | -------------------------------- |
188
+ | `ctx.get(cacheableVar)` | Allowed |
189
+ | `ctx.get(nonCacheableVar)` | Throws |
190
+ | `ctx.set(var, value)` (cacheable) | Allowed |
191
+ | `ctx.header()`, `ctx.cookie()`, etc | Throws (response side effects) |
192
+
193
+ Write is dumb — `ctx.set()` stores the cache metadata but does not enforce.
194
+ Enforcement happens at read time (`ctx.get()`), where ALS detects the cache
195
+ scope and rejects non-cacheable reads.
196
+
165
197
  ## Loaders Are Always Fresh
166
198
 
167
199
  Loaders are **never cached** by route-level `cache()`. Even on a full cache hit
@@ -173,6 +173,14 @@ const router = createRouter<AppBindings>({
173
173
  KV entries require `expirationTtl >= 60s`. Short-lived entries (< 60s total TTL)
174
174
  are only cached in L1.
175
175
 
176
+ ## Context Variables Inside Cache Boundaries
177
+
178
+ Context variables (`createVar`) are cacheable by default and can be read and
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.
183
+
176
184
  ## Nested Cache Boundaries
177
185
 
178
186
  Override cache settings for specific sections:
@@ -139,7 +139,9 @@ function GlobalNav() {
139
139
  }
140
140
  ```
141
141
 
142
- `href()` is an identity function at runtime but provides compile-time validation via `ValidPaths` type. Paths are validated against registered route patterns using `PatternToPath`.
142
+ `href()` provides compile-time validation via `ValidPaths` type. Paths are validated against registered route patterns using `PatternToPath`.
143
+
144
+ `href()` is a raw path helper — it is **not** basename-aware. It returns the path as-is (or with the include mount prefix via `useHref()`). For basename-aware navigation, use `Link`, `useRouter().push()`, or `reverse()`, which auto-prefix root-relative paths with the router's basename.
143
145
 
144
146
  ## Client: useHref()
145
147
 
@@ -65,24 +65,10 @@ export const urlpatterns = urls(({ path, loader }) => [
65
65
 
66
66
  ## Consuming Loader Data
67
67
 
68
- Loaders are the **live data layer** they resolve fresh on every request.
69
- The way you consume them depends on whether you're in a server component
70
- (route handler) or a client component.
71
-
72
- > **IMPORTANT: Prefer consuming loaders in client components.** Keeping data
73
- > fetching in loaders and consumption in client components creates a clean
74
- > separation: the server-side handler renders static markup that can be
75
- > freely cached with `cache()`, while loader data stays fresh on every
76
- > request. When you consume loaders in server handlers via `ctx.use()`, the
77
- > handler output depends on the loader data, which means caching the handler
78
- > also caches the data — defeating the purpose of the live data layer.
79
-
80
- ### In Client Components (Preferred)
81
-
82
- Client components use `useLoader()` from `@rangojs/router/client`.
83
- The loader **must** be registered with `loader()` in the route's DSL
84
- segments so the framework knows to resolve it during SSR and stream
85
- the data to the client:
68
+ Register loaders with `loader()` in the DSL and consume them in client
69
+ components with `useLoader()`. This is the recommended pattern it keeps
70
+ data fetching on the server and consumption on the client, with a clean
71
+ separation that works correctly with `cache()`.
86
72
 
87
73
  ```typescript
88
74
  "use client";
@@ -96,40 +82,60 @@ function ProductDetails() {
96
82
  ```
97
83
 
98
84
  ```typescript
99
- // Route definition — loader() registration required for client consumption
85
+ // Route definition — loader() registration required
100
86
  path("/product/:slug", ProductPage, { name: "product" }, () => [
101
- loader(ProductLoader), // Required for useLoader() in client components
87
+ loader(ProductLoader),
102
88
  ]);
103
89
  ```
104
90
 
105
- ### In Route Handlers (Server Components)
91
+ DSL loaders are the **live data layer** — they resolve fresh on every
92
+ request, even when the route is inside a `cache()` boundary. The router
93
+ excludes them from the segment cache at storage time and re-resolves them
94
+ on retrieval. This means `cache()` gives you cached UI + fresh data by
95
+ default.
106
96
 
107
- In server components, use `ctx.use(Loader)` directly in the route handler.
108
- This doesn't require `loader()` registration in the DSL — it works
109
- standalone. **However**, prefer client-side consumption when possible (see
110
- note above).
97
+ ### Cache safety
111
98
 
112
- ```typescript
113
- import { ProductLoader } from "./loaders/product";
99
+ DSL loaders can safely read `createVar({ cache: false })` variables
100
+ because they are always resolved fresh. The read guard is bypassed for
101
+ loader functions — they never produce stale data.
102
+
103
+ ### ctx.use(Loader) — escape hatch
104
+
105
+ For cases where you need loader data in the server handler itself (e.g.,
106
+ to set ctx variables or make routing decisions), use `ctx.use(Loader)`:
114
107
 
115
- // Route handler — server component
108
+ ```typescript
116
109
  path("/product/:slug", async (ctx) => {
117
110
  const { product } = await ctx.use(ProductLoader);
118
- return <h1>{product.name}</h1>;
119
- }, { name: "product" })
111
+ ctx.set(Product, product); // make available to children
112
+ return <ProductPage />;
113
+ }, { name: "product" }, () => [
114
+ loader(ProductLoader), // still register for client consumption
115
+ ])
120
116
  ```
121
117
 
122
- When you do register with `loader()` in the DSL, `ctx.use()` returns the
118
+ When you register with `loader()` in the DSL, `ctx.use()` returns the
123
119
  same memoized result — loaders never run twice per request.
124
120
 
121
+ **Limitations of ctx.use(Loader):**
122
+
123
+ - The handler output depends on the loader data. If the route is inside
124
+ `cache()`, the handler is cached with the loader result baked in —
125
+ defeating the live data guarantee.
126
+ - Non-cacheable variable reads (`createVar({ cache: false })`) inside the
127
+ handler still throw, even if the data came from a loader.
128
+ - Prefer DSL `loader()` + client `useLoader()` for data that depends on
129
+ non-cacheable context variables.
130
+
125
131
  **Never use `useLoader()` in server components** — it is a client-only API.
126
132
 
127
133
  ### Summary
128
134
 
129
- | Context | API | `loader()` DSL required? |
130
- | ---------------------------- | ------------------- | ------------------------ |
131
- | Client component (preferred) | `useLoader(Loader)` | **Yes** |
132
- | Route handler (server) | `ctx.use(Loader)` | No |
135
+ | Pattern | API | Cache-safe | Recommended |
136
+ | ---------------------- | ------------------- | ---------- | ----------- |
137
+ | DSL + client component | `useLoader(Loader)` | Yes | Yes |
138
+ | Handler escape hatch | `ctx.use(Loader)` | No | When needed |
133
139
 
134
140
  ## Loader Context
135
141
 
@@ -548,7 +554,7 @@ export const ProductLoader = createLoader(async (ctx) => {
548
554
  .first();
549
555
 
550
556
  if (!product) {
551
- throw new Response("Product not found", { status: 404 });
557
+ notFound("Product not found");
552
558
  }
553
559
 
554
560
  return { product };
@@ -564,10 +570,9 @@ export const CartLoader = createLoader(async (ctx) => {
564
570
  return { cart };
565
571
  });
566
572
 
567
- // urls.tsx
573
+ // urls.tsx — register loaders in the DSL
568
574
  export const urlpatterns = urls(({ path, layout, loader, loading, cache, revalidate }) => [
569
575
  layout(<ShopLayout />, () => [
570
- // Shared cart loader for all shop routes
571
576
  loader(CartLoader, () => [
572
577
  revalidate(({ actionId }) => actionId?.includes("Cart") ?? false),
573
578
  ]),
@@ -579,17 +584,22 @@ export const urlpatterns = urls(({ path, layout, loader, loading, cache, revalid
579
584
  ]),
580
585
  ]);
581
586
 
582
- // pages/product.tsx — server component (route handler)
587
+ // components/ProductDetails.tsx — consume in client component
588
+ "use client";
589
+ import { useLoader } from "@rangojs/router/client";
583
590
  import { ProductLoader, CartLoader } from "./loaders/shop";
584
591
 
585
- async function ProductPage(ctx) {
586
- const { product } = await ctx.use(ProductLoader);
587
- const { cart } = await ctx.use(CartLoader);
592
+ function ProductDetails() {
593
+ const { data: { product } } = useLoader(ProductLoader);
594
+ const { data: { cart } } = useLoader(CartLoader);
588
595
 
589
596
  return (
590
597
  <div>
591
598
  <h1>{product.name}</h1>
592
- <AddToCartButton productId={product.id} inCart={cart?.items.includes(product.id)} />
599
+ <AddToCartButton
600
+ productId={product.id}
601
+ inCart={cart?.items.includes(product.id)}
602
+ />
593
603
  </div>
594
604
  );
595
605
  }
@@ -26,6 +26,8 @@ const router = createRouter<AppEnv>({})
26
26
  .routes(urlpatterns);
27
27
  ```
28
28
 
29
+ When the router has a `basename`, pattern-scoped `.use()` patterns are automatically prefixed. For example, with `basename: "/app"`, `.use("/admin/*", mw)` matches `/app/admin/*`.
30
+
29
31
  ### Route middleware (`middleware()` in `urls()`)
30
32
 
31
33
  Registered inside `urls()` callback. Wraps **rendering only** -- it does NOT wrap server action execution. Actions run before route middleware, so when route middleware executes during post-action revalidation, it can observe state that the action set (cookies, context variables, headers).
@@ -92,6 +92,73 @@ path("/dashboard/:id", (ctx) => {
92
92
  ])
93
93
  ```
94
94
 
95
+ ## Setting Handles (Meta, Breadcrumbs)
96
+
97
+ Parallel slot handlers can call `ctx.use(Meta)` or `ctx.use(Breadcrumbs)` to
98
+ push handle data. The data is associated with the **parent** layout or route
99
+ segment, not the parallel segment itself. This is because parallels execute
100
+ after their parent handler and inherit its segment scope.
101
+
102
+ This works well for document-level metadata — the handle data follows the
103
+ parent's lifecycle (appears when the parent is mounted, removed when it
104
+ unmounts).
105
+
106
+ ```typescript
107
+ parallel({
108
+ "@meta": (ctx) => {
109
+ const meta = ctx.use(Meta);
110
+ meta({ title: "Product Detail" });
111
+ meta({ name: "description", content: "..." });
112
+ return null; // UI-less slot, only sets metadata
113
+ },
114
+ "@sidebar": (ctx) => <Sidebar />,
115
+ })
116
+ ```
117
+
118
+ Multiple parallels on the same parent can each push handle data — they all
119
+ accumulate under the parent segment ID.
120
+
121
+ ### Pattern: `@meta` slot for per-route metadata overrides
122
+
123
+ A dedicated `@meta` parallel slot lets routes define metadata separately from
124
+ their handler logic. The layout sets defaults via a title template, and each
125
+ route overrides via its own `@meta` slot. Since child segments push after
126
+ parents and `collectMeta` uses last-wins deduplication, overrides work
127
+ naturally.
128
+
129
+ ```typescript
130
+ // Layout sets defaults
131
+ layout((ctx) => {
132
+ ctx.use(Meta)({ title: { template: "%s | Store", default: "Store" } });
133
+ return <StoreLayout />;
134
+ }, () => [
135
+ // Route with @meta override — decoupled from handler rendering
136
+ path("/:slug", ProductPage, { name: "product" }, () => [
137
+ parallel({
138
+ "@meta": async (ctx) => {
139
+ const product = await ctx.use(ProductLoader);
140
+ const meta = ctx.use(Meta);
141
+ meta({ title: product.name });
142
+ meta({ name: "description", content: product.description });
143
+ meta({
144
+ "script:ld+json": {
145
+ "@context": "https://schema.org",
146
+ "@type": "Product",
147
+ name: product.name,
148
+ description: product.description,
149
+ },
150
+ });
151
+ return null; // UI-less slot
152
+ },
153
+ }),
154
+ ]),
155
+ ])
156
+ ```
157
+
158
+ This keeps the route handler focused on rendering UI while metadata
159
+ (title, description, Open Graph, JSON-LD) lives in a composable slot that
160
+ can be added, removed, or swapped per route without touching the handler.
161
+
95
162
  ## Parallel Routes with Loaders
96
163
 
97
164
  Add loaders and loading states to parallel routes: