@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4027 -685
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4007 -687
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +51 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5291 -662
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/{context-logger.d.ts → server/context-logger.d.ts} +2 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -7
  68. package/{src → dist/server}/render/shell.ts +28 -13
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +79 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +80 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1232
  163. package/dist/render/assemble.d.ts +0 -15
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -45
  169. package/dist/router.js +0 -1671
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1120
  172. package/src/render/assemble.ts +0 -66
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -483
  176. package/src/render/loaders.ts +0 -117
  177. package/src/router.ts +0 -439
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
package/src/link.tsx DELETED
@@ -1,1120 +0,0 @@
1
- import { log } from "evlog";
2
- import type React from "react";
3
- import {
4
- createContext,
5
- createElement,
6
- useCallback,
7
- useContext,
8
- useEffect,
9
- useRef,
10
- useState,
11
- } from "react";
12
- import type { RuntimeRoute } from "./client";
13
-
14
- // ── Types ─────────────────────────────────────────────────────────────────────
15
-
16
- /**
17
- * Augment this interface via declaration merging in furin-env.d.ts
18
- * to get type-safe `to` autocompletion and per-route `search` types on <Link>.
19
- *
20
- * @example
21
- * // furin-env.d.ts (auto-generated by Furin at project root)
22
- * import "@teyik0/furin/link";
23
- * declare module "@teyik0/furin/link" {
24
- * interface RouteManifest {
25
- * "/blog": { search?: { page?: number; tag?: string } };
26
- * "/": { search?: never };
27
- * [key: `/blog/${string}`]: { search?: never };
28
- * }
29
- * }
30
- */
31
- // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
32
- export interface RouteManifest {}
33
-
34
- /**
35
- * The valid `to` pathname union derived from the augmented RouteManifest.
36
- * Falls back to `string` when furin-env.d.ts has not been generated yet.
37
- * When augmented, also includes `https://` and `http://` for external links.
38
- */
39
- export type RouteTo = keyof RouteManifest extends never
40
- ? string
41
- : keyof RouteManifest | `https://${string}` | `http://${string}`;
42
-
43
- /**
44
- * The typed search params for a given `to` pathname.
45
- * Falls back to a permissive record when RouteManifest is not augmented.
46
- */
47
- export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
48
- ? Record<string, string | number | boolean | null | undefined>
49
- : To extends keyof RouteManifest
50
- ? RouteManifest[To] extends { search?: infer S }
51
- ? S
52
- : undefined
53
- : undefined;
54
-
55
- export type PreloadStrategy = false | "intent" | "viewport" | "render";
56
-
57
- export interface LinkProps<To extends RouteTo = RouteTo>
58
- extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
59
- /**
60
- * Extra props merged onto the anchor when the link is active.
61
- * `isActive` is also passed so one function can handle both states.
62
- * Styles and classNames from `activeProps` win over the static props.
63
- */
64
- activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
65
- /** Static children or a render function receiving active state. */
66
- children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
67
- /** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
68
- disabled?: boolean;
69
- /** Optional URL fragment (without the #). */
70
- hash?: string;
71
- /**
72
- * Extra props merged onto the anchor when the link is NOT active.
73
- * Styles and classNames from `inactiveProps` win over the static props.
74
- */
75
- inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
76
- /** Preload strategy. Default: "intent" (preload on hover/focus). */
77
- preload?: PreloadStrategy;
78
- /** Delay in ms before intent preload triggers. Default: 50. */
79
- preloadDelay?: number;
80
- /** How long a preloaded entry stays fresh (ms). Default: 30_000. */
81
- preloadStaleTime?: number;
82
- /** If true, uses history.replaceState instead of pushState (no new history entry). */
83
- replace?: boolean;
84
- /**
85
- * Whether to scroll after SPA navigation. Default: true.
86
- * - If the destination href has a `#hash`, scrolls to that element.
87
- * - Otherwise scrolls to the top of the page.
88
- * Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
89
- */
90
- resetScroll?: boolean;
91
- /** Typed search params for this route. Auto-completed from the route's query schema. */
92
- search?: RouteSearch<To>;
93
- to: To;
94
- }
95
-
96
- /**
97
- * Builds a full href string from a pathname, optional search params, and optional hash.
98
- * Null/undefined search values are omitted.
99
- *
100
- * @internal Exported for unit testing only.
101
- */
102
- export function buildHref(
103
- to: string,
104
- search?: Record<string, unknown> | null,
105
- hash?: string
106
- ): string {
107
- let url = to;
108
- if (search && Object.keys(search).length > 0) {
109
- const params = new URLSearchParams();
110
- for (const [k, v] of Object.entries(search)) {
111
- if (v != null) {
112
- params.set(k, String(v));
113
- }
114
- }
115
- const qs = params.toString();
116
- if (qs) {
117
- url += `?${qs}`;
118
- }
119
- }
120
- if (hash) {
121
- url += `#${hash}`;
122
- }
123
- return url;
124
- }
125
-
126
- // ── Revalidation helpers ────────────────────────────────────────────────────────
127
-
128
- /**
129
- * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
130
- * each path entry. Header format: `"/path1,/path2:layout,/path3"`
131
- *
132
- * Intended to be called from a `window.fetch` interceptor or SPA navigation
133
- * handler so that client-side prefetch caches are busted automatically whenever
134
- * a server-side `revalidatePath()` call is made within the same request.
135
- *
136
- * @example
137
- * ```ts
138
- * const res = await fetch("/api/publish");
139
- * applyRevalidateHeader(res.headers, (path, type) => {
140
- * console.log("invalidate", path, type);
141
- * });
142
- * ```
143
- */
144
- export function applyRevalidateHeader(
145
- headers: Headers,
146
- invalidate: (path: string, type?: "page" | "layout") => void
147
- ): void {
148
- const headerValue = headers.get("x-furin-revalidate");
149
- if (!headerValue) {
150
- return;
151
- }
152
- for (const entry of headerValue.split(",")) {
153
- const trimmed = entry.trim();
154
- if (!trimmed) {
155
- continue;
156
- }
157
- if (trimmed.endsWith(":layout")) {
158
- invalidate(trimmed.slice(0, -":layout".length), "layout");
159
- } else {
160
- invalidate(trimmed, "page");
161
- }
162
- }
163
- }
164
-
165
- // ── Auto-refresh helpers ───────────────────────────────────────────────────────
166
-
167
- /**
168
- * Returns `true` when `currentPath` is targeted by at least one invalidation entry,
169
- * using the same matching rules as `invalidatePrefetch`:
170
- * - `type: 'page'` — exact pathname match (query string stripped)
171
- * - `type: 'layout'` — prefix match: the path itself OR any descendant
172
- *
173
- * @internal Exported for unit testing only.
174
- */
175
- export function shouldAutoRefreshPath(
176
- currentPath: string,
177
- invalidations: ReadonlyArray<{ path: string; type: "page" | "layout" }>
178
- ): boolean {
179
- // Strip query string for comparison — revalidatePath works on pathnames
180
- const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
181
- return invalidations.some(({ path, type }) => {
182
- if (type === "page") {
183
- return path === normalizedCurrent;
184
- }
185
- // layout: match the path itself and all descendants
186
- const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
187
- return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
188
- });
189
- }
190
-
191
- // ── Router context ─────────────────────────────────────────────────────────────
192
-
193
- export interface RouterContextValue {
194
- /**
195
- * Sub-path prefix for static deployments (e.g. "/furin").
196
- * Empty string when the site is served from root.
197
- * Used by `Link` to build correct physical hrefs for the `<a>` element.
198
- */
199
- basePath: string;
200
- /** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
201
- currentHref: string;
202
- defaultPreload: PreloadStrategy;
203
- defaultPreloadDelay: number;
204
- defaultPreloadStaleTime: number;
205
- /**
206
- * Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
207
- * made on the server. Called automatically by the `window.fetch` interceptor when
208
- * the server emits `X-Furin-Revalidate` headers.
209
- *
210
- * - `type: 'page'` (default) — exact URL match
211
- * - `type: 'layout'` — prefix match (path + all nested children)
212
- */
213
- invalidatePrefetch: (path: string, type?: "page" | "layout") => void;
214
- isNavigating: boolean;
215
- navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
216
- prefetch: (href: string, opts?: { staleTime?: number }) => void;
217
- /**
218
- * Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
219
- * loaders, and updates the rendered tree — without adding a history entry or
220
- * resetting scroll (unless `resetScroll: true` is passed).
221
- *
222
- * Prefer this over `navigate(window.location.pathname)` after a mutation.
223
- *
224
- * @example
225
- * ```tsx
226
- * const { refresh } = useRouter();
227
- * await apiClient.api.boards.post({ name });
228
- * await refresh();
229
- * ```
230
- */
231
- refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
232
- }
233
-
234
- export const RouterContext = createContext<RouterContextValue | null>(null);
235
-
236
- /**
237
- * Returns the current router context.
238
- * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
239
- */
240
- export function useRouter(): RouterContextValue {
241
- return (
242
- useContext(RouterContext) ?? {
243
- basePath: "",
244
- // Use the same "/" as SSR_FALLBACK_ROUTER so SSR and client render the
245
- // same active-state when no RouterProvider is present, avoiding hydration mismatches.
246
- currentHref: "/",
247
- navigate: (href) => {
248
- window.location.href = href;
249
- return Promise.resolve();
250
- },
251
- prefetch: () => {
252
- /* noop fallback */
253
- },
254
- invalidatePrefetch: () => {
255
- /* noop fallback */
256
- },
257
- refresh: () => {
258
- window.location.reload();
259
- return Promise.resolve();
260
- },
261
- isNavigating: false,
262
- defaultPreload: "intent",
263
- defaultPreloadDelay: 50,
264
- defaultPreloadStaleTime: 30_000,
265
- }
266
- );
267
- }
268
-
269
- // ── RouterProvider ─────────────────────────────────────────────────────────────
270
-
271
- export interface ClientRoute {
272
- component?: React.ComponentType<Record<string, unknown>>;
273
- load: () => Promise<{
274
- default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
275
- }>;
276
- pageRoute?: RuntimeRoute;
277
- pattern: string;
278
- regex: RegExp;
279
- }
280
-
281
- /**
282
- * A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
283
- * The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
284
- * on navigation via fetchPageState.
285
- */
286
- export type LoadedClientRoute = ClientRoute & {
287
- component: React.ComponentType<Record<string, unknown>>;
288
- pageRoute: RuntimeRoute;
289
- };
290
-
291
- export interface RouterProviderProps {
292
- /**
293
- * When `true` (default), the router automatically re-fetches the current page
294
- * whenever a server `revalidatePath()` call targets it. The signal is the
295
- * `X-Furin-Revalidate` header detected on any `window.fetch` response.
296
- *
297
- * Set to `false` to opt out and call `router.refresh()` manually instead.
298
- */
299
- autoRefresh?: boolean;
300
- /**
301
- * Sub-path prefix for static deployments (e.g. "/furin").
302
- * Must start with "/" and have no trailing slash.
303
- * Default: "" (site served from root).
304
- *
305
- * When set:
306
- * - `currentHref` stores **logical** paths (prefix stripped) for correct active-state detection.
307
- * - `navigate(logicalHref)` pushes `basePath + logicalHref` to browser history.
308
- * - `fetch` calls use the physical path `basePath + logicalHref`.
309
- */
310
- basePath?: string;
311
- defaultPreload?: PreloadStrategy;
312
- defaultPreloadDelay?: number;
313
- defaultPreloadStaleTime?: number;
314
- initialData: Record<string, unknown>;
315
- initialMatch: LoadedClientRoute;
316
- /** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
317
- prefetchCacheSize?: number;
318
- root: RuntimeRoute | null;
319
- routes: ClientRoute[];
320
- }
321
-
322
- interface RouterState {
323
- data: Record<string, unknown>;
324
- /** The canonical href after server-side redirects (e.g. query-default redirect). */
325
- finalHref?: string;
326
- match: LoadedClientRoute;
327
- title?: string;
328
- }
329
-
330
- /** @internal */
331
- export interface CacheEntry {
332
- createdAt: number;
333
- promise: Promise<RouterState | null>;
334
- staleTime: number;
335
- }
336
-
337
- /** @internal Exported for unit testing only. */
338
- export function shouldRefetch(entry: CacheEntry): boolean {
339
- return Date.now() - entry.createdAt > entry.staleTime;
340
- }
341
-
342
- const HASH_FRAGMENT_RE = /#.*$/;
343
-
344
- function stripHashFromHref(href: string): string {
345
- return href.replace(HASH_FRAGMENT_RE, "");
346
- }
347
-
348
- /** @internal Exported for unit testing only. */
349
- export function buildPageElement(
350
- match: LoadedClientRoute,
351
- root: RuntimeRoute | null,
352
- data: Record<string, unknown>
353
- ): React.ReactNode {
354
- let element: React.ReactNode = createElement(match.component, data);
355
-
356
- // Collect non-root layouts from the route chain (bottom-up)
357
- const allLayouts: React.ComponentType<Record<string, unknown> & { children: React.ReactNode }>[] =
358
- [];
359
- let current: RuntimeRoute | undefined = match.pageRoute;
360
- while (current) {
361
- if (current.layout) {
362
- allLayouts.unshift(current.layout);
363
- }
364
- current = current.parent;
365
- }
366
-
367
- // If a root layout exists, the first entry in allLayouts IS the root — skip it here
368
- const layouts = root ? allLayouts.slice(1) : allLayouts;
369
-
370
- for (let i = layouts.length - 1; i >= 0; i--) {
371
- const Layout = layouts[i];
372
- if (Layout) {
373
- // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
374
- element = createElement(Layout, { ...data } as any, element);
375
- }
376
- }
377
-
378
- if (root?.layout) {
379
- // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
380
- element = createElement(root.layout, { ...data } as any, element);
381
- }
382
-
383
- return element;
384
- }
385
-
386
- /** Scrolls to a hash target or the top of the page after SPA navigation. */
387
- function handleScrollRestoration(
388
- href: string,
389
- navigationToken: number,
390
- navVersion: { current: number }
391
- ): void {
392
- const destUrl = new URL(href, window.location.origin);
393
- if (destUrl.hash) {
394
- const id = decodeURIComponent(destUrl.hash.slice(1));
395
- const scrollToHashTarget = () => {
396
- if (navVersion.current !== navigationToken) {
397
- return;
398
- }
399
-
400
- const element = document.getElementById(id);
401
- if (element) {
402
- element.scrollIntoView({ behavior: "instant", block: "start" });
403
- }
404
- };
405
-
406
- window.requestAnimationFrame(() => {
407
- scrollToHashTarget();
408
- if (document.getElementById(id)) {
409
- return;
410
- }
411
-
412
- window.requestAnimationFrame(() => {
413
- scrollToHashTarget();
414
- });
415
- });
416
- } else {
417
- window.scrollTo({ top: 0, behavior: "instant" });
418
- }
419
- }
420
-
421
- // ── Scroll restoration helpers ─────────────────────────────────────────────────
422
-
423
- const SCROLL_STORAGE_KEY = "__furin_scroll__";
424
-
425
- function getHistoryKey(state: unknown): string | undefined {
426
- return (state as { _furinKey?: string } | null)?._furinKey;
427
- }
428
-
429
- function generateHistoryKey(): string {
430
- return Math.random().toString(36).slice(2, 9);
431
- }
432
-
433
- function saveScrollPosition(key: string): void {
434
- try {
435
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
436
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
437
- positions[key] = window.scrollY;
438
- const keys = Object.keys(positions);
439
- if (keys.length > 50) {
440
- delete positions[keys[0] as string];
441
- }
442
- sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
443
- } catch {
444
- // sessionStorage unavailable (private mode, quota exceeded, etc.)
445
- }
446
- }
447
-
448
- function restoreScrollPosition(key: string, token: number, version: { current: number }): void {
449
- try {
450
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
451
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
452
- const y = positions[key] ?? 0;
453
- window.requestAnimationFrame(() => {
454
- window.requestAnimationFrame(() => {
455
- if (version.current !== token) {
456
- return;
457
- }
458
- window.scrollTo({ top: y, behavior: "instant" });
459
- });
460
- });
461
- } catch {
462
- window.scrollTo({ top: 0, behavior: "instant" });
463
- }
464
- }
465
-
466
- // ── Path helpers ───────────────────────────────────────────────────────────────
467
-
468
- /** Strips basePath prefix from a physical pathname, returning the logical path. */
469
- function toLogical(physicalPathname: string, basePath: string): string {
470
- if (
471
- basePath &&
472
- physicalPathname.startsWith(basePath) &&
473
- // Require a path boundary after the prefix so "/furin" doesn't match "/furinity/foo"
474
- (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")
475
- ) {
476
- return physicalPathname.slice(basePath.length) || "/";
477
- }
478
- return physicalPathname;
479
- }
480
-
481
- export function RouterProvider({
482
- routes,
483
- root,
484
- initialMatch,
485
- initialData,
486
- autoRefresh = true,
487
- basePath = "",
488
- defaultPreload = "intent",
489
- defaultPreloadDelay = 50,
490
- defaultPreloadStaleTime = 30_000,
491
- prefetchCacheSize = 50,
492
- }: RouterProviderProps): React.ReactElement {
493
- const [state, setState] = useState<RouterState>({
494
- match: initialMatch,
495
- data: initialData,
496
- });
497
- const [isNavigating, setIsNavigating] = useState(false);
498
- // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
499
- // detection works with route patterns that never include the basePath prefix.
500
- const [currentHref, setCurrentHref] = useState<string>(() => {
501
- if (typeof window === "undefined") {
502
- return "/";
503
- }
504
- return toLogical(window.location.pathname, basePath) + window.location.search;
505
- });
506
- const prefetchCache = useRef(new Map<string, CacheEntry>());
507
- /** Monotonic counter to discard stale navigations (race condition guard). */
508
- const navVersion = useRef(0);
509
-
510
- const fetchPageState = useCallback(
511
- async (logicalHref: string): Promise<RouterState | null> => {
512
- try {
513
- // Physical href: what the browser/server actually receives.
514
- // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
515
- const physicalHref = basePath + logicalHref;
516
- const url = new URL(physicalHref, window.location.origin);
517
- // Route matching always uses the LOGICAL pathname (basePath stripped).
518
- const logicalPathname = toLogical(url.pathname, basePath);
519
- const match = routes.find((r) => r.regex.test(logicalPathname));
520
- if (!match) {
521
- return null;
522
- }
523
-
524
- // Parallelize HTML data fetch + JS chunk load for this route.
525
- // The browser module cache makes match.load() near-instant for already-loaded pages.
526
- const [res, loadedMod] = await Promise.all([fetch(physicalHref), match.load()]);
527
-
528
- // Stale-deploy detection: if the server reports a different buildId, the client
529
- // bundle is outdated and SPA navigation would mount wrong components / stale code.
530
- // Force a full page reload to pick up the new bundle.
531
- const serverBuildId = res.headers.get("x-furin-build-id");
532
- if (serverBuildId) {
533
- const metaEl =
534
- typeof document === "undefined"
535
- ? null
536
- : document.querySelector<HTMLMetaElement>('meta[name="furin-build-id"]');
537
- const clientBuildId = metaEl?.content;
538
- if (clientBuildId && serverBuildId !== clientBuildId) {
539
- window.location.href = physicalHref;
540
- return null;
541
- }
542
- }
543
-
544
- // Server error — bail out so we don't render with incomplete/missing data.
545
- // The `navigate` fallback will do a full-page load to show the proper error page.
546
- if (!res.ok) {
547
- log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
548
- return null;
549
- }
550
-
551
- // Detect server-side redirects (e.g. query-default redirect /?→/?city=Paris).
552
- // fetch() follows 302 automatically; res.url is the final URL, res.redirected is true.
553
- // Detect server-side redirects (e.g. query-default redirect /?→/?city=Paris).
554
- // Convert the physical redirect URL back to a logical href (basePath stripped).
555
- let finalHref: string | undefined;
556
- if (res.redirected) {
557
- const final = new URL(res.url);
558
- finalHref = toLogical(final.pathname, basePath) + final.search;
559
- }
560
-
561
- const html = await res.text();
562
- const doc = new DOMParser().parseFromString(html, "text/html");
563
-
564
- const dataEl = doc.getElementById("__FURIN_DATA__");
565
- const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
566
-
567
- const loadedMatch: LoadedClientRoute = {
568
- ...match,
569
- component: loadedMod.default.component,
570
- pageRoute: loadedMod.default._route,
571
- };
572
-
573
- return { match: loadedMatch, data, title: doc.title, finalHref };
574
- } catch (err: unknown) {
575
- log.error({ action: "navigate_failed", href: basePath + logicalHref, error: String(err) });
576
- return null;
577
- }
578
- },
579
- [routes, basePath]
580
- );
581
-
582
- const invalidatePrefetch = useCallback((path: string, type: "page" | "layout" = "page") => {
583
- const normalizedPath = stripHashFromHref(path);
584
-
585
- if (type === "page") {
586
- for (const key of [...prefetchCache.current.keys()]) {
587
- if (stripHashFromHref(key) === normalizedPath) {
588
- prefetchCache.current.delete(key);
589
- }
590
- }
591
- return;
592
- }
593
-
594
- // layout: prefix match — evict the path itself and all nested children
595
- const prefix =
596
- normalizedPath === "/" || normalizedPath.endsWith("/")
597
- ? normalizedPath
598
- : `${normalizedPath}/`;
599
- for (const key of [...prefetchCache.current.keys()]) {
600
- const normalizedKey = stripHashFromHref(key);
601
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
602
- prefetchCache.current.delete(key);
603
- }
604
- }
605
- }, []);
606
-
607
- const prefetch = useCallback(
608
- (href: string, opts?: { staleTime?: number }) => {
609
- const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
610
- const existing = prefetchCache.current.get(href);
611
- if (existing && !shouldRefetch(existing)) {
612
- return;
613
- }
614
- prefetchCache.current.set(href, {
615
- promise: fetchPageState(href),
616
- createdAt: Date.now(),
617
- staleTime,
618
- });
619
- // Evict the oldest entry when the cap is exceeded
620
- if (prefetchCache.current.size > prefetchCacheSize) {
621
- const oldest = prefetchCache.current.keys().next().value as string;
622
- prefetchCache.current.delete(oldest);
623
- }
624
- },
625
- [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
626
- );
627
-
628
- const navigate = useCallback(
629
- async (logicalHref: string, opts?: { replace?: boolean; resetScroll?: boolean }) => {
630
- // logicalHref is the route-relative path (no basePath).
631
- // The prefetch cache is keyed by logical hrefs.
632
- prefetch(logicalHref);
633
- const myVersion = ++navVersion.current;
634
- setIsNavigating(true);
635
- try {
636
- const newState = await prefetchCache.current.get(logicalHref)?.promise;
637
- // Discard if a newer navigation was started while we were waiting
638
- if (navVersion.current !== myVersion) {
639
- return;
640
- }
641
- if (!newState) {
642
- log.warn({
643
- action: "navigate_fallback",
644
- href: logicalHref,
645
- reason: "prefetch_returned_null",
646
- });
647
- // Fall back to full-page navigation using the physical URL.
648
- window.location.href = basePath + logicalHref;
649
- return;
650
- }
651
- setState(newState);
652
- if (newState.title) {
653
- document.title = newState.title;
654
- }
655
- // effectiveHref is logical (finalHref from fetchPageState is also logical).
656
- const effectiveLogical = newState.finalHref ?? logicalHref;
657
- // Push the PHYSICAL path to browser history.
658
- const physicalEffective = basePath + effectiveLogical;
659
- if (opts?.replace) {
660
- // Preserve the existing key — same history entry, URL just updated.
661
- window.history.replaceState(
662
- {
663
- ...((history.state as object) ?? {}),
664
- _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
665
- },
666
- "",
667
- physicalEffective
668
- );
669
- } else {
670
- // Save current position before leaving, then push a fresh entry.
671
- const currentKey = getHistoryKey(history.state);
672
- if (currentKey) {
673
- saveScrollPosition(currentKey);
674
- }
675
- window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
676
- }
677
- // Store the LOGICAL path in currentHref so Link active-state works.
678
- const effectiveUrl = new URL(physicalEffective, window.location.origin);
679
- const logicalPath = toLogical(effectiveUrl.pathname, basePath);
680
- setCurrentHref(logicalPath + effectiveUrl.search);
681
- if (opts?.resetScroll ?? true) {
682
- handleScrollRestoration(physicalEffective, myVersion, navVersion);
683
- }
684
- } finally {
685
- // Only clear navigating flag if this is still the latest navigation
686
- if (navVersion.current === myVersion) {
687
- setIsNavigating(false);
688
- }
689
- }
690
- },
691
- [prefetch, basePath]
692
- );
693
-
694
- const refresh = useCallback(
695
- async (opts?: { resetScroll?: boolean }) => {
696
- // Convert the physical browser URL to a logical href before navigating.
697
- const logicalPath = toLogical(window.location.pathname, basePath);
698
- const logicalHref = logicalPath + window.location.search;
699
- // Bust the cache for this exact logical page so navigate always re-fetches
700
- invalidatePrefetch(logicalHref, "page");
701
- await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
702
- },
703
- [navigate, invalidatePrefetch, basePath]
704
- );
705
-
706
- const handlePopState = useCallback(async () => {
707
- // Capture the destination key immediately — history.state is already the
708
- // destination entry when popstate fires, before any awaits.
709
- const destKey = getHistoryKey(history.state);
710
- // Convert physical browser URL to logical href for cache lookup + fetchPageState.
711
- const logicalPath = toLogical(window.location.pathname, basePath);
712
- const logicalHref = logicalPath + window.location.search;
713
- const myVersion = ++navVersion.current;
714
- setIsNavigating(true);
715
- try {
716
- // Check prefetch cache before fetching fresh (keyed by logical href)
717
- const cached = prefetchCache.current.get(logicalHref);
718
- let newState: RouterState | null;
719
- if (cached && !shouldRefetch(cached)) {
720
- newState = await cached.promise;
721
- } else {
722
- newState = await fetchPageState(logicalHref);
723
- }
724
- // Discard if a newer navigation was started while we were waiting
725
- if (navVersion.current !== myVersion) {
726
- return;
727
- }
728
- if (!newState) {
729
- log.warn({
730
- action: "popstate_fallback",
731
- href: logicalHref,
732
- reason: "fetchPageState_returned_null",
733
- });
734
- window.location.reload();
735
- return;
736
- }
737
- setState(newState);
738
- if (newState.title) {
739
- document.title = newState.title;
740
- }
741
- // effectiveHref is logical (includes search); push physical to history if server redirected.
742
- const effectiveLogical = newState.finalHref ?? logicalHref;
743
- if (newState.finalHref) {
744
- // Preserve _furinKey so restoreScrollPosition still works after a redirect.
745
- window.history.replaceState(history.state, "", basePath + effectiveLogical);
746
- }
747
- // effectiveLogical already contains the search params — no URL round-trip needed.
748
- setCurrentHref(effectiveLogical);
749
- // Restore the saved scroll position for this history entry (double rAF waits
750
- // for React to finish painting the new page before scrolling).
751
- if (destKey) {
752
- restoreScrollPosition(destKey, myVersion, navVersion);
753
- } else {
754
- window.scrollTo({ top: 0, behavior: "instant" });
755
- }
756
- } finally {
757
- if (navVersion.current === myVersion) {
758
- setIsNavigating(false);
759
- }
760
- }
761
- }, [fetchPageState, basePath]);
762
-
763
- // Disable native scroll restoration and assign a key to the initial history entry
764
- useEffect(() => {
765
- const prevScrollRestoration = history.scrollRestoration;
766
- history.scrollRestoration = "manual";
767
- if (!getHistoryKey(history.state)) {
768
- history.replaceState(
769
- { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
770
- ""
771
- );
772
- }
773
- return () => {
774
- history.scrollRestoration = prevScrollRestoration;
775
- };
776
- }, []);
777
-
778
- // Handle browser back/forward
779
- useEffect(() => {
780
- window.addEventListener("popstate", handlePopState);
781
- return () => window.removeEventListener("popstate", handlePopState);
782
- }, [handlePopState]);
783
-
784
- // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
785
- // This ensures that API routes calling revalidatePath() automatically bust the
786
- // client prefetch cache, even for non-navigation fetches (e.g. form submissions).
787
- // When autoRefresh=true (default), also re-fetches the current page if it was invalidated.
788
- useEffect(() => {
789
- if (typeof window === "undefined") {
790
- return;
791
- }
792
- const originalFetch = window.fetch;
793
- const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
794
- const response = await originalFetch.apply(window, args);
795
- const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
796
- applyRevalidateHeader(response.headers, (path, type = "page") => {
797
- invalidatePrefetch(path, type);
798
- invalidated.push({ path, type });
799
- });
800
- if (autoRefresh && invalidated.length > 0) {
801
- const currentPath = window.location.pathname + window.location.search;
802
- if (shouldAutoRefreshPath(currentPath, invalidated)) {
803
- // fire-and-forget: don't block the original fetch caller
804
- refresh();
805
- }
806
- }
807
- return response;
808
- };
809
- // Copy static fetch methods (e.g. preconnect) so the patched value satisfies typeof fetch.
810
- Object.assign(wrapped, originalFetch);
811
- // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
812
- window.fetch = wrapped as any;
813
- return () => {
814
- window.fetch = originalFetch;
815
- };
816
- }, [invalidatePrefetch, refresh, autoRefresh]);
817
-
818
- return createElement(
819
- RouterContext.Provider,
820
- {
821
- value: {
822
- basePath,
823
- currentHref,
824
- navigate,
825
- prefetch,
826
- refresh,
827
- invalidatePrefetch,
828
- isNavigating,
829
- defaultPreload,
830
- defaultPreloadDelay,
831
- defaultPreloadStaleTime,
832
- },
833
- },
834
- buildPageElement(state.match, root, state.data)
835
- ) as React.ReactElement;
836
- }
837
-
838
- // ── Link ───────────────────────────────────────────────────────────────────────
839
-
840
- interface LinkView {
841
- extraProps: React.AnchorHTMLAttributes<HTMLAnchorElement>;
842
- href: string;
843
- isActive: boolean;
844
- logicalHref: string;
845
- resolvedChildren: React.ReactNode;
846
- }
847
-
848
- /**
849
- * Shared href/active-state/props computation used by both LinkInteractive (CSR)
850
- * and renderLinkElement (SSR). Centralising this keeps the two render paths in sync.
851
- */
852
- function computeLinkView<To extends RouteTo>(
853
- {
854
- to,
855
- search,
856
- hash,
857
- children,
858
- activeProps,
859
- inactiveProps,
860
- }: Pick<LinkProps<To>, "to" | "search" | "hash" | "children" | "activeProps" | "inactiveProps">,
861
- router: RouterContextValue
862
- ): LinkView {
863
- const logicalHref = buildHref(
864
- to as string,
865
- search as Record<string, unknown> | null | undefined,
866
- hash
867
- );
868
- const logicalHrefWithoutHash = buildHref(
869
- to as string,
870
- search as Record<string, unknown> | null | undefined,
871
- undefined
872
- );
873
- const href = router.basePath + logicalHref;
874
- const isActive = router.currentHref === logicalHrefWithoutHash;
875
- const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
876
- const extraProps: React.AnchorHTMLAttributes<HTMLAnchorElement> = {
877
- ...(inactiveProps && !isActive ? inactiveProps() : {}),
878
- ...(activeProps ? activeProps({ isActive }) : {}),
879
- };
880
- return { logicalHref, href, isActive, resolvedChildren, extraProps };
881
- }
882
-
883
- /**
884
- * Full interactive Link — only rendered on the client where hooks are safe.
885
- * Never rendered during SSR so it's immune to duplicate-React-instance issues
886
- * that can arise when page modules are loaded via the furin-dev-page virtual
887
- * namespace (Bun HMR).
888
- */
889
- function LinkInteractive<To extends RouteTo>({
890
- to,
891
- search,
892
- hash,
893
- preload,
894
- preloadDelay,
895
- preloadStaleTime,
896
- replace,
897
- disabled,
898
- resetScroll,
899
- activeProps,
900
- inactiveProps,
901
- onClick,
902
- onMouseEnter,
903
- onMouseLeave,
904
- onFocus,
905
- children,
906
- ...anchorProps
907
- }: LinkProps<To>): React.ReactElement {
908
- const router = useRouter();
909
- const anchorRef = useRef<HTMLAnchorElement>(null);
910
- const intentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
911
-
912
- // logicalHref: route-relative path (no basePath), used for navigation + active state.
913
- // physicalHref (href): what the browser sees — basePath + logicalHref.
914
- const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView(
915
- { to, search, hash, children, activeProps, inactiveProps },
916
- router
917
- );
918
-
919
- const effectivePreload = preload ?? router.defaultPreload;
920
- const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
921
- const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
922
-
923
- const triggerPrefetch = useCallback(() => {
924
- // prefetch() expects the logical href (no basePath prefix).
925
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
926
- }, [router, logicalHref, effectiveStaleTime]);
927
-
928
- // "render": preload immediately on mount
929
- useEffect(() => {
930
- if (effectivePreload === "render") {
931
- triggerPrefetch();
932
- }
933
- }, [effectivePreload, triggerPrefetch]);
934
-
935
- // "viewport": preload when link enters viewport
936
- useEffect(() => {
937
- if (effectivePreload !== "viewport" || !anchorRef.current) {
938
- return;
939
- }
940
- const observer = new IntersectionObserver(
941
- ([entry]) => {
942
- if (entry?.isIntersecting) {
943
- triggerPrefetch();
944
- observer.disconnect();
945
- }
946
- },
947
- { rootMargin: "200px" }
948
- );
949
- observer.observe(anchorRef.current);
950
- return () => observer.disconnect();
951
- }, [effectivePreload, triggerPrefetch]);
952
-
953
- const isInternal = (url: string): boolean => {
954
- try {
955
- return new URL(url, window.location.origin).origin === window.location.origin;
956
- } catch {
957
- return false;
958
- }
959
- };
960
-
961
- const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
962
- onClick?.(e);
963
- if (e.defaultPrevented || disabled) {
964
- return;
965
- }
966
- // Let browser handle modifier+click (new tab, etc.)
967
- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
968
- return;
969
- }
970
- // Let browser handle non-self targets (e.g. target="_blank")
971
- if (anchorProps.target && anchorProps.target !== "_self") {
972
- return;
973
- }
974
- // Let browser handle external links
975
- if (!isInternal(href)) {
976
- return;
977
- }
978
- e.preventDefault();
979
- // navigate() expects the logical href (no basePath prefix).
980
- router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
981
- };
982
-
983
- const handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
984
- onMouseEnter?.(e);
985
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
986
- intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
987
- }
988
- };
989
-
990
- const handleMouseLeave = (e: React.MouseEvent<HTMLAnchorElement>) => {
991
- onMouseLeave?.(e);
992
- if (intentTimerRef.current !== null) {
993
- clearTimeout(intentTimerRef.current);
994
- intentTimerRef.current = null;
995
- }
996
- };
997
-
998
- const handleFocus = (e: React.FocusEvent<HTMLAnchorElement>) => {
999
- onFocus?.(e);
1000
- if (!disabled && effectivePreload === "intent" && isInternal(href)) {
1001
- triggerPrefetch();
1002
- }
1003
- };
1004
-
1005
- return createElement(
1006
- "a",
1007
- {
1008
- ref: anchorRef,
1009
- href,
1010
- onClick: handleClick,
1011
- onMouseEnter: handleMouseEnter,
1012
- onMouseLeave: handleMouseLeave,
1013
- onFocus: handleFocus,
1014
- ...(isActive ? { "data-status": "active" } : {}),
1015
- ...anchorProps,
1016
- ...extraProps,
1017
- ...(disabled ? { "aria-disabled": true } : {}),
1018
- },
1019
- resolvedChildren
1020
- );
1021
- }
1022
-
1023
- // ── SSR fallback router ────────────────────────────────────────────────────────
1024
-
1025
- /**
1026
- * Static fallback used by Link during SSR when there is no RouterProvider.
1027
- * Must not reference `window` — this object is created at module parse time.
1028
- */
1029
- const SSR_FALLBACK_ROUTER: RouterContextValue = {
1030
- basePath: "",
1031
- currentHref: "/",
1032
- navigate: () => Promise.resolve(),
1033
- prefetch: () => {
1034
- /* noop */
1035
- },
1036
- invalidatePrefetch: () => {
1037
- /* noop */
1038
- },
1039
- refresh: () => Promise.resolve(),
1040
- isNavigating: false,
1041
- defaultPreload: "intent",
1042
- defaultPreloadDelay: 50,
1043
- defaultPreloadStaleTime: 30_000,
1044
- };
1045
-
1046
- /**
1047
- * Pure render helper — no hooks, safe to call from any context including SSR.
1048
- * Computes href, active state, and applies activeProps / inactiveProps before
1049
- * returning the final `<a>` element.
1050
- */
1051
- function renderLinkElement<To extends RouteTo>(
1052
- props: LinkProps<To>,
1053
- router: RouterContextValue
1054
- ): React.ReactElement {
1055
- const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
1056
-
1057
- // Destructure to strip Link-specific and client-only props before spreading onto <a>.
1058
- const {
1059
- to: _to,
1060
- search: _search,
1061
- hash: _hash,
1062
- children: _children,
1063
- activeProps: _ap,
1064
- inactiveProps: _ip,
1065
- disabled,
1066
- preload: _p,
1067
- preloadDelay: _pd,
1068
- preloadStaleTime: _ps,
1069
- replace: _r,
1070
- resetScroll: _rs,
1071
- onClick: _oc,
1072
- onMouseEnter: _ome,
1073
- onMouseLeave: _oml,
1074
- onFocus: _of,
1075
- ...anchorProps
1076
- } = props;
1077
-
1078
- return createElement(
1079
- "a",
1080
- {
1081
- href,
1082
- ...(isActive ? { "data-status": "active" } : {}),
1083
- ...anchorProps,
1084
- ...extraProps,
1085
- ...(disabled ? { "aria-disabled": true } : {}),
1086
- },
1087
- resolvedChildren
1088
- );
1089
- }
1090
-
1091
- /**
1092
- * SSR-aware Link component.
1093
- *
1094
- * - **Server (SSR):** uses `RouterContext.Consumer` (a render-prop, not a hook)
1095
- * to read basePath / currentHref from any enclosing RouterProvider, then
1096
- * falls back to `SSR_FALLBACK_ROUTER` when no provider is present.
1097
- * `Context.Consumer` bypasses `ReactCurrentDispatcher` entirely, so it is
1098
- * safe even when two React instances coexist in the module graph (Bun HMR).
1099
- * - **Client:** delegates to `LinkInteractive` which adds preloading, SPA
1100
- * navigation, active-state tracking and all other interactive features.
1101
- */
1102
- export function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactElement {
1103
- if (typeof window === "undefined") {
1104
- // Use Context.Consumer instead of useContext — the Consumer is processed
1105
- // by react-dom/server directly (no dispatcher lookup), so it works even
1106
- // when link.tsx is loaded under a second React instance via the
1107
- // furin-dev-page virtual namespace after a Bun HMR reload.
1108
- return createElement(RouterContext.Consumer, {
1109
- // biome-ignore lint/correctness/noChildrenProp: render-prop pattern requires children-as-function
1110
- children: (routerCtx: RouterContextValue | null) =>
1111
- renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER),
1112
- });
1113
- }
1114
-
1115
- // ── Client rendering ──────────────────────────────────────────────────────
1116
- return createElement(
1117
- LinkInteractive as React.ComponentType<LinkProps<RouteTo>>,
1118
- props as LinkProps<RouteTo>
1119
- );
1120
- }