@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,116 @@
1
+ import type React from "react";
2
+ import { createElement } from "react";
3
+ import type { RuntimeRoute } from "../../client.ts";
4
+ import { type BoundaryOptions, FurinErrorBoundary, wrapSegmentBoundaries } from "../boundaries.tsx";
5
+ import { FurinServerError } from "../server-error.ts";
6
+ import { RouterContext } from "./context.ts";
7
+ import type {
8
+ ClientSegmentBoundary,
9
+ LoadedClientRoute,
10
+ RootBoundaryOptions,
11
+ RouterContextValue,
12
+ } from "./types.ts";
13
+
14
+ /**
15
+ * Composes the outermost tree produced by `RouterProvider`:
16
+ *
17
+ * <RouterContext.Provider value={context}>
18
+ * <FurinErrorBoundary digest onReset resetKey>
19
+ * {pageElement}
20
+ * </FurinErrorBoundary>
21
+ * </RouterContext.Provider>
22
+ *
23
+ * `RouterContext.Provider` is the OUTERMOST element so that a root-level
24
+ * `error.tsx` rendered by the boundary can still call `useRouter()` / render
25
+ * `<Link>` (the context is in scope above the boundary).
26
+ *
27
+ * @internal Exported for unit testing only.
28
+ */
29
+ export function buildRouterTree(
30
+ context: RouterContextValue,
31
+ pageElement: React.ReactNode,
32
+ options: RootBoundaryOptions
33
+ ): React.ReactElement {
34
+ return (
35
+ <RouterContext.Provider value={context}>
36
+ <FurinErrorBoundary {...options}>{pageElement}</FurinErrorBoundary>
37
+ </RouterContext.Provider>
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Internal helper component that throws a `FurinServerError` during render
43
+ * so the nearest `<FurinErrorBoundary>` catches it and renders the user's
44
+ * `error.tsx` (or the built-in default) — without forcing a full-page reload.
45
+ */
46
+ function RouteErrorThrower({
47
+ error,
48
+ }: {
49
+ error: { digest: string; message: string; status: number };
50
+ }): React.ReactElement {
51
+ throw new FurinServerError(error);
52
+ }
53
+
54
+ /** @internal Exported for unit testing only. */
55
+ export function buildPageElement(
56
+ match: LoadedClientRoute,
57
+ root: RuntimeRoute | null,
58
+ data: Record<string, unknown>,
59
+ options: BoundaryOptions | undefined,
60
+ error: { digest: string; message: string; status: number } | undefined
61
+ ): React.ReactNode {
62
+ let element: React.ReactNode = error
63
+ ? createElement(RouteErrorThrower, { error })
64
+ : createElement(match.component, data);
65
+
66
+ // Reconstruct the FULL route chain (shallow→deep, index 0 = root) by walking
67
+ // parents. We keep every route — not only the ones declaring a layout — so a
68
+ // route's chain index equals its directory depth. This mirrors the server's
69
+ // `buildElement` exactly, which is what guarantees the per-segment boundaries
70
+ // and layouts attach at the same depths on both sides (hydration parity).
71
+ // Compacting to layouts-only (the previous approach) misaligned boundaries
72
+ // and dropped the first nested layout whenever an ancestor lacked a layout.
73
+ const chain: RuntimeRoute[] = [];
74
+ let current: RuntimeRoute | undefined = match.pageRoute;
75
+ while (current) {
76
+ chain.unshift(current);
77
+ current = current.parent;
78
+ }
79
+
80
+ // Index boundaries by depth for O(1) lookup. A boundary's `depth` maps 1:1 to
81
+ // the route-chain index (depth 0 = root layout, handled separately below).
82
+ const byDepth = new Map<number, ClientSegmentBoundary>();
83
+ for (const segment of match.segmentBoundaries ?? []) {
84
+ byDepth.set(segment.depth, segment);
85
+ }
86
+
87
+ // When a root route is present it occupies chain index 0 and is wrapped
88
+ // separately below (root layout + depth-0 boundary), mirroring the server's
89
+ // `buildElement`. When `root` is null there is no separate root, so chain
90
+ // index 0 is an ordinary route whose layout + boundary participate in the
91
+ // loop too.
92
+ const rootOffset = root ? 1 : 0;
93
+
94
+ // Inside-out: at each non-root depth wrap the subtree with its same-depth
95
+ // boundary (so the boundary sits INSIDE the layout), then wrap with the
96
+ // layout itself when this route declares one.
97
+ for (let i = chain.length - 1; i >= rootOffset; i--) {
98
+ element = wrapSegmentBoundaries(element, byDepth.get(i), options);
99
+ const Layout = chain[i]?.layout;
100
+ if (Layout) {
101
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
102
+ element = createElement(Layout, { ...data } as any, element);
103
+ }
104
+ }
105
+
106
+ if (root) {
107
+ // Depth 0 boundary wraps EVERYTHING below the root layout.
108
+ element = wrapSegmentBoundaries(element, byDepth.get(0), options);
109
+ if (root.layout) {
110
+ // biome-ignore lint/suspicious/noExplicitAny: spread loses `children` type info for createElement
111
+ element = createElement(root.layout, { ...data } as any, element);
112
+ }
113
+ }
114
+
115
+ return element;
116
+ }
@@ -0,0 +1,38 @@
1
+ import { createContext, useContext } from "react";
2
+ import type { RouterContextValue } from "./types.ts";
3
+
4
+ export const RouterContext = createContext<RouterContextValue | null>(null);
5
+
6
+ export const CLIENT_FALLBACK_ROUTER: RouterContextValue = {
7
+ basePath: "",
8
+ // Use the same "/" as SSR_FALLBACK_ROUTER so SSR and client render the
9
+ // same active-state when no RouterProvider is present, avoiding hydration mismatches.
10
+ currentHref: "/",
11
+ navigate: (href, _opts) => {
12
+ window.location.href = href;
13
+ return Promise.resolve();
14
+ },
15
+ prefetch: (_href, _opts) => {
16
+ /* noop fallback */
17
+ },
18
+ invalidatePrefetch: (_path, _type) => {
19
+ /* noop fallback */
20
+ },
21
+ refresh: (_opts) => {
22
+ window.location.reload();
23
+ return Promise.resolve();
24
+ },
25
+ isNavigating: false,
26
+ defaultPreload: "intent",
27
+ defaultPreloadDelay: 50,
28
+ defaultPreloadStaleTime: 30_000,
29
+ };
30
+
31
+ /**
32
+ * Returns the current router context.
33
+ * Provides a graceful fallback (full-page navigation) when used outside RouterProvider.
34
+ */
35
+ export function useRouter(): RouterContextValue {
36
+ const ctx = useContext(RouterContext);
37
+ return ctx ?? CLIENT_FALLBACK_ROUTER;
38
+ }
@@ -0,0 +1,41 @@
1
+ export const SCROLL_STORAGE_KEY = "__furin_scroll__";
2
+
3
+ export function getHistoryKey(state: unknown): string | undefined {
4
+ return (state as { _furinKey?: string } | null)?._furinKey;
5
+ }
6
+
7
+ export function generateHistoryKey(): string {
8
+ return Math.random().toString(36).slice(2, 9);
9
+ }
10
+
11
+ export function saveScrollPosition(key: string): void {
12
+ try {
13
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
14
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
15
+ positions[key] = window.scrollY;
16
+ const keys = Object.keys(positions);
17
+ if (keys.length > 50) {
18
+ delete positions[keys[0] as string];
19
+ }
20
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
21
+ } catch {
22
+ // sessionStorage unavailable (private mode, quota exceeded, etc.)
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Returns `true` when the server reports a different build-id from the one
28
+ * embedded in the initial HTML (`<meta name="furin-build-id">`).
29
+ */
30
+ export function isStaleDeployResponse(res: Response): boolean {
31
+ const serverBuildId = res.headers.get("x-furin-build-id");
32
+ if (!serverBuildId) {
33
+ return false;
34
+ }
35
+ const metaEl =
36
+ typeof document === "undefined"
37
+ ? null
38
+ : document.querySelector<HTMLMetaElement>('meta[name="furin-build-id"]');
39
+ const clientBuildId = metaEl?.content;
40
+ return Boolean(clientBuildId && serverBuildId !== clientBuildId);
41
+ }
@@ -0,0 +1,47 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: client/router barrel — public surface of the SPA router
2
+ export { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
3
+ export { CLIENT_FALLBACK_ROUTER, RouterContext, useRouter } from "./context.ts";
4
+ export {
5
+ generateHistoryKey,
6
+ getHistoryKey,
7
+ isStaleDeployResponse,
8
+ SCROLL_STORAGE_KEY,
9
+ saveScrollPosition,
10
+ } from "./history.ts";
11
+ export {
12
+ applyRevalidateHeader,
13
+ buildHref,
14
+ normalizeHref,
15
+ normalizePath,
16
+ shouldAutoRefreshPath,
17
+ shouldInterceptClick,
18
+ shouldRefetch,
19
+ stripHashFromHref,
20
+ TRAILING_SLASHES_RE,
21
+ toLogical,
22
+ } from "./link-utils.ts";
23
+ export { RouterProvider } from "./provider.tsx";
24
+ export {
25
+ buildDataEndpoint,
26
+ buildNotFoundPageElement,
27
+ classifySpaResponse,
28
+ detectStaticMode,
29
+ parsePageResponse,
30
+ pickDeepestNotFound,
31
+ } from "./spa-response.ts";
32
+ export type {
33
+ CacheEntry,
34
+ ClientRoute,
35
+ ClientSegmentBoundary,
36
+ LinkProps,
37
+ LoadedClientRoute,
38
+ PreloadStrategy,
39
+ RootBoundaryOptions,
40
+ RouteManifest,
41
+ RouterContextValue,
42
+ RouterProviderProps,
43
+ RouterState,
44
+ RouteSearch,
45
+ RouteTo,
46
+ SpaResponseKind,
47
+ } from "./types.ts";
@@ -0,0 +1,180 @@
1
+ import type { CacheEntry } from "./types.ts";
2
+
3
+ const HASH_FRAGMENT_RE = /#.*$/;
4
+ /** Strips one or more trailing slashes — used by `buildDataEndpoint` in static mode. */
5
+ export const TRAILING_SLASHES_RE = /\/+$/;
6
+
7
+ /**
8
+ * Builds a full href string from a pathname, optional search params, and optional hash.
9
+ * Null/undefined search values are omitted.
10
+ *
11
+ * @internal Exported for unit testing only.
12
+ */
13
+ export function buildHref(
14
+ to: string,
15
+ search: Record<string, unknown> | null | undefined,
16
+ hash: string | undefined
17
+ ): string {
18
+ let url = to;
19
+ if (search && Object.keys(search).length > 0) {
20
+ const params = new URLSearchParams();
21
+ for (const [k, v] of Object.entries(search)) {
22
+ if (v != null) {
23
+ params.set(k, String(v));
24
+ }
25
+ }
26
+ const qs = params.toString();
27
+ if (qs) {
28
+ url += `?${qs}`;
29
+ }
30
+ }
31
+ if (hash) {
32
+ url += `#${hash}`;
33
+ }
34
+ return url;
35
+ }
36
+
37
+ /**
38
+ * Parses the `X-Furin-Revalidate` response header and calls `invalidate` for
39
+ * each path entry. Header format: `"/path1,/path2:layout,/path3"`
40
+ */
41
+ export function applyRevalidateHeader(
42
+ headers: Headers,
43
+ invalidate: (path: string, type: "page" | "layout" | undefined) => void
44
+ ): void {
45
+ const headerValue = headers.get("x-furin-revalidate");
46
+ if (!headerValue) {
47
+ return;
48
+ }
49
+ for (const entry of headerValue.split(",")) {
50
+ const trimmed = entry.trim();
51
+ if (!trimmed) {
52
+ continue;
53
+ }
54
+ if (trimmed.endsWith(":layout")) {
55
+ invalidate(trimmed.slice(0, -":layout".length), "layout");
56
+ } else {
57
+ invalidate(trimmed, "page");
58
+ }
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Returns `true` when `currentPath` is targeted by at least one invalidation entry.
64
+ *
65
+ * @internal Exported for unit testing only.
66
+ */
67
+ export function shouldAutoRefreshPath(
68
+ currentPath: string,
69
+ invalidations: ReadonlyArray<{ path: string; type: "page" | "layout" }>
70
+ ): boolean {
71
+ const normalizedCurrent = currentPath.split("?")[0] ?? currentPath;
72
+ return invalidations.some(({ path, type }) => {
73
+ if (type === "page") {
74
+ return path === normalizedCurrent;
75
+ }
76
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
77
+ return normalizedCurrent === path || normalizedCurrent.startsWith(prefix);
78
+ });
79
+ }
80
+
81
+ export function stripHashFromHref(href: string): string {
82
+ return href.replace(HASH_FRAGMENT_RE, "");
83
+ }
84
+
85
+ /** Strips trailing slashes from a pathname or href. Root `/` is preserved.
86
+ * Query strings and hashes are preserved and re-attached after normalization. */
87
+ export function normalizeHref(href: string): string {
88
+ const url = new URL(href, "http://localhost");
89
+ let pathname = url.pathname;
90
+ if (pathname !== "/") {
91
+ pathname = pathname.replace(/\/+$/g, "");
92
+ }
93
+ return pathname + url.search + url.hash;
94
+ }
95
+
96
+ /** Strips a single trailing slash from a pathname. Root `/` and empty string are preserved. */
97
+ export function normalizePath(path: string): string {
98
+ if (path === "/" || path === "") {
99
+ return path;
100
+ }
101
+ return path.endsWith("/") ? path.slice(0, -1) : path;
102
+ }
103
+
104
+ /** @internal Exported for unit testing only. */
105
+ export function shouldRefetch(entry: CacheEntry): boolean {
106
+ return Date.now() - entry.createdAt > entry.staleTime;
107
+ }
108
+
109
+ /**
110
+ * Decides whether a native `<a>` click should be intercepted and converted
111
+ * to an SPA navigation. Returns the logical href to navigate to, or `null`
112
+ * when the browser should handle the click normally.
113
+ *
114
+ * @internal Exported for unit testing only.
115
+ */
116
+ export function shouldInterceptClick(
117
+ anchor: { href: string; target: string; hasAttribute(name: string): boolean },
118
+ event: { metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean },
119
+ basePath: string,
120
+ currentOrigin: string,
121
+ currentPathname: string
122
+ ): string | null {
123
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
124
+ return null;
125
+ }
126
+
127
+ if (anchor.target && anchor.target !== "_self") {
128
+ return null;
129
+ }
130
+
131
+ if (anchor.hasAttribute("download")) {
132
+ return null;
133
+ }
134
+
135
+ const href = anchor.href;
136
+ if (!href) {
137
+ return null;
138
+ }
139
+
140
+ let url: URL;
141
+ try {
142
+ url = new URL(href, currentOrigin);
143
+ } catch {
144
+ return null;
145
+ }
146
+
147
+ if (url.origin !== currentOrigin) {
148
+ return null;
149
+ }
150
+
151
+ // Hash-only navigation on the same page — let the browser handle scrolling.
152
+ if (normalizePath(url.pathname) === normalizePath(currentPathname) && url.hash) {
153
+ return null;
154
+ }
155
+
156
+ const logicalPath = normalizeHref(toLogical(url.pathname, basePath));
157
+ const normalizedBase = normalizePath(basePath);
158
+ const normalizedPathname = normalizePath(url.pathname);
159
+ if (
160
+ normalizedBase &&
161
+ normalizedPathname !== normalizedBase &&
162
+ !normalizedPathname.startsWith(`${normalizedBase}/`)
163
+ ) {
164
+ return null;
165
+ }
166
+ return logicalPath + url.search + url.hash;
167
+ }
168
+
169
+ /** Strips basePath prefix from a physical pathname, returning the logical path. */
170
+ export function toLogical(physicalPathname: string, basePath: string): string {
171
+ if (
172
+ basePath &&
173
+ physicalPathname.startsWith(basePath) &&
174
+ // Require a path boundary after the prefix so "/furin" doesn't match "/furinity/foo"
175
+ (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")
176
+ ) {
177
+ return physicalPathname.slice(basePath.length) || "/";
178
+ }
179
+ return physicalPathname;
180
+ }