@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.2
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.
- package/LICENSE +21 -0
- package/README.md +33 -0
- package/package.json +61 -25
- package/src/adapter/bun.ts +90 -41
- package/src/adapter/static.ts +100 -40
- package/src/build/client.ts +13 -14
- package/src/build/compile-entry.ts +20 -14
- package/src/build/entry-template.ts +90 -8
- package/src/build/hydrate.ts +219 -36
- package/src/build/index.ts +10 -9
- package/src/build/route-types.ts +65 -9
- package/src/build/scan-server.ts +52 -67
- package/src/build/server-routes-entry.ts +7 -11
- package/src/build/shared.ts +2 -1
- package/src/build/ssg-cache.ts +32 -0
- package/src/build/types.ts +5 -1
- package/src/cli/index.ts +1 -0
- package/src/client/boundaries.tsx +259 -0
- package/src/client/default-screens.tsx +304 -0
- package/src/client/link.tsx +347 -0
- package/src/client/router/boundary-tree.tsx +116 -0
- package/src/client/router/context.ts +40 -0
- package/src/client/router/history.ts +41 -0
- package/src/client/router/index.ts +56 -0
- package/src/client/router/link-utils.ts +177 -0
- package/src/client/router/navigation.ts +61 -0
- package/src/client/router/provider.tsx +759 -0
- package/src/client/router/search/index.ts +99 -0
- package/src/client/router/search-store.ts +86 -0
- package/src/client/router/spa-response.ts +143 -0
- package/src/client/router/types.ts +271 -0
- package/src/client/server-error.ts +47 -0
- package/src/client.ts +80 -3
- package/src/config.ts +11 -3
- package/src/env.d.ts +1 -0
- package/src/furin.ts +114 -29
- package/src/plugin/index.ts +7 -8
- package/src/plugin/transform-client.ts +146 -120
- package/src/server/auto-invalidate/index.ts +10 -0
- package/src/server/auto-invalidate/plugin.ts +25 -0
- package/src/server/auto-invalidate/registry.ts +60 -0
- package/src/server/auto-invalidate/runtime.ts +133 -0
- package/src/server/auto-invalidate/types.ts +16 -0
- package/src/server/cache/dev-loader.ts +211 -0
- package/src/server/cache/index.ts +34 -0
- package/src/server/cache/invalidation.ts +111 -0
- package/src/server/cache/isr-ssg.ts +41 -0
- package/src/server/cache/isr.ts +17 -0
- package/src/server/cache/registry.ts +35 -0
- package/src/server/cache/route-cache.ts +124 -0
- package/src/server/cache/ssg.ts +15 -0
- package/src/{context-logger.ts → server/context-logger.ts} +5 -0
- package/src/server/dev-inspector.ts +60 -0
- package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
- package/src/{internal.ts → server/internal.ts} +17 -0
- package/src/server/lang-detect.ts +46 -0
- package/src/server/render/assemble.ts +133 -0
- package/src/server/render/element.tsx +113 -0
- package/src/server/render/index.ts +22 -0
- package/src/server/render/isr.ts +317 -0
- package/src/server/render/loaders.ts +328 -0
- package/src/server/render/not-found.ts +98 -0
- package/src/{render → server/render}/shell.ts +28 -13
- package/src/server/render/ssg.ts +148 -0
- package/src/server/render/ssr.ts +583 -0
- package/src/server/router/discovery.ts +474 -0
- package/src/server/router/hmr.ts +376 -0
- package/src/server/router/index.ts +28 -0
- package/src/server/router/patterns.ts +219 -0
- package/src/server/router/plugin.ts +384 -0
- package/src/server/router/schemas.ts +278 -0
- package/src/server/router/types.ts +59 -0
- package/src/shared/await.tsx +192 -0
- package/src/shared/deferred-ndjson.ts +244 -0
- package/src/shared/digest.ts +71 -0
- package/src/shared/error.ts +49 -0
- package/src/shared/not-found.ts +40 -0
- package/src/shared/search-params.ts +182 -0
- package/src/shared/utils/ast-walk.ts +51 -0
- package/src/{utils.ts → shared/utils/index.ts} +32 -1
- package/dist/adapter/bun.d.ts +0 -3
- package/dist/adapter/static.d.ts +0 -3
- package/dist/build/client.d.ts +0 -25
- package/dist/build/compile-entry.d.ts +0 -23
- package/dist/build/entry-template.d.ts +0 -14
- package/dist/build/hydrate.d.ts +0 -24
- package/dist/build/index.d.ts +0 -7
- package/dist/build/index.js +0 -3727
- package/dist/build/route-types.d.ts +0 -21
- package/dist/build/scan-server.d.ts +0 -8
- package/dist/build/server-routes-entry.d.ts +0 -23
- package/dist/build/shared.d.ts +0 -11
- package/dist/build/types.d.ts +0 -76
- package/dist/cli/config.d.ts +0 -9
- package/dist/cli/index.d.ts +0 -2
- package/dist/cli/index.js +0 -3762
- package/dist/client.d.ts +0 -195
- package/dist/client.js +0 -20
- package/dist/config.d.ts +0 -47
- package/dist/config.js +0 -28
- package/dist/context-logger.d.ts +0 -26
- package/dist/dev-page-plugin.d.ts +0 -109
- package/dist/furin.d.ts +0 -34
- package/dist/furin.js +0 -2744
- package/dist/internal.d.ts +0 -19
- package/dist/link.d.ts +0 -245
- package/dist/link.js +0 -1232
- package/dist/plugin/index.d.ts +0 -20
- package/dist/plugin/index.js +0 -1408
- package/dist/plugin/transform-client.d.ts +0 -9
- package/dist/render/assemble.d.ts +0 -15
- package/dist/render/cache.d.ts +0 -95
- package/dist/render/element.d.ts +0 -4
- package/dist/render/index.d.ts +0 -27
- package/dist/render/loaders.d.ts +0 -12
- package/dist/render/shell.d.ts +0 -29
- package/dist/render/template.d.ts +0 -6
- package/dist/router.d.ts +0 -45
- package/dist/router.js +0 -1671
- package/dist/runtime-env.d.ts +0 -3
- package/dist/utils.d.ts +0 -6
- package/src/link.tsx +0 -1120
- package/src/render/assemble.ts +0 -66
- package/src/render/cache.ts +0 -241
- package/src/render/element.tsx +0 -28
- package/src/render/index.ts +0 -483
- package/src/render/loaders.ts +0 -117
- package/src/router.ts +0 -439
- /package/src/{render → server/render}/template.ts +0 -0
- /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { RouteManifest as LinkRouteManifest, RouteSearch, RouteTo } from "@teyik0/furin/link";
|
|
2
|
+
import { useCallback, useContext, useRef, useSyncExternalStore } from "react";
|
|
3
|
+
import {
|
|
4
|
+
findSearchDefaultsForRouteTarget,
|
|
5
|
+
type SearchParamsInput,
|
|
6
|
+
} from "../../../shared/search-params.ts";
|
|
7
|
+
import { buildHref } from "../link-utils.ts";
|
|
8
|
+
import { FALLBACK_SEARCH_STORE, SearchStoreContext } from "../search-store.ts";
|
|
9
|
+
|
|
10
|
+
export interface RouteManifest extends LinkRouteManifest {}
|
|
11
|
+
|
|
12
|
+
export type SearchRouteTo = keyof LinkRouteManifest extends never
|
|
13
|
+
? RouteTo
|
|
14
|
+
: (string & {}) | keyof LinkRouteManifest;
|
|
15
|
+
|
|
16
|
+
type SearchRouteSearch<To extends SearchRouteTo> = keyof LinkRouteManifest extends never
|
|
17
|
+
? RouteSearch<To & RouteTo>
|
|
18
|
+
: To extends keyof LinkRouteManifest
|
|
19
|
+
? LinkRouteManifest[To] extends { search?: infer S }
|
|
20
|
+
? S
|
|
21
|
+
: undefined
|
|
22
|
+
: undefined;
|
|
23
|
+
|
|
24
|
+
export type EmptyRouteSearch = Record<PropertyKey, never>;
|
|
25
|
+
|
|
26
|
+
export type ResolvedRouteSearch<To extends SearchRouteTo> =
|
|
27
|
+
SearchRouteSearch<To> extends never | undefined
|
|
28
|
+
? EmptyRouteSearch
|
|
29
|
+
: NonNullable<SearchRouteSearch<To>>;
|
|
30
|
+
|
|
31
|
+
export type SetSearchInput<To extends SearchRouteTo> =
|
|
32
|
+
| Partial<ResolvedRouteSearch<To>>
|
|
33
|
+
| ((prev: ResolvedRouteSearch<To>) => Partial<ResolvedRouteSearch<To>>);
|
|
34
|
+
|
|
35
|
+
export interface SetSearchOptions {
|
|
36
|
+
replace?: boolean;
|
|
37
|
+
resetScroll?: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type SetSearch<To extends SearchRouteTo> = (
|
|
41
|
+
next: SetSearchInput<To>,
|
|
42
|
+
opts?: SetSearchOptions
|
|
43
|
+
) => Promise<void>;
|
|
44
|
+
|
|
45
|
+
function pathnameFromLogicalHref(logicalHref: string): string {
|
|
46
|
+
return new URL(logicalHref, "http://furin.local").pathname;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function useSearchSelection<To extends SearchRouteTo, TSelected>(
|
|
50
|
+
selector: (search: ResolvedRouteSearch<To>) => TSelected
|
|
51
|
+
): TSelected {
|
|
52
|
+
const store = useContext(SearchStoreContext) ?? FALLBACK_SEARCH_STORE;
|
|
53
|
+
const selectorRef = useRef(selector);
|
|
54
|
+
selectorRef.current = selector;
|
|
55
|
+
|
|
56
|
+
const getSnapshot = useCallback(
|
|
57
|
+
() => selectorRef.current(store.getSnapshot().search as ResolvedRouteSearch<To>),
|
|
58
|
+
[store]
|
|
59
|
+
);
|
|
60
|
+
const getServerSnapshot = useCallback(
|
|
61
|
+
() => selectorRef.current(store.getServerSnapshot().search as ResolvedRouteSearch<To>),
|
|
62
|
+
[store]
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
return useSyncExternalStore(store.subscribe, getSnapshot, getServerSnapshot);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function useSearch<To extends SearchRouteTo>(
|
|
69
|
+
_from: To
|
|
70
|
+
): [ResolvedRouteSearch<To>, SetSearch<To>];
|
|
71
|
+
export function useSearch<To extends SearchRouteTo, TSelected>(
|
|
72
|
+
_from: To,
|
|
73
|
+
selector: (search: ResolvedRouteSearch<To>) => TSelected
|
|
74
|
+
): [TSelected, SetSearch<To>];
|
|
75
|
+
export function useSearch<To extends SearchRouteTo, TSelected>(
|
|
76
|
+
_from: To,
|
|
77
|
+
selector?: (search: ResolvedRouteSearch<To>) => TSelected
|
|
78
|
+
): [ResolvedRouteSearch<To> | TSelected, SetSearch<To>] {
|
|
79
|
+
const store = useContext(SearchStoreContext) ?? FALLBACK_SEARCH_STORE;
|
|
80
|
+
const selected = useSearchSelection<To, ResolvedRouteSearch<To> | TSelected>((search) =>
|
|
81
|
+
selector ? selector(search) : search
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
const setSearch = useCallback<SetSearch<To>>(
|
|
85
|
+
(next, opts) => {
|
|
86
|
+
const snapshot = store.getSnapshot();
|
|
87
|
+
const search = snapshot.search as ResolvedRouteSearch<To>;
|
|
88
|
+
const patch = typeof next === "function" ? next(search) : next;
|
|
89
|
+
const merged = { ...search, ...patch } as SearchParamsInput;
|
|
90
|
+
const pathname = pathnameFromLogicalHref(snapshot.currentHref);
|
|
91
|
+
const searchDefaults = findSearchDefaultsForRouteTarget(pathname, snapshot.searchRoutes);
|
|
92
|
+
const href = buildHref(pathname, merged, undefined, searchDefaults);
|
|
93
|
+
return snapshot.navigate(href, opts);
|
|
94
|
+
},
|
|
95
|
+
[store]
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
return [selected, setSearch];
|
|
99
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { createContext } from "react";
|
|
2
|
+
import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
|
|
3
|
+
import type { RouterContextValue } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
export interface SearchStoreSnapshot {
|
|
6
|
+
currentHref: string;
|
|
7
|
+
navigate: RouterContextValue["navigate"];
|
|
8
|
+
search: SearchParamsInput;
|
|
9
|
+
searchRoutes: SearchRouteMetadata[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type SearchStoreListener = () => void;
|
|
13
|
+
|
|
14
|
+
export interface SearchStore {
|
|
15
|
+
flush: () => void;
|
|
16
|
+
getServerSnapshot: () => SearchStoreSnapshot;
|
|
17
|
+
getSnapshot: () => SearchStoreSnapshot;
|
|
18
|
+
setSnapshot: (next: SearchStoreSnapshot) => void;
|
|
19
|
+
subscribe: (listener: SearchStoreListener) => () => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function searchSnapshotChanged(a: SearchStoreSnapshot, b: SearchStoreSnapshot): boolean {
|
|
23
|
+
return (
|
|
24
|
+
a.currentHref !== b.currentHref ||
|
|
25
|
+
a.navigate !== b.navigate ||
|
|
26
|
+
a.search !== b.search ||
|
|
27
|
+
a.searchRoutes !== b.searchRoutes
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createSearchStore(initialSnapshot: SearchStoreSnapshot): SearchStore {
|
|
32
|
+
let snapshot = initialSnapshot;
|
|
33
|
+
let version = 0;
|
|
34
|
+
let flushedVersion = 0;
|
|
35
|
+
const listeners = new Set<SearchStoreListener>();
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
flush: () => {
|
|
39
|
+
if (flushedVersion === version) {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
flushedVersion = version;
|
|
43
|
+
for (const listener of [...listeners]) {
|
|
44
|
+
listener();
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
getServerSnapshot: () => snapshot,
|
|
48
|
+
getSnapshot: () => snapshot,
|
|
49
|
+
setSnapshot: (next) => {
|
|
50
|
+
if (!searchSnapshotChanged(snapshot, next)) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
snapshot = next;
|
|
54
|
+
version++;
|
|
55
|
+
},
|
|
56
|
+
subscribe: (listener) => {
|
|
57
|
+
listeners.add(listener);
|
|
58
|
+
return () => {
|
|
59
|
+
listeners.delete(listener);
|
|
60
|
+
};
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function searchSnapshotFromRouterContext(context: RouterContextValue): SearchStoreSnapshot {
|
|
66
|
+
return {
|
|
67
|
+
currentHref: context.currentHref,
|
|
68
|
+
navigate: context.navigate,
|
|
69
|
+
search: context.search,
|
|
70
|
+
searchRoutes: context.searchRoutes,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const FALLBACK_SEARCH_STORE = createSearchStore({
|
|
75
|
+
currentHref: "/",
|
|
76
|
+
navigate: (href, _opts) => {
|
|
77
|
+
if (typeof window !== "undefined") {
|
|
78
|
+
window.location.href = href;
|
|
79
|
+
}
|
|
80
|
+
return Promise.resolve();
|
|
81
|
+
},
|
|
82
|
+
search: {},
|
|
83
|
+
searchRoutes: [],
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
export const SearchStoreContext = createContext<SearchStore | null>(null);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type React from "react";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
import type { NotFoundComponent } from "../../shared/not-found.ts";
|
|
4
|
+
import { DefaultNotFoundScreen } from "../default-screens.tsx";
|
|
5
|
+
import { TRAILING_SLASHES_RE, toLogical } from "./link-utils.ts";
|
|
6
|
+
import type { ClientSegmentBoundary, SpaResponseKind } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
function isFurinErrorPayload(
|
|
9
|
+
value: unknown
|
|
10
|
+
): value is { digest: string; message: string; status: number } {
|
|
11
|
+
if (!value || typeof value !== "object") {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
const v = value as { digest?: unknown; message?: unknown; status?: unknown };
|
|
15
|
+
return (
|
|
16
|
+
typeof v.digest === "string" && typeof v.message === "string" && typeof v.status === "number"
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Pure classifier for an SPA-nav fetch result. Takes the HTTP status and the
|
|
22
|
+
* already-parsed `__FURIN_DATA__` payload.
|
|
23
|
+
*
|
|
24
|
+
* Sentinels (`__furinError`, `__furinStatus`) are trusted over the raw HTTP
|
|
25
|
+
* status — proxies / CDNs sometimes rewrite the status code but pass the body
|
|
26
|
+
* through untouched. A non-2xx response without any sentinel triggers a bail
|
|
27
|
+
* so the browser handles it (could be an error page, redirect, etc.).
|
|
28
|
+
*
|
|
29
|
+
* @internal Exported for unit testing only.
|
|
30
|
+
*/
|
|
31
|
+
export function classifySpaResponse(
|
|
32
|
+
status: number,
|
|
33
|
+
data: Record<string, unknown> | null
|
|
34
|
+
): SpaResponseKind {
|
|
35
|
+
if (!data) {
|
|
36
|
+
return { kind: "bail" };
|
|
37
|
+
}
|
|
38
|
+
if (isFurinErrorPayload(data.__furinError)) {
|
|
39
|
+
return { kind: "error", error: data.__furinError };
|
|
40
|
+
}
|
|
41
|
+
if (((status >= 200 && status < 300) || status === 404) && data.__furinStatus === 404) {
|
|
42
|
+
const notFound = data.__furinNotFound as { data?: unknown; message?: string } | undefined;
|
|
43
|
+
return { kind: "not-found", error: notFound ?? {} };
|
|
44
|
+
}
|
|
45
|
+
if (status >= 200 && status < 300) {
|
|
46
|
+
return { kind: "ok" };
|
|
47
|
+
}
|
|
48
|
+
return { kind: "bail" };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Picks the deepest not-found component declared on the match's boundary chain.
|
|
53
|
+
*
|
|
54
|
+
* @internal Exported for unit testing only.
|
|
55
|
+
*/
|
|
56
|
+
export function pickDeepestNotFound(
|
|
57
|
+
boundaries: ClientSegmentBoundary[] | undefined
|
|
58
|
+
): NotFoundComponent | undefined {
|
|
59
|
+
if (!boundaries) {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
for (let i = boundaries.length - 1; i >= 0; i--) {
|
|
63
|
+
const seg = boundaries[i];
|
|
64
|
+
if (seg?.notFound) {
|
|
65
|
+
return seg.notFound;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const DefaultClientNotFoundFallback: NotFoundComponent = ({ error }) =>
|
|
72
|
+
createElement(DefaultNotFoundScreen, { message: error.message });
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Builds the bare not-found element rendered inline by RouterProvider on SPA
|
|
76
|
+
* navigation when the server signalled a 404.
|
|
77
|
+
*
|
|
78
|
+
* @internal Exported for unit testing only.
|
|
79
|
+
*/
|
|
80
|
+
export function buildNotFoundPageElement(
|
|
81
|
+
boundaries: ClientSegmentBoundary[] | undefined,
|
|
82
|
+
error: { data?: unknown; message?: string }
|
|
83
|
+
): React.ReactNode {
|
|
84
|
+
const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
|
|
85
|
+
return createElement(Fallback, { error });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Parses the HTML payload of a page response into the pieces `fetchPageState`
|
|
90
|
+
* cares about: the document (for title), the __FURIN_DATA__ loader payload,
|
|
91
|
+
* and the logical `finalHref` after any server-side redirect.
|
|
92
|
+
*/
|
|
93
|
+
export async function parsePageResponse(
|
|
94
|
+
res: Response,
|
|
95
|
+
basePath: string
|
|
96
|
+
): Promise<{ data: Record<string, unknown> | null; finalHref: string | undefined; title: string }> {
|
|
97
|
+
let finalHref: string | undefined;
|
|
98
|
+
if (res.redirected) {
|
|
99
|
+
const final = new URL(res.url);
|
|
100
|
+
finalHref = toLogical(final.pathname, basePath) + final.search;
|
|
101
|
+
}
|
|
102
|
+
const html = await res.text();
|
|
103
|
+
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
104
|
+
const dataEl = doc.getElementById("__FURIN_DATA__");
|
|
105
|
+
const data = dataEl ? JSON.parse(dataEl.textContent || "{}") : null;
|
|
106
|
+
return { data, finalHref, title: doc.title };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Builds the URL the SPA navigation flow uses to fetch a route's loader data.
|
|
111
|
+
*
|
|
112
|
+
* Two transports are supported:
|
|
113
|
+
*
|
|
114
|
+
* • **Runtime (SSR/ISR/dev)** — `${basePath}/_furin/data?path=<logicalHref>`.
|
|
115
|
+
* • **Static export** — `${basePath}<logicalPathname>/__furin_data.ndjson`.
|
|
116
|
+
*
|
|
117
|
+
* @internal Exported for unit testing.
|
|
118
|
+
*/
|
|
119
|
+
export function buildDataEndpoint(
|
|
120
|
+
basePath: string,
|
|
121
|
+
logicalHref: string,
|
|
122
|
+
staticMode: boolean
|
|
123
|
+
): string {
|
|
124
|
+
if (!staticMode) {
|
|
125
|
+
return `${basePath}/_furin/data?path=${encodeURIComponent(logicalHref)}`;
|
|
126
|
+
}
|
|
127
|
+
const parsed = new URL(logicalHref, "http://x");
|
|
128
|
+
const pathname = parsed.pathname.replace(TRAILING_SLASHES_RE, "");
|
|
129
|
+
return `${basePath}${pathname}/__furin_data.ndjson`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Reads `<meta name="furin-mode" content="static">` from the document at boot.
|
|
134
|
+
*
|
|
135
|
+
* @internal Exported for unit testing.
|
|
136
|
+
*/
|
|
137
|
+
export function detectStaticMode(): boolean {
|
|
138
|
+
if (typeof document === "undefined") {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
const meta = document.querySelector<HTMLMetaElement>('meta[name="furin-mode"]');
|
|
142
|
+
return meta?.content === "static";
|
|
143
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import type React from "react";
|
|
2
|
+
import type { RuntimeRoute } from "../../client.ts";
|
|
3
|
+
import type { ErrorComponent } from "../../shared/error.ts";
|
|
4
|
+
import type { NotFoundComponent } from "../../shared/not-found.ts";
|
|
5
|
+
import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Augment this interface via declaration merging in furin-env.d.ts
|
|
9
|
+
* to get type-safe `to` autocompletion and per-route `search` types on <Link>.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* // furin-env.d.ts (auto-generated by Furin at project root)
|
|
13
|
+
* import "@teyik0/furin/link";
|
|
14
|
+
* declare module "@teyik0/furin/link" {
|
|
15
|
+
* interface RouteManifest {
|
|
16
|
+
* "/blog": { search?: { page?: number; tag?: string } };
|
|
17
|
+
* "/": { search?: never };
|
|
18
|
+
* [key: `/blog/${string}`]: { search?: never };
|
|
19
|
+
* }
|
|
20
|
+
* }
|
|
21
|
+
*/
|
|
22
|
+
// biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
|
|
23
|
+
export interface RouteManifest {}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The valid `to` pathname union derived from the augmented RouteManifest.
|
|
27
|
+
* Falls back to `string` when furin-env.d.ts has not been generated yet.
|
|
28
|
+
* When augmented, also includes `https://` and `http://` for external links.
|
|
29
|
+
*/
|
|
30
|
+
export type RouteTo = keyof RouteManifest extends never
|
|
31
|
+
? string
|
|
32
|
+
: (string & {}) | keyof RouteManifest | `https://${string}` | `http://${string}`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The typed search params for a given `to` pathname.
|
|
36
|
+
* Falls back to a permissive record when RouteManifest is not augmented.
|
|
37
|
+
*/
|
|
38
|
+
export type RouteSearch<To extends RouteTo> = keyof RouteManifest extends never
|
|
39
|
+
? SearchParamsInput
|
|
40
|
+
: To extends keyof RouteManifest
|
|
41
|
+
? RouteManifest[To] extends { searchInput?: infer I }
|
|
42
|
+
? I
|
|
43
|
+
: RouteManifest[To] extends { search?: infer S }
|
|
44
|
+
? S
|
|
45
|
+
: undefined
|
|
46
|
+
: undefined;
|
|
47
|
+
|
|
48
|
+
export type PreloadStrategy = false | "intent" | "viewport" | "render";
|
|
49
|
+
|
|
50
|
+
export interface LinkProps<To extends RouteTo = RouteTo>
|
|
51
|
+
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "children"> {
|
|
52
|
+
/**
|
|
53
|
+
* Extra props merged onto the anchor when the link is active.
|
|
54
|
+
* `isActive` is also passed so one function can handle both states.
|
|
55
|
+
* Styles and classNames from `activeProps` win over the static props.
|
|
56
|
+
*/
|
|
57
|
+
activeProps?: (opts: { isActive: boolean }) => React.AnchorHTMLAttributes<HTMLAnchorElement>;
|
|
58
|
+
/** Static children or a render function receiving active state. */
|
|
59
|
+
children?: React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode);
|
|
60
|
+
/** Prevents navigation and prefetch; adds aria-disabled="true". The href stays intact for right-click. */
|
|
61
|
+
disabled?: boolean;
|
|
62
|
+
/** Optional URL fragment (without the #). */
|
|
63
|
+
hash?: string;
|
|
64
|
+
/**
|
|
65
|
+
* Extra props merged onto the anchor when the link is NOT active.
|
|
66
|
+
* Styles and classNames from `inactiveProps` win over the static props.
|
|
67
|
+
*/
|
|
68
|
+
inactiveProps?: () => React.AnchorHTMLAttributes<HTMLAnchorElement>;
|
|
69
|
+
/** Preload strategy. Default: "intent" (preload on hover/focus). */
|
|
70
|
+
preload?: PreloadStrategy;
|
|
71
|
+
/** Delay in ms before intent preload triggers. Default: 50. */
|
|
72
|
+
preloadDelay?: number;
|
|
73
|
+
/** How long a preloaded entry stays fresh (ms). Default: 30_000. */
|
|
74
|
+
preloadStaleTime?: number;
|
|
75
|
+
/** If true, uses history.replaceState instead of pushState (no new history entry). */
|
|
76
|
+
replace?: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Whether to scroll after SPA navigation. Default: true.
|
|
79
|
+
* - If the destination href has a `#hash`, scrolls to that element.
|
|
80
|
+
* - Otherwise scrolls to the top of the page.
|
|
81
|
+
* Set to `false` to suppress all scroll behaviour (e.g. tab/drawer navigation).
|
|
82
|
+
*/
|
|
83
|
+
resetScroll?: boolean;
|
|
84
|
+
/** Typed search params for this route. Auto-completed from the route's query schema. */
|
|
85
|
+
search?: RouteSearch<To>;
|
|
86
|
+
to: To;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface RouterContextValue {
|
|
90
|
+
/**
|
|
91
|
+
* Sub-path prefix for static deployments (e.g. "/furin").
|
|
92
|
+
* Empty string when the site is served from root.
|
|
93
|
+
* Used by `Link` to build correct physical hrefs for the `<a>` element.
|
|
94
|
+
*/
|
|
95
|
+
basePath: string;
|
|
96
|
+
/** Current **logical** pathname + search (basePath stripped). Used by Link for active-state detection. */
|
|
97
|
+
currentHref: string;
|
|
98
|
+
defaultPreload: PreloadStrategy;
|
|
99
|
+
defaultPreloadDelay: number;
|
|
100
|
+
defaultPreloadStaleTime: number;
|
|
101
|
+
/**
|
|
102
|
+
* Evicts one or more prefetch cache entries, mirroring a `revalidatePath()` call
|
|
103
|
+
* made on the server. Called automatically by the `window.fetch` interceptor when
|
|
104
|
+
* the server emits `X-Furin-Revalidate` headers.
|
|
105
|
+
*
|
|
106
|
+
* - `type: 'page'` (default) — exact URL match
|
|
107
|
+
* - `type: 'layout'` — prefix match (path + all nested children)
|
|
108
|
+
*/
|
|
109
|
+
invalidatePrefetch: (path: string, type: "page" | "layout") => void;
|
|
110
|
+
isNavigating: boolean;
|
|
111
|
+
navigate: (href: string, opts?: { replace?: boolean; resetScroll?: boolean }) => Promise<void>;
|
|
112
|
+
prefetch: (href: string, opts?: { staleTime?: number }) => void;
|
|
113
|
+
/**
|
|
114
|
+
* Re-fetches the current page in-place: busts the prefetch cache entry, re-runs
|
|
115
|
+
* loaders, and updates the rendered tree — without adding a history entry or
|
|
116
|
+
* resetting scroll (unless `resetScroll: true` is passed).
|
|
117
|
+
*
|
|
118
|
+
* Prefer this over `navigate(window.location.pathname)` after a mutation.
|
|
119
|
+
*/
|
|
120
|
+
refresh: (opts?: { resetScroll?: boolean }) => Promise<void>;
|
|
121
|
+
/** Current server-resolved query params for the rendered route. */
|
|
122
|
+
search: SearchParamsInput;
|
|
123
|
+
/** Route-level search defaults used to build clean hrefs without default params. */
|
|
124
|
+
searchRoutes: SearchRouteMetadata[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Client-side mirror of `SegmentBoundary` from router.ts. Unlike the server
|
|
129
|
+
* version this does NOT carry the directory path — it's purely a (depth,
|
|
130
|
+
* fallback) pair because the client never reads files, only renders.
|
|
131
|
+
*/
|
|
132
|
+
export interface ClientSegmentBoundary {
|
|
133
|
+
depth: number;
|
|
134
|
+
error?: ErrorComponent;
|
|
135
|
+
notFound?: NotFoundComponent;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface ClientRoute {
|
|
139
|
+
component?: React.ComponentType<Record<string, unknown>>;
|
|
140
|
+
load: () => Promise<{
|
|
141
|
+
default: { component: React.ComponentType<Record<string, unknown>>; _route: RuntimeRoute };
|
|
142
|
+
segmentBoundaries?: ClientSegmentBoundary[];
|
|
143
|
+
}>;
|
|
144
|
+
pageRoute?: RuntimeRoute;
|
|
145
|
+
pattern: string;
|
|
146
|
+
regex: RegExp;
|
|
147
|
+
searchDefaults?: SearchParamsInput;
|
|
148
|
+
/**
|
|
149
|
+
* Per-segment boundary chain, ordered shallow→deep. Each `depth` maps 1:1
|
|
150
|
+
* to the route-chain index used on the server side, so `buildPageElement`
|
|
151
|
+
* can interleave boundaries at the exact same positions that the server
|
|
152
|
+
* used in `buildElement` — guaranteeing hydration consistency.
|
|
153
|
+
*/
|
|
154
|
+
segmentBoundaries?: ClientSegmentBoundary[];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* A ClientRoute that has been loaded — component and pageRoute are guaranteed defined.
|
|
159
|
+
* The initial route is eagerly loaded in the hydrate entry; subsequent routes are loaded
|
|
160
|
+
* on navigation via fetchPageState.
|
|
161
|
+
*/
|
|
162
|
+
export type LoadedClientRoute = ClientRoute & {
|
|
163
|
+
component: React.ComponentType<Record<string, unknown>>;
|
|
164
|
+
pageRoute: RuntimeRoute;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
export interface RouterProviderProps {
|
|
168
|
+
/**
|
|
169
|
+
* When `true` (default), the router automatically re-fetches the current page
|
|
170
|
+
* whenever a server `revalidatePath()` call targets it. The signal is the
|
|
171
|
+
* `X-Furin-Revalidate` header detected on any `window.fetch` response.
|
|
172
|
+
*
|
|
173
|
+
* Set to `false` to opt out and call `router.refresh()` manually instead.
|
|
174
|
+
*/
|
|
175
|
+
autoRefresh: boolean;
|
|
176
|
+
/**
|
|
177
|
+
* Sub-path prefix for static deployments (e.g. "/furin").
|
|
178
|
+
* Must start with "/" and have no trailing slash.
|
|
179
|
+
* Default: "" (site served from root).
|
|
180
|
+
*/
|
|
181
|
+
basePath: string;
|
|
182
|
+
defaultPreload: PreloadStrategy;
|
|
183
|
+
defaultPreloadDelay: number;
|
|
184
|
+
defaultPreloadStaleTime: number;
|
|
185
|
+
initialData: Record<string, unknown>;
|
|
186
|
+
/**
|
|
187
|
+
* Slice 10 — server-logged error digest threaded from
|
|
188
|
+
* `__FURIN_DATA__.__furinError.digest`. Forwarded onto the root-level
|
|
189
|
+
* `FurinErrorBoundary` so that if a client-side error escapes the
|
|
190
|
+
* per-segment boundaries (root layout crash, hydration mismatch, …), the
|
|
191
|
+
* fallback UI surfaces the id a user would find in server logs.
|
|
192
|
+
*/
|
|
193
|
+
initialDigest: string | undefined;
|
|
194
|
+
/**
|
|
195
|
+
* The route matched at hydration time. `null` is a valid value ONLY when
|
|
196
|
+
* `initialNotFound` is also provided.
|
|
197
|
+
*/
|
|
198
|
+
initialMatch: LoadedClientRoute | null;
|
|
199
|
+
/**
|
|
200
|
+
* When set, the provider boots into the inline not-found state as if a
|
|
201
|
+
* prior SPA navigation hit a 404.
|
|
202
|
+
*/
|
|
203
|
+
initialNotFound: { data?: unknown; message?: string } | undefined;
|
|
204
|
+
/** Maximum number of prefetch cache entries. Oldest entry is evicted when exceeded. Default: 50. */
|
|
205
|
+
prefetchCacheSize: number;
|
|
206
|
+
root: RuntimeRoute | null;
|
|
207
|
+
routes: ClientRoute[];
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** @internal Router state held inside RouterProvider. Exported so CacheEntry can reference it. */
|
|
211
|
+
export interface RouterState {
|
|
212
|
+
data: Record<string, unknown>;
|
|
213
|
+
/**
|
|
214
|
+
* Set when the server's NDJSON payload carried an `__furinError` sentinel.
|
|
215
|
+
*/
|
|
216
|
+
error?: { digest: string; message: string; status: number };
|
|
217
|
+
/** The canonical href after server-side redirects (e.g. query-default redirect). */
|
|
218
|
+
finalHref?: string;
|
|
219
|
+
/**
|
|
220
|
+
* The currently rendered route.
|
|
221
|
+
*
|
|
222
|
+
* `null` is a valid value ONLY when `notFound` is also set.
|
|
223
|
+
*/
|
|
224
|
+
match: LoadedClientRoute | null;
|
|
225
|
+
/**
|
|
226
|
+
* Slice 8 — set when the matched route's loader threw `notFound()` on the server.
|
|
227
|
+
*/
|
|
228
|
+
notFound?: { data?: unknown; message?: string };
|
|
229
|
+
/**
|
|
230
|
+
* Explicit boundary chain to use for the not-found render.
|
|
231
|
+
*/
|
|
232
|
+
notFoundBoundaries?: ClientSegmentBoundary[] | undefined;
|
|
233
|
+
title?: string;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** @internal */
|
|
237
|
+
export interface CacheEntry {
|
|
238
|
+
createdAt: number;
|
|
239
|
+
promise: Promise<RouterState | null>;
|
|
240
|
+
staleTime: number;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Classification of a fetch response during SPA navigation. Returned by the
|
|
245
|
+
* pure `classifySpaResponse` so `fetchPageState` stays a thin orchestrator.
|
|
246
|
+
*
|
|
247
|
+
* - `ok` — 2xx response with usable loader data; render normally.
|
|
248
|
+
* - `not-found` — server signalled `__FURIN_DATA__.__furinStatus === 404`.
|
|
249
|
+
* - `error` — server signalled `__FURIN_DATA__.__furinError`.
|
|
250
|
+
* - `bail` — any other non-2xx without sentinels.
|
|
251
|
+
*
|
|
252
|
+
* @internal Exported for unit testing only.
|
|
253
|
+
*/
|
|
254
|
+
export type SpaResponseKind =
|
|
255
|
+
| { kind: "ok" }
|
|
256
|
+
| { kind: "not-found"; error: { data?: unknown; message?: string } }
|
|
257
|
+
| { kind: "error"; error: { digest: string; message: string; status: number } }
|
|
258
|
+
| { kind: "bail" };
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Root-level safety-net options forwarded onto the outermost
|
|
262
|
+
* `FurinErrorBoundary` that wraps the entire RouterProvider tree.
|
|
263
|
+
*/
|
|
264
|
+
export interface RootBoundaryOptions {
|
|
265
|
+
/**
|
|
266
|
+
* Server-logged error id propagated from `__FURIN_DATA__.__furinError.digest`.
|
|
267
|
+
*/
|
|
268
|
+
digest?: string;
|
|
269
|
+
onReset?: () => void;
|
|
270
|
+
resetKey?: string | number;
|
|
271
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-thrown error carrying an HTTP status and a server-computed digest
|
|
3
|
+
* across SSR and SPA navigation.
|
|
4
|
+
*
|
|
5
|
+
* Why a class (not property-stamping):
|
|
6
|
+
* - Mirrors the `FurinNotFoundError` pattern (consistency).
|
|
7
|
+
* - Type-narrowable via `instanceof` and the brand check.
|
|
8
|
+
* - Survives error wrappers (Sentry / monitoring libs that re-throw
|
|
9
|
+
* `new Error(original.message)` would strip property stamps).
|
|
10
|
+
*
|
|
11
|
+
* Used by:
|
|
12
|
+
* - `FurinErrorBoundary.getDerivedStateFromError` — to honour the server's
|
|
13
|
+
* digest instead of recomputing one client-side (the latter would produce a
|
|
14
|
+
* different hash because the public message + synthetic stack differ from the
|
|
15
|
+
* original server-side error).
|
|
16
|
+
* - SPA navigation: `RouterProvider` throws this during render of the route
|
|
17
|
+
* position when `__furinError` was sentinelled into the NDJSON payload, so
|
|
18
|
+
* the nearest error boundary catches it without forcing a full-page reload.
|
|
19
|
+
*/
|
|
20
|
+
const SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR" as const;
|
|
21
|
+
|
|
22
|
+
export interface FurinServerErrorPayload {
|
|
23
|
+
digest: string;
|
|
24
|
+
message: string;
|
|
25
|
+
status: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class FurinServerError extends Error {
|
|
29
|
+
readonly __furinBrand = SERVER_ERROR_BRAND;
|
|
30
|
+
readonly digest: string;
|
|
31
|
+
readonly status: number;
|
|
32
|
+
|
|
33
|
+
constructor(args: FurinServerErrorPayload) {
|
|
34
|
+
super(args.message);
|
|
35
|
+
this.status = args.status;
|
|
36
|
+
this.digest = args.digest;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isFurinServerError(err: unknown): err is FurinServerError {
|
|
41
|
+
return (
|
|
42
|
+
err instanceof FurinServerError ||
|
|
43
|
+
(typeof err === "object" &&
|
|
44
|
+
err !== null &&
|
|
45
|
+
(err as { __furinBrand?: unknown }).__furinBrand === SERVER_ERROR_BRAND)
|
|
46
|
+
);
|
|
47
|
+
}
|