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

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.
@@ -0,0 +1,870 @@
1
+ // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
+ import { createElement, type ReactNode } from "react";
3
+ import { renderToReadableStream } from "react-dom/server";
4
+ import { FurinNotFoundError } from "../not-found.ts";
5
+ import type { RootLayout } from "../router.ts";
6
+ import { normalizeHref, RouterContext, type RouterContextValue } from "../router-provider.tsx";
7
+ import { assembleHTML, resolvePath, splitTemplate, streamToString } from "./assemble.ts";
8
+ import {
9
+ getISRCache,
10
+ getSSGCache,
11
+ type ISRCacheEntry,
12
+ type SsgCacheEntry,
13
+ setISRCache,
14
+ setSSGCache,
15
+ } from "./cache.ts";
16
+ import { computeErrorDigest } from "./digest.ts";
17
+ import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
18
+ import { type LoaderResult, runLoaders } from "./loaders.ts";
19
+ import { buildHeadInjection, safeJson } from "./shell.ts";
20
+ import { getDevTemplate, getProductionTemplate } from "./template.ts";
21
+
22
+ // ── Re-exports (public API) ──────────────────────────────────────────────────
23
+ // biome-ignore lint/performance/noBarrelFile: acnowledged
24
+ export { type LoaderContext, streamToString } from "./assemble.ts";
25
+ export { buildElement } from "./element.tsx";
26
+ export { type LoaderResult, runLoaders } from "./loaders.ts";
27
+
28
+ // ── Types ────────────────────────────────────────────────────────────────────
29
+
30
+ import type { Context } from "elysia";
31
+ import { createLogger, runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
32
+ import type { ResolvedRoute } from "../router.ts";
33
+ import { IS_DEV } from "../runtime-env.ts";
34
+ import type { LoaderContext } from "./assemble.ts";
35
+ import { generateIndexHtml } from "./shell.ts";
36
+
37
+ interface RenderResult {
38
+ headers: Record<string, string>;
39
+ html: string;
40
+ status: number;
41
+ }
42
+
43
+ // ── Shared render preparation ────────────────────────────────────────────────
44
+
45
+ interface PreparedRender {
46
+ componentProps: Record<string, unknown>;
47
+ element: ReactNode;
48
+ /** Set when the prepared element is an error UI. Surfaced to the client via
49
+ * `__FURIN_DATA__.__furinError.digest` and logged server-side. */
50
+ errorDigest?: string;
51
+ headData: string;
52
+ headers: Record<string, string>;
53
+ loader_ms: number;
54
+ /**
55
+ * Slice 8 — populated only when the loader threw `notFound()`. Mirrored into
56
+ * `__FURIN_DATA__.__furinNotFound` so the client-side `classifySpaResponse`
57
+ * can render the not-found UI inline on SPA navigation instead of falling
58
+ * back to a full-page reload.
59
+ */
60
+ notFoundError?: { data?: unknown; message?: string };
61
+ ssrContext: RouterContextValue;
62
+ status: number;
63
+ template: string;
64
+ }
65
+
66
+ function withSSRRouterContext(element: ReactNode, contextValue: RouterContextValue): ReactNode {
67
+ return createElement(RouterContext.Provider, { value: contextValue }, element);
68
+ }
69
+
70
+ /**
71
+ * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
72
+ * (streaming). Runs loaders, builds props, head injection, resolves template,
73
+ * and creates the React element.
74
+ *
75
+ * Returns the redirect Response directly when a loader redirects, so callers
76
+ * never need try/catch for redirect handling.
77
+ *
78
+ * `precomputedLoaderResult`: when provided (dev "Live ISR" cache hit), the
79
+ * loader chain is skipped entirely and the cached `LoaderResult` is used as
80
+ * if the loaders had just run. Callers must pass `undefined` explicitly
81
+ * when no cached result is available.
82
+ */
83
+ async function prepareRender(
84
+ route: ResolvedRoute,
85
+ ctx: Context,
86
+ root: RootLayout,
87
+ basePath: string | undefined,
88
+ throwOnFailure: boolean,
89
+ precomputedLoaderResult: LoaderResult | undefined
90
+ ): Promise<PreparedRender | Response> {
91
+ const loaderStart = Date.now();
92
+ const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx, root.route));
93
+ const loader_ms = Date.now() - loaderStart;
94
+
95
+ if (loaderResult.type === "redirect") {
96
+ return loaderResult.response;
97
+ }
98
+
99
+ // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
100
+ // silently generating a 404/500 page for buggy loaders.
101
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
102
+ throw loaderResult.error;
103
+ }
104
+
105
+ const isNotFound = loaderResult.type === "not-found";
106
+ const isError = loaderResult.type === "error";
107
+ const isFallback = isNotFound || isError;
108
+ const data = isFallback ? {} : loaderResult.data;
109
+ const headers = loaderResult.headers;
110
+ const componentProps = {
111
+ ...data,
112
+ params: ctx.params,
113
+ query: ctx.query,
114
+ path: ctx.path,
115
+ };
116
+
117
+ const headData = isFallback ? "" : buildHeadInjection(route.page?.head?.(componentProps));
118
+
119
+ // An explicitly-set production template (static pre-render, compiled Bun server)
120
+ // always wins over the IS_DEV flag. This decouples template resolution from the
121
+ // IS_DEV singleton so callers never need to flip IS_DEV just to get the right shell.
122
+ const prodTemplate = getProductionTemplate();
123
+ const template =
124
+ prodTemplate ??
125
+ (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
126
+
127
+ let element: ReactNode;
128
+ let status = 200;
129
+ let errorDigest: string | undefined;
130
+ let notFoundError: { data?: unknown; message?: string } | undefined;
131
+ if (loaderResult.type === "not-found") {
132
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
133
+ status = 404;
134
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
135
+ } else if (loaderResult.type === "error") {
136
+ errorDigest = computeErrorDigest(loaderResult.error);
137
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
138
+ status = 500;
139
+ } else {
140
+ element = buildElement(route, componentProps, root.route);
141
+ }
142
+
143
+ // Inject RouterContext so Link components have the correct currentHref for
144
+ // active-state detection and basePath-aware href generation. Previously this
145
+ // was only done for SSG (basePath !== undefined), which caused hydration
146
+ // mismatches in SSR/ISR because SSR_FALLBACK_ROUTER hardcodes currentHref "/"
147
+ // while the client hydrates with the real pathname.
148
+ const ssrContext: RouterContextValue = {
149
+ basePath: basePath ?? "",
150
+ currentHref: normalizeHref(ctx.path),
151
+ navigate: () => Promise.resolve(),
152
+ prefetch: () => {
153
+ /* noop */
154
+ },
155
+ invalidatePrefetch: () => {
156
+ /* noop */
157
+ },
158
+ refresh: () => Promise.resolve(),
159
+ isNavigating: false,
160
+ defaultPreload: "intent",
161
+ defaultPreloadDelay: 50,
162
+ defaultPreloadStaleTime: 30_000,
163
+ };
164
+ element = withSSRRouterContext(element, ssrContext);
165
+
166
+ return {
167
+ componentProps,
168
+ element,
169
+ errorDigest,
170
+ headData,
171
+ headers,
172
+ loader_ms,
173
+ notFoundError,
174
+ ssrContext,
175
+ status,
176
+ template,
177
+ };
178
+ }
179
+
180
+ // ── Helpers ──────────────────────────────────────────────────────────────────
181
+
182
+ function renderForPath(
183
+ route: ResolvedRoute,
184
+ params: Record<string, string>,
185
+ root: RootLayout,
186
+ origin: string,
187
+ mode: "ssg" | "isr",
188
+ basePath: string | undefined
189
+ ): Promise<RenderResult | Response> {
190
+ return runInSyntheticRenderScope(
191
+ async () => {
192
+ const resolvedPath = resolvePath(route.pattern, params);
193
+ const ctx: Context = {
194
+ params,
195
+ query: {},
196
+ request: new Request(`${origin}${resolvedPath}`),
197
+ headers: {},
198
+ cookie: {},
199
+ redirect: (url: string, status: number | undefined) =>
200
+ new Response(null, { status: status ?? 302, headers: { Location: url } }),
201
+ set: { headers: {} },
202
+ path: resolvedPath,
203
+ } as Context;
204
+
205
+ const prepared = await prepareRender(route, ctx, root, basePath, true, undefined);
206
+ if (prepared instanceof Response) {
207
+ return prepared;
208
+ }
209
+
210
+ useLogger().set({
211
+ furin: {
212
+ render: mode,
213
+ route: route.pattern,
214
+ cache: mode === "isr" ? "revalidated" : "miss",
215
+ loader_ms: prepared.loader_ms,
216
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
217
+ },
218
+ });
219
+
220
+ const { componentProps, element, headData, headers, status, template } = prepared;
221
+ const stream = await renderToReadableStream(element);
222
+ await stream.allReady;
223
+ const reactHtml = await streamToString(stream);
224
+ return {
225
+ html: assembleHTML(template, headData, reactHtml, componentProps),
226
+ headers,
227
+ status,
228
+ };
229
+ },
230
+ { route: route.pattern, render: mode }
231
+ );
232
+ }
233
+
234
+ // ── Core pipeline ────────────────────────────────────────────────────────────
235
+
236
+ export async function renderToHTML(
237
+ route: ResolvedRoute,
238
+ ctx: Context,
239
+ root: RootLayout
240
+ ): Promise<RenderResult> {
241
+ const prepared = await prepareRender(route, ctx, root, undefined, false, undefined);
242
+
243
+ // Redirect — re-throw so callers like prerenderSSG / handleISR can catch it
244
+ if (prepared instanceof Response) {
245
+ throw prepared;
246
+ }
247
+
248
+ const { componentProps, element, headData, headers, status, template } = prepared;
249
+
250
+ const stream = await renderToReadableStream(element);
251
+ await stream.allReady;
252
+ const reactHtml = await streamToString(stream);
253
+
254
+ return {
255
+ html: assembleHTML(template, headData, reactHtml, componentProps),
256
+ headers,
257
+ status,
258
+ };
259
+ }
260
+
261
+ // ── Public render functions ──────────────────────────────────────────────────
262
+
263
+ export async function renderToStream(
264
+ route: ResolvedRoute,
265
+ ctx: Context,
266
+ root: RootLayout
267
+ ): Promise<ReadableStream | Response> {
268
+ const response = await renderSSR(route, ctx, root, undefined);
269
+ if (!response.ok) {
270
+ return response;
271
+ }
272
+ return response.body ?? new ReadableStream();
273
+ }
274
+
275
+ export async function prerenderSSG(
276
+ route: ResolvedRoute,
277
+ params: Record<string, string>,
278
+ root: RootLayout,
279
+ origin: string,
280
+ basePath: string | undefined
281
+ ): Promise<SsgCacheEntry | Response> {
282
+ const resolvedPath = resolvePath(route.pattern, params);
283
+
284
+ const cached = getSSGCache(resolvedPath);
285
+ if (cached) {
286
+ return cached;
287
+ }
288
+
289
+ const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
290
+ if (renderResult instanceof Response) {
291
+ return renderResult;
292
+ }
293
+ const result = renderResult;
294
+
295
+ const entry: SsgCacheEntry = { html: result.html, cachedAt: Date.now(), status: result.status };
296
+ setSSGCache(resolvedPath, entry);
297
+
298
+ return entry;
299
+ }
300
+
301
+ export async function renderSSR(
302
+ route: ResolvedRoute,
303
+ ctx: Context,
304
+ root: RootLayout,
305
+ precomputedLoaderResult: LoaderResult | undefined
306
+ ): Promise<Response> {
307
+ const prepared = await prepareRender(route, ctx, root, undefined, false, precomputedLoaderResult);
308
+
309
+ // Redirect — return directly as a Response
310
+ if (prepared instanceof Response) {
311
+ return prepared;
312
+ }
313
+
314
+ useLogger().set({
315
+ furin: {
316
+ render: route.mode,
317
+ route: route.pattern,
318
+ loader_ms: prepared.loader_ms,
319
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
320
+ },
321
+ });
322
+
323
+ const { componentProps, element, headData, headers, template } = prepared;
324
+
325
+ // Split template around placeholders
326
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
327
+
328
+ // Shell-render gate: if the React shell (pre-Suspense render) throws, recover
329
+ // by rendering the nearest error.tsx. If THAT also throws, fall back to the
330
+ // built-in DefaultErrorComponent to break recursion.
331
+ let reactStream: ReadableStream<Uint8Array>;
332
+ let status = prepared.status;
333
+ let shellErrored = false;
334
+ let finalDigest = prepared.errorDigest;
335
+ try {
336
+ reactStream = await renderToReadableStream(element);
337
+ } catch (shellError) {
338
+ shellErrored = true;
339
+ status = 500;
340
+ finalDigest = computeErrorDigest(shellError);
341
+ // Log the shell-render error — prepared.errorDigest (if any) was for the
342
+ // loader-level error that never made it to the stream; this is a new one.
343
+ useLogger().set({
344
+ furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
345
+ });
346
+ try {
347
+ reactStream = await renderToReadableStream(
348
+ withSSRRouterContext(
349
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest),
350
+ prepared.ssrContext
351
+ )
352
+ );
353
+ } catch {
354
+ // User's error.tsx also threw — render the built-in default which is
355
+ // pure markup and cannot crash.
356
+ reactStream = await renderToReadableStream(
357
+ withSSRRouterContext(
358
+ buildErrorElement(undefined, shellError, finalDigest),
359
+ prepared.ssrContext
360
+ )
361
+ );
362
+ }
363
+ }
364
+
365
+ // In error-recovery mode, don't inject loader data (it may contain the
366
+ // failing state that caused the crash). Use an empty payload so rehydration
367
+ // is a no-op rather than repeating the error. When we DO have a digest
368
+ // (either from loader error or shell recovery), expose it under __furinError
369
+ // so the client-side ErrorBoundary can surface the same id on rehydrate.
370
+ const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...componentProps };
371
+ if (finalDigest) {
372
+ dataPayload.__furinError = { digest: finalDigest };
373
+ }
374
+ // Slice 8 — SPA 404 signal. When the loader threw `notFound()`, the response
375
+ // status is 404 and the body contains the rendered not-found UI. We ALSO
376
+ // embed a machine-readable signal in __FURIN_DATA__ so that a mid-SPA-nav
377
+ // client can detect the case without guessing from the HTML, and render the
378
+ // not-found component inline instead of performing a jarring full-page
379
+ // reload. Mirrors the existing `__furinError.digest` channel for 500s.
380
+ if (status === 404 && !shellErrored) {
381
+ dataPayload.__furinStatus = 404;
382
+ if (prepared.notFoundError) {
383
+ dataPayload.__furinNotFound = prepared.notFoundError;
384
+ }
385
+ }
386
+ const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
387
+ dataPayload
388
+ )}</script>`;
389
+
390
+ // Pipe head + React stream + tail into a single ReadableStream
391
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
392
+ const writer = writable.getWriter();
393
+ const enc = new TextEncoder();
394
+
395
+ (async () => {
396
+ await writer.write(enc.encode(headPre + headData + bodyPre));
397
+ const reader = reactStream.getReader();
398
+ for (;;) {
399
+ const { done, value } = await reader.read();
400
+ if (done) {
401
+ break;
402
+ }
403
+ await writer.write(value);
404
+ }
405
+ await writer.write(enc.encode(dataScript + bodyPost));
406
+ await writer.close();
407
+ })().catch((err) => writer.abort(err));
408
+
409
+ return new Response(readable, {
410
+ status,
411
+ headers: {
412
+ "Content-Type": "text/html; charset=utf-8",
413
+ "Cache-Control": "no-store, no-cache, must-revalidate",
414
+ ...headers,
415
+ },
416
+ });
417
+ }
418
+
419
+ // ── Catch-all 404 ────────────────────────────────────────────────────────────
420
+
421
+ /**
422
+ * Renders the root-level not-found component into a complete 404 HTML Response.
423
+ * Used by the Elysia `.onError` catch-all when no route matches the request URL.
424
+ *
425
+ * Template resolution mirrors the main render path:
426
+ * prod template (if pre-rendered / compiled server)
427
+ * → dev template from Bun's HTML bundler (in dev, for the rewritten script tag)
428
+ * → static `generateIndexHtml()` (last-resort fallback; test harness, SSR with no request).
429
+ *
430
+ * The dev-template branch is critical: Bun's HTML bundler rewrites
431
+ * `./_hydrate.tsx` to the hashed client chunk URL (e.g. `/_bun/client/index-*.js`).
432
+ * If we served the raw `generateIndexHtml()` output, the browser would try to
433
+ * load `./_hydrate.tsx` relative to the current URL (e.g. `/foo/_hydrate.tsx`),
434
+ * 404, and the page would be left static — so clicking any in-page link would
435
+ * trigger a full document load instead of SPA navigation.
436
+ *
437
+ * If the user's not-found.tsx itself throws, falls back to the built-in
438
+ * DefaultNotFoundComponent to break recursion.
439
+ *
440
+ * @param root - Resolved root layout (carries the user's `not-found.tsx` ref).
441
+ * @param request - The incoming request. Required in dev to resolve the HMR
442
+ * entry origin. Pass `undefined` in contexts where no request is available
443
+ * (tests, SSG warmup) — the function will fall through to the static shell.
444
+ */
445
+ export async function renderRootNotFound(
446
+ root: RootLayout,
447
+ request: Request | undefined
448
+ ): Promise<Response> {
449
+ const prodTemplate = getProductionTemplate();
450
+ let template: string;
451
+ if (prodTemplate !== null) {
452
+ template = prodTemplate;
453
+ } else if (IS_DEV && request !== undefined) {
454
+ try {
455
+ template = await getDevTemplate(new URL(request.url).origin);
456
+ } catch (devTemplateErr) {
457
+ // Loopback failed (server not listening yet, URL unreachable, etc.) —
458
+ // still return SOMETHING so the user doesn't see a raw error. The
459
+ // generated HTML will be non-interactive (see JSDoc), but that's
460
+ // strictly better than a 500.
461
+ useLogger().set({
462
+ furin: {
463
+ render: "not-found",
464
+ action: "dev_template_fallback",
465
+ error: devTemplateErr instanceof Error ? devTemplateErr.message : String(devTemplateErr),
466
+ },
467
+ });
468
+ template = generateIndexHtml();
469
+ }
470
+ } else {
471
+ template = generateIndexHtml();
472
+ }
473
+ const notFoundError = new FurinNotFoundError(undefined);
474
+
475
+ const notFoundContext: RouterContextValue = {
476
+ basePath: "",
477
+ currentHref: request ? normalizeHref(new URL(request.url).pathname) : "/",
478
+ navigate: () => Promise.resolve(),
479
+ prefetch: () => {
480
+ /* noop */
481
+ },
482
+ invalidatePrefetch: () => {
483
+ /* noop */
484
+ },
485
+ refresh: () => Promise.resolve(),
486
+ isNavigating: false,
487
+ defaultPreload: "intent",
488
+ defaultPreloadDelay: 50,
489
+ defaultPreloadStaleTime: 30_000,
490
+ };
491
+
492
+ useLogger().set({
493
+ furin: {
494
+ render: "not-found",
495
+ action: "catch_all",
496
+ path: request ? new URL(request.url).pathname : "/",
497
+ },
498
+ });
499
+
500
+ let reactStream: Awaited<ReturnType<typeof renderToReadableStream>>;
501
+ try {
502
+ reactStream = await renderToReadableStream(
503
+ withSSRRouterContext(buildNotFoundElement(root.notFound, notFoundError), notFoundContext)
504
+ );
505
+ } catch {
506
+ // User's not-found.tsx crashed — fall back to the built-in default.
507
+ reactStream = await renderToReadableStream(
508
+ withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)
509
+ );
510
+ }
511
+ await reactStream.allReady;
512
+ const reactHtml = await streamToString(reactStream);
513
+ // Embed the SPA 404 signal so client-side `fetchPageState` can detect the
514
+ // catch-all 404 via `classifySpaResponse` and render inline instead of doing
515
+ // a jarring full-page reload when navigating to an unmatched URL.
516
+ const html = assembleHTML(template, "", reactHtml, { __furinStatus: 404 });
517
+
518
+ return new Response(html, {
519
+ status: 404,
520
+ headers: { "Content-Type": "text/html; charset=utf-8" },
521
+ });
522
+ }
523
+
524
+ // ── ISR helpers ──────────────────────────────────────────────────────────────
525
+
526
+ /**
527
+ * Builds the Cache-Control header value for an ISR response.
528
+ * Browser: max-age=0 + must-revalidate forces a conditional request every time.
529
+ * CDN: s-maxage=N + stale-while-revalidate=N allow CDN-level serving + BG refresh.
530
+ */
531
+ function isrCacheControl(isFresh: boolean, revalidate: number): string {
532
+ const sMaxAge = isFresh ? revalidate : 0;
533
+ return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
534
+ }
535
+
536
+ /**
537
+ * Serves a response from an existing ISR cache entry.
538
+ * Handles stale-while-revalidate background refresh and ETag conditional requests.
539
+ * Returns `undefined` when a 304 Not Modified is sent (no body needed).
540
+ */
541
+ function serveISRCacheHit(
542
+ cached: ISRCacheEntry,
543
+ ctx: Context,
544
+ route: ResolvedRoute,
545
+ params: Record<string, string>,
546
+ cacheKey: string,
547
+ revalidate: number,
548
+ root: RootLayout,
549
+ buildId: string
550
+ ): string | undefined {
551
+ const isFresh = Date.now() - cached.generatedAt < revalidate * 1000;
552
+
553
+ // Kick off background refresh for stale entries *before* the ETag check
554
+ // so conditional requests (304) do not permanently suppress cache refreshes.
555
+ if (!isFresh) {
556
+ revalidateInBackground(route, params, cacheKey, revalidate, root, ctx);
557
+ }
558
+
559
+ // ETag = "buildId:generatedAt" — encodes both the deploy version and freshness.
560
+ // Only emit when buildId is non-empty (dev has no buildId).
561
+ const etag = buildId ? `"${buildId}:${cached.generatedAt}"` : null;
562
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
563
+ // RFC 7232 §4.1: a 304 MUST echo the ETag and SHOULD include Cache-Control
564
+ // so the browser continues sending If-None-Match on future requests.
565
+ ctx.set.status = 304;
566
+ ctx.set.headers.etag = etag;
567
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
568
+ return;
569
+ }
570
+
571
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
572
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
573
+ if (etag) {
574
+ ctx.set.headers.etag = etag;
575
+ }
576
+
577
+ useLogger().set({
578
+ furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" },
579
+ });
580
+ return cached.html;
581
+ }
582
+
583
+ /**
584
+ * Handles the ISR non-200 render path: shell-recovery with fallback error
585
+ * component, structured logging, and cache-control headers. Extracted from
586
+ * handleISR to keep cyclomatic complexity under the lint threshold.
587
+ */
588
+ async function renderISRNon200(
589
+ prepared: PreparedRender,
590
+ route: ResolvedRoute,
591
+ ctx: Context,
592
+ root: RootLayout,
593
+ errorDigest: string | undefined,
594
+ renderStart: number,
595
+ buildId: string
596
+ ): Promise<string> {
597
+ const { componentProps, element, headData, template, status, notFoundError } = prepared;
598
+ const fallbackProps: Record<string, unknown> = { ...componentProps };
599
+ if (status === 404) {
600
+ fallbackProps.__furinStatus = 404;
601
+ if (notFoundError) {
602
+ fallbackProps.__furinNotFound = notFoundError;
603
+ }
604
+ }
605
+
606
+ // Shell-render gate: if the React render throws for the non-200 ISR branch,
607
+ // recover by rendering the fallback error component so that a broken
608
+ // user error/not-found UI cannot crash the ISR path entirely.
609
+ let reactStream: Awaited<ReturnType<typeof renderToReadableStream>>;
610
+ let finalStatus = status;
611
+ let finalDigest = errorDigest;
612
+ try {
613
+ reactStream = await renderToReadableStream(element);
614
+ } catch (shellError) {
615
+ finalStatus = 500;
616
+ finalDigest = computeErrorDigest(shellError);
617
+ useLogger().set({
618
+ furin: {
619
+ render: "isr",
620
+ route: route.pattern,
621
+ cache: "miss",
622
+ digest: finalDigest,
623
+ phase: "shell",
624
+ },
625
+ });
626
+ fallbackProps.__furinError = { digest: finalDigest };
627
+ fallbackProps.__furinStatus = 500;
628
+ try {
629
+ reactStream = await renderToReadableStream(
630
+ withSSRRouterContext(
631
+ buildErrorElement(route.error ?? root.error, shellError, finalDigest),
632
+ prepared.ssrContext
633
+ )
634
+ );
635
+ } catch {
636
+ // User's error.tsx also threw — render the built-in default (pure markup,
637
+ // cannot crash).
638
+ reactStream = await renderToReadableStream(
639
+ withSSRRouterContext(
640
+ buildErrorElement(undefined, shellError, finalDigest),
641
+ prepared.ssrContext
642
+ )
643
+ );
644
+ }
645
+ }
646
+ if (!fallbackProps.__furinError && errorDigest) {
647
+ fallbackProps.__furinError = { digest: errorDigest };
648
+ }
649
+
650
+ await reactStream.allReady;
651
+ const reactHtml = await streamToString(reactStream);
652
+ const html = assembleHTML(template, headData, reactHtml, fallbackProps);
653
+ const generatedAt = Date.now();
654
+
655
+ const renderMs = generatedAt - renderStart;
656
+ useLogger().set({
657
+ furin: {
658
+ render: "isr",
659
+ route: route.pattern,
660
+ cache: "miss",
661
+ render_ms: renderMs,
662
+ ...(finalDigest ? { digest: finalDigest } : {}),
663
+ status: finalStatus,
664
+ },
665
+ });
666
+
667
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
668
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
669
+ ctx.set.headers["cache-control"] = "no-store";
670
+ if (etag) {
671
+ ctx.set.headers.etag = etag;
672
+ }
673
+ ctx.set.status = finalStatus;
674
+ return html;
675
+ }
676
+
677
+ export async function handleISR(
678
+ route: ResolvedRoute,
679
+ ctx: Context,
680
+ root: RootLayout,
681
+ buildId = ""
682
+ ) {
683
+ const revalidate = route.page._route.revalidate ?? 60;
684
+ const params = ctx.params ?? {};
685
+ const cacheKey = resolvePath(route.pattern, params);
686
+
687
+ const cached = getISRCache(cacheKey);
688
+ if (cached) {
689
+ return serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId);
690
+ }
691
+
692
+ const renderStart = Date.now();
693
+ const prepared = await prepareRender(route, ctx, root, undefined, false, undefined);
694
+
695
+ // Redirect — return directly
696
+ if (prepared instanceof Response) {
697
+ return prepared;
698
+ }
699
+
700
+ const { componentProps, element, headData, template, status, errorDigest } = prepared;
701
+
702
+ if (status !== 200) {
703
+ return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
704
+ }
705
+
706
+ const stream = await renderToReadableStream(element);
707
+ await stream.allReady;
708
+ const reactHtml = await streamToString(stream);
709
+ const html = assembleHTML(template, headData, reactHtml, componentProps);
710
+ const generatedAt = Date.now();
711
+
712
+ useLogger().set({
713
+ furin: {
714
+ render: "isr",
715
+ route: route.pattern,
716
+ cache: "miss",
717
+ render_ms: generatedAt - renderStart,
718
+ },
719
+ });
720
+
721
+ setISRCache(cacheKey, { html, generatedAt, revalidate });
722
+
723
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
724
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
725
+ ctx.set.headers["cache-control"] = isrCacheControl(true, revalidate);
726
+ if (etag) {
727
+ ctx.set.headers.etag = etag;
728
+ }
729
+ return html;
730
+ }
731
+
732
+ // ── SSG warm-up ──────────────────────────────────────────────────────────────
733
+
734
+ /** Maximum number of concurrent `prerenderSSG` calls during SSG warm-up. */
735
+ const SSG_WARM_CONCURRENCY = 4;
736
+
737
+ /**
738
+ * Pre-renders all SSG routes that declare `staticParams` and populates the
739
+ * in-memory cache before the first real request arrives.
740
+ * Should be called from the Elysia `onStart` hook (production only).
741
+ *
742
+ * Uses a bounded worker pool (SSG_WARM_CONCURRENCY slots) so large sites
743
+ * with many routes × param sets cannot exhaust memory or CPU during startup.
744
+ * Failures are isolated per (route, params) pair and logged without aborting
745
+ * the rest of the warm-up.
746
+ */
747
+ export async function warmSSGCache(
748
+ routes: ResolvedRoute[],
749
+ root: RootLayout,
750
+ origin: string
751
+ ): Promise<void> {
752
+ const targets = routes.filter((r) => r.mode === "ssg" && r.page.staticParams);
753
+ const warmupLogger = createLogger({});
754
+ warmupLogger.set({
755
+ furin: {
756
+ render: "ssg",
757
+ action: "warmup",
758
+ routes: targets.length,
759
+ },
760
+ });
761
+ warmupLogger.emit();
762
+
763
+ // Collect all (route, params) render tasks, handling per-route errors early.
764
+ const tasks: Array<() => Promise<void>> = [];
765
+ for (const route of targets) {
766
+ let paramSets: Record<string, string>[];
767
+ try {
768
+ paramSets = (await route.page.staticParams?.()) ?? [];
769
+ } catch (err) {
770
+ const errorLogger = createLogger({});
771
+ errorLogger.set({
772
+ furin: {
773
+ render: "ssg",
774
+ action: "warmup_failed",
775
+ route: route.pattern,
776
+ },
777
+ });
778
+ errorLogger.error(err instanceof Error ? err : new Error(String(err)));
779
+ errorLogger.emit();
780
+ continue;
781
+ }
782
+ for (const params of paramSets) {
783
+ tasks.push(async () => {
784
+ try {
785
+ await prerenderSSG(route, params, root, origin, undefined);
786
+ } catch (err) {
787
+ const errorLogger = createLogger({});
788
+ errorLogger.set({
789
+ furin: {
790
+ render: "ssg",
791
+ action: "prerender_failed",
792
+ route: route.pattern,
793
+ },
794
+ });
795
+ errorLogger.error(err instanceof Error ? err : new Error(String(err)));
796
+ errorLogger.emit();
797
+ }
798
+ });
799
+ }
800
+ }
801
+
802
+ if (tasks.length === 0) {
803
+ return;
804
+ }
805
+
806
+ // Drain the task queue with a fixed-size worker pool.
807
+ const queue = [...tasks];
808
+ const workers = Array.from({ length: Math.min(SSG_WARM_CONCURRENCY, tasks.length) }, async () => {
809
+ while (queue.length > 0) {
810
+ await queue.shift()?.();
811
+ }
812
+ });
813
+ await Promise.all(workers);
814
+ }
815
+
816
+ /** Tracks in-flight ISR revalidations to prevent thundering herd. */
817
+ const pendingRevalidations = new Set<string>();
818
+
819
+ function revalidateInBackground(
820
+ route: ResolvedRoute,
821
+ params: Record<string, string>,
822
+ cacheKey: string,
823
+ revalidate: number,
824
+ root: RootLayout,
825
+ originalCtx: LoaderContext
826
+ ) {
827
+ if (pendingRevalidations.has(cacheKey)) {
828
+ const logger = createLogger({});
829
+ logger.set({
830
+ furin: {
831
+ render: "isr",
832
+ route: route.pattern,
833
+ cache: "revalidation_skipped",
834
+ reason: "already_in_flight",
835
+ },
836
+ });
837
+ logger.emit();
838
+ return;
839
+ }
840
+ pendingRevalidations.add(cacheKey);
841
+
842
+ renderForPath(route, params, root, new URL(originalCtx.request.url).origin, "isr", undefined)
843
+ .then((result) => {
844
+ if (result instanceof Response) {
845
+ // A loader called ctx.redirect() during ISR revalidation.
846
+ // Silently drop it — the next real request will hit the loader again.
847
+ return;
848
+ }
849
+ setISRCache(cacheKey, {
850
+ html: result.html,
851
+ generatedAt: Date.now(),
852
+ revalidate,
853
+ });
854
+ })
855
+ .catch((err: unknown) => {
856
+ const logger = createLogger({});
857
+ logger.set({
858
+ furin: {
859
+ render: "isr",
860
+ route: route.pattern,
861
+ cache: "revalidation_failed",
862
+ },
863
+ });
864
+ logger.error(err instanceof Error ? err : new Error(String(err)));
865
+ logger.emit();
866
+ })
867
+ .finally(() => {
868
+ pendingRevalidations.delete(cacheKey);
869
+ });
870
+ }