@rangojs/router 0.0.0-experimental.8678bb02 → 0.0.0-experimental.87

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 (147) hide show
  1. package/README.md +126 -38
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +847 -384
  4. package/dist/vite/index.js.bak +5448 -0
  5. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  6. package/package.json +5 -5
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/handler-use/SKILL.md +362 -0
  9. package/skills/hooks/SKILL.md +28 -20
  10. package/skills/intercept/SKILL.md +20 -0
  11. package/skills/layout/SKILL.md +22 -0
  12. package/skills/links/SKILL.md +91 -17
  13. package/skills/loader/SKILL.md +35 -2
  14. package/skills/middleware/SKILL.md +34 -3
  15. package/skills/migrate-nextjs/SKILL.md +560 -0
  16. package/skills/migrate-react-router/SKILL.md +765 -0
  17. package/skills/parallel/SKILL.md +59 -0
  18. package/skills/prerender/SKILL.md +110 -68
  19. package/skills/rango/SKILL.md +24 -22
  20. package/skills/response-routes/SKILL.md +8 -0
  21. package/skills/route/SKILL.md +24 -0
  22. package/skills/router-setup/SKILL.md +35 -0
  23. package/skills/streams-and-websockets/SKILL.md +283 -0
  24. package/skills/typesafety/SKILL.md +3 -1
  25. package/src/__internal.ts +1 -1
  26. package/src/browser/app-shell.ts +52 -0
  27. package/src/browser/app-version.ts +14 -0
  28. package/src/browser/navigation-bridge.ts +87 -6
  29. package/src/browser/navigation-client.ts +128 -77
  30. package/src/browser/navigation-store.ts +68 -9
  31. package/src/browser/partial-update.ts +60 -7
  32. package/src/browser/prefetch/cache.ts +129 -21
  33. package/src/browser/prefetch/fetch.ts +156 -18
  34. package/src/browser/prefetch/queue.ts +36 -5
  35. package/src/browser/rango-state.ts +53 -13
  36. package/src/browser/react/Link.tsx +72 -8
  37. package/src/browser/react/NavigationProvider.tsx +57 -11
  38. package/src/browser/react/context.ts +7 -2
  39. package/src/browser/react/use-handle.ts +9 -58
  40. package/src/browser/react/use-navigation.ts +22 -2
  41. package/src/browser/react/use-params.ts +11 -1
  42. package/src/browser/react/use-router.ts +29 -9
  43. package/src/browser/rsc-router.tsx +60 -9
  44. package/src/browser/scroll-restoration.ts +10 -8
  45. package/src/browser/segment-reconciler.ts +36 -14
  46. package/src/browser/server-action-bridge.ts +8 -18
  47. package/src/browser/types.ts +33 -5
  48. package/src/build/generate-manifest.ts +6 -6
  49. package/src/build/generate-route-types.ts +3 -0
  50. package/src/build/route-trie.ts +50 -24
  51. package/src/build/route-types/include-resolution.ts +8 -1
  52. package/src/build/route-types/router-processing.ts +211 -72
  53. package/src/build/route-types/scan-filter.ts +8 -1
  54. package/src/cache/cf/cf-cache-store.ts +5 -7
  55. package/src/client.tsx +84 -230
  56. package/src/deps/browser.ts +0 -1
  57. package/src/handle.ts +40 -0
  58. package/src/index.rsc.ts +6 -1
  59. package/src/index.ts +49 -6
  60. package/src/outlet-context.ts +1 -1
  61. package/src/prerender/store.ts +5 -4
  62. package/src/prerender.ts +138 -77
  63. package/src/response-utils.ts +28 -0
  64. package/src/reverse.ts +27 -2
  65. package/src/route-definition/dsl-helpers.ts +210 -35
  66. package/src/route-definition/helpers-types.ts +61 -14
  67. package/src/route-definition/index.ts +3 -0
  68. package/src/route-definition/redirect.ts +9 -1
  69. package/src/route-definition/resolve-handler-use.ts +155 -0
  70. package/src/route-types.ts +18 -0
  71. package/src/router/content-negotiation.ts +100 -1
  72. package/src/router/handler-context.ts +70 -17
  73. package/src/router/intercept-resolution.ts +9 -4
  74. package/src/router/lazy-includes.ts +6 -6
  75. package/src/router/loader-resolution.ts +153 -21
  76. package/src/router/manifest.ts +22 -13
  77. package/src/router/match-api.ts +127 -192
  78. package/src/router/match-middleware/cache-lookup.ts +28 -8
  79. package/src/router/match-middleware/segment-resolution.ts +53 -0
  80. package/src/router/match-result.ts +82 -4
  81. package/src/router/middleware-types.ts +2 -28
  82. package/src/router/middleware.ts +32 -7
  83. package/src/router/navigation-snapshot.ts +182 -0
  84. package/src/router/pattern-matching.ts +60 -9
  85. package/src/router/prerender-match.ts +110 -10
  86. package/src/router/preview-match.ts +30 -102
  87. package/src/router/request-classification.ts +310 -0
  88. package/src/router/route-snapshot.ts +245 -0
  89. package/src/router/router-interfaces.ts +36 -4
  90. package/src/router/router-options.ts +37 -11
  91. package/src/router/segment-resolution/fresh.ts +70 -5
  92. package/src/router/segment-resolution/revalidation.ts +87 -9
  93. package/src/router/trie-matching.ts +10 -4
  94. package/src/router/url-params.ts +49 -0
  95. package/src/router.ts +54 -7
  96. package/src/rsc/handler.ts +478 -399
  97. package/src/rsc/helpers.ts +69 -41
  98. package/src/rsc/loader-fetch.ts +18 -3
  99. package/src/rsc/manifest-init.ts +5 -1
  100. package/src/rsc/progressive-enhancement.ts +14 -3
  101. package/src/rsc/response-route-handler.ts +14 -1
  102. package/src/rsc/rsc-rendering.ts +15 -2
  103. package/src/rsc/server-action.ts +10 -2
  104. package/src/rsc/ssr-setup.ts +2 -2
  105. package/src/rsc/types.ts +6 -4
  106. package/src/segment-content-promise.ts +67 -0
  107. package/src/segment-loader-promise.ts +122 -0
  108. package/src/segment-system.tsx +11 -61
  109. package/src/server/context.ts +65 -5
  110. package/src/server/handle-store.ts +19 -0
  111. package/src/server/loader-registry.ts +9 -8
  112. package/src/server/request-context.ts +142 -55
  113. package/src/ssr/index.tsx +3 -0
  114. package/src/static-handler.ts +18 -6
  115. package/src/types/cache-types.ts +4 -4
  116. package/src/types/handler-context.ts +17 -43
  117. package/src/types/loader-types.ts +37 -11
  118. package/src/types/request-scope.ts +126 -0
  119. package/src/types/route-entry.ts +12 -1
  120. package/src/types/segments.ts +1 -1
  121. package/src/urls/include-helper.ts +24 -14
  122. package/src/urls/path-helper-types.ts +39 -6
  123. package/src/urls/path-helper.ts +47 -12
  124. package/src/urls/pattern-types.ts +12 -0
  125. package/src/urls/response-types.ts +18 -16
  126. package/src/use-loader.tsx +77 -5
  127. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  128. package/src/vite/discovery/discover-routers.ts +5 -1
  129. package/src/vite/discovery/prerender-collection.ts +128 -74
  130. package/src/vite/discovery/state.ts +13 -4
  131. package/src/vite/index.ts +4 -0
  132. package/src/vite/plugin-types.ts +60 -5
  133. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  134. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  135. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  136. package/src/vite/plugins/expose-id-utils.ts +12 -0
  137. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  138. package/src/vite/plugins/expose-internal-ids.ts +257 -40
  139. package/src/vite/plugins/performance-tracks.ts +64 -206
  140. package/src/vite/plugins/refresh-cmd.ts +88 -26
  141. package/src/vite/rango.ts +40 -18
  142. package/src/vite/router-discovery.ts +237 -37
  143. package/src/vite/utils/banner.ts +1 -1
  144. package/src/vite/utils/package-resolution.ts +1 -1
  145. package/src/vite/utils/prerender-utils.ts +37 -5
  146. package/src/vite/utils/shared-utils.ts +3 -2
  147. package/src/browser/debug-channel.ts +0 -93
@@ -1,16 +1,20 @@
1
1
  ---
2
2
  name: links
3
- description: URL generation with ctx.reverse (server), href (client), useHref (mounted), useMount, and scopedReverse
4
- argument-hint: [href|useHref|useMount|scopedReverse]
3
+ description: URL generation with ctx.reverse (server default), href (client), useHref (mounted), useMount, and scopedReverse
4
+ argument-hint: [ctx.reverse|href|useHref|useMount|scopedReverse]
5
5
  ---
6
6
 
7
7
  # Links & URL Generation
8
8
 
9
9
  @rangojs/router provides different href APIs for server and client contexts.
10
10
 
11
+ **Default server API: `ctx.reverse()`.** Generate URLs from the handler context — it's typed, auto-fills mount params, and resolves local (`.name`) and absolute (`name.sub`) names.
12
+
13
+ **`reverse()` is server-only.** It depends on the route manifest and handler context, neither of which are available in the browser. Client components receive URLs as props, loader data, or server-action return values — they never call `reverse` directly.
14
+
11
15
  ## Server: ctx.reverse()
12
16
 
13
- Available in route handlers via HandlerContext. Resolves named routes using the full route map.
17
+ Available in route handlers via HandlerContext. Resolves named routes using the full route map. This is the default way to generate URLs on the server.
14
18
 
15
19
  ```typescript
16
20
  import { urls, scopedReverse } from "@rangojs/router";
@@ -103,7 +107,7 @@ path("/search", (ctx) => {
103
107
 
104
108
  ### scopedReverse() - type-safe ctx.reverse
105
109
 
106
- Wraps `ctx.reverse` with local route type information for autocomplete and validation:
110
+ Wraps `ctx.reverse` with local route type information for autocomplete and validation. Runtime behavior is identical to `ctx.reverse` — `scopedReverse` is a type-only cast. The same dot-prefix rule applies: local names use `.name`, global names use `name.sub`.
107
111
 
108
112
  ```typescript
109
113
  import { scopedReverse } from "@rangojs/router";
@@ -111,18 +115,83 @@ import { scopedReverse } from "@rangojs/router";
111
115
  path("/product/:slug", (ctx) => {
112
116
  const reverse = scopedReverse<typeof shopPatterns>(ctx.reverse);
113
117
 
114
- reverse("cart"); // Type-safe local name
115
- reverse("product", { slug: "widget" }); // Type-safe with params
116
- reverse("blog.post"); // Absolute names (dot notation) always allowed
117
- reverse("/about"); // Path-based always allowed
118
+ reverse(".cart"); // Local name (dot-prefixed) resolves in include scope
119
+ reverse(".product", { slug: "widget" }); // Local name with params
120
+ reverse("blog.post", { slug: "hi" }); // Global name (dotted) full route map
118
121
 
119
122
  return <ProductPage slug={ctx.params.slug} />;
120
123
  }, { name: "product" })
121
124
  ```
122
125
 
126
+ `reverse()` does not accept raw path strings (`"/about"`). For static paths in client components, use `href("/about")`; on the server, look up the route by name.
127
+
128
+ ## Client components: receive URLs as props
129
+
130
+ `reverse()` is not available inside `"use client"` modules — there is no handler context and no route manifest in the browser bundle. Generate the URL on the server and hand it to the client component.
131
+
132
+ Three patterns, in order of preference:
133
+
134
+ 1. Pass as a prop from a server component:
135
+
136
+ ```tsx
137
+ // server
138
+ function BlogPostPage(ctx: HandlerContext) {
139
+ return <ShareButton url={ctx.reverse(".post", { slug: ctx.params.slug })} />;
140
+ }
141
+ ```
142
+
143
+ ```tsx
144
+ "use client";
145
+
146
+ export function ShareButton({ url }: { url: string }) {
147
+ return (
148
+ <button onClick={() => navigator.clipboard.writeText(url)}>Share</button>
149
+ );
150
+ }
151
+ ```
152
+
153
+ 2. Return from a loader (attached to the route via the DSL):
154
+
155
+ ```tsx
156
+ // server — loaders/nav.ts
157
+ export const NavLoader = createLoader((ctx) => ({
158
+ home: ctx.reverse("home"),
159
+ blog: ctx.reverse("blog.index"),
160
+ }));
161
+
162
+ // server — urls.tsx: attach the loader so useLoader has data in context
163
+ const urlpatterns = urls(({ path, loader }) => [
164
+ path("/", HomePage, { name: "home" }, () => [loader(NavLoader)]),
165
+ ]);
166
+ ```
167
+
168
+ ```tsx
169
+ "use client";
170
+
171
+ function Nav() {
172
+ const { data } = useLoader(NavLoader);
173
+ return <Link to={data.home}>Home</Link>;
174
+ }
175
+ ```
176
+
177
+ `useLoader()` requires the loader to be attached to an active route. If you need on-demand fetching instead, use `useFetchLoader()`.
178
+
179
+ 3. Return from a server action:
180
+
181
+ ```tsx
182
+ "use server";
183
+
184
+ export async function getProductUrl(slug: string) {
185
+ const ctx = getRequestContext();
186
+ return ctx.reverse("product", { slug });
187
+ }
188
+ ```
189
+
190
+ For static path strings (not named routes), client components can use `href()` — see below.
191
+
123
192
  ## Client: href()
124
193
 
125
- Plain function for absolute path-based URLs. No hook needed - works anywhere.
194
+ Plain function for absolute path-based URLs. No hook needed - works anywhere in client components. `href()` validates paths at compile time, but does **not** resolve named routes — for named routes, use one of the patterns above.
126
195
 
127
196
  ```typescript
128
197
  "use client";
@@ -139,7 +208,9 @@ function GlobalNav() {
139
208
  }
140
209
  ```
141
210
 
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`.
211
+ `href()` provides compile-time validation via `ValidPaths` type. Paths are validated against registered route patterns using `PatternToPath`.
212
+
213
+ `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
214
 
144
215
  ## Client: useHref()
145
216
 
@@ -185,13 +256,16 @@ function MountInfo() {
185
256
 
186
257
  ## When to use what
187
258
 
188
- | Context | API | Resolves | Use for |
189
- | ---------------- | ------------------------------- | ------------------------------- | ----------------------------------- |
190
- | Server handler | `ctx.reverse("name")` | Named routes (local + absolute) | Server-side URL generation |
191
- | Server handler | `scopedReverse<T>(ctx.reverse)` | Same, with type safety | Type-safe server URLs |
192
- | Client component | `href("/path")` | Absolute paths | Global navigation |
193
- | Client component | `useHref()` | Mount-prefixed paths | Local navigation inside `include()` |
194
- | Client component | `useMount()` | Raw mount path | Custom mount-aware logic |
259
+ | Context | API | Resolves | Use for |
260
+ | ---------------- | -------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------- |
261
+ | Server handler | `ctx.reverse("name")` | Named routes (local + absolute) | **Default** server-side URL generation |
262
+ | Server handler | `scopedReverse<T>(ctx.reverse)` | Same, with type safety | Type-safe server URLs |
263
+ | Client component | (URL passed as prop / loader data / action return) | Named routes | Any URL derived from a named route — generate on server, pass in |
264
+ | Client component | `href("/path")` | Absolute paths (static strings) | Static navigation where no named-route lookup is needed |
265
+ | Client component | `useHref()` | Mount-prefixed paths | Local navigation inside `include()` |
266
+ | Client component | `useMount()` | Raw mount path | Custom mount-aware logic |
267
+
268
+ > `reverse()` is server-only. Client components never import or call it — they receive the already-resolved string.
195
269
 
196
270
  ## Complete example: mounted module
197
271
 
@@ -139,7 +139,29 @@ same memoized result — loaders never run twice per request.
139
139
 
140
140
  ## Loader Context
141
141
 
142
- Loaders receive the same context as route handlers:
142
+ Loaders receive the same context shape as route handlers.
143
+
144
+ ### Full field surface
145
+
146
+ | Field | Type | Notes |
147
+ | -------------- | ------------------------------ | --------------------------------------------------------------------------------------------------- |
148
+ | `params` | `TParams` | Merged route + explicit loader params; overridable by fetchable `load({ params })`. |
149
+ | `routeParams` | `Record<string, string>` | Server-trusted route params from URL pattern matching; cannot be overridden. |
150
+ | `request` | `Request` | The incoming `Request` (headers, method, body, `signal` for abort). |
151
+ | `url` | `URL` | Parsed request URL. |
152
+ | `pathname` | `string` | URL pathname (shortcut for `ctx.url.pathname`). |
153
+ | `searchParams` | `URLSearchParams` | Shortcut for `ctx.url.searchParams`. |
154
+ | `search` | `ResolveSearchSchema<TSearch>` | Typed query params when a search schema is declared on the route; `{}` otherwise. |
155
+ | `env` | `TEnv` | Plain bindings from `createRouter<TEnv>()` (DB, KV, secrets, etc.). |
156
+ | `get` | `(key \| ContextVar) => value` | Reads variables/context-vars set by middleware. |
157
+ | `use` | `(loader \| handle) => T` | Access another loader's data (Promise) or a handle's collected data (after `await ctx.rendered()`). |
158
+ | `rendered` | `() => Promise<void>` | **Experimental.** DSL loaders only — waits for non-loader segments before reading handle data. |
159
+ | `method` | `string` | HTTP method. `"GET"` for SSR loader runs; reflects real method for fetchable loaders. |
160
+ | `body` | `TBody \| undefined` | Parsed request body for fetchable POST/PUT/PATCH/DELETE calls. |
161
+ | `formData` | `FormData \| undefined` | Present when a fetchable loader is invoked via form submission. |
162
+ | `reverse` | `ScopedReverseFunction` | Generate type-checked URLs from route names (same scoped semantics as route handlers). |
163
+
164
+ ### Example
143
165
 
144
166
  ```typescript
145
167
  export const ProductLoader = createLoader(async (ctx) => {
@@ -163,10 +185,21 @@ export const ProductLoader = createLoader(async (ctx) => {
163
185
  // Variables set by middleware (from RSCRouter.Vars augmentation)
164
186
  const user = ctx.get("user");
165
187
 
166
- return { product: await fetchProduct(slug) };
188
+ // Type-checked URLs for payloads. `.name` resolves within the current
189
+ // include() scope; a bare `name` resolves globally. See /route and
190
+ // /typesafety for scope rules and route-name autocomplete.
191
+ const detailUrl = ctx.reverse(".detail", { slug });
192
+
193
+ return {
194
+ product: await fetchProduct(slug),
195
+ links: { self: detailUrl },
196
+ };
167
197
  });
168
198
  ```
169
199
 
200
+ See `/route` for the full handler-context contract (shared with loaders) and
201
+ `/typesafety` for route-name typing that powers `ctx.reverse` autocomplete.
202
+
170
203
  ### params vs routeParams
171
204
 
172
205
  - `ctx.params` — merged route params + explicit loader params. For fetchable
@@ -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).
@@ -135,17 +137,46 @@ export const urlpatterns = urls(({ path, layout, middleware }) => [
135
137
  ## Middleware with Multiple Handlers
136
138
 
137
139
  ```typescript
138
- // Spread multiple middleware from a single export
140
+ // Group multiple middleware in an array
139
141
  export const shopMiddleware = [loggerMiddleware, mockAuthMiddleware];
140
142
 
141
- // In routes
143
+ // In routes — pass the array directly
142
144
  layout(<ShopLayout />, () => [
143
- middleware(...shopMiddleware),
145
+ middleware(shopMiddleware),
144
146
 
145
147
  path("/shop", ShopIndex, { name: "shop" }),
146
148
  ])
147
149
  ```
148
150
 
151
+ ## Wrapping Middleware (Scoped to Children)
152
+
153
+ Use the wrapping form to scope middleware to a subset of routes without
154
+ introducing a visible layout:
155
+
156
+ ```typescript
157
+ urls(({ path, middleware }) => [
158
+ // authMw only applies to /admin and /admin/settings
159
+ middleware(authMw, () => [
160
+ path("/admin", AdminPage, { name: "admin" }),
161
+ path("/admin/settings", SettingsPage, { name: "settings" }),
162
+ ]),
163
+
164
+ // Public route — no authMw
165
+ path("/", HomePage, { name: "home" }),
166
+ ]);
167
+ ```
168
+
169
+ Multiple middleware with wrapping:
170
+
171
+ ```typescript
172
+ middleware([authMw, loggingMw], () => [
173
+ path("/admin", AdminPage, { name: "admin" }),
174
+ ]);
175
+ ```
176
+
177
+ This creates a transparent layout (`<Outlet />`) that carries the middleware.
178
+ The middleware does not affect sibling routes outside the callback.
179
+
149
180
  ## Middleware Context
150
181
 
151
182
  ```typescript