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

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 (175) hide show
  1. package/README.md +188 -35
  2. package/dist/bin/rango.js +130 -47
  3. package/dist/vite/index.js +1884 -537
  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 +7 -5
  7. package/skills/breadcrumbs/SKILL.md +3 -1
  8. package/skills/cache-guide/SKILL.md +32 -0
  9. package/skills/caching/SKILL.md +8 -0
  10. package/skills/handler-use/SKILL.md +362 -0
  11. package/skills/hooks/SKILL.md +33 -20
  12. package/skills/i18n/SKILL.md +276 -0
  13. package/skills/intercept/SKILL.md +20 -0
  14. package/skills/layout/SKILL.md +22 -0
  15. package/skills/links/SKILL.md +93 -17
  16. package/skills/loader/SKILL.md +123 -46
  17. package/skills/middleware/SKILL.md +36 -3
  18. package/skills/migrate-nextjs/SKILL.md +562 -0
  19. package/skills/migrate-react-router/SKILL.md +769 -0
  20. package/skills/parallel/SKILL.md +133 -0
  21. package/skills/prerender/SKILL.md +110 -68
  22. package/skills/rango/SKILL.md +26 -22
  23. package/skills/response-routes/SKILL.md +8 -0
  24. package/skills/route/SKILL.md +75 -0
  25. package/skills/router-setup/SKILL.md +87 -2
  26. package/skills/server-actions/SKILL.md +739 -0
  27. package/skills/streams-and-websockets/SKILL.md +283 -0
  28. package/skills/typesafety/SKILL.md +19 -1
  29. package/src/__internal.ts +1 -1
  30. package/src/browser/app-shell.ts +52 -0
  31. package/src/browser/app-version.ts +14 -0
  32. package/src/browser/event-controller.ts +44 -4
  33. package/src/browser/navigation-bridge.ts +95 -7
  34. package/src/browser/navigation-client.ts +128 -53
  35. package/src/browser/navigation-store.ts +68 -9
  36. package/src/browser/partial-update.ts +93 -12
  37. package/src/browser/prefetch/cache.ts +129 -21
  38. package/src/browser/prefetch/fetch.ts +156 -18
  39. package/src/browser/prefetch/queue.ts +92 -29
  40. package/src/browser/prefetch/resource-ready.ts +77 -0
  41. package/src/browser/rango-state.ts +53 -13
  42. package/src/browser/react/Link.tsx +72 -8
  43. package/src/browser/react/NavigationProvider.tsx +82 -21
  44. package/src/browser/react/context.ts +7 -2
  45. package/src/browser/react/filter-segment-order.ts +51 -7
  46. package/src/browser/react/use-handle.ts +9 -58
  47. package/src/browser/react/use-navigation.ts +22 -2
  48. package/src/browser/react/use-params.ts +17 -4
  49. package/src/browser/react/use-router.ts +29 -9
  50. package/src/browser/react/use-segments.ts +11 -8
  51. package/src/browser/rsc-router.tsx +60 -9
  52. package/src/browser/scroll-restoration.ts +10 -8
  53. package/src/browser/segment-reconciler.ts +36 -14
  54. package/src/browser/server-action-bridge.ts +8 -6
  55. package/src/browser/types.ts +46 -5
  56. package/src/build/generate-manifest.ts +6 -6
  57. package/src/build/generate-route-types.ts +3 -0
  58. package/src/build/route-trie.ts +52 -25
  59. package/src/build/route-types/include-resolution.ts +8 -1
  60. package/src/build/route-types/router-processing.ts +211 -72
  61. package/src/build/route-types/scan-filter.ts +8 -1
  62. package/src/cache/cache-runtime.ts +15 -11
  63. package/src/cache/cache-scope.ts +46 -5
  64. package/src/cache/cf/cf-cache-store.ts +5 -7
  65. package/src/cache/taint.ts +55 -0
  66. package/src/client.tsx +84 -230
  67. package/src/context-var.ts +72 -2
  68. package/src/handle.ts +40 -0
  69. package/src/index.rsc.ts +6 -1
  70. package/src/index.ts +49 -6
  71. package/src/outlet-context.ts +1 -1
  72. package/src/prerender/store.ts +5 -4
  73. package/src/prerender.ts +138 -77
  74. package/src/response-utils.ts +28 -0
  75. package/src/reverse.ts +28 -2
  76. package/src/route-definition/dsl-helpers.ts +210 -35
  77. package/src/route-definition/helpers-types.ts +73 -20
  78. package/src/route-definition/index.ts +3 -0
  79. package/src/route-definition/redirect.ts +9 -1
  80. package/src/route-definition/resolve-handler-use.ts +155 -0
  81. package/src/route-types.ts +18 -0
  82. package/src/router/content-negotiation.ts +100 -1
  83. package/src/router/handler-context.ts +102 -25
  84. package/src/router/intercept-resolution.ts +9 -4
  85. package/src/router/lazy-includes.ts +6 -6
  86. package/src/router/loader-resolution.ts +159 -21
  87. package/src/router/manifest.ts +22 -13
  88. package/src/router/match-api.ts +128 -192
  89. package/src/router/match-handlers.ts +1 -0
  90. package/src/router/match-middleware/background-revalidation.ts +12 -1
  91. package/src/router/match-middleware/cache-lookup.ts +74 -14
  92. package/src/router/match-middleware/cache-store.ts +21 -4
  93. package/src/router/match-middleware/segment-resolution.ts +53 -0
  94. package/src/router/match-result.ts +112 -9
  95. package/src/router/metrics.ts +6 -1
  96. package/src/router/middleware-types.ts +20 -33
  97. package/src/router/middleware.ts +56 -12
  98. package/src/router/navigation-snapshot.ts +182 -0
  99. package/src/router/pattern-matching.ts +101 -17
  100. package/src/router/prerender-match.ts +110 -10
  101. package/src/router/preview-match.ts +30 -102
  102. package/src/router/request-classification.ts +310 -0
  103. package/src/router/revalidation.ts +15 -1
  104. package/src/router/route-snapshot.ts +245 -0
  105. package/src/router/router-context.ts +1 -0
  106. package/src/router/router-interfaces.ts +36 -4
  107. package/src/router/router-options.ts +37 -11
  108. package/src/router/segment-resolution/fresh.ts +114 -18
  109. package/src/router/segment-resolution/helpers.ts +29 -24
  110. package/src/router/segment-resolution/revalidation.ts +257 -127
  111. package/src/router/trie-matching.ts +18 -13
  112. package/src/router/types.ts +1 -0
  113. package/src/router/url-params.ts +49 -0
  114. package/src/router.ts +55 -7
  115. package/src/rsc/handler.ts +478 -383
  116. package/src/rsc/helpers.ts +69 -41
  117. package/src/rsc/loader-fetch.ts +23 -3
  118. package/src/rsc/manifest-init.ts +5 -1
  119. package/src/rsc/progressive-enhancement.ts +18 -2
  120. package/src/rsc/response-route-handler.ts +14 -1
  121. package/src/rsc/rsc-rendering.ts +20 -1
  122. package/src/rsc/server-action.ts +12 -0
  123. package/src/rsc/ssr-setup.ts +2 -2
  124. package/src/rsc/types.ts +15 -1
  125. package/src/segment-content-promise.ts +67 -0
  126. package/src/segment-loader-promise.ts +122 -0
  127. package/src/segment-system.tsx +22 -62
  128. package/src/server/context.ts +76 -4
  129. package/src/server/handle-store.ts +19 -0
  130. package/src/server/loader-registry.ts +9 -8
  131. package/src/server/request-context.ts +185 -57
  132. package/src/ssr/index.tsx +8 -1
  133. package/src/static-handler.ts +18 -6
  134. package/src/types/cache-types.ts +4 -4
  135. package/src/types/handler-context.ts +145 -68
  136. package/src/types/loader-types.ts +41 -15
  137. package/src/types/request-scope.ts +126 -0
  138. package/src/types/route-entry.ts +12 -1
  139. package/src/types/segments.ts +18 -1
  140. package/src/urls/include-helper.ts +24 -14
  141. package/src/urls/path-helper-types.ts +39 -6
  142. package/src/urls/path-helper.ts +47 -12
  143. package/src/urls/pattern-types.ts +12 -0
  144. package/src/urls/response-types.ts +18 -16
  145. package/src/use-loader.tsx +77 -5
  146. package/src/vite/debug.ts +184 -0
  147. package/src/vite/discovery/bundle-postprocess.ts +30 -33
  148. package/src/vite/discovery/discover-routers.ts +36 -4
  149. package/src/vite/discovery/gate-state.ts +171 -0
  150. package/src/vite/discovery/prerender-collection.ts +175 -74
  151. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  152. package/src/vite/discovery/state.ts +13 -4
  153. package/src/vite/index.ts +4 -0
  154. package/src/vite/plugin-types.ts +60 -5
  155. package/src/vite/plugins/cjs-to-esm.ts +5 -0
  156. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  157. package/src/vite/plugins/client-ref-hashing.ts +16 -4
  158. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  159. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  160. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  161. package/src/vite/plugins/expose-action-id.ts +52 -28
  162. package/src/vite/plugins/expose-id-utils.ts +12 -0
  163. package/src/vite/plugins/expose-ids/handler-transform.ts +30 -0
  164. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  165. package/src/vite/plugins/expose-internal-ids.ts +563 -316
  166. package/src/vite/plugins/performance-tracks.ts +96 -0
  167. package/src/vite/plugins/refresh-cmd.ts +88 -26
  168. package/src/vite/plugins/use-cache-transform.ts +56 -43
  169. package/src/vite/plugins/version-injector.ts +37 -11
  170. package/src/vite/rango.ts +63 -11
  171. package/src/vite/router-discovery.ts +732 -86
  172. package/src/vite/utils/banner.ts +1 -1
  173. package/src/vite/utils/package-resolution.ts +41 -1
  174. package/src/vite/utils/prerender-utils.ts +38 -5
  175. package/src/vite/utils/shared-utils.ts +3 -2
@@ -0,0 +1,276 @@
1
+ ---
2
+ name: i18n
3
+ description: Locale-aware routing with `include("/:locale?", ...)`, locale resolution chains, and react-intl integration
4
+ argument-hint: "[topic]"
5
+ ---
6
+
7
+ # Internationalization (i18n) and Locale Routing
8
+
9
+ Rango doesn't ship an i18n module. The router gives you the URL primitives
10
+ (optional include prefixes, constraints, typed reverse) and you compose
11
+ them with whatever message library you use — `react-intl`, `lingui`,
12
+ `@formatjs/intl`, or hand-rolled.
13
+
14
+ This skill covers:
15
+
16
+ - Mounting routes under an optional locale prefix (`/`, `/en`, `/gb`)
17
+ - Constraining the prefix to a known locale set
18
+ - Resolving the active locale (URL → cookie → `Accept-Language` → default)
19
+ - Generating localized URLs via `reverse()` round-trip
20
+ - Wiring `react-intl` into an RSC route tree
21
+
22
+ ## URL Shape: Optional Locale Prefix
23
+
24
+ Mount your localized routes under an optional include prefix so the
25
+ default locale lives at the bare URL and other locales get a prefix:
26
+
27
+ ```typescript
28
+ // urls.tsx
29
+ import { urls } from "@rangojs/router";
30
+ import { menuRoutes } from "./menu";
31
+
32
+ export const urlpatterns = urls(({ include }) => [
33
+ include("/:locale?", menuRoutes, { name: "menu" }),
34
+ ]);
35
+ ```
36
+
37
+ URLs that match:
38
+
39
+ | URL | Matched route | `ctx.params.locale` |
40
+ | -------------- | --------------- | ------------------- |
41
+ | `/` | `menu.index` | `undefined` |
42
+ | `/en` | `menu.index` | `"en"` |
43
+ | `/c/breads` | `menu.category` | `undefined` |
44
+ | `/en/c/breads` | `menu.category` | `"en"` |
45
+
46
+ > **Constrain to known locales** when you want unknown locales to fall
47
+ > through to other routes (or 404) instead of being treated as a slug:
48
+ >
49
+ > ```typescript
50
+ > include("/:locale(en|gb|fr)?", menuRoutes, { name: "menu" });
51
+ > ```
52
+ >
53
+ > `/de` now 404s (constraint rejects `de`), and `/c/breads` continues to
54
+ > match `menu.category` with `locale: undefined`. Without the constraint,
55
+ > `/de` would match `menu.index` with `locale: "de"`.
56
+
57
+ ## Reading the Locale in Handlers
58
+
59
+ Absent optionals are `undefined` (not `""`), so `??` coalesces correctly:
60
+
61
+ ```typescript
62
+ import { Handler } from "@rangojs/router";
63
+
64
+ export const MenuIndex: Handler<"menu.index"> = (ctx) => {
65
+ // ctx.params.locale is `string | undefined`
66
+ const locale = resolveLocale(ctx);
67
+ return <Welcome locale={locale} />;
68
+ };
69
+ ```
70
+
71
+ The `resolveLocale` helper below implements a typical fallback chain.
72
+
73
+ ## Locale Resolution
74
+
75
+ URL is the strongest signal but you usually want a fallback chain:
76
+
77
+ 1. **URL prefix** — if the user navigates to `/gb/...`, honor it
78
+ 2. **Cookie** — sticky preference set by a previous language switcher
79
+ 3. **`Accept-Language`** — browser hint
80
+ 4. **Default** — your app default
81
+
82
+ Put it in a small helper that every locale-aware handler calls:
83
+
84
+ ```typescript
85
+ // lib/locale.ts
86
+ import { cookies, headers } from "@rangojs/router";
87
+
88
+ export const SUPPORTED_LOCALES = ["en", "gb", "fr"] as const;
89
+ export type Locale = (typeof SUPPORTED_LOCALES)[number];
90
+ const DEFAULT_LOCALE: Locale = "en";
91
+
92
+ const isSupported = (v: string): v is Locale =>
93
+ (SUPPORTED_LOCALES as readonly string[]).includes(v);
94
+
95
+ export function resolveLocale(ctx: {
96
+ params: Record<string, string | undefined>;
97
+ }): Locale {
98
+ const fromUrl = ctx.params.locale;
99
+ if (fromUrl && isSupported(fromUrl)) return fromUrl;
100
+
101
+ const fromCookie = cookies().get("locale")?.value;
102
+ if (fromCookie && isSupported(fromCookie)) return fromCookie;
103
+
104
+ const accept = headers().get("accept-language") ?? "";
105
+ for (const tag of accept.split(",")) {
106
+ const code = tag.split(";")[0].trim().split("-")[0];
107
+ if (isSupported(code)) return code as Locale;
108
+ }
109
+ return DEFAULT_LOCALE;
110
+ }
111
+ ```
112
+
113
+ If you want to redirect to the canonical URL when the resolved locale
114
+ doesn't match the URL (e.g., user has `gb` cookie but visits `/`), do
115
+ that in a global middleware so it covers actions too:
116
+
117
+ ```typescript
118
+ import { redirect } from "@rangojs/router";
119
+
120
+ router.use("/*", async (ctx, next) => {
121
+ const fromUrl = ctx.params.locale;
122
+ const resolved = resolveLocale(ctx);
123
+ if (resolved !== DEFAULT_LOCALE && !fromUrl) {
124
+ return redirect(`/${resolved}${ctx.url.pathname}`);
125
+ }
126
+ await next();
127
+ });
128
+ ```
129
+
130
+ ## Generating Localized URLs
131
+
132
+ `reverse()` treats `undefined` and `""` for an optional param as "absent"
133
+ and collapses the segment cleanly. The round-trip is symmetric with the
134
+ matcher:
135
+
136
+ ```typescript
137
+ ctx.reverse("menu.index", { locale: "" }); // → "/"
138
+ ctx.reverse("menu.index", { locale: undefined }); // → "/"
139
+ ctx.reverse("menu.index", { locale: "en" }); // → "/en"
140
+ ctx.reverse("menu.category", { locale: "en", slug: "breads" }); // → "/en/c/breads"
141
+ ctx.reverse("menu.category", { slug: "breads" }); // → "/c/breads"
142
+ ```
143
+
144
+ If the active locale is the app default and your URL strategy hides it
145
+ (`"en"` → `/`, others → `/<locale>`), normalize before calling reverse:
146
+
147
+ ```typescript
148
+ const normalized = locale === DEFAULT_LOCALE ? undefined : locale;
149
+ const href = ctx.reverse("menu.category", { locale: normalized, slug });
150
+ ```
151
+
152
+ ## react-intl Integration
153
+
154
+ `react-intl` needs a `<IntlProvider>` wrapping the tree, with `locale`
155
+ and `messages` props. The cleanest split: load messages on the server
156
+ (handler or layout), pass them through to a client provider component.
157
+
158
+ ### Messages loader
159
+
160
+ Load message bundles per locale. Keep them server-side so they stream
161
+ through the RSC payload and don't bloat the client bundle:
162
+
163
+ ```typescript
164
+ // lib/messages.ts
165
+ import type { Locale } from "./locale";
166
+
167
+ const loaders: Record<Locale, () => Promise<Record<string, string>>> = {
168
+ en: () => import("../messages/en.json").then((m) => m.default),
169
+ gb: () => import("../messages/gb.json").then((m) => m.default),
170
+ fr: () => import("../messages/fr.json").then((m) => m.default),
171
+ };
172
+
173
+ export async function loadMessages(locale: Locale) {
174
+ return loaders[locale]();
175
+ }
176
+ ```
177
+
178
+ ### Server layout: hand off to the client provider
179
+
180
+ ```tsx
181
+ // layouts/intl-layout.tsx (server component)
182
+ import type { ReactNode } from "react";
183
+ import { resolveLocale } from "../lib/locale";
184
+ import { loadMessages } from "../lib/messages";
185
+ import { IntlClientProvider } from "../components/intl-client-provider";
186
+
187
+ export async function IntlLayout({
188
+ ctx,
189
+ children,
190
+ }: {
191
+ ctx: any;
192
+ children: ReactNode;
193
+ }) {
194
+ const locale = resolveLocale(ctx);
195
+ const messages = await loadMessages(locale);
196
+ return (
197
+ <IntlClientProvider locale={locale} messages={messages}>
198
+ {children}
199
+ </IntlClientProvider>
200
+ );
201
+ }
202
+ ```
203
+
204
+ ### Client provider
205
+
206
+ ```tsx
207
+ // components/intl-client-provider.tsx
208
+ "use client";
209
+
210
+ import { IntlProvider } from "react-intl";
211
+ import type { ReactNode } from "react";
212
+
213
+ export function IntlClientProvider({
214
+ locale,
215
+ messages,
216
+ children,
217
+ }: {
218
+ locale: string;
219
+ messages: Record<string, string>;
220
+ children: ReactNode;
221
+ }) {
222
+ return (
223
+ <IntlProvider
224
+ locale={locale}
225
+ defaultLocale="en"
226
+ messages={messages}
227
+ onError={(err) => {
228
+ if (err.code === "MISSING_TRANSLATION") return; // common, log only
229
+ console.error(err);
230
+ }}
231
+ >
232
+ {children}
233
+ </IntlProvider>
234
+ );
235
+ }
236
+ ```
237
+
238
+ ### Mounting
239
+
240
+ Wrap your localized routes with the layout:
241
+
242
+ ```typescript
243
+ import { urls } from "@rangojs/router";
244
+ import { IntlLayout } from "./layouts/intl-layout";
245
+ import { menuRoutes } from "./menu";
246
+
247
+ export const urlpatterns = urls(({ layout, include }) => [
248
+ layout(IntlLayout, () => [
249
+ include("/:locale?", menuRoutes, { name: "menu" }),
250
+ ]),
251
+ ]);
252
+ ```
253
+
254
+ `<FormattedMessage>`, `useIntl()`, etc. work in any client component
255
+ under the layout. Server components can use `formatjs`'s `createIntl()`
256
+ directly with the same `messages` map for static text.
257
+
258
+ ## Common Pitfalls
259
+
260
+ | Pitfall | Fix |
261
+ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
262
+ | `ctx.params.locale === ""` returns `false` | Absent optionals are `undefined`, not `""`. Use `=== undefined` or `??`. |
263
+ | `ctx.params.locale ?? "en"` returns `""` | Pre-fix behavior. After the include-prefix fix this works correctly. |
264
+ | Bare `/` 404s when mounted via `include("/:locale?", routes)` | Requires the all-optional pattern fix in `compilePattern` (shipped). |
265
+ | Unknown locale (e.g. `/de`) matches as `locale: "de"` | Add a constraint: `:locale(en\|gb\|fr)?`. Unknown values now 404. |
266
+ | Reverse produces `//c/breads` for absent locale | `reverse()` collapses `undefined`/`""` segments — should not happen. File a bug. |
267
+ | Locale switcher loses search params | Read `ctx.url.search` and pass to `reverse(..., undefined, parsedSearch)`. |
268
+ | Action middleware can't read `ctx.params.locale` | Route middleware doesn't wrap action execution. Use global `router.use()` for actions. |
269
+
270
+ ## Cross-references
271
+
272
+ - `/route` — optional URL param syntax and runtime contract
273
+ - `/typesafety` — `RouteParams<"name">` typing for optionals
274
+ - `/middleware` — global vs route middleware scope (matters for actions)
275
+ - `/server-actions` — actions and the global-vs-route middleware boundary
276
+ - `/links` — `ctx.reverse()` and locale-aware URL generation
@@ -311,3 +311,23 @@ export const shopPatterns = urls(({
311
311
  ]),
312
312
  ]);
313
313
  ```
314
+
315
+ ## Handler-attached `.use`
316
+
317
+ Intercept handlers can carry their own middleware, loaders, loading state, error/notFound boundaries, and even nested `layout`/`route`/`when` defaults via `.use` — useful for self-contained modal components that travel with their own data and chrome.
318
+
319
+ ```typescript
320
+ const QuickViewModal: Handler = async (ctx) => {
321
+ const product = await ctx.use(ProductLoader);
322
+ return <QuickView product={product} />;
323
+ };
324
+ QuickViewModal.use = () => [
325
+ loader(ProductLoader),
326
+ loading(<QuickViewSkeleton />),
327
+ layout(<ModalChrome />),
328
+ ];
329
+
330
+ intercept("@modal", "product", QuickViewModal);
331
+ ```
332
+
333
+ Explicit `use()` at the mount site merges with `handler.use` (handler defaults first, explicit second). See [skills/handler-use](../handler-use/SKILL.md) for merge order and the per-mount-site allowed-types table.
@@ -308,3 +308,25 @@ export const shopPatterns = urls(({ path, layout, parallel, loader, revalidate }
308
308
  ]),
309
309
  ]);
310
310
  ```
311
+
312
+ ## Handler-attached `.use`
313
+
314
+ Layout handlers can carry their own middleware, default parallels, and includes via `.use` so a layout becomes a self-contained unit reusable across mount sites.
315
+
316
+ ```typescript
317
+ const AdminLayout: Handler = (ctx) => {
318
+ const user = ctx.get(CurrentUser);
319
+ return <Admin user={user} />;
320
+ };
321
+ AdminLayout.use = () => [
322
+ middleware(requireAdmin),
323
+ parallel({ "@adminNotifs": AdminNotifsSlot }),
324
+ ];
325
+
326
+ // Mount site declares structure only; defaults travel with the layout.
327
+ layout(AdminLayout, () => [
328
+ path("/admin", AdminIndex, { name: "admin.index" }),
329
+ ]);
330
+ ```
331
+
332
+ Allowed item types in a layout's `.use` mirror the layout `use()` callback (the broadest set). Explicit `use()` at the mount site merges with `handler.use` (handler defaults first, explicit second). See [skills/handler-use](../handler-use/SKILL.md) for merge order and per-mount-site allowed types.
@@ -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,85 @@ 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
+ See `/server-actions` for the full action surface (`getRequestContext()` is the same context middleware and handlers use).
191
+
192
+ For static path strings (not named routes), client components can use `href()` — see below.
193
+
123
194
  ## Client: href()
124
195
 
125
- Plain function for absolute path-based URLs. No hook needed - works anywhere.
196
+ 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
197
 
127
198
  ```typescript
128
199
  "use client";
@@ -139,7 +210,9 @@ function GlobalNav() {
139
210
  }
140
211
  ```
141
212
 
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`.
213
+ `href()` provides compile-time validation via `ValidPaths` type. Paths are validated against registered route patterns using `PatternToPath`.
214
+
215
+ `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
216
 
144
217
  ## Client: useHref()
145
218
 
@@ -185,13 +258,16 @@ function MountInfo() {
185
258
 
186
259
  ## When to use what
187
260
 
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 |
261
+ | Context | API | Resolves | Use for |
262
+ | ---------------- | -------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------- |
263
+ | Server handler | `ctx.reverse("name")` | Named routes (local + absolute) | **Default** server-side URL generation |
264
+ | Server handler | `scopedReverse<T>(ctx.reverse)` | Same, with type safety | Type-safe server URLs |
265
+ | Client component | (URL passed as prop / loader data / action return) | Named routes | Any URL derived from a named route — generate on server, pass in |
266
+ | Client component | `href("/path")` | Absolute paths (static strings) | Static navigation where no named-route lookup is needed |
267
+ | Client component | `useHref()` | Mount-prefixed paths | Local navigation inside `include()` |
268
+ | Client component | `useMount()` | Raw mount path | Custom mount-aware logic |
269
+
270
+ > `reverse()` is server-only. Client components never import or call it — they receive the already-resolved string.
195
271
 
196
272
  ## Complete example: mounted module
197
273