@teyik0/furin 0.1.0-alpha.8 → 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 +4734 -548
  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 +4713 -549
  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 +54 -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 +5288 -601
  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/server/context-logger.d.ts +28 -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 -4
  68. package/{src → dist/server}/render/shell.ts +31 -9
  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 +83 -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 +83 -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/server/context-logger.ts +76 -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 -1173
  163. package/dist/render/assemble.d.ts +0 -13
  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 -34
  169. package/dist/router.js +0 -830
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1035
  172. package/src/render/assemble.ts +0 -64
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -479
  176. package/src/render/loaders.ts +0 -113
  177. package/src/router.ts +0 -400
  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
@@ -1,11 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { parseSync } from "oxc-parser";
3
-
4
- // Minimal AST node shapes — just what we need
5
- interface AstNode {
6
- type: string;
7
- [key: string]: unknown;
8
- }
2
+ import { parse, type CallExpression, type ObjectExpression, type ObjectProperty } from "yuku-parser";
3
+ import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
4
+ import { walkAST } from "../shared/utils/ast-walk.ts";
9
5
 
10
6
  /**
11
7
  * Statically scans a server entry file and returns all `pagesDir` string
@@ -16,31 +12,45 @@ interface AstNode {
16
12
  */
17
13
  export function scanFurinInstances(serverEntryPath: string): string[] {
18
14
  const code = readFileSync(serverEntryPath, "utf8");
19
- const { program, errors } = parseSync(serverEntryPath, code);
20
- if (errors.length > 0) {
15
+ const lang = detectLangFromPath(serverEntryPath);
16
+
17
+ // Declaration files contain no runtime code — skip parsing.
18
+ if (lang === "dts") {
19
+ return [];
20
+ }
21
+
22
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
23
+ const firstError = diagnostics.find((d) => d.severity === "error");
24
+ if (firstError) {
25
+ console.error("[furin] scan-server: parse error:", firstError.message, "in", serverEntryPath);
21
26
  return [];
22
27
  }
23
28
 
24
29
  const results: string[] = [];
25
- walkNode(program as unknown as AstNode, results);
30
+ walkAST(program, (node) => {
31
+ if (node.type === "CallExpression") {
32
+ checkFurinCall(node as unknown as CallExpression, results);
33
+ }
34
+ });
26
35
  return results;
27
36
  }
28
37
 
29
- const SKIP_KEYS = new Set(["type", "start", "end"]);
30
-
31
38
  /** Checks whether `node` is a `furin({ pagesDir: "..." })` call and, if so, pushes the value. */
32
- function checkFurinCall(node: AstNode, out: string[]): void {
33
- const callee = node.callee as AstNode | undefined;
34
- const args = node.arguments as AstNode[] | undefined;
35
- const isFurinCall =
36
- callee?.type === "Identifier" && (callee as { name?: string }).name === "furin";
39
+ function checkFurinCall(node: CallExpression, out: string[]): void {
40
+ const isFurinCall = node.callee.type === "Identifier" && node.callee.name === "furin";
37
41
 
38
- if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
42
+ if (!isFurinCall || node.arguments.length === 0) {
39
43
  return;
40
44
  }
41
45
 
42
- const firstArg = args[0] as AstNode;
43
- if (firstArg?.type !== "ObjectExpression") {
46
+ // Unwrap TS expression wrappers like `furin({...} as Config)` or
47
+ // `furin({...} satisfies Options)` so we still see the ObjectExpression.
48
+ const firstArgNode = node.arguments[0];
49
+ if (!firstArgNode) {
50
+ return;
51
+ }
52
+ const firstArg = unwrapTSExpression(firstArgNode);
53
+ if (!isObjectExpressionNode(firstArg)) {
44
54
  return;
45
55
  }
46
56
 
@@ -50,61 +60,36 @@ function checkFurinCall(node: AstNode, out: string[]): void {
50
60
  }
51
61
  }
52
62
 
53
- /** Recurses into all child AST node values (arrays and plain objects). */
54
- function walkChildren(node: AstNode, out: string[]): void {
55
- for (const key of Object.keys(node)) {
56
- if (SKIP_KEYS.has(key)) {
63
+ function isObjectExpressionNode(node: { type: string }): node is ObjectExpression {
64
+ return node.type === "ObjectExpression";
65
+ }
66
+
67
+ function extractStringProperty(obj: ObjectExpression, propName: string): string | null {
68
+ for (const prop of obj.properties) {
69
+ if (prop.type !== "Property") {
57
70
  continue;
58
71
  }
59
- const child = node[key];
60
- if (Array.isArray(child)) {
61
- for (const item of child) {
62
- if (item && typeof item === "object") {
63
- walkNode(item as AstNode, out);
64
- }
65
- }
66
- } else if (child && typeof child === "object") {
67
- walkNode(child as AstNode, out);
72
+ const value = getStringPropertyValue(prop, propName);
73
+
74
+ if (value !== undefined) {
75
+ return value;
68
76
  }
69
77
  }
78
+ return null;
70
79
  }
71
80
 
72
- function walkNode(node: AstNode, out: string[]): void {
73
- if (!node || typeof node !== "object") {
74
- return;
75
- }
76
- if (node.type === "CallExpression") {
77
- checkFurinCall(node, out);
78
- }
79
- walkChildren(node, out);
80
- }
81
+ function getStringPropertyValue(prop: ObjectProperty, propName: string): string | null | undefined {
82
+ const keyMatches =
83
+ (prop.key.type === "Identifier" && prop.key.name === propName) ||
84
+ (prop.key.type === "Literal" && prop.key.value === propName);
81
85
 
82
- function extractStringProperty(obj: AstNode, propName: string): string | null {
83
- const properties = obj.properties as AstNode[] | undefined;
84
- if (!Array.isArray(properties)) {
85
- return null;
86
+ if (!keyMatches) {
87
+ return undefined;
86
88
  }
87
89
 
88
- for (const prop of properties) {
89
- if (prop.type !== "Property") {
90
- continue;
91
- }
92
- const key = prop.key as AstNode & { name?: string; value?: unknown };
93
- const value = prop.value as AstNode & { value?: unknown };
94
-
95
- const keyMatches =
96
- (key.type === "Identifier" && key.name === propName) ||
97
- (key.type === "Literal" && key.value === propName);
98
-
99
- if (!keyMatches) {
100
- continue;
101
- }
102
-
103
- // Only accept string literals — ignore template literals, identifiers, etc.
104
- if (value?.type === "Literal" && typeof value.value === "string") {
105
- return value.value;
106
- }
107
- return null; // dynamic path — silently skip
90
+ // Only accept string literals — ignore template literals, identifiers, etc.
91
+ if (prop.value.type === "Literal" && typeof prop.value.value === "string") {
92
+ return prop.value.value;
108
93
  }
109
- return null;
94
+ return null; // dynamic path — silently skip
110
95
  }
@@ -1,16 +1,8 @@
1
1
  import { writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { buildEntrySource } from "./entry-template";
3
+ import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
4
  import { ensureDir } from "./shared";
5
5
 
6
- export interface ServerRoutesEntryOptions {
7
- buildId?: string;
8
- outDir: string;
9
- rootPath: string;
10
- routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
11
- serverEntry: string;
12
- }
13
-
14
6
  /**
15
7
  * Generates `server.ts` — an intermediate entry used to produce `server.js`.
16
8
  *
@@ -22,8 +14,9 @@ export interface ServerRoutesEntryOptions {
22
14
  * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
23
15
  * the self-contained `server.js` bundle, then deletes this file.
24
16
  */
25
- export function generateServerRoutesEntry(options: ServerRoutesEntryOptions): string {
26
- const { buildId, outDir, rootPath, routes, serverEntry } = options;
17
+ export function generateServerRoutesEntry(options: BuildEntryOptions): string {
18
+ const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata, ssgCache } =
19
+ options;
27
20
  ensureDir(outDir);
28
21
  const source = buildEntrySource({
29
22
  buildId,
@@ -31,6 +24,9 @@ export function generateServerRoutesEntry(options: ServerRoutesEntryOptions): st
31
24
  rootPath,
32
25
  routes,
33
26
  serverEntry,
27
+ rootConventions,
28
+ routeMetadata,
29
+ ssgCache,
34
30
  });
35
31
 
36
32
  // Named "server.ts" so Bun.build() outputs "server.js"
@@ -1,7 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
3
  import type { BuildTarget } from "../config";
4
- import type { ResolvedRoute } from "../router";
4
+ import type { ResolvedRoute } from "../server/router/index.ts";
5
5
  import type { BuildRouteManifestEntry, TargetBuildManifest } from "./types";
6
6
 
7
7
  // import.meta.dir/path/url are inlined at bundle time to the OUTPUT file's
@@ -0,0 +1,31 @@
1
+ import type { SsgCacheEntry } from "../server/cache/index.ts";
2
+ import { prerenderSSG } from "../server/render/index.ts";
3
+ import type { ResolvedRoute, RootLayout } from "../server/router/index.ts";
4
+ import { resolvePath } from "../server/render/assemble.ts";
5
+
6
+ export type SSGCacheSnapshot = Record<string, SsgCacheEntry>;
7
+
8
+ export async function buildSSGCacheSnapshot(
9
+ routes: ResolvedRoute[],
10
+ root: RootLayout,
11
+ origin: string
12
+ ): Promise<SSGCacheSnapshot> {
13
+ const snapshot: SSGCacheSnapshot = {};
14
+
15
+ for (const route of routes) {
16
+ if (route.mode !== "ssg" || !route.page.staticParams) {
17
+ continue;
18
+ }
19
+
20
+ const paramSets = await route.page.staticParams();
21
+ for (const params of paramSets) {
22
+ const entry = await prerenderSSG(route, params, root, origin, undefined);
23
+ if (entry instanceof Response) {
24
+ continue;
25
+ }
26
+ snapshot[resolvePath(route.pattern, params)] = entry;
27
+ }
28
+ }
29
+
30
+ return snapshot;
31
+ }
@@ -1,5 +1,5 @@
1
1
  import type { BuildTarget, StaticExportConfig } from "../config";
2
- import type { ResolvedRoute } from "../router";
2
+ import type { ResolvedRoute } from "../server/router/index.ts";
3
3
 
4
4
  export interface BuildClientOptions {
5
5
  /**
@@ -8,6 +8,8 @@ export interface BuildClientOptions {
8
8
  * correct physical URLs. Pass "" for root deployments.
9
9
  */
10
10
  basePath: string;
11
+ /** Inject the evlog client logger into the hydrate entry. Off by default. */
12
+ clientLogging: boolean;
11
13
  outDir: string;
12
14
  pagesDir?: string;
13
15
  plugins?: Bun.BunPlugin[];
@@ -53,6 +55,8 @@ export interface BuildManifest {
53
55
  }
54
56
 
55
57
  export interface BuildAppOptions {
58
+ /** Inject the evlog client logger into the hydrate entry. Defaults to false. */
59
+ clientLogging?: boolean;
56
60
  compile?: "server" | "embed";
57
61
  pagesDir?: string;
58
62
  plugins?: Bun.BunPlugin[];
package/src/cli/index.ts CHANGED
@@ -93,6 +93,7 @@ if (command === "build") {
93
93
  serverEntry: resolvedServerEntry,
94
94
  plugins: config.plugins,
95
95
  staticConfig: config.static,
96
+ clientLogging: config.clientLogging ?? false,
96
97
  });
97
98
 
98
99
  const built = Object.keys(result.targets).join(", ") || "none";
@@ -0,0 +1,259 @@
1
+ import { Component, Fragment, type ReactNode } from "react";
2
+ import { computeErrorDigest } from "../shared/digest.ts";
3
+ import { type ErrorComponent, getPublicErrorMessage } from "../shared/error.ts";
4
+ import { isNotFoundError, type NotFoundComponent } from "../shared/not-found.ts";
5
+ import { DefaultErrorFallback, DefaultNotFoundFallback } from "./default-screens.tsx";
6
+ import { isFurinServerError } from "./server-error.ts";
7
+
8
+ /**
9
+ * Default HTTP status surfaced to error UIs when the caught error has no
10
+ * intrinsic status (e.g. a thrown `Error`, a non-Error throw). The loader
11
+ * pipeline produces a `FurinServerError` with the right status when a thrown
12
+ * `Response` is the cause; everything else collapses to 500.
13
+ */
14
+ const DEFAULT_ERROR_STATUS = 500;
15
+
16
+ const SERVER_RESET_NOOP = () => {
17
+ /* reset is a client-only action; on the server the response is already committed */
18
+ };
19
+
20
+ interface ErrorBoundaryProps {
21
+ children: ReactNode;
22
+ /**
23
+ * Server-provided digest for an error rendered server-side. Honoured only
24
+ * for the FIRST error this boundary surfaces post-hydration — i.e. when the
25
+ * latched error is plausibly the same one the server already logged. After
26
+ * any reset, or when subsequent client-side errors are caught, the boundary
27
+ * computes a fresh digest from the actual caught error so distinct failures
28
+ * keep distinct IDs.
29
+ */
30
+ digest?: string;
31
+ /** Component rendered when an error is caught. Omit to use the built-in default. */
32
+ fallback?: ErrorComponent;
33
+ /**
34
+ * Invoked AFTER the boundary has cleared its local error state. Slice 7
35
+ * wires this to `router.navigate(currentHref, { force: true })` so the
36
+ * loader re-runs.
37
+ */
38
+ onReset?: () => void;
39
+ /**
40
+ * When this value changes the boundary clears its error state, effectively
41
+ * retrying the render of `children`. Slice 7 drives this from router
42
+ * navigation success.
43
+ */
44
+ resetKey?: string | number;
45
+ }
46
+
47
+ interface ErrorBoundaryState {
48
+ /**
49
+ * Digest computed at the moment the error was latched. Stored in state so
50
+ * each distinct caught error gets its own ID, instead of all of them
51
+ * inheriting the server-provided `digest` prop.
52
+ */
53
+ digest: string | null;
54
+ /** Unmount/remount counter — bumped on reset to force React to discard
55
+ * the previous subtree (including any broken state). */
56
+ epoch: number;
57
+ error: Error | null;
58
+ }
59
+
60
+ /**
61
+ * Catches generic errors thrown during render of `children`. Lets
62
+ * `FurinNotFoundError` bubble past so a sibling `<FurinNotFoundBoundary>`
63
+ * can handle it.
64
+ *
65
+ * Must be a class: React error catching (`getDerivedStateFromError`,
66
+ * `componentDidCatch`) has no function-component equivalent.
67
+ */
68
+ // biome-ignore lint/style/useReactFunctionComponents: React error boundaries require a class component.
69
+ export class FurinErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
70
+ override state: ErrorBoundaryState = {
71
+ digest: null,
72
+ epoch: 0,
73
+ error: null,
74
+ };
75
+
76
+ static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
77
+ // Compute the digest right at catch-time so the value is anchored to THIS
78
+ // specific error instance. Doing it here (vs. lazily in render) also means
79
+ // a re-render with the same latched error keeps the same ID.
80
+ return { digest: computeErrorDigest(error), error };
81
+ }
82
+
83
+ override componentDidUpdate(prevProps: ErrorBoundaryProps) {
84
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
85
+ this.reset();
86
+ }
87
+ }
88
+
89
+ reset = () => {
90
+ // setState is async; running onReset BEFORE the state has actually flipped
91
+ // would expose stale `state.error` to anything the callback transitively
92
+ // reads (e.g. router.refresh re-rendering this very subtree). The second
93
+ // argument to setState fires after the commit, which is what we want.
94
+ this.setState(
95
+ (s) => ({ digest: null, epoch: s.epoch + 1, error: null }),
96
+ () => {
97
+ this.props.onReset?.();
98
+ }
99
+ );
100
+ };
101
+
102
+ override render(): ReactNode {
103
+ const { error, epoch, digest } = this.state;
104
+ if (error) {
105
+ // notFound() is a control-flow signal — bubble it up to the nearest
106
+ // FurinNotFoundBoundary rather than displaying an error UI for it.
107
+ if (isNotFoundError(error)) {
108
+ throw error;
109
+ }
110
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
111
+ // Digest precedence:
112
+ // 1. FurinServerError.digest — when the server emitted an error
113
+ // sentinel through the SPA-nav payload, the synthesized error
114
+ // carries the server's own digest so logs correlate without
115
+ // recomputing a different hash from a synthetic stack.
116
+ // 2. state.digest — computed at catch time, always correct for the
117
+ // ACTUAL caught error.
118
+ // 3. props.digest — the server-rendered digest, only meaningful for
119
+ // the very first error post-hydration; we still honour it as a
120
+ // last-resort fallback in case state.digest is somehow missing
121
+ // (e.g. tests that inject state by hand).
122
+ // 4. recompute on the spot — defensive, should never be reached.
123
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
124
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
125
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
126
+ // Status precedence: FurinServerError carries the original Response.status
127
+ // (or the loader's computed 500 for non-Response throws); everything else
128
+ // collapses to the default 500.
129
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
130
+ return (
131
+ <Fallback
132
+ error={{ message, digest: finalDigest, status }}
133
+ reset={typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset}
134
+ />
135
+ );
136
+ }
137
+ // The `key` trick ensures that after a reset, children remount fresh
138
+ // rather than retaining stale state from the failed render.
139
+ return <Fragment key={epoch}>{this.props.children}</Fragment>;
140
+ }
141
+ }
142
+
143
+ interface NotFoundBoundaryProps {
144
+ children: ReactNode;
145
+ fallback?: NotFoundComponent;
146
+ resetKey?: string | number;
147
+ }
148
+
149
+ interface NotFoundBoundaryState {
150
+ epoch: number;
151
+ error: Error | null;
152
+ }
153
+
154
+ /**
155
+ * Catches `FurinNotFoundError` (thrown by `notFound()`) and renders the
156
+ * nearest not-found UI. Generic errors are re-thrown from render() so a
157
+ * parent `<FurinErrorBoundary>` can handle them.
158
+ *
159
+ * Must be a class: React error catching has no function-component equivalent.
160
+ */
161
+ // biome-ignore lint/style/useReactFunctionComponents: React error boundaries require a class component.
162
+ export class FurinNotFoundBoundary extends Component<NotFoundBoundaryProps, NotFoundBoundaryState> {
163
+ override state: NotFoundBoundaryState = { epoch: 0, error: null };
164
+
165
+ static getDerivedStateFromError(error: Error): Partial<NotFoundBoundaryState> {
166
+ return { error };
167
+ }
168
+
169
+ override componentDidUpdate(prevProps: NotFoundBoundaryProps) {
170
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
171
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
172
+ }
173
+ }
174
+
175
+ override render(): ReactNode {
176
+ const { error, epoch } = this.state;
177
+ if (error) {
178
+ if (!isNotFoundError(error)) {
179
+ throw error;
180
+ }
181
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
182
+ return <Fallback error={{ message: error.message, data: error.data }} />;
183
+ }
184
+ return <Fragment key={epoch}>{this.props.children}</Fragment>;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Options passed to `wrapSegmentBoundaries` when running on the client.
190
+ * The server path omits them entirely.
191
+ */
192
+ export interface BoundaryOptions {
193
+ onReset?: () => void;
194
+ resetKey?: string | number;
195
+ }
196
+
197
+ /**
198
+ * Minimal shape of a segment boundary descriptor, accepted by both server-side
199
+ * `SegmentBoundary` and client-side `ClientSegmentBoundary`.
200
+ */
201
+ export interface SegmentBoundaryLike {
202
+ error?: ErrorComponent;
203
+ notFound?: NotFoundComponent;
204
+ }
205
+
206
+ /**
207
+ * Wraps `inner` with the boundary pair declared at a single segment depth.
208
+ *
209
+ * The ordering is deliberate and MUST be kept identical on server **and**
210
+ * client so that hydration sees the exact same React tree:
211
+ *
212
+ * <FurinErrorBoundary>
213
+ * <FurinNotFoundBoundary>{inner}</FurinNotFoundBoundary>
214
+ * </FurinErrorBoundary>
215
+ *
216
+ * `FurinErrorBoundary` is OUTSIDE because it re-throws `FurinNotFoundError`
217
+ * during render, allowing an ancestor not-found boundary to catch it. Placing
218
+ * the not-found boundary inside would mean the same-depth error boundary
219
+ * catches a `notFound()` throw first, latches onto it, and the re-throw would
220
+ * not find a `NotFoundBoundary` deeper than itself — it needs one higher up.
221
+ *
222
+ * @param inner - React subtree to wrap.
223
+ * @param segment - Boundary descriptor for this depth (may be undefined).
224
+ * @param options - Optional client-side reset options (ignored on server).
225
+ * @returns The wrapped React node.
226
+ */
227
+ export function wrapSegmentBoundaries(
228
+ inner: ReactNode,
229
+ segment: SegmentBoundaryLike | undefined,
230
+ options: BoundaryOptions | undefined
231
+ ): ReactNode {
232
+ if (!segment) {
233
+ return inner;
234
+ }
235
+
236
+ let wrapped: ReactNode = inner;
237
+
238
+ if (segment.notFound) {
239
+ wrapped = (
240
+ <FurinNotFoundBoundary fallback={segment.notFound} resetKey={options?.resetKey}>
241
+ {wrapped}
242
+ </FurinNotFoundBoundary>
243
+ );
244
+ }
245
+
246
+ if (segment.error) {
247
+ wrapped = (
248
+ <FurinErrorBoundary
249
+ fallback={segment.error}
250
+ onReset={options?.onReset}
251
+ resetKey={options?.resetKey}
252
+ >
253
+ {wrapped}
254
+ </FurinErrorBoundary>
255
+ );
256
+ }
257
+
258
+ return wrapped;
259
+ }