@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
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Built-in fallback UIs for the framework's default 404 and 500 pages.
3
+ *
4
+ * Design constraints:
5
+ * 1. INLINE STYLES ONLY. We can't assume the user has Tailwind / a CSS
6
+ * reset / any stylesheet at all — the page must look identical whether
7
+ * this renders before or after the user's stylesheets.
8
+ * 2. ZERO RUNTIME DEPENDENCIES. These render server-side as static HTML and
9
+ * hydrate without needing any JS to look right. Only the "Try again"
10
+ * button needs hydration to function (it falls back to a no-op on SSR).
11
+ * 3. NO EXTERNAL FONTS. Use the system monospace + sans stacks so the
12
+ * typography is consistent without a network round-trip.
13
+ *
14
+ * Visual language: terminal/dev-tool aesthetic — black background, faint
15
+ * grid, monospace for technical bits, no chrome. Hierarchy is carried by
16
+ * typography + spacing alone so the screen feels at-home in any project
17
+ * regardless of brand.
18
+ */
19
+ import type { CSSProperties, ReactNode } from "react";
20
+ import type { ErrorComponent } from "../shared/error.ts";
21
+ import type { NotFoundComponent } from "../shared/not-found.ts";
22
+ import { Link } from "./link.tsx";
23
+
24
+ const FONT_SANS =
25
+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
26
+ const FONT_MONO =
27
+ 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
28
+
29
+ const COLOR_BG = "#000000";
30
+ const COLOR_TEXT = "#ffffff";
31
+ const COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)";
32
+ const COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)";
33
+ const COLOR_GRID = "rgba(255, 255, 255, 0.04)";
34
+ const COLOR_BRACKET = "rgba(255, 255, 255, 0.55)";
35
+ const COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)";
36
+
37
+ const PAGE_STYLE: CSSProperties = {
38
+ alignItems: "center",
39
+ backgroundColor: COLOR_BG,
40
+ // Faint grid: two repeating gradients crossed for the lattice look.
41
+ backgroundImage: `
42
+ linear-gradient(${COLOR_GRID} 1px, transparent 1px),
43
+ linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
44
+ `,
45
+ backgroundSize: "32px 32px, 32px 32px",
46
+ boxSizing: "border-box",
47
+ color: COLOR_TEXT,
48
+ display: "flex",
49
+ fontFamily: FONT_SANS,
50
+ fontSize: "16px",
51
+ justifyContent: "center",
52
+ lineHeight: 1.5,
53
+ margin: 0,
54
+ minHeight: "100vh",
55
+ padding: "32px",
56
+ width: "100%",
57
+ };
58
+
59
+ const FRAME_STYLE: CSSProperties = {
60
+ boxSizing: "border-box",
61
+ maxWidth: "880px",
62
+ position: "relative",
63
+ width: "100%",
64
+ };
65
+
66
+ const BRACKET_BASE: CSSProperties = {
67
+ height: "40px",
68
+ position: "absolute",
69
+ width: "40px",
70
+ };
71
+
72
+ function CornerBracket({ corner }: { corner: "tl" | "tr" | "bl" | "br" }) {
73
+ // L-shaped bracket built from two 2px borders on the inside corners.
74
+ const top = corner === "tl" || corner === "tr";
75
+ const left = corner === "tl" || corner === "bl";
76
+ const style: CSSProperties = {
77
+ ...BRACKET_BASE,
78
+ [top ? "top" : "bottom"]: 0,
79
+ [left ? "left" : "right"]: 0,
80
+ [`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
81
+ [`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`,
82
+ };
83
+ return <span aria-hidden="true" style={style} />;
84
+ }
85
+
86
+ const CARD_STYLE: CSSProperties = {
87
+ boxSizing: "border-box",
88
+ margin: "0 auto",
89
+ maxWidth: "640px",
90
+ padding: "64px 24px",
91
+ textAlign: "center",
92
+ };
93
+
94
+ // Borders are deliberately absent on every element except the danger-coloured
95
+ // error badge. The visual hierarchy is carried by typography + spacing alone.
96
+
97
+ const BADGE_STYLE: CSSProperties = {
98
+ border: `1px solid ${COLOR_DANGER_DIM}`,
99
+ color: COLOR_TEXT,
100
+ display: "inline-block",
101
+ fontFamily: FONT_SANS,
102
+ fontSize: "32px",
103
+ fontWeight: 600,
104
+ letterSpacing: "0.08em",
105
+ marginBottom: "16px",
106
+ padding: "12px 36px",
107
+ };
108
+
109
+ const HEADING_STYLE: CSSProperties = {
110
+ color: COLOR_TEXT,
111
+ fontFamily: FONT_SANS,
112
+ fontSize: "24px",
113
+ fontWeight: 600,
114
+ margin: "0 0 24px 0",
115
+ };
116
+
117
+ const CODE_BOX_STYLE: CSSProperties = {
118
+ color: COLOR_TEXT_DIM,
119
+ display: "inline-block",
120
+ fontFamily: FONT_MONO,
121
+ fontSize: "13px",
122
+ letterSpacing: "0.02em",
123
+ margin: "0 0 32px 0",
124
+ padding: "8px 0",
125
+ };
126
+
127
+ const CODE_LABEL_STYLE: CSSProperties = {
128
+ color: COLOR_TEXT_MUTED,
129
+ marginRight: "10px",
130
+ textTransform: "uppercase",
131
+ };
132
+
133
+ const DESCRIPTION_WRAPPER_STYLE: CSSProperties = {
134
+ color: COLOR_TEXT_DIM,
135
+ fontSize: "15px",
136
+ margin: "0 auto 40px auto",
137
+ maxWidth: "440px",
138
+ padding: 0,
139
+ textAlign: "center",
140
+ };
141
+
142
+ const ACTIONS_STYLE: CSSProperties = {
143
+ display: "flex",
144
+ flexWrap: "wrap",
145
+ gap: "16px",
146
+ justifyContent: "center",
147
+ };
148
+
149
+ const BUTTON_BASE: CSSProperties = {
150
+ border: 0,
151
+ cursor: "pointer",
152
+ display: "inline-flex",
153
+ fontFamily: FONT_SANS,
154
+ fontSize: "14px",
155
+ fontWeight: 500,
156
+ lineHeight: 1,
157
+ minWidth: "120px",
158
+ padding: "10px 16px",
159
+ textAlign: "center",
160
+ textDecoration: "none",
161
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
162
+ appearance: "none",
163
+ alignItems: "center",
164
+ justifyContent: "center",
165
+ boxSizing: "border-box",
166
+ };
167
+
168
+ // Outlined buttons: thin neutral border, no fill — discreet enough to blend
169
+ // with the dark canvas while still reading as a clickable affordance.
170
+ const BUTTON_PRIMARY: CSSProperties = {
171
+ ...BUTTON_BASE,
172
+ backgroundColor: COLOR_TEXT,
173
+ border: `1px solid ${COLOR_TEXT}`,
174
+ boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
175
+ color: COLOR_BG,
176
+ fontWeight: 600,
177
+ };
178
+
179
+ const BUTTON_SECONDARY: CSSProperties = {
180
+ ...BUTTON_BASE,
181
+ backgroundColor: "transparent",
182
+ border: "1px solid rgba(255, 255, 255, 0.22)",
183
+ color: COLOR_TEXT_DIM,
184
+ };
185
+
186
+ // Hairline rule under the badge — the only neutral chrome line we keep, just
187
+ // to anchor the badge visually without competing with it.
188
+ const DIVIDER_STYLE: CSSProperties = {
189
+ backgroundColor: "rgba(255, 255, 255, 0.12)",
190
+ border: 0,
191
+ height: "1px",
192
+ margin: "0 0 40px 0",
193
+ width: "100%",
194
+ };
195
+
196
+ interface ScreenFrameProps {
197
+ badge: ReactNode;
198
+ children: ReactNode;
199
+ }
200
+
201
+ /**
202
+ * Reset the host page's chrome so the dark background covers the entire
203
+ * viewport — including the area behind the scrollbar and the default 8px
204
+ * margin browsers apply to <body>. We can't do this with inline styles
205
+ * alone (they only target the element they're on, not html/body), and we
206
+ * can't ship a CSS file (the user might not have Tailwind / a bundler
207
+ * step). React 19 hoists <style> nodes to <head> automatically, so this
208
+ * works in both SSR and hydration without a flash of white chrome.
209
+ *
210
+ * `overscroll-behavior: none` also prevents the white "bounce" area on
211
+ * macOS Safari / Chrome when scrolling past the viewport edges.
212
+ */
213
+ const RESET_CSS = `
214
+ html, body {
215
+ margin: 0;
216
+ padding: 0;
217
+ background-color: ${COLOR_BG};
218
+ overscroll-behavior: none;
219
+ }
220
+ `;
221
+
222
+ function ScreenFrame({ badge, children }: ScreenFrameProps) {
223
+ return (
224
+ <div style={PAGE_STYLE}>
225
+ <style>{RESET_CSS}</style>
226
+ <div style={FRAME_STYLE}>
227
+ <CornerBracket corner="tl" />
228
+ <CornerBracket corner="tr" />
229
+ <CornerBracket corner="bl" />
230
+ <CornerBracket corner="br" />
231
+ <div style={CARD_STYLE}>
232
+ {badge}
233
+ <hr style={DIVIDER_STYLE} />
234
+ {children}
235
+ </div>
236
+ </div>
237
+ </div>
238
+ );
239
+ }
240
+
241
+ interface DefaultErrorScreenProps {
242
+ digest: string;
243
+ message: string;
244
+ reset: () => void;
245
+ }
246
+
247
+ export function DefaultErrorScreen({ message, digest, reset }: DefaultErrorScreenProps) {
248
+ return (
249
+ // react-doctor-disable-next-line react-doctor/design-no-em-dash-in-jsx-text
250
+ <ScreenFrame badge={<div style={BADGE_STYLE}>500 — ERROR</div>}>
251
+ <h1 style={HEADING_STYLE}>Something went wrong</h1>
252
+ <div style={CODE_BOX_STYLE}>
253
+ <span style={CODE_LABEL_STYLE}>CODE:</span>
254
+ <span>{digest}</span>
255
+ </div>
256
+ <p style={DESCRIPTION_WRAPPER_STYLE}>
257
+ {message
258
+ ? message
259
+ : "We encountered an unexpected error. Please try again or return to the home page."}
260
+ </p>
261
+ <div style={ACTIONS_STYLE}>
262
+ <Link style={BUTTON_PRIMARY} to="/">
263
+ Go Home
264
+ </Link>
265
+ <button onClick={reset} style={BUTTON_SECONDARY} type="button">
266
+ Try again
267
+ </button>
268
+ </div>
269
+ </ScreenFrame>
270
+ );
271
+ }
272
+
273
+ interface DefaultNotFoundScreenProps {
274
+ message: string | undefined;
275
+ }
276
+
277
+ export function DefaultNotFoundScreen({ message }: DefaultNotFoundScreenProps) {
278
+ return (
279
+ // react-doctor-disable-next-line react-doctor/design-no-em-dash-in-jsx-text
280
+ <ScreenFrame badge={<div style={BADGE_STYLE}>404 — NOT FOUND</div>}>
281
+ <h1 style={HEADING_STYLE}>This page does not exist</h1>
282
+ <p style={DESCRIPTION_WRAPPER_STYLE}>
283
+ {message
284
+ ? message
285
+ : "The page you are looking for could not be found. It may have been moved or removed."}
286
+ </p>
287
+ <div style={ACTIONS_STYLE}>
288
+ <Link style={BUTTON_PRIMARY} to="/">
289
+ Go Home
290
+ </Link>
291
+ </div>
292
+ </ScreenFrame>
293
+ );
294
+ }
295
+
296
+ /** Adapter that turns `DefaultErrorScreen` into an `ErrorComponent` shape. */
297
+ export const DefaultErrorFallback: ErrorComponent = ({ error, reset }) => (
298
+ <DefaultErrorScreen digest={error.digest} message={error.message} reset={reset} />
299
+ );
300
+
301
+ /** Adapter that turns `DefaultNotFoundScreen` into a `NotFoundComponent` shape. */
302
+ export const DefaultNotFoundFallback: NotFoundComponent = ({ error }) => (
303
+ <DefaultNotFoundScreen message={error.message} />
304
+ );
@@ -0,0 +1,338 @@
1
+ import type React from "react";
2
+ import { createElement, useCallback, useEffect, useRef } from "react";
3
+ import {
4
+ buildHref,
5
+ CLIENT_FALLBACK_ROUTER,
6
+ type LinkProps,
7
+ normalizeHref,
8
+ RouterContext,
9
+ type RouterContextValue,
10
+ type RouteTo,
11
+ useRouter,
12
+ } from "./router/index.ts";
13
+
14
+ // biome-ignore lint/performance/noBarrelFile: re-exporting router symbols preserves backward compatibility for @teyik0/furin/link consumers
15
+ export * from "./router/index.ts";
16
+
17
+ // ── Link ───────────────────────────────────────────────────────────────────────
18
+
19
+ interface LinkView {
20
+ extraProps: React.AnchorHTMLAttributes<HTMLAnchorElement>;
21
+ href: string;
22
+ isActive: boolean;
23
+ logicalHref: string;
24
+ resolvedChildren: React.ReactNode;
25
+ }
26
+
27
+ /**
28
+ * Shared href/active-state/props computation used by both LinkInteractive (CSR)
29
+ * and renderLinkElement (SSR). Centralising this keeps the two render paths in sync.
30
+ */
31
+ function computeLinkView<To extends RouteTo>(
32
+ {
33
+ to,
34
+ search,
35
+ hash,
36
+ children,
37
+ activeProps,
38
+ inactiveProps,
39
+ }: Pick<LinkProps<To>, "to" | "search" | "hash" | "children" | "activeProps" | "inactiveProps">,
40
+ router: RouterContextValue
41
+ ): LinkView {
42
+ const logicalHref = buildHref(
43
+ to as string,
44
+ search as Record<string, unknown> | null | undefined,
45
+ hash
46
+ );
47
+ const logicalHrefWithoutHash = buildHref(
48
+ to as string,
49
+ search as Record<string, unknown> | null | undefined,
50
+ undefined
51
+ );
52
+ const isAbsolute =
53
+ logicalHref.startsWith("http://") ||
54
+ logicalHref.startsWith("https://") ||
55
+ logicalHref.startsWith("//");
56
+ const href = isAbsolute ? logicalHref : router.basePath + logicalHref;
57
+ const isActive = !isAbsolute && router.currentHref === normalizeHref(logicalHrefWithoutHash);
58
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
59
+ const extraProps: React.AnchorHTMLAttributes<HTMLAnchorElement> = {
60
+ ...(inactiveProps && !isActive ? inactiveProps() : {}),
61
+ ...(activeProps ? activeProps({ isActive }) : {}),
62
+ };
63
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
64
+ }
65
+
66
+ /**
67
+ * Full interactive Link — only rendered on the client where hooks are safe.
68
+ * Never rendered during SSR so it's immune to duplicate-React-instance issues
69
+ * that can arise when page modules are loaded via the furin-dev-page virtual
70
+ * namespace (Bun HMR).
71
+ */
72
+ function LinkInteractive<To extends RouteTo>({
73
+ to,
74
+ search,
75
+ hash,
76
+ preload,
77
+ preloadDelay,
78
+ preloadStaleTime,
79
+ replace,
80
+ disabled,
81
+ resetScroll,
82
+ activeProps,
83
+ inactiveProps,
84
+ onClick,
85
+ onMouseEnter,
86
+ onMouseLeave,
87
+ onFocus,
88
+ children,
89
+ // @ts-expect-error: defensive strip of accidental href prop passed via spread
90
+ href: _href,
91
+ ...anchorProps
92
+ }: LinkProps<To>): React.ReactElement {
93
+ const router = useRouter();
94
+ const anchorRef = useRef<HTMLAnchorElement>(null);
95
+ const intentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
96
+
97
+ // logicalHref: route-relative path (no basePath), used for navigation + active state.
98
+ // physicalHref (href): what the browser sees — basePath + logicalHref.
99
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView(
100
+ { to, search, hash, children, activeProps, inactiveProps },
101
+ router
102
+ );
103
+ const effectivePreload = preload ?? router.defaultPreload;
104
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
105
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
106
+
107
+ const { prefetch } = router;
108
+ const triggerPrefetch = useCallback(() => {
109
+ // prefetch() expects the logical href (no basePath prefix).
110
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
111
+ }, [prefetch, logicalHref, effectiveStaleTime]);
112
+
113
+ // "render": preload immediately on mount
114
+ useEffect(() => {
115
+ if (effectivePreload === "render") {
116
+ triggerPrefetch();
117
+ }
118
+ }, [effectivePreload, triggerPrefetch]);
119
+
120
+ // "viewport": preload when link enters viewport
121
+ useEffect(() => {
122
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
123
+ return;
124
+ }
125
+ const observer = new IntersectionObserver(
126
+ ([entry]) => {
127
+ if (entry?.isIntersecting) {
128
+ triggerPrefetch();
129
+ observer.disconnect();
130
+ }
131
+ },
132
+ { rootMargin: "200px" }
133
+ );
134
+ observer.observe(anchorRef.current);
135
+ return () => observer.disconnect();
136
+ }, [effectivePreload, triggerPrefetch]);
137
+
138
+ // Clear any pending intent prefetch timer on unmount to avoid leaking
139
+ // setTimeout callbacks between test cases (or across re-renders).
140
+ useEffect(
141
+ () => () => {
142
+ if (intentTimerRef.current !== null) {
143
+ clearTimeout(intentTimerRef.current);
144
+ intentTimerRef.current = null;
145
+ }
146
+ },
147
+ []
148
+ );
149
+
150
+ const isInternal = (url: string): boolean => {
151
+ try {
152
+ return new URL(url, window.location.origin).origin === window.location.origin;
153
+ } catch {
154
+ return false;
155
+ }
156
+ };
157
+
158
+ const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
159
+ onClick?.(e);
160
+ if (e.defaultPrevented) {
161
+ return;
162
+ }
163
+ if (disabled) {
164
+ e.preventDefault();
165
+ return;
166
+ }
167
+ // Let browser handle modifier+click (new tab, etc.)
168
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
169
+ return;
170
+ }
171
+ // Let browser handle non-self targets (e.g. target="_blank")
172
+ if (anchorProps.target && anchorProps.target !== "_self") {
173
+ return;
174
+ }
175
+ // Let browser handle external links
176
+ if (!isInternal(href)) {
177
+ return;
178
+ }
179
+ e.preventDefault();
180
+ // When there is no RouterProvider, fall back to a full-page navigation so
181
+ // the link is still functional (e.g. in storybooks or third-party pages).
182
+ if (typeof window !== "undefined" && router.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
183
+ window.location.href = href;
184
+ return;
185
+ }
186
+ // navigate() expects the logical href (no basePath prefix).
187
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
188
+ };
189
+
190
+ const handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
191
+ onMouseEnter?.(e);
192
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
193
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
194
+ }
195
+ };
196
+
197
+ const handleMouseLeave = (e: React.MouseEvent<HTMLAnchorElement>) => {
198
+ onMouseLeave?.(e);
199
+ if (intentTimerRef.current !== null) {
200
+ clearTimeout(intentTimerRef.current);
201
+ intentTimerRef.current = null;
202
+ }
203
+ };
204
+
205
+ const handleFocus = (e: React.FocusEvent<HTMLAnchorElement>) => {
206
+ onFocus?.(e);
207
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
208
+ triggerPrefetch();
209
+ }
210
+ };
211
+
212
+ return createElement(
213
+ "a",
214
+ {
215
+ ref: anchorRef,
216
+ href,
217
+ "data-furin-link": true,
218
+ onClick: handleClick,
219
+ onMouseEnter: handleMouseEnter,
220
+ onMouseLeave: handleMouseLeave,
221
+ onFocus: handleFocus,
222
+ ...(isActive ? { "data-status": "active" } : {}),
223
+ ...anchorProps,
224
+ ...extraProps,
225
+ ...(disabled ? { "aria-disabled": true } : {}),
226
+ },
227
+ resolvedChildren
228
+ );
229
+ }
230
+
231
+ // ── SSR fallback router ────────────────────────────────────────────────────────
232
+
233
+ /**
234
+ * Static fallback used by Link during SSR when there is no RouterProvider.
235
+ * Must not reference `window` — this object is created at module parse time.
236
+ */
237
+ /** @internal Exported for unit testing only. */
238
+ export const SSR_FALLBACK_ROUTER: RouterContextValue = {
239
+ basePath: "",
240
+ currentHref: "/",
241
+ navigate: (_href, _opts) => Promise.resolve(),
242
+ prefetch: (_href, _opts) => {
243
+ /* noop */
244
+ },
245
+ invalidatePrefetch: (_path, _type) => {
246
+ /* noop */
247
+ },
248
+ refresh: (_opts) => Promise.resolve(),
249
+ isNavigating: false,
250
+ defaultPreload: "intent",
251
+ defaultPreloadDelay: 50,
252
+ defaultPreloadStaleTime: 30_000,
253
+ };
254
+
255
+ /**
256
+ * Pure render helper — no hooks, safe to call from any context including SSR.
257
+ * Computes href, active state, and applies activeProps / inactiveProps before
258
+ * returning the final `<a>` element.
259
+ */
260
+ function renderLinkElement<To extends RouteTo>(
261
+ props: LinkProps<To>,
262
+ router: RouterContextValue
263
+ ): React.ReactElement {
264
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
265
+
266
+ // Destructure to strip Link-specific and client-only props before spreading onto <a>.
267
+ const {
268
+ to: _to,
269
+ search: _search,
270
+ hash: _hash,
271
+ children: _children,
272
+ activeProps: _ap,
273
+ inactiveProps: _ip,
274
+ disabled,
275
+ preload: _p,
276
+ preloadDelay: _pd,
277
+ preloadStaleTime: _ps,
278
+ replace: _r,
279
+ resetScroll: _rs,
280
+ onClick: _oc,
281
+ onMouseEnter: _ome,
282
+ onMouseLeave: _oml,
283
+ onFocus: _of,
284
+ // @ts-expect-error: defensive strip of accidental href prop passed via spread
285
+ href: _href,
286
+ ...anchorProps
287
+ } = props;
288
+
289
+ return createElement(
290
+ "a",
291
+ {
292
+ href,
293
+ "data-furin-link": true,
294
+ ...(isActive ? { "data-status": "active" } : {}),
295
+ ...anchorProps,
296
+ ...extraProps,
297
+ ...(disabled ? { "aria-disabled": true } : {}),
298
+ },
299
+ resolvedChildren
300
+ );
301
+ }
302
+
303
+ /**
304
+ * SSR-aware Link component.
305
+ *
306
+ * - **Server (SSR):** uses `RouterContext.Consumer` (a render-prop, not a hook)
307
+ * to read basePath / currentHref from any enclosing RouterProvider, then
308
+ * falls back to `SSR_FALLBACK_ROUTER` when no provider is present.
309
+ * `Context.Consumer` bypasses `ReactCurrentDispatcher` entirely, so it is
310
+ * safe even when two React instances coexist in the module graph (Bun HMR).
311
+ * - **Client:** delegates to `LinkInteractive` which adds preloading, SPA
312
+ * navigation, active-state tracking and all other interactive features.
313
+ */
314
+ export function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactElement {
315
+ if (typeof window === "undefined") {
316
+ // Use Context.Consumer instead of useContext — the Consumer is processed
317
+ // by react-dom/server directly (no dispatcher lookup), so it works even
318
+ // when link.tsx is loaded under a second React instance via the
319
+ // furin-dev-page virtual namespace after a Bun HMR reload.
320
+ return createElement(RouterContext.Consumer, {
321
+ // biome-ignore lint/correctness/noChildrenProp: render-prop pattern — RouterContext.Consumer requires children as a function; cannot be passed as createElement 3rd arg due to TypeScript overloads
322
+ children: (routerCtx: RouterContextValue | null) =>
323
+ renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER),
324
+ });
325
+ }
326
+
327
+ // ── Client rendering ──────────────────────────────────────────────────────
328
+ return createElement(
329
+ LinkInteractive as React.ComponentType<LinkProps<RouteTo>>,
330
+ props as LinkProps<RouteTo>
331
+ );
332
+ }
333
+
334
+ // ── Deferred hydration helpers ─────────────────────────────────────────────────
335
+ // Re-exported here so generated `_hydrate.tsx` files can import from
336
+ // `@teyik0/furin/link` (already a client-only bundle entry) without requiring
337
+ // apps to add "seroval" as a direct dependency.
338
+ export { fromCrossJSON } from "seroval";