@teyik0/furin 0.1.0-alpha.10

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 (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
@@ -0,0 +1,176 @@
1
+ import { Component, Fragment, type ReactNode } from "react";
2
+ import { type ErrorComponent, getPublicErrorMessage } from "../error.ts";
3
+ import { isNotFoundError, type NotFoundComponent } from "../not-found.ts";
4
+ import { DefaultErrorScreen, DefaultNotFoundScreen } from "./default-screens.tsx";
5
+ import { computeErrorDigest } from "./digest.ts";
6
+
7
+ const DefaultErrorFallback: ErrorComponent = ({ error, reset }) => (
8
+ <DefaultErrorScreen digest={error.digest} message={error.message} reset={reset} />
9
+ );
10
+
11
+ const DefaultNotFoundFallback: NotFoundComponent = ({ error }) => (
12
+ <DefaultNotFoundScreen message={error.message} />
13
+ );
14
+
15
+ const SERVER_RESET_NOOP = () => {
16
+ /* reset is a client-only action; on the server the response is already committed */
17
+ };
18
+
19
+ interface ErrorBoundaryProps {
20
+ children: ReactNode;
21
+ /**
22
+ * Server-provided digest for an error rendered server-side. Honoured only
23
+ * for the FIRST error this boundary surfaces post-hydration — i.e. when the
24
+ * latched error is plausibly the same one the server already logged. After
25
+ * any reset, or when subsequent client-side errors are caught, the boundary
26
+ * computes a fresh digest from the actual caught error so distinct failures
27
+ * keep distinct IDs.
28
+ */
29
+ digest?: string;
30
+ /** Component rendered when an error is caught. Omit to use the built-in default. */
31
+ fallback?: ErrorComponent;
32
+ /**
33
+ * Invoked AFTER the boundary has cleared its local error state. Slice 7
34
+ * wires this to `router.navigate(currentHref, { force: true })` so the
35
+ * loader re-runs.
36
+ */
37
+ onReset?: () => void;
38
+ /**
39
+ * When this value changes the boundary clears its error state, effectively
40
+ * retrying the render of `children`. Slice 7 drives this from router
41
+ * navigation success.
42
+ */
43
+ resetKey?: string | number;
44
+ }
45
+
46
+ interface ErrorBoundaryState {
47
+ /**
48
+ * Digest computed at the moment the error was latched. Stored in state so
49
+ * each distinct caught error gets its own ID, instead of all of them
50
+ * inheriting the server-provided `digest` prop.
51
+ */
52
+ digest: string | null;
53
+ /** Unmount/remount counter — bumped on reset to force React to discard
54
+ * the previous subtree (including any broken state). */
55
+ epoch: number;
56
+ error: Error | null;
57
+ }
58
+
59
+ /**
60
+ * Catches generic errors thrown during render of `children`. Lets
61
+ * `FurinNotFoundError` bubble past so a sibling `<FurinNotFoundBoundary>`
62
+ * can handle it.
63
+ *
64
+ * Must be a class: React error catching (`getDerivedStateFromError`,
65
+ * `componentDidCatch`) has no function-component equivalent.
66
+ */
67
+ // biome-ignore lint/style/useReactFunctionComponents: React error boundaries require a class component.
68
+ export class FurinErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
69
+ override state: ErrorBoundaryState = {
70
+ digest: null,
71
+ epoch: 0,
72
+ error: null,
73
+ };
74
+
75
+ static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
76
+ // Compute the digest right at catch-time so the value is anchored to THIS
77
+ // specific error instance. Doing it here (vs. lazily in render) also means
78
+ // a re-render with the same latched error keeps the same ID.
79
+ return { digest: computeErrorDigest(error), error };
80
+ }
81
+
82
+ override componentDidUpdate(prevProps: ErrorBoundaryProps) {
83
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
84
+ this.reset();
85
+ }
86
+ }
87
+
88
+ reset = () => {
89
+ // setState is async; running onReset BEFORE the state has actually flipped
90
+ // would expose stale `state.error` to anything the callback transitively
91
+ // reads (e.g. router.refresh re-rendering this very subtree). The second
92
+ // argument to setState fires after the commit, which is what we want.
93
+ this.setState(
94
+ (s) => ({ digest: null, epoch: s.epoch + 1, error: null }),
95
+ () => {
96
+ this.props.onReset?.();
97
+ }
98
+ );
99
+ };
100
+
101
+ override render(): ReactNode {
102
+ const { error, epoch, digest } = this.state;
103
+ if (error) {
104
+ // notFound() is a control-flow signal — bubble it up to the nearest
105
+ // FurinNotFoundBoundary rather than displaying an error UI for it.
106
+ if (isNotFoundError(error)) {
107
+ throw error;
108
+ }
109
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
110
+ // Digest precedence:
111
+ // 1. state.digest — computed at catch time, always correct for the
112
+ // ACTUAL caught error.
113
+ // 2. props.digest — the server-rendered digest, only meaningful for
114
+ // the very first error post-hydration; we still honour it as a
115
+ // last-resort fallback in case state.digest is somehow missing
116
+ // (e.g. tests that inject state by hand).
117
+ // 3. recompute on the spot — defensive, should never be reached.
118
+ const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
119
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
120
+ return (
121
+ <Fallback
122
+ error={{ message, digest: finalDigest }}
123
+ reset={typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset}
124
+ />
125
+ );
126
+ }
127
+ // The `key` trick ensures that after a reset, children remount fresh
128
+ // rather than retaining stale state from the failed render.
129
+ return <Fragment key={epoch}>{this.props.children}</Fragment>;
130
+ }
131
+ }
132
+
133
+ interface NotFoundBoundaryProps {
134
+ children: ReactNode;
135
+ fallback?: NotFoundComponent;
136
+ resetKey?: string | number;
137
+ }
138
+
139
+ interface NotFoundBoundaryState {
140
+ epoch: number;
141
+ error: Error | null;
142
+ }
143
+
144
+ /**
145
+ * Catches `FurinNotFoundError` (thrown by `notFound()`) and renders the
146
+ * nearest not-found UI. Generic errors are re-thrown from render() so a
147
+ * parent `<FurinErrorBoundary>` can handle them.
148
+ *
149
+ * Must be a class: React error catching has no function-component equivalent.
150
+ */
151
+ // biome-ignore lint/style/useReactFunctionComponents: React error boundaries require a class component.
152
+ export class FurinNotFoundBoundary extends Component<NotFoundBoundaryProps, NotFoundBoundaryState> {
153
+ override state: NotFoundBoundaryState = { epoch: 0, error: null };
154
+
155
+ static getDerivedStateFromError(error: Error): Partial<NotFoundBoundaryState> {
156
+ return { error };
157
+ }
158
+
159
+ override componentDidUpdate(prevProps: NotFoundBoundaryProps) {
160
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
161
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
162
+ }
163
+ }
164
+
165
+ override render(): ReactNode {
166
+ const { error, epoch } = this.state;
167
+ if (error) {
168
+ if (!isNotFoundError(error)) {
169
+ throw error;
170
+ }
171
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
172
+ return <Fallback error={{ message: error.message, data: error.data }} />;
173
+ }
174
+ return <Fragment key={epoch}>{this.props.children}</Fragment>;
175
+ }
176
+ }
@@ -0,0 +1,251 @@
1
+ export interface ISRCacheEntry {
2
+ generatedAt: number;
3
+ html: string;
4
+ revalidate: number;
5
+ }
6
+
7
+ export interface SsgCacheEntry {
8
+ cachedAt: number;
9
+ html: string;
10
+ status: number;
11
+ }
12
+
13
+ /** Maximum number of ISR cache entries before LRU eviction kicks in. */
14
+ const MAX_ISR_CACHE_SIZE = 1000;
15
+ /** Maximum number of SSG cache entries before LRU eviction kicks in. */
16
+ const MAX_SSG_CACHE_SIZE = 1000;
17
+
18
+ export const isrCache = new Map<string, ISRCacheEntry>();
19
+ export const ssgCache = new Map<string, SsgCacheEntry>();
20
+
21
+ /**
22
+ * Evicts the oldest entry from a Map when its size exceeds the given limit.
23
+ * JS Maps maintain insertion order, so the first key is always the oldest.
24
+ */
25
+ function evictOldest<V>(map: Map<string, V>, maxSize: number): void {
26
+ if (map.size > maxSize) {
27
+ const oldest = map.keys().next().value;
28
+ if (oldest !== undefined) {
29
+ map.delete(oldest);
30
+ }
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Gets an ISR cache entry and refreshes its recency so it is treated as
36
+ * recently used by the LRU eviction policy. Without this, a hot entry that
37
+ * was written early would be evicted before a cold entry written later.
38
+ */
39
+ export function getISRCache(key: string): ISRCacheEntry | undefined {
40
+ const entry = isrCache.get(key);
41
+ if (entry !== undefined) {
42
+ // Re-insert at the end to mark as most-recently used
43
+ isrCache.delete(key);
44
+ isrCache.set(key, entry);
45
+ }
46
+ return entry;
47
+ }
48
+
49
+ /**
50
+ * Gets an SSG cache entry and refreshes its recency so it is treated as
51
+ * recently used by the LRU eviction policy.
52
+ */
53
+ export function getSSGCache(key: string): SsgCacheEntry | undefined {
54
+ const entry = ssgCache.get(key);
55
+ if (entry !== undefined) {
56
+ ssgCache.delete(key);
57
+ ssgCache.set(key, entry);
58
+ }
59
+ return entry;
60
+ }
61
+
62
+ /** Sets an ISR cache entry with LRU eviction. */
63
+ export function setISRCache(key: string, entry: ISRCacheEntry): void {
64
+ // Delete first to re-insert at the end (refresh insertion order for LRU)
65
+ isrCache.delete(key);
66
+ isrCache.set(key, entry);
67
+ evictOldest(isrCache, MAX_ISR_CACHE_SIZE);
68
+ }
69
+
70
+ /** Sets an SSG cache entry with LRU eviction. */
71
+ export function setSSGCache(key: string, entry: SsgCacheEntry): void {
72
+ ssgCache.delete(key);
73
+ ssgCache.set(key, entry);
74
+ evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
75
+ }
76
+
77
+ // ── Build ID ─────────────────────────────────────────────────────────────────
78
+
79
+ let _buildId = "";
80
+
81
+ /** Set once at server startup from the CompileContext. */
82
+ export function setBuildId(id: string): void {
83
+ _buildId = id;
84
+ }
85
+
86
+ /** Returns the current deployment build ID, or empty string in dev / before set. */
87
+ export function getBuildId(): string {
88
+ return _buildId;
89
+ }
90
+
91
+ import { AsyncLocalStorage } from "node:async_hooks";
92
+ // ── Pending invalidations (server → client bridge) ───────────────────────────
93
+ //
94
+ // Per-request scoping via AsyncLocalStorage: furin wraps each request's full
95
+ // lifecycle (handler + all hooks) inside `_requestInvalidationScope.run()` so
96
+ // that `revalidatePath()` and `consumePendingInvalidations()` share an isolated
97
+ // Set per request. The global `_globalPendingInvalidations` is a fallback for
98
+ // calls made outside a request context (e.g. scripts, tests, warmup code).
99
+ import { createLogger } from "../context-logger.ts";
100
+
101
+ const _requestInvalidationScope = new AsyncLocalStorage<Set<string>>();
102
+ const _globalPendingInvalidations = new Set<string>();
103
+
104
+ function _activeInvalidationSet(): Set<string> {
105
+ return _requestInvalidationScope.getStore() ?? _globalPendingInvalidations;
106
+ }
107
+
108
+ /**
109
+ * Wraps `fn` in a fresh per-request invalidation scope.
110
+ * Call this around the entire Elysia request handle so that all lifecycle
111
+ * hooks share an isolated invalidation Set.
112
+ * @internal
113
+ */
114
+ export function _runWithRequestInvalidationScope<T>(fn: () => T): T {
115
+ return _requestInvalidationScope.run(new Set<string>(), fn);
116
+ }
117
+
118
+ /**
119
+ * Consume and clear all pending invalidation paths for the current request.
120
+ * Called by the Elysia `onAfterHandle` hook to populate `X-Furin-Revalidate`.
121
+ * @internal
122
+ */
123
+ export function consumePendingInvalidations(): string[] {
124
+ const set = _activeInvalidationSet();
125
+ if (set.size === 0) {
126
+ return [];
127
+ }
128
+ const paths = [...set];
129
+ set.clear();
130
+ return paths;
131
+ }
132
+
133
+ // ── CDN purger hook ───────────────────────────────────────────────────────────
134
+
135
+ type CachePurger = (paths: string[]) => Promise<void>;
136
+ let _cachePurger: CachePurger | null = null;
137
+
138
+ /**
139
+ * Register a CDN cache purger that will be called whenever `revalidatePath()`
140
+ * is invoked. Intended for use by platform adapters (Vercel, Cloudflare, etc.).
141
+ *
142
+ * The purger is called fire-and-forget — errors are logged but do not affect
143
+ * the HTTP response.
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * // In a Vercel adapter:
148
+ * import { setCachePurger } from "@teyik0/furin";
149
+ * setCachePurger(async (paths) => {
150
+ * await fetch("https://api.vercel.com/v1/edge-cache/purge", {
151
+ * method: "POST",
152
+ * headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
153
+ * body: JSON.stringify({ urls: paths }),
154
+ * });
155
+ * });
156
+ * ```
157
+ */
158
+ export function setCachePurger(fn: CachePurger): void {
159
+ _cachePurger = fn;
160
+ }
161
+
162
+ /** @internal */
163
+ export function callCachePurger(paths: string[]): void {
164
+ if (!_cachePurger || paths.length === 0) {
165
+ return;
166
+ }
167
+ _cachePurger(paths).catch((err: unknown) => {
168
+ const logger = createLogger({});
169
+ logger.set({
170
+ furin: {
171
+ action: "cdn_purge_failed",
172
+ paths,
173
+ },
174
+ });
175
+ logger.error(err instanceof Error ? err : new Error(String(err)));
176
+ logger.emit();
177
+ });
178
+ }
179
+
180
+ // ── revalidatePath ───────────────────────────────────────────────────────────
181
+
182
+ /**
183
+ * Programmatically invalidate the server-side cache for a given path.
184
+ *
185
+ * - `type: 'page'` (default): exact URL match.
186
+ * - `type: 'layout'`: the path itself plus all nested children (prefix match).
187
+ *
188
+ * Works for ISR and SSG routes. SSR routes are always fresh (no server-side
189
+ * cache), but calling this still queues a client-side prefetch invalidation
190
+ * via the `X-Furin-Revalidate` response header.
191
+ *
192
+ * If a CDN purger has been registered via `setCachePurger()`, it will also be
193
+ * called asynchronously to purge the CDN edge cache.
194
+ *
195
+ * @returns `true` if at least one server-side cache entry was removed.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * // In an API route or webhook handler:
200
+ * import { revalidatePath } from "@teyik0/furin";
201
+ *
202
+ * revalidatePath("/blog/my-post"); // invalidate a single page
203
+ * revalidatePath("/blog", "layout"); // invalidate /blog + all children
204
+ * ```
205
+ */
206
+ export function revalidatePath(path: string, type: "page" | "layout" = "page"): boolean {
207
+ // Queue for client-side notification via X-Furin-Revalidate header
208
+ _activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
209
+
210
+ let deleted = false;
211
+
212
+ if (type === "page") {
213
+ deleted = isrCache.delete(path) || deleted;
214
+ deleted = ssgCache.delete(path) || deleted;
215
+ callCachePurger([path]);
216
+ return deleted;
217
+ }
218
+
219
+ // layout: prefix match — invalidate the path itself + all nested children
220
+ const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
221
+ const purgedPaths: string[] = [];
222
+
223
+ for (const key of isrCache.keys()) {
224
+ if (key === path || key.startsWith(prefix)) {
225
+ isrCache.delete(key);
226
+ deleted = true;
227
+ purgedPaths.push(key);
228
+ }
229
+ }
230
+ for (const key of ssgCache.keys()) {
231
+ if (key === path || key.startsWith(prefix)) {
232
+ ssgCache.delete(key);
233
+ deleted = true;
234
+ if (!purgedPaths.includes(key)) {
235
+ purgedPaths.push(key);
236
+ }
237
+ }
238
+ }
239
+
240
+ callCachePurger(purgedPaths.length > 0 ? purgedPaths : [path]);
241
+ return deleted;
242
+ }
243
+
244
+ /** @internal — resets all module state between tests */
245
+ export function __resetCacheState(): void {
246
+ isrCache.clear();
247
+ ssgCache.clear();
248
+ _buildId = "";
249
+ _globalPendingInvalidations.clear();
250
+ _cachePurger = null;
251
+ }