@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
@@ -1,22 +1,6 @@
1
1
  import MagicString from "magic-string";
2
- import { parse } from "yuku-parser";
3
-
4
- // ---------------------------------------------------------------------------
5
- // Bun.Transpiler singleton — strips TypeScript + JSX before AST work.
6
- // Force classic JSX transform (React.createElement) regardless of the
7
- // project tsconfig's "jsx": "react-jsx" setting — the Bun.build() step
8
- // that consumes this output handles the automatic runtime itself.
9
- // ---------------------------------------------------------------------------
10
- const bunTranspiler = new Bun.Transpiler({
11
- loader: "tsx",
12
- tsconfig: {
13
- compilerOptions: {
14
- jsx: "react",
15
- jsxFactory: "React.createElement",
16
- jsxFragmentFactory: "React.Fragment",
17
- },
18
- },
19
- });
2
+ import { parse, type SourceLang } from "yuku-parser";
3
+ import { detectLangFromPath, unwrapTSExpression } from "../lang-detect";
20
4
 
21
5
  // loader: data fetching (runs on server only)
22
6
  // query / params: Elysia TypeBox schemas — validated server-side, not used in browser
@@ -184,17 +168,83 @@ function removeServerProperties(s: MagicString, source: string, obj: ObjectExpre
184
168
  return true;
185
169
  }
186
170
 
171
+ // TypeScript-specific node types that introduce a type-only scope. Any
172
+ // Identifier / JSXIdentifier beneath one of these nodes is a TypeScript type
173
+ // reference, not a runtime value reference, and must not count toward DCE refs.
174
+ const TYPE_SCOPE_NODES = new Set([
175
+ "TSTypeAnnotation", // `: Type` on variables, params, return types
176
+ "TSTypeParameterDeclaration", // `<T>` in generic type-param declarations
177
+ "TSTypeParameterInstantiation", // `<T>` in generic instantiation positions
178
+ "TSInterfaceDeclaration", // `interface Foo { … }` — entirely type-level
179
+ "TSTypeAliasDeclaration", // `type Foo = …` — entirely type-level
180
+ "TSTypePredicate", // `x is Type` in return-type position
181
+ "TSClassImplements", // `class C implements Iface` — the implements clause is type-only
182
+ ]);
183
+
184
+ // Walk `node` and add every Identifier / JSXIdentifier found inside it to
185
+ // `excluded`. Called for nodes that are entirely in type position (e.g. a
186
+ // TSTypeAnnotation) so their descendant identifiers are ignored by DCE.
187
+ function markTypeDescendants(node: unknown, excluded: Set<unknown>): void {
188
+ if (!node || typeof node !== "object") {
189
+ return;
190
+ }
191
+ if (Array.isArray(node)) {
192
+ for (const item of node) {
193
+ markTypeDescendants(item, excluded);
194
+ }
195
+ return;
196
+ }
197
+ const n = node as AstNode;
198
+ if (n.type === "Identifier" || n.type === "JSXIdentifier") {
199
+ excluded.add(n);
200
+ }
201
+ for (const key of Object.keys(n)) {
202
+ if (key === "type" || key === "start" || key === "end") {
203
+ continue;
204
+ }
205
+ markTypeDescendants(n[key], excluded);
206
+ }
207
+ }
208
+
209
+ // Excludes identifiers that appear in TypeScript type-only positions from the
210
+ // `excluded` set. Extracted from the Pass-1 walk callback to keep cognitive
211
+ // complexity within the allowed budget.
212
+ function excludeTypePositionIdentifiers(node: AstNode, excluded: Set<unknown>): void {
213
+ if (TYPE_SCOPE_NODES.has(node.type)) {
214
+ markTypeDescendants(node, excluded);
215
+ return;
216
+ }
217
+ // TSAsExpression (`x as T`), TSSatisfiesExpression (`x satisfies T`), and
218
+ // TSTypeAssertion (`<T>x`) are mixed: the expression child is runtime; only
219
+ // the typeAnnotation child is type-only.
220
+ if (
221
+ node.type === "TSAsExpression" ||
222
+ node.type === "TSSatisfiesExpression" ||
223
+ node.type === "TSTypeAssertion"
224
+ ) {
225
+ markTypeDescendants(node.typeAnnotation as unknown, excluded);
226
+ }
227
+ }
228
+
187
229
  // ---------------------------------------------------------------------------
188
- // Collect all Identifier names referenced in the AST (excluding imports).
189
- // Skips identifiers that appear as static (non-computed) property keys or
190
- // as static member-expression properties (both require computed=false),
191
- // because those positions are not identifier *references* and including them
192
- // would prevent DCE of same-named imports.
230
+ // Collect all Identifier / JSXIdentifier names referenced in the AST
231
+ // (excluding imports). Skips identifiers in non-reference positions:
232
+ //
233
+ // • Static (non-computed) object property keys — `{ loader: fn }`
234
+ // • Static (non-computed) member access properties — `obj.prop`
235
+ // • JSX attribute names — `<div className=...>`
236
+ // • Right-hand side of a JSXMemberExpression chain — `<UI.Button>` (Button)
237
+ // • TypeScript type positions — `: MyType`, `<T>`, etc.
238
+ //
193
239
  // Computed keys like `{ [someVar]: v }` are left in — they ARE references.
240
+ // JSX tag positions ARE references — `<Link>` requires the `Link` binding
241
+ // to be in scope, so omitting JSXIdentifier (the default after the parser
242
+ // switch from Bun.Transpiler to yuku-parser) silently drops imports that
243
+ // are only used as JSX tags.
194
244
  // ---------------------------------------------------------------------------
195
245
  function collectReferencedNames(program: AstNode): Set<string> {
196
246
  const refs = new Set<string>();
197
- // Nodes that occupy a non-reference Identifier position.
247
+ // Nodes that occupy a non-reference Identifier / JSXIdentifier position.
198
248
  const excluded = new Set<unknown>();
199
249
 
200
250
  for (const stmt of program.body ?? []) {
@@ -211,6 +261,18 @@ function collectReferencedNames(program: AstNode): Set<string> {
211
261
  if (node.type === "MemberExpression" && !node.computed) {
212
262
  excluded.add(node.property);
213
263
  }
264
+ // `<div className="...">` — the attribute *name* is a key, not a ref.
265
+ if (node.type === "JSXAttribute") {
266
+ excluded.add(node.name);
267
+ }
268
+ // `<UI.Button>` — `UI` is the live binding, `.Button` is a property
269
+ // lookup on it. Exclude the property side of every JSXMemberExpression
270
+ // so a same-named import (e.g. `import { Button } from ...`) doesn't
271
+ // get falsely kept alive by every `<Foo.Button>` in the file.
272
+ if (node.type === "JSXMemberExpression") {
273
+ excluded.add(node.property);
274
+ }
275
+ excludeTypePositionIdentifiers(node, excluded);
214
276
  });
215
277
  }
216
278
 
@@ -224,7 +286,7 @@ function collectReferencedNames(program: AstNode): Set<string> {
224
286
  return;
225
287
  }
226
288
  if (
227
- node.type === "Identifier" &&
289
+ (node.type === "Identifier" || node.type === "JSXIdentifier") &&
228
290
  typeof (node as AstNode & { name: string }).name === "string"
229
291
  ) {
230
292
  refs.add((node as AstNode & { name: string }).name);
@@ -259,6 +321,7 @@ function removeUnusedSpecifiers(
259
321
  while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
260
322
  removeEnd++;
261
323
  }
324
+ // react-doctor-disable-next-line react-doctor/js-set-map-lookups
262
325
  if (!code.slice(spec.end, removeEnd).includes(",")) {
263
326
  while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
264
327
  removeStart--;
@@ -278,9 +341,9 @@ function removeUnusedSpecifiers(
278
341
  // original-source positions, which diverge from output positions whenever
279
342
  // earlier passes have removed content.
280
343
  // ---------------------------------------------------------------------------
281
- export function deadCodeElimination(s: MagicString): MagicString {
344
+ export function deadCodeElimination(s: MagicString, lang: SourceLang): MagicString {
282
345
  const code = s.toString();
283
- const { program, diagnostics } = parse(code, { sourceType: "module" });
346
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
284
347
  const firstError = diagnostics.find((d) => d.severity === "error");
285
348
  if (firstError) {
286
349
  console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
@@ -328,15 +391,16 @@ function removeServerExports(s: MagicString, source: string, program: AstNode):
328
391
  if (node.type !== "CallExpression") {
329
392
  return;
330
393
  }
331
- const call = node as unknown as CallExpression;
394
+ const call = node as CallExpression;
332
395
  if (!isTargetCall(call)) {
333
396
  return;
334
397
  }
335
- const arg = call.arguments[0];
398
+ // Unwrap `createRoute({...} as Config)` / `page({...} satisfies Opts)` etc.
399
+ const arg = call.arguments[0] ? unwrapTSExpression(call.arguments[0]) : undefined;
336
400
  if (!arg || arg.type !== "ObjectExpression") {
337
401
  return;
338
402
  }
339
- if (removeServerProperties(s, source, arg as unknown as ObjectExpression)) {
403
+ if (removeServerProperties(s, source, arg as ObjectExpression)) {
340
404
  removedServerCode = true;
341
405
  }
342
406
  });
@@ -345,25 +409,30 @@ function removeServerExports(s: MagicString, source: string, program: AstNode):
345
409
  }
346
410
 
347
411
  export function transformForClient(code: string, filename: string): TransformResult {
348
- // Pass 1 — Bun.Transpiler: strip TypeScript + JSX → plain JS.
349
- const plainJs = bunTranspiler.transformSync(code);
412
+ // .d.ts files have no runtime code — yuku rejects parsing them as modules.
413
+ // Treat as a passthrough so callers don't need to pre-filter.
414
+ const lang = detectLangFromPath(filename);
415
+ if (lang === "dts") {
416
+ return { code, map: null, removedServerCode: false };
417
+ }
350
418
 
351
- // Pass 2 — yuku-parser: parse plain JS to ESTree AST with span offsets.
352
- const { program, diagnostics } = parse(plainJs, { sourceType: "module" });
419
+ // Pass 1 — yuku-parser: parse TS/TSX/JS/JSX directly to ESTree AST with
420
+ // span offsets calibrated against `code` itself (no transpile step).
421
+ const { program, diagnostics } = parse(code, { sourceType: "module", lang });
353
422
  const firstError = diagnostics.find((d) => d.severity === "error");
354
423
  if (firstError) {
355
424
  throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
356
425
  }
357
426
 
358
- // Pass 3 — MagicString: surgically remove server-only properties.
359
- let s = new MagicString(plainJs);
360
- const removedServerCode = removeServerExports(s, plainJs, program as unknown as AstNode);
427
+ // Pass 2 — MagicString: surgically remove server-only properties.
428
+ let s = new MagicString(code);
429
+ const removedServerCode = removeServerExports(s, code, program as unknown as AstNode);
361
430
 
362
- // Pass 4 — DCE: prune imports that are no longer referenced.
431
+ // Pass 3 — DCE: prune imports that are no longer referenced.
363
432
  // deadCodeElimination returns a fresh MagicString keyed on the current
364
433
  // output so its internal AST offsets remain consistent.
365
434
  if (removedServerCode) {
366
- s = deadCodeElimination(s);
435
+ s = deadCodeElimination(s, lang);
367
436
  }
368
437
 
369
438
  return {
@@ -1,6 +1,73 @@
1
+ import type { toCrossJSON } from "seroval";
1
2
  import type { buildHeadInjection } from "./shell";
2
3
  import { safeJson } from "./shell";
3
4
 
5
+ /**
6
+ * Single source of truth for the global registry name used by the SSR
7
+ * streaming script, the client hydration entry, and any test helper. Keeping
8
+ * it centralised here avoids `<script>`/JS source drift if the name is ever
9
+ * renamed.
10
+ */
11
+ export const FURIN_DEFERRED_GLOBAL = "__FURIN_DEFERRED__";
12
+
13
+ // ── Deferred streaming helpers ─────────────────────────────────────────────────
14
+
15
+ /**
16
+ * Generates the `window.__FURIN_DEFERRED__` registry script that is injected
17
+ * BEFORE the React stream starts. It sets up the resolve/reject/getPromise API
18
+ * for late chunks.
19
+ *
20
+ * Client-side `<Await>` components call `getPromise(key)` to obtain a Promise
21
+ * they can pass to React 19's `use()`. The late resolution scripts call
22
+ * `resolve(key, chunk)` / `reject(key, chunk)` to settle those Promises.
23
+ *
24
+ * Synchronous loader data is NOT carried here — it lives exclusively in the
25
+ * `__FURIN_DATA__` JSON script that the hydrate entry reads.
26
+ *
27
+ * CSP note: this is an inline `<script>` — nonce support is a v2 concern.
28
+ */
29
+ export function buildDeferredScript(deferredKeys: string[]): string {
30
+ const keysJson = safeJson(deferredKeys);
31
+ return `<script id="${FURIN_DEFERRED_GLOBAL}">
32
+ window.${FURIN_DEFERRED_GLOBAL} = {
33
+ _deferredKeys: ${keysJson},
34
+ _chunks: {},
35
+ _resolvers: {},
36
+ resolve(key, chunk) {
37
+ this._chunks[key] = { a: 0, v: chunk };
38
+ },
39
+ reject(key, chunk) {
40
+ this._chunks[key] = { a: 1, v: chunk };
41
+ },
42
+ getPromise(key) {
43
+ if (!this._resolvers[key]) {
44
+ var res, rej;
45
+ var p = new Promise(function(resolve, reject) { res = resolve; rej = reject; });
46
+ this._resolvers[key] = { resolve: res, reject: rej, promise: p };
47
+ }
48
+ return this._resolvers[key].promise;
49
+ }
50
+ };
51
+ </script>`;
52
+ }
53
+
54
+ /**
55
+ * Generates a late `<script>` that settles one deferred Promise on the client.
56
+ * The `chunk` must be a seroval CrossJSON value produced by `toCrossJSON(value)`.
57
+ *
58
+ * @param key - The Promise key (matches what `getPromise(key)` was called with)
59
+ * @param chunk - The already-serialised CrossJSON value
60
+ * @param action - "resolve" or "reject"
61
+ */
62
+ export function buildDeferredResolution(
63
+ key: string,
64
+ chunk: ReturnType<typeof toCrossJSON>,
65
+ action: "resolve" | "reject"
66
+ ): string {
67
+ const chunkJson = safeJson(chunk);
68
+ return `<script>window.${FURIN_DEFERRED_GLOBAL}.${action}(${safeJson(key)},${chunkJson})</script>`;
69
+ }
70
+
4
71
  /** Minimal context passed to background / synthetic render helpers — only `request` is needed. */
5
72
  export interface LoaderContext {
6
73
  request: Request;
@@ -1,6 +1,7 @@
1
1
  import { Component, Fragment, type ReactNode } from "react";
2
2
  import { type ErrorComponent, getPublicErrorMessage } from "../error.ts";
3
3
  import { isNotFoundError, type NotFoundComponent } from "../not-found.ts";
4
+ import { isFurinServerError } from "../server-error.ts";
4
5
  import { DefaultErrorScreen, DefaultNotFoundScreen } from "./default-screens.tsx";
5
6
  import { computeErrorDigest } from "./digest.ts";
6
7
 
@@ -8,6 +9,14 @@ const DefaultErrorFallback: ErrorComponent = ({ error, reset }) => (
8
9
  <DefaultErrorScreen digest={error.digest} message={error.message} reset={reset} />
9
10
  );
10
11
 
12
+ /**
13
+ * Default HTTP status surfaced to error UIs when the caught error has no
14
+ * intrinsic status (e.g. a thrown `Error`, a non-Error throw). The loader
15
+ * pipeline produces a `FurinServerError` with the right status when a thrown
16
+ * `Response` is the cause; everything else collapses to 500.
17
+ */
18
+ const DEFAULT_ERROR_STATUS = 500;
19
+
11
20
  const DefaultNotFoundFallback: NotFoundComponent = ({ error }) => (
12
21
  <DefaultNotFoundScreen message={error.message} />
13
22
  );
@@ -108,18 +117,27 @@ export class FurinErrorBoundary extends Component<ErrorBoundaryProps, ErrorBound
108
117
  }
109
118
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
110
119
  // Digest precedence:
111
- // 1. state.digest — computed at catch time, always correct for the
120
+ // 1. FurinServerError.digest — when the server emitted an error
121
+ // sentinel through the SPA-nav payload, the synthesized error
122
+ // carries the server's own digest so logs correlate without
123
+ // recomputing a different hash from a synthetic stack.
124
+ // 2. state.digest — computed at catch time, always correct for the
112
125
  // ACTUAL caught error.
113
- // 2. props.digest — the server-rendered digest, only meaningful for
126
+ // 3. props.digest — the server-rendered digest, only meaningful for
114
127
  // the very first error post-hydration; we still honour it as a
115
128
  // last-resort fallback in case state.digest is somehow missing
116
129
  // (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);
130
+ // 4. recompute on the spot — defensive, should never be reached.
131
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
132
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
119
133
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
134
+ // Status precedence: FurinServerError carries the original Response.status
135
+ // (or the loader's computed 500 for non-Response throws); everything else
136
+ // collapses to the default 500.
137
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
120
138
  return (
121
139
  <Fallback
122
- error={{ message, digest: finalDigest }}
140
+ error={{ message, digest: finalDigest, status }}
123
141
  reset={typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset}
124
142
  />
125
143
  );
@@ -13,6 +13,13 @@ export interface ISRCacheEntry {
13
13
  export interface SsgCacheEntry {
14
14
  cachedAt: number;
15
15
  html: string;
16
+ /**
17
+ * NDJSON payload identical in shape to what the live `/_furin/data` endpoint
18
+ * emits. Persisted alongside the HTML by the static adapter so SPA navigation
19
+ * on a static-hosted deployment can fetch loader data without going through
20
+ * a runtime endpoint that does not exist on a file server.
21
+ */
22
+ ndjson: string;
16
23
  status: number;
17
24
  }
18
25
 
@@ -104,14 +104,6 @@ const BADGE_STYLE: CSSProperties = {
104
104
  padding: "12px 36px",
105
105
  };
106
106
 
107
- // 404 isn't an "error" in the same sense as a 500, so we drop the danger ring
108
- // entirely and let the typography stand on its own.
109
- const NOT_FOUND_BADGE_STYLE: CSSProperties = {
110
- ...BADGE_STYLE,
111
- border: 0,
112
- padding: 0,
113
- };
114
-
115
107
  const HEADING_STYLE: CSSProperties = {
116
108
  color: COLOR_TEXT,
117
109
  fontFamily: FONT_SANS,
@@ -228,8 +220,7 @@ html, body {
228
220
  function ScreenFrame({ badge, children }: ScreenFrameProps) {
229
221
  return (
230
222
  <div style={PAGE_STYLE}>
231
- {/* biome-ignore lint/security/noDangerouslySetInnerHtml: literal CSS string, no user input */}
232
- <style dangerouslySetInnerHTML={{ __html: RESET_CSS }} />
223
+ <style>{RESET_CSS}</style>
233
224
  <div style={FRAME_STYLE}>
234
225
  <CornerBracket corner="tl" />
235
226
  <CornerBracket corner="tr" />
@@ -253,6 +244,7 @@ interface DefaultErrorScreenProps {
253
244
 
254
245
  export function DefaultErrorScreen({ message, digest, reset }: DefaultErrorScreenProps) {
255
246
  return (
247
+ // react-doctor-disable-next-line react-doctor/design-no-em-dash-in-jsx-text
256
248
  <ScreenFrame badge={<div style={BADGE_STYLE}>500 — ERROR</div>}>
257
249
  <h1 style={HEADING_STYLE}>Something went wrong</h1>
258
250
  <div style={CODE_BOX_STYLE}>
@@ -282,7 +274,8 @@ interface DefaultNotFoundScreenProps {
282
274
 
283
275
  export function DefaultNotFoundScreen({ message }: DefaultNotFoundScreenProps) {
284
276
  return (
285
- <ScreenFrame badge={<div style={NOT_FOUND_BADGE_STYLE}>404 — NOT FOUND</div>}>
277
+ // react-doctor-disable-next-line react-doctor/design-no-em-dash-in-jsx-text
278
+ <ScreenFrame badge={<div style={BADGE_STYLE}>404 — NOT FOUND</div>}>
286
279
  <h1 style={HEADING_STYLE}>This page does not exist</h1>
287
280
  <p style={DESCRIPTION_WRAPPER_STYLE}>
288
281
  {message
@@ -108,12 +108,35 @@ const SERVER_RESET_NOOP = () => {
108
108
  /* reset is a client-only action; the response is already committed here */
109
109
  };
110
110
 
111
+ /**
112
+ * Builds the error element rendered when a loader (or the SSR shell) fails.
113
+ *
114
+ * @param component - User-declared `error.tsx` component, or `undefined` to
115
+ * fall back to the built-in `DefaultErrorScreen` with a generic message.
116
+ * @param error - The original thrown value. Kept for `errorMessageOf` lookup
117
+ * when no explicit `messageOverride` is provided (e.g. shell-render errors).
118
+ * @param digest - 10-hex-char digest correlating with server logs.
119
+ * @param messageOverride - Pre-extracted public message. Set by the loader
120
+ * pipeline when the thrown value is a `Response` (whose body has already
121
+ * been consumed in `runLoaders`); pass `undefined` to derive the message
122
+ * from `error` via `errorMessageOf`.
123
+ * @param status - HTTP status to surface in `ErrorProps.error.status`. The
124
+ * loader pipeline passes the thrown `Response.status` (default 500); the
125
+ * shell-error recovery path always passes 500.
126
+ */
111
127
  export function buildErrorElement(
112
128
  component: ErrorComponent | undefined,
113
129
  error: unknown,
114
- digest: string
130
+ digest: string,
131
+ messageOverride: string | undefined,
132
+ status: number
115
133
  ): ReactNode {
116
134
  const ErrorView = component ?? DefaultErrorComponent;
117
- const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
118
- return <ErrorView error={{ message, digest }} reset={SERVER_RESET_NOOP} />;
135
+ let message: string;
136
+ if (component) {
137
+ message = messageOverride ?? errorMessageOf(error);
138
+ } else {
139
+ message = "An unexpected error occurred.";
140
+ }
141
+ return <ErrorView error={{ message, digest, status }} reset={SERVER_RESET_NOOP} />;
119
142
  }