@ivogt/rsc-router 0.0.0-experimental.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 (123) hide show
  1. package/README.md +19 -0
  2. package/package.json +131 -0
  3. package/src/__mocks__/version.ts +6 -0
  4. package/src/__tests__/route-definition.test.ts +63 -0
  5. package/src/browser/event-controller.ts +876 -0
  6. package/src/browser/index.ts +18 -0
  7. package/src/browser/link-interceptor.ts +121 -0
  8. package/src/browser/lru-cache.ts +69 -0
  9. package/src/browser/merge-segment-loaders.ts +126 -0
  10. package/src/browser/navigation-bridge.ts +891 -0
  11. package/src/browser/navigation-client.ts +155 -0
  12. package/src/browser/navigation-store.ts +823 -0
  13. package/src/browser/partial-update.ts +545 -0
  14. package/src/browser/react/Link.tsx +248 -0
  15. package/src/browser/react/NavigationProvider.tsx +228 -0
  16. package/src/browser/react/ScrollRestoration.tsx +94 -0
  17. package/src/browser/react/context.ts +53 -0
  18. package/src/browser/react/index.ts +52 -0
  19. package/src/browser/react/location-state-shared.ts +120 -0
  20. package/src/browser/react/location-state.ts +62 -0
  21. package/src/browser/react/use-action.ts +240 -0
  22. package/src/browser/react/use-client-cache.ts +56 -0
  23. package/src/browser/react/use-handle.ts +178 -0
  24. package/src/browser/react/use-link-status.ts +134 -0
  25. package/src/browser/react/use-navigation.ts +150 -0
  26. package/src/browser/react/use-segments.ts +188 -0
  27. package/src/browser/request-controller.ts +149 -0
  28. package/src/browser/rsc-router.tsx +310 -0
  29. package/src/browser/scroll-restoration.ts +324 -0
  30. package/src/browser/server-action-bridge.ts +747 -0
  31. package/src/browser/shallow.ts +35 -0
  32. package/src/browser/types.ts +443 -0
  33. package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
  34. package/src/cache/__tests__/memory-store.test.ts +484 -0
  35. package/src/cache/cache-scope.ts +565 -0
  36. package/src/cache/cf/__tests__/cf-cache-store.test.ts +361 -0
  37. package/src/cache/cf/cf-cache-store.ts +274 -0
  38. package/src/cache/cf/index.ts +19 -0
  39. package/src/cache/index.ts +52 -0
  40. package/src/cache/memory-segment-store.ts +150 -0
  41. package/src/cache/memory-store.ts +253 -0
  42. package/src/cache/types.ts +366 -0
  43. package/src/client.rsc.tsx +88 -0
  44. package/src/client.tsx +609 -0
  45. package/src/components/DefaultDocument.tsx +20 -0
  46. package/src/default-error-boundary.tsx +88 -0
  47. package/src/deps/browser.ts +8 -0
  48. package/src/deps/html-stream-client.ts +2 -0
  49. package/src/deps/html-stream-server.ts +2 -0
  50. package/src/deps/rsc.ts +10 -0
  51. package/src/deps/ssr.ts +2 -0
  52. package/src/errors.ts +259 -0
  53. package/src/handle.ts +120 -0
  54. package/src/handles/MetaTags.tsx +178 -0
  55. package/src/handles/index.ts +6 -0
  56. package/src/handles/meta.ts +247 -0
  57. package/src/href-client.ts +128 -0
  58. package/src/href.ts +139 -0
  59. package/src/index.rsc.ts +69 -0
  60. package/src/index.ts +84 -0
  61. package/src/loader.rsc.ts +204 -0
  62. package/src/loader.ts +47 -0
  63. package/src/network-error-thrower.tsx +21 -0
  64. package/src/outlet-context.ts +15 -0
  65. package/src/root-error-boundary.tsx +277 -0
  66. package/src/route-content-wrapper.tsx +198 -0
  67. package/src/route-definition.ts +1333 -0
  68. package/src/route-map-builder.ts +140 -0
  69. package/src/route-types.ts +148 -0
  70. package/src/route-utils.ts +89 -0
  71. package/src/router/__tests__/match-context.test.ts +104 -0
  72. package/src/router/__tests__/match-pipelines.test.ts +537 -0
  73. package/src/router/__tests__/match-result.test.ts +566 -0
  74. package/src/router/__tests__/on-error.test.ts +935 -0
  75. package/src/router/__tests__/pattern-matching.test.ts +577 -0
  76. package/src/router/error-handling.ts +287 -0
  77. package/src/router/handler-context.ts +60 -0
  78. package/src/router/loader-resolution.ts +326 -0
  79. package/src/router/manifest.ts +116 -0
  80. package/src/router/match-context.ts +261 -0
  81. package/src/router/match-middleware/background-revalidation.ts +236 -0
  82. package/src/router/match-middleware/cache-lookup.ts +261 -0
  83. package/src/router/match-middleware/cache-store.ts +250 -0
  84. package/src/router/match-middleware/index.ts +81 -0
  85. package/src/router/match-middleware/intercept-resolution.ts +268 -0
  86. package/src/router/match-middleware/segment-resolution.ts +174 -0
  87. package/src/router/match-pipelines.ts +214 -0
  88. package/src/router/match-result.ts +212 -0
  89. package/src/router/metrics.ts +62 -0
  90. package/src/router/middleware.test.ts +1355 -0
  91. package/src/router/middleware.ts +748 -0
  92. package/src/router/pattern-matching.ts +271 -0
  93. package/src/router/revalidation.ts +190 -0
  94. package/src/router/router-context.ts +299 -0
  95. package/src/router/types.ts +96 -0
  96. package/src/router.ts +3484 -0
  97. package/src/rsc/__tests__/helpers.test.ts +175 -0
  98. package/src/rsc/handler.ts +942 -0
  99. package/src/rsc/helpers.ts +64 -0
  100. package/src/rsc/index.ts +56 -0
  101. package/src/rsc/nonce.ts +18 -0
  102. package/src/rsc/types.ts +225 -0
  103. package/src/segment-system.tsx +405 -0
  104. package/src/server/__tests__/request-context.test.ts +171 -0
  105. package/src/server/context.ts +340 -0
  106. package/src/server/handle-store.ts +230 -0
  107. package/src/server/loader-registry.ts +174 -0
  108. package/src/server/request-context.ts +470 -0
  109. package/src/server/root-layout.tsx +10 -0
  110. package/src/server/tsconfig.json +14 -0
  111. package/src/server.ts +126 -0
  112. package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
  113. package/src/ssr/index.tsx +215 -0
  114. package/src/types.ts +1473 -0
  115. package/src/use-loader.tsx +346 -0
  116. package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
  117. package/src/vite/expose-action-id.ts +344 -0
  118. package/src/vite/expose-handle-id.ts +209 -0
  119. package/src/vite/expose-loader-id.ts +357 -0
  120. package/src/vite/expose-location-state-id.ts +177 -0
  121. package/src/vite/index.ts +608 -0
  122. package/src/vite/version.d.ts +12 -0
  123. package/src/vite/virtual-entries.ts +109 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * rsc-router/loader (RSC/server version)
3
+ *
4
+ * Server-side createLoader implementation with full loader functionality.
5
+ * Only used in react-server context via export conditions.
6
+ *
7
+ * For non-fetchable loaders: returns a loader definition with fn included
8
+ * For fetchable loaders: stores fn in registry and returns a serializable loader with action
9
+ *
10
+ * The $$id is injected by the Vite exposeLoaderId plugin as a hidden parameter.
11
+ * Users don't need to pass any name - IDs are auto-generated from file path.
12
+ */
13
+
14
+ import type {
15
+ FetchableLoaderOptions,
16
+ LoaderDefinition,
17
+ LoaderFn,
18
+ } from "./types.js";
19
+ import type { MiddlewareFn } from "./router/middleware.js";
20
+ import { getRequestContext } from "./server/request-context.js";
21
+
22
+ // Internal registry for fetchable loaders (server-side only)
23
+ // Maps loader $$id to its function and middleware
24
+ //
25
+ // WHY TWO REGISTRIES?
26
+ // This registry (fetchableLoaderRegistry) is populated immediately when createLoader() runs.
27
+ // The other registry in loader-registry.ts (loaderRegistry) is a cache used by the RSC handler
28
+ // for GET-based fetching. The RSC handler calls getFetchableLoader() from here to populate
29
+ // its cache. This separation allows:
30
+ // 1. Server actions to look up loaders directly without going through lazy loading
31
+ // 2. The RSC handler to use lazy loading for production builds
32
+ // 3. Both to share the same source of truth (this registry)
33
+ const fetchableLoaderRegistry = new Map<
34
+ string,
35
+ { fn: LoaderFn<any, any, any>; middleware: MiddlewareFn[] }
36
+ >();
37
+
38
+ /**
39
+ * Register a fetchable loader's function internally
40
+ * Called during module initialization with the $$id
41
+ */
42
+ function registerFetchableLoader(
43
+ id: string,
44
+ fn: LoaderFn<any, any, any>,
45
+ middleware: MiddlewareFn[]
46
+ ): void {
47
+ fetchableLoaderRegistry.set(id, { fn, middleware });
48
+ }
49
+
50
+ /**
51
+ * Get a fetchable loader's function from the internal registry by $$id
52
+ *
53
+ * This is used internally by:
54
+ * - Server actions (loaderAction) to execute loader functions
55
+ * - loader-registry.ts to populate the main registry for GET-based fetching
56
+ *
57
+ * Loaders are registered here when createLoader() is called with fetchable: true.
58
+ * The $$id is injected by the Vite exposeLoaderId plugin.
59
+ *
60
+ * @param id - The loader's $$id (auto-generated from file path + export name)
61
+ * @returns The loader function and middleware, or undefined if not found
62
+ *
63
+ * @internal This is primarily for internal use by the router infrastructure
64
+ */
65
+ export function getFetchableLoader(
66
+ id: string
67
+ ): { fn: LoaderFn<any, any, any>; middleware: MiddlewareFn[] } | undefined {
68
+ return fetchableLoaderRegistry.get(id);
69
+ }
70
+
71
+ // Overload 1: With function only (not fetchable)
72
+ export function createLoader<T>(
73
+ fn: LoaderFn<T, Record<string, string | undefined>, any>
74
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
75
+
76
+ // Overload 2: Fetchable with `true` (no middleware)
77
+ export function createLoader<T>(
78
+ fn: LoaderFn<T, Record<string, string | undefined>, any>,
79
+ fetchable: true
80
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
81
+
82
+ // Overload 3: Fetchable with middleware options
83
+ export function createLoader<T>(
84
+ fn: LoaderFn<T, Record<string, string | undefined>, any>,
85
+ options: FetchableLoaderOptions
86
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
87
+
88
+ // Implementation - the $$id parameter is injected by Vite plugin, not user-provided
89
+ export function createLoader<T>(
90
+ fn: LoaderFn<T, Record<string, string | undefined>, any>,
91
+ fetchable?: true | FetchableLoaderOptions,
92
+ // Hidden parameter injected by Vite exposeLoaderId plugin
93
+ __injectedId?: string
94
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>> {
95
+ // The $$id will be set on the returned object by Vite plugin
96
+ // For fetchable loaders, __injectedId is also passed as a parameter
97
+ const loaderId = __injectedId || "";
98
+
99
+ // If not fetchable, return a simple stub with fn included
100
+ if (fetchable === undefined) {
101
+ return {
102
+ __brand: "loader",
103
+ $$id: loaderId,
104
+ fn: fn as LoaderFn<Awaited<T>, Record<string, string | undefined>, any>,
105
+ };
106
+ }
107
+
108
+ // Fetchable loader - store fn in registry and return a serializable object
109
+ const middleware: MiddlewareFn[] =
110
+ fetchable === true ? [] : fetchable?.middleware || [];
111
+
112
+ // Register the function in the internal registry by $$id (server-side only)
113
+ // The server action will look it up by $$id when executed
114
+ if (fn && loaderId) {
115
+ registerFetchableLoader(loaderId, fn, middleware);
116
+ }
117
+
118
+ // Create server action for form-based fetching
119
+ // This action is serializable and can be passed to client components
120
+ // The loaderId is captured in closure (it's a primitive string)
121
+ //
122
+ // IMPORTANT: The signature must be (prevState, formData) for useActionState compatibility.
123
+ // When used with useActionState, React passes the previous state as the first argument.
124
+ // The prevState is ignored here since loaders are stateless data fetchers.
125
+ async function loaderAction(
126
+ _prevState: Awaited<T> | null,
127
+ formData: FormData
128
+ ): Promise<Awaited<T>> {
129
+ "use server";
130
+
131
+ // Look up the loader from registry by $$id
132
+ const registered = fetchableLoaderRegistry.get(loaderId);
133
+ if (!registered) {
134
+ throw new Error(`Loader "${loaderId}" not found in registry`);
135
+ }
136
+
137
+ // Get request context (env, request, url, variables) from the RSC handler
138
+ // This is set by runWithRequestContext in rsc/index.ts when executing actions
139
+ const requestCtx = getRequestContext();
140
+
141
+ // Convert FormData to params object
142
+ const params: Record<string, string> = {};
143
+ formData.forEach((value, key) => {
144
+ if (typeof value === "string") {
145
+ params[key] = value;
146
+ }
147
+ });
148
+
149
+ // Use real request/url from context, or fall back to synthetic for edge cases
150
+ const actionUrl = requestCtx?.url ?? new URL("http://localhost/");
151
+ const actionRequest = requestCtx?.request ?? new Request(actionUrl, { method: "POST" });
152
+ const env = requestCtx?.env ?? {};
153
+
154
+ // Merge variables from request context (app-level middleware) with loader-specific variables
155
+ // requestCtx.var is the shared variables object from the handler
156
+ const variables: Record<string, any> = { ...requestCtx?.var };
157
+
158
+ // Execute middleware for auth checks, headers, cookies
159
+ // Headers/cookies set on ctx.res will be merged into the final response
160
+ if (registered.middleware.length > 0 && requestCtx?.res) {
161
+ const { executeServerActionMiddleware } = await import(
162
+ "./router/middleware.js"
163
+ );
164
+ await executeServerActionMiddleware(
165
+ registered.middleware,
166
+ actionRequest,
167
+ env,
168
+ params,
169
+ variables,
170
+ requestCtx.res
171
+ );
172
+ }
173
+
174
+ // Build context using createHandlerContext for consistency with route handlers
175
+ // Variables are now accessed from request context via getRequestContext()
176
+ const { createHandlerContext } = await import("./router/handler-context.js");
177
+ const baseCtx = createHandlerContext(
178
+ params,
179
+ actionRequest,
180
+ actionUrl.searchParams,
181
+ actionUrl.pathname,
182
+ actionUrl,
183
+ env
184
+ );
185
+
186
+ // Extend with server action specific properties
187
+ const ctx: any = {
188
+ ...baseCtx,
189
+ method: "POST",
190
+ formData,
191
+ };
192
+
193
+ // Execute and return result
194
+ return registered.fn(ctx);
195
+ }
196
+
197
+ // Return a loader object with action for form-based fetching
198
+ // The exposeLoaderId plugin will set $$id on this object
199
+ return {
200
+ __brand: "loader",
201
+ $$id: loaderId,
202
+ action: loaderAction,
203
+ };
204
+ }
package/src/loader.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * rsc-router/loader (client version)
3
+ *
4
+ * Client-only stub for createLoader. Returns a minimal loader definition
5
+ * that can be passed to hooks like useLoader. The actual loader function
6
+ * is not included - it only exists on the server.
7
+ *
8
+ * The $$id is injected by the Vite exposeLoaderId plugin.
9
+ */
10
+
11
+ import type {
12
+ FetchableLoaderOptions,
13
+ LoaderDefinition,
14
+ LoaderFn,
15
+ } from "./types.js";
16
+
17
+ // Overload 1: With function only (not fetchable)
18
+ export function createLoader<T>(
19
+ fn: LoaderFn<T, Record<string, string | undefined>, any>
20
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
21
+
22
+ // Overload 2: Fetchable with `true` (no middleware)
23
+ export function createLoader<T>(
24
+ fn: LoaderFn<T, Record<string, string | undefined>, any>,
25
+ fetchable: true
26
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
27
+
28
+ // Overload 3: Fetchable with middleware options
29
+ export function createLoader<T>(
30
+ fn: LoaderFn<T, Record<string, string | undefined>, any>,
31
+ options: FetchableLoaderOptions
32
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>>;
33
+
34
+ // Implementation - client stub that just returns the loader definition
35
+ // The $$id parameter is injected by Vite plugin, not user-provided
36
+ export function createLoader<T>(
37
+ _fn: LoaderFn<T, Record<string, string | undefined>, any>,
38
+ _fetchable?: true | FetchableLoaderOptions,
39
+ __injectedId?: string
40
+ ): LoaderDefinition<Awaited<T>, Record<string, string | undefined>> {
41
+ // Client only needs the $$id for identification
42
+ // The actual loader function is only used on the server
43
+ return {
44
+ __brand: "loader",
45
+ $$id: __injectedId || "",
46
+ };
47
+ }
@@ -0,0 +1,21 @@
1
+ "use client";
2
+
3
+ import type { ReactNode } from "react";
4
+ import type { NetworkError } from "./errors.js";
5
+
6
+ interface NetworkErrorThrowerProps {
7
+ error: NetworkError;
8
+ }
9
+
10
+ /**
11
+ * Client component that throws a NetworkError during render.
12
+ * Used to trigger the root error boundary when a network error occurs
13
+ * during navigation or server actions.
14
+ *
15
+ * This must be a separate component because:
16
+ * 1. Errors must be thrown during React's render phase to be caught by error boundaries
17
+ * 2. The error occurs in async code (fetch), so we need to propagate it to React's render
18
+ */
19
+ export function NetworkErrorThrower({ error }: NetworkErrorThrowerProps): ReactNode {
20
+ throw error;
21
+ }
@@ -0,0 +1,15 @@
1
+ import { Context, createContext, type ReactNode } from "react";
2
+ import type { ResolvedSegment } from "./types";
3
+
4
+ export interface OutletContextValue {
5
+ content: ReactNode;
6
+ parallel?: ResolvedSegment[];
7
+ segment?: ResolvedSegment;
8
+ loaderData?: Record<string, any>;
9
+ parent?: OutletContextValue | null;
10
+ /** Loading component for Suspense fallback (from segment's loading() definition) */
11
+ loading?: ReactNode;
12
+ }
13
+
14
+ export const OutletContext: Context<OutletContextValue | null> =
15
+ createContext<OutletContextValue | null>(null);
@@ -0,0 +1,277 @@
1
+ "use client";
2
+
3
+ import { Component, useState, type ReactNode } from "react";
4
+ import type { ClientErrorBoundaryFallbackProps } from "./types.js";
5
+
6
+ /**
7
+ * Check if an error is a network-related error
8
+ */
9
+ function isNetworkError(error: Error): boolean {
10
+ return error.name === "NetworkError";
11
+ }
12
+
13
+ /**
14
+ * Network error fallback UI with retry functionality
15
+ * Shows a connection-specific message and allows retrying via page refresh
16
+ */
17
+ function NetworkErrorFallback({
18
+ error,
19
+ reset,
20
+ }: ClientErrorBoundaryFallbackProps): ReactNode {
21
+ const [isRetrying, setIsRetrying] = useState(false);
22
+
23
+ const handleRetry = (): void => {
24
+ setIsRetrying(true);
25
+ // Refresh the page to retry the request
26
+ window.location.reload();
27
+ };
28
+
29
+ return (
30
+ <div
31
+ style={{
32
+ fontFamily: "system-ui, -apple-system, sans-serif",
33
+ padding: "2rem",
34
+ maxWidth: "600px",
35
+ margin: "2rem auto",
36
+ textAlign: "center",
37
+ }}
38
+ >
39
+ <div
40
+ style={{
41
+ fontSize: "3rem",
42
+ marginBottom: "1rem",
43
+ }}
44
+ >
45
+ {/* Simple cloud with x icon using CSS */}
46
+ <span style={{ color: "#9ca3af" }}>&#9729;</span>
47
+ </div>
48
+ <h1
49
+ style={{
50
+ color: "#374151",
51
+ fontSize: "1.5rem",
52
+ marginBottom: "0.5rem",
53
+ }}
54
+ >
55
+ Connection Error
56
+ </h1>
57
+ <p
58
+ style={{
59
+ color: "#6b7280",
60
+ marginBottom: "1.5rem",
61
+ }}
62
+ >
63
+ {error.message || "Unable to connect to the server. Please check your internet connection."}
64
+ </p>
65
+ <div style={{ display: "flex", gap: "1rem", justifyContent: "center" }}>
66
+ <button
67
+ type="button"
68
+ onClick={handleRetry}
69
+ disabled={isRetrying}
70
+ style={{
71
+ padding: "0.75rem 1.5rem",
72
+ backgroundColor: isRetrying ? "#9ca3af" : "#2563eb",
73
+ color: "white",
74
+ border: "none",
75
+ borderRadius: "0.375rem",
76
+ cursor: isRetrying ? "not-allowed" : "pointer",
77
+ fontSize: "1rem",
78
+ fontWeight: 500,
79
+ }}
80
+ >
81
+ {isRetrying ? "Retrying..." : "Retry"}
82
+ </button>
83
+ <button
84
+ type="button"
85
+ onClick={() => window.history.back()}
86
+ style={{
87
+ padding: "0.75rem 1.5rem",
88
+ backgroundColor: "transparent",
89
+ color: "#6b7280",
90
+ border: "1px solid #d1d5db",
91
+ borderRadius: "0.375rem",
92
+ cursor: "pointer",
93
+ fontSize: "1rem",
94
+ }}
95
+ >
96
+ Go Back
97
+ </button>
98
+ </div>
99
+ </div>
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Default fallback UI for root error boundary
105
+ * This is shown when an unhandled error bubbles up to the root
106
+ */
107
+ function RootErrorFallback({ error, reset }: ClientErrorBoundaryFallbackProps): ReactNode {
108
+ return (
109
+ <div
110
+ style={{
111
+ fontFamily: "system-ui, -apple-system, sans-serif",
112
+ padding: "2rem",
113
+ maxWidth: "600px",
114
+ margin: "2rem auto",
115
+ }}
116
+ >
117
+ <h1
118
+ style={{
119
+ color: "#dc2626",
120
+ fontSize: "1.5rem",
121
+ marginBottom: "1rem",
122
+ }}
123
+ >
124
+ Internal Server Error
125
+ </h1>
126
+ <p
127
+ style={{
128
+ color: "#374151",
129
+ marginBottom: "1rem",
130
+ }}
131
+ >
132
+ An unexpected error occurred while processing your request.
133
+ </p>
134
+ <div
135
+ style={{
136
+ background: "#fef2f2",
137
+ border: "1px solid #fecaca",
138
+ borderRadius: "0.5rem",
139
+ padding: "1rem",
140
+ marginBottom: "1rem",
141
+ }}
142
+ >
143
+ <p
144
+ style={{
145
+ fontWeight: 600,
146
+ color: "#991b1b",
147
+ marginBottom: "0.5rem",
148
+ }}
149
+ >
150
+ {error.name}: {error.message}
151
+ </p>
152
+ {error.stack && (
153
+ <pre
154
+ style={{
155
+ fontSize: "0.75rem",
156
+ color: "#6b7280",
157
+ overflow: "auto",
158
+ whiteSpace: "pre-wrap",
159
+ wordBreak: "break-word",
160
+ }}
161
+ >
162
+ {error.stack}
163
+ </pre>
164
+ )}
165
+ </div>
166
+ <div style={{ display: "flex", gap: "1rem" }}>
167
+ <button
168
+ type="button"
169
+ onClick={reset}
170
+ style={{
171
+ padding: "0.5rem 1rem",
172
+ backgroundColor: "#2563eb",
173
+ color: "white",
174
+ border: "none",
175
+ borderRadius: "0.25rem",
176
+ cursor: "pointer",
177
+ }}
178
+ >
179
+ Try Again
180
+ </button>
181
+ <a
182
+ href="/"
183
+ style={{
184
+ display: "inline-block",
185
+ padding: "0.5rem 1rem",
186
+ color: "#2563eb",
187
+ textDecoration: "underline",
188
+ }}
189
+ >
190
+ Go to homepage
191
+ </a>
192
+ </div>
193
+ </div>
194
+ );
195
+ }
196
+
197
+ interface RootErrorBoundaryState {
198
+ hasError: boolean;
199
+ error: Error | null;
200
+ }
201
+
202
+ /**
203
+ * Root error boundary component
204
+ *
205
+ * Wraps the entire segment tree to catch any unhandled errors that bubble up.
206
+ * This prevents the entire app from crashing with a white screen.
207
+ *
208
+ * This is a client component with an inline fallback to avoid the
209
+ * "Functions cannot be passed to Client Components" RSC error.
210
+ */
211
+ export class RootErrorBoundary extends Component<
212
+ { children: ReactNode },
213
+ RootErrorBoundaryState
214
+ > {
215
+ constructor(props: { children: ReactNode }) {
216
+ super(props);
217
+ this.state = { hasError: false, error: null };
218
+ }
219
+
220
+ static getDerivedStateFromError(error: Error): RootErrorBoundaryState {
221
+ return { hasError: true, error };
222
+ }
223
+
224
+ componentDidMount(): void {
225
+ // Listen for popstate (back/forward navigation) to reset error state
226
+ window.addEventListener("popstate", this.handlePopState);
227
+ }
228
+
229
+ componentWillUnmount(): void {
230
+ window.removeEventListener("popstate", this.handlePopState);
231
+ }
232
+
233
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
234
+ console.error("[RootErrorBoundary] Unhandled error caught:", error, errorInfo);
235
+ }
236
+
237
+ componentDidUpdate(prevProps: { children: ReactNode }): void {
238
+ // Reset error state when children change (e.g., navigation)
239
+ // This allows the app to recover after navigation away from an errored route
240
+ if (this.state.hasError && prevProps.children !== this.props.children) {
241
+ this.setState({ hasError: false, error: null });
242
+ }
243
+ }
244
+
245
+ handlePopState = (): void => {
246
+ // Reset error state on back/forward navigation
247
+ if (this.state.hasError) {
248
+ this.setState({ hasError: false, error: null });
249
+ }
250
+ };
251
+
252
+ reset = (): void => {
253
+ this.setState({ hasError: false, error: null });
254
+ };
255
+
256
+ render(): ReactNode {
257
+ if (this.state.hasError && this.state.error) {
258
+ const errorInfo = {
259
+ message: this.state.error.message,
260
+ name: this.state.error.name,
261
+ stack: this.state.error.stack,
262
+ cause: this.state.error.cause,
263
+ segmentId: "root",
264
+ segmentType: "route" as const,
265
+ };
266
+
267
+ // Use specialized fallback for network errors
268
+ if (isNetworkError(this.state.error)) {
269
+ return <NetworkErrorFallback error={errorInfo} reset={this.reset} />;
270
+ }
271
+
272
+ return <RootErrorFallback error={errorInfo} reset={this.reset} />;
273
+ }
274
+
275
+ return this.props.children;
276
+ }
277
+ }