@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.3

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 (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
@@ -1,545 +1,585 @@
1
- // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
-
3
- import type { Context } from "elysia";
4
- import { createElement, type ReactNode } from "react";
5
- import { renderToReadableStream } from "react-dom/server";
6
- import { toCrossJSON, toCrossJSONAsync } from "seroval";
7
- import {
8
- normalizeHref,
9
- RouterContext,
10
- type RouterContextValue,
11
- } from "../../client/router/index.ts";
12
- import { computeErrorDigest } from "../../shared/digest.ts";
13
- import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
14
- // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
15
- import type { ResolvedRoute, RootLayout } from "../router/index.ts";
16
- import { IS_DEV } from "../runtime-env.ts";
17
- import {
18
- assembleHTML,
19
- buildDeferredResolution,
20
- buildDeferredScript,
21
- resolvePath,
22
- splitTemplate,
23
- streamToString,
24
- } from "./assemble.ts";
25
- import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
26
- import { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
27
- import { buildHeadInjection, generateIndexHtml, safeJson } from "./shell.ts";
28
- import { getDevTemplate, getProductionTemplate } from "./template.ts";
29
-
30
- // Re-export types consumed by sibling render modules (not a public barrel).
31
- export type { LoaderContext } from "./assemble.ts";
32
- export type { LoaderResult } from "./loaders.ts";
33
-
34
- // ── Types ────────────────────────────────────────────────────────────────────
35
-
36
- export interface RenderResult {
37
- headers: Record<string, string>;
38
- html: string;
39
- /**
40
- * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
41
- * resolved sync + deferred data. Identical in shape to the body the live
42
- * `/_furin/data` endpoint emits, so the SPA client can consume both
43
- * interchangeably.
44
- */
45
- ndjson: string;
46
- status: number;
47
- }
48
-
49
- export interface PreparedRender {
50
- /**
51
- * All props passed to the React component tree. For deferred renders this
52
- * includes the Promise objects (for `<Await resolve={promise}>`) alongside
53
- * the scalar sync fields. Never serialise this directly — use `syncData`.
54
- */
55
- componentProps: Record<string, unknown>;
56
- /**
57
- * Promise-valued fields from a `defer()` loader return. Undefined for normal
58
- * (non-deferred) loaders. These are streamed as late `<script>` chunks after
59
- * the React stream finishes.
60
- */
61
- deferredPromises: Record<string, Promise<unknown>> | undefined;
62
- element: ReactNode;
63
- /** Set when the prepared element is an error UI. */
64
- errorDigest?: string;
65
- headData: string;
66
- headers: Record<string, string>;
67
- loader_ms: number;
68
- /**
69
- * Populated only when the loader threw `notFound()`. Mirrored into
70
- * `__FURIN_DATA__.__furinNotFound` so the client-side can render the
71
- * not-found UI inline on SPA navigation.
72
- */
73
- notFoundError?: { data?: unknown; message?: string };
74
- ssrContext: RouterContextValue;
75
- status: number;
76
- /**
77
- * JSON-serialisable subset of `componentProps`. For deferred renders this
78
- * excludes the Promise fields (those are streamed separately).
79
- */
80
- syncData: Record<string, unknown>;
81
- template: string;
82
- }
83
-
84
- // ── Shared helpers ───────────────────────────────────────────────────────────
85
-
86
- export function withSSRRouterContext(
87
- element: ReactNode,
88
- contextValue: RouterContextValue
89
- ): ReactNode {
90
- return createElement(RouterContext.Provider, { value: contextValue }, element);
91
- }
92
-
93
- interface ShellFallbackResult {
94
- /**
95
- * Set when the primary element threw synchronously during render and a
96
- * fallback error UI was streamed instead. Carries the digest so the caller
97
- * can surface it in logs and the `__furinError` payload.
98
- */
99
- shellError: { digest: string } | undefined;
100
- stream: Awaited<ReturnType<typeof renderToReadableStream>>;
101
- }
102
-
103
- /**
104
- * Renders `element` to a React stream, recovering from a synchronous shell
105
- * throw with a 500 error UI. The supplied error component (route-level, else
106
- * root-level) is tried first; if it ALSO throws, the built-in error element is
107
- * used, so a broken custom error page can never take down the whole response.
108
- *
109
- * Shared by SSR (which pipes the stream) and ISR/SSG non-200 (which drains it
110
- * to a string) — both start from this same React stream and only diverge in how
111
- * they consume it and which fields they log.
112
- */
113
- export async function renderElementWithShellFallback(
114
- element: ReactNode,
115
- errorComponent: Parameters<typeof buildErrorElement>[0],
116
- ssrContext: RouterContextValue
117
- ): Promise<ShellFallbackResult> {
118
- try {
119
- return { stream: await renderToReadableStream(element), shellError: undefined };
120
- } catch (error) {
121
- const digest = computeErrorDigest(error);
122
- try {
123
- const stream = await renderToReadableStream(
124
- withSSRRouterContext(
125
- buildErrorElement(errorComponent, error, digest, undefined, 500),
126
- ssrContext
127
- )
128
- );
129
- return { stream, shellError: { digest } };
130
- } catch {
131
- const stream = await renderToReadableStream(
132
- withSSRRouterContext(
133
- buildErrorElement(undefined, error, digest, undefined, 500),
134
- ssrContext
135
- )
136
- );
137
- return { stream, shellError: { digest } };
138
- }
139
- }
140
- }
141
-
142
- /**
143
- * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
144
- * the HTML is pre-rendered and cached, so the deferred fields would be absent
145
- * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
146
- * with `undefined`. Fail fast at the loader boundary.
147
- */
148
- export function assertDeferredModeAllowed(
149
- route: ResolvedRoute,
150
- deferredPromises: Record<string, Promise<unknown>> | undefined
151
- ): void {
152
- if (deferredPromises !== undefined && route.mode !== "ssr") {
153
- throw new Error(
154
- `[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
155
- "defer() streams data progressively and is only supported in SSR. " +
156
- "Return the data directly (await it inside the loader) or switch the route to SSR mode."
157
- );
158
- }
159
- }
160
-
161
- /**
162
- * Builds the success-path element and head injection. `head()` is user code
163
- * that runs synchronously, outside the render pipeline's shell-error handling,
164
- * so a throw is converted into a 500 error render that surfaces through the
165
- * framework error UI instead of escaping `prepareRender` and crashing the
166
- * request. Re-throws when `throwOnFailure` is set (build-time SSG) so CI fails
167
- * loudly.
168
- */
169
- function buildSuccessRender(
170
- route: ResolvedRoute,
171
- root: RootLayout,
172
- componentProps: Record<string, unknown>,
173
- throwOnFailure: boolean
174
- ): { element: ReactNode; headData: string; errorDigest: string | undefined; status: number } {
175
- try {
176
- const headData = buildHeadInjection(route.page?.head?.(componentProps));
177
- const element = buildElement(route, componentProps, root.route);
178
- return { element, headData, errorDigest: undefined, status: 200 };
179
- } catch (headError) {
180
- if (throwOnFailure) {
181
- throw headError;
182
- }
183
- const errorDigest = computeErrorDigest(headError);
184
- const element = buildErrorElement(
185
- route.error ?? root.error,
186
- headError,
187
- errorDigest,
188
- undefined,
189
- 500
190
- );
191
- return { element, headData: "", errorDigest, status: 500 };
192
- }
193
- }
194
-
195
- /**
196
- * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
197
- * (streaming). Runs loaders, builds props, head injection, resolves template,
198
- * and creates the React element.
199
- *
200
- * Returns the redirect Response directly when a loader redirects, so callers
201
- * never need try/catch for redirect handling.
202
- */
203
- export async function prepareRender(
204
- route: ResolvedRoute,
205
- ctx: Context,
206
- root: RootLayout,
207
- basePath: string | undefined,
208
- throwOnFailure: boolean,
209
- precomputedLoaderResult: LoaderResult | undefined
210
- ): Promise<PreparedRender | Response> {
211
- const loaderStart = Date.now();
212
- const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
213
- const loader_ms = Date.now() - loaderStart;
214
-
215
- if (loaderResult.type === "redirect") {
216
- return loaderResult.response;
217
- }
218
-
219
- // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
220
- // silently generating a 404/500 page for buggy loaders.
221
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
222
- throw loaderResult.error;
223
- }
224
-
225
- const isNotFound = loaderResult.type === "not-found";
226
- const isError = loaderResult.type === "error";
227
- const isFallback = isNotFound || isError;
228
- const syncData = isFallback ? {} : loaderResult.syncData;
229
- const deferredPromises =
230
- !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
231
- assertDeferredModeAllowed(route, deferredPromises);
232
-
233
- const headers = loaderResult.headers;
234
- const componentProps = {
235
- ...syncData,
236
- ...(deferredPromises ?? {}),
237
- params: ctx.params,
238
- query: ctx.query,
239
- path: ctx.path,
240
- };
241
-
242
- const prodTemplate = getProductionTemplate();
243
- const template =
244
- prodTemplate ??
245
- (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
246
-
247
- let element: ReactNode;
248
- let headData = "";
249
- let status = 200;
250
- let errorDigest: string | undefined;
251
- let notFoundError: { data?: unknown; message?: string } | undefined;
252
- if (loaderResult.type === "not-found") {
253
- element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
254
- status = 404;
255
- notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
256
- } else if (loaderResult.type === "error") {
257
- errorDigest = computeErrorDigest(loaderResult.error);
258
- element = buildErrorElement(
259
- route.error ?? root.error,
260
- loaderResult.error,
261
- errorDigest,
262
- loaderResult.message,
263
- loaderResult.status
264
- );
265
- status = loaderResult.status;
266
- } else {
267
- const success = buildSuccessRender(route, root, componentProps, throwOnFailure);
268
- element = success.element;
269
- headData = success.headData;
270
- errorDigest = success.errorDigest;
271
- status = success.status;
272
- }
273
-
274
- const ssrContext: RouterContextValue = {
275
- basePath: basePath ?? "",
276
- currentHref: normalizeHref(ctx.path),
277
- navigate: (_href, _opts) => Promise.resolve(),
278
- prefetch: (_href, _opts) => {
279
- /* noop */
280
- },
281
- invalidatePrefetch: (_path, _type) => {
282
- /* noop */
283
- },
284
- refresh: (_opts) => Promise.resolve(),
285
- isNavigating: false,
286
- defaultPreload: "intent",
287
- defaultPreloadDelay: 50,
288
- defaultPreloadStaleTime: 30_000,
289
- };
290
- element = withSSRRouterContext(element, ssrContext);
291
-
292
- return {
293
- componentProps,
294
- deferredPromises,
295
- element,
296
- errorDigest,
297
- headData,
298
- headers,
299
- loader_ms,
300
- notFoundError,
301
- syncData,
302
- ssrContext,
303
- status,
304
- template,
305
- };
306
- }
307
-
308
- // ── Helpers ──────────────────────────────────────────────────────────────────
309
-
310
- export function renderForPath(
311
- route: ResolvedRoute,
312
- params: Record<string, string>,
313
- root: RootLayout,
314
- origin: string,
315
- mode: "ssg" | "isr",
316
- basePath: string | undefined
317
- ): Promise<RenderResult | Response> {
318
- return runInSyntheticRenderScope(
319
- async () => {
320
- const resolvedPath = resolvePath(route.pattern, params);
321
- const ctx: Context = {
322
- params,
323
- query: {},
324
- request: new Request(`${origin}${resolvedPath}`),
325
- headers: {},
326
- cookie: {},
327
- redirect: (url: string, status: number | undefined) =>
328
- new Response(null, { status: status ?? 302, headers: { Location: url } }),
329
- set: { headers: {} },
330
- path: resolvedPath,
331
- } as Context;
332
-
333
- const prepared = await prepareRender(route, ctx, root, basePath, true, undefined);
334
- if (prepared instanceof Response) {
335
- return prepared;
336
- }
337
-
338
- useLogger().set({
339
- furin: {
340
- render: mode,
341
- route: route.pattern,
342
- cache: mode === "isr" ? "revalidated" : "miss",
343
- loader_ms: prepared.loader_ms,
344
- ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
345
- },
346
- });
347
-
348
- const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
349
- const stream = await renderToReadableStream(element);
350
- await stream.allReady;
351
- const reactHtml = await streamToString(stream);
352
- return {
353
- html: assembleHTML(template, headData, reactHtml, syncData),
354
- headers,
355
- ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
356
- status,
357
- };
358
- },
359
- { route: route.pattern, render: mode }
360
- );
361
- }
362
-
363
- /**
364
- * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
365
- * NDJSON shape the live `/_furin/data` endpoint emits.
366
- */
367
- export async function serializeLoaderDataNdjson(
368
- syncData: Record<string, unknown>,
369
- deferredPromises: Record<string, Promise<unknown>> | undefined
370
- ): Promise<string> {
371
- const payload: Record<string, unknown> = {
372
- ...syncData,
373
- ...(deferredPromises ?? {}),
374
- };
375
- const serialized = await toCrossJSONAsync(payload);
376
- return `${JSON.stringify(serialized)}\n`;
377
- }
378
-
379
- // ── Core pipeline ────────────────────────────────────────────────────────────
380
-
381
- export async function renderToHTML(
382
- route: ResolvedRoute,
383
- ctx: Context,
384
- root: RootLayout
385
- ): Promise<RenderResult> {
386
- const prepared = await prepareRender(route, ctx, root, undefined, false, undefined);
387
-
388
- if (prepared instanceof Response) {
389
- throw prepared;
390
- }
391
-
392
- const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
393
-
394
- const stream = await renderToReadableStream(element);
395
- await stream.allReady;
396
- const reactHtml = await streamToString(stream);
397
-
398
- return {
399
- html: assembleHTML(template, headData, reactHtml, syncData),
400
- headers,
401
- ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
402
- status,
403
- };
404
- }
405
-
406
- export async function renderToStream(
407
- route: ResolvedRoute,
408
- ctx: Context,
409
- root: RootLayout
410
- ): Promise<ReadableStream | Response> {
411
- const response = await renderSSR(route, ctx, root, undefined);
412
- if (!response.ok) {
413
- return response;
414
- }
415
- return response.body ?? new ReadableStream();
416
- }
417
-
418
- export async function renderSSR(
419
- route: ResolvedRoute,
420
- ctx: Context,
421
- root: RootLayout,
422
- precomputedLoaderResult: LoaderResult | undefined
423
- ): Promise<Response> {
424
- const prepared = await prepareRender(route, ctx, root, undefined, false, precomputedLoaderResult);
425
-
426
- if (prepared instanceof Response) {
427
- return prepared;
428
- }
429
-
430
- useLogger().set({
431
- furin: {
432
- render: route.mode,
433
- route: route.pattern,
434
- loader_ms: prepared.loader_ms,
435
- ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
436
- },
437
- });
438
-
439
- const { deferredPromises, element, headData, headers, syncData, template } = prepared;
440
-
441
- const { headPre, bodyPre, bodyPost } = splitTemplate(template);
442
-
443
- const { stream: reactStream, shellError } = await renderElementWithShellFallback(
444
- element,
445
- route.error ?? root.error,
446
- prepared.ssrContext
447
- );
448
- const shellErrored = shellError !== undefined;
449
- let status = prepared.status;
450
- let finalDigest = prepared.errorDigest;
451
- if (shellError) {
452
- status = 500;
453
- finalDigest = shellError.digest;
454
- useLogger().set({
455
- furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
456
- });
457
- }
458
-
459
- const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
460
- if (finalDigest) {
461
- dataPayload.__furinError = { digest: finalDigest, status };
462
- }
463
- if (status === 404 && !shellErrored) {
464
- dataPayload.__furinStatus = 404;
465
- if (prepared.notFoundError) {
466
- dataPayload.__furinNotFound = prepared.notFoundError;
467
- }
468
- }
469
- if (
470
- process.env.NODE_ENV !== "production" &&
471
- dataPayload.__furinError !== undefined &&
472
- dataPayload.__furinNotFound !== undefined
473
- ) {
474
- throw new Error(
475
- "[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload."
476
- );
477
- }
478
-
479
- const hasDeferred = !shellErrored && deferredPromises !== undefined;
480
-
481
- const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
482
- const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
483
-
484
- const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
485
- dataPayload
486
- )}</script>`;
487
-
488
- const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
489
- const writer = writable.getWriter();
490
- const enc = new TextEncoder();
491
-
492
- (async () => {
493
- await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
494
-
495
- const reader = reactStream.getReader();
496
- for (;;) {
497
- const { done, value } = await reader.read();
498
- if (done) {
499
- break;
500
- }
501
- await writer.write(value);
502
- }
503
-
504
- const [earlyBodyPost, finalBodyPost] = hasDeferred
505
- ? splitBeforeBodyClose(bodyPost)
506
- : ["", bodyPost];
507
- await writer.write(enc.encode(dataScript + earlyBodyPost));
508
-
509
- if (hasDeferred) {
510
- await Promise.all(
511
- Object.entries(deferredPromises).map(async ([key, promise]) => {
512
- try {
513
- const resolvedValue = await promise;
514
- const chunk = toCrossJSON(resolvedValue);
515
- await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
516
- } catch (err) {
517
- const normalized = await serializeDeferredRejection(err);
518
- const chunk = toCrossJSON(normalized);
519
- await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
520
- }
521
- })
522
- );
523
- }
524
-
525
- await writer.write(enc.encode(finalBodyPost));
526
- await writer.close();
527
- })().catch((err) => writer.abort(err));
528
-
529
- return new Response(readable, {
530
- status,
531
- headers: {
532
- "Content-Type": "text/html; charset=utf-8",
533
- "Cache-Control": "no-store, no-cache, must-revalidate",
534
- ...headers,
535
- },
536
- });
537
- }
538
-
539
- export function splitBeforeBodyClose(bodyPost: string): [string, string] {
540
- const index = bodyPost.toLowerCase().lastIndexOf("</body>");
541
- if (index === -1) {
542
- return [bodyPost, ""];
543
- }
544
- return [bodyPost.slice(0, index), bodyPost.slice(index)];
545
- }
1
+ // biome-ignore-all lint/correctness/useHookAtTopLevel: useLogger is not a hook attached to a react component
2
+
3
+ import type { Context } from "elysia";
4
+ import { createElement, type ReactNode } from "react";
5
+ import { renderToReadableStream } from "react-dom/server";
6
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
7
+ import {
8
+ normalizeHref,
9
+ RouterContext,
10
+ type RouterContextValue,
11
+ SearchStoreContext,
12
+ } from "../../client/router/index.ts";
13
+ import {
14
+ createSearchStore,
15
+ searchSnapshotFromRouterContext,
16
+ } from "../../client/router/search-store.ts";
17
+ import { computeErrorDigest } from "../../shared/digest.ts";
18
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
19
+ import { runInSyntheticRenderScope, useLogger } from "../context-logger.ts";
20
+ // FurinNotFoundError is used indirectly via buildNotFoundElement in element.tsx
21
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
22
+ import { IS_DEV } from "../runtime-env.ts";
23
+ import {
24
+ assembleHTML,
25
+ buildDeferredResolution,
26
+ buildDeferredScript,
27
+ buildSyncRuntimeScript,
28
+ resolvePath,
29
+ splitTemplate,
30
+ streamToString,
31
+ } from "./assemble.ts";
32
+ import { buildElement, buildErrorElement, buildNotFoundElement } from "./element.tsx";
33
+ import { type LoaderResult, runLoaders, serializeDeferredRejection } from "./loaders.ts";
34
+ import { buildHeadInjection, generateIndexHtml, safeJson } from "./shell.ts";
35
+ import { getDevTemplate, getProductionTemplate } from "./template.ts";
36
+
37
+ // Re-export types consumed by sibling render modules (not a public barrel).
38
+ export type { LoaderContext } from "./assemble.ts";
39
+ export type { LoaderResult } from "./loaders.ts";
40
+
41
+ // ── Types ────────────────────────────────────────────────────────────────────
42
+
43
+ export interface RenderResult {
44
+ headers: Record<string, string>;
45
+ html: string;
46
+ /**
47
+ * NDJSON payload (one CrossJSON-serialised line) carrying the loader's
48
+ * resolved sync + deferred data. Identical in shape to the body the live
49
+ * `/_furin/data` endpoint emits, so the SPA client can consume both
50
+ * interchangeably.
51
+ */
52
+ ndjson: string;
53
+ status: number;
54
+ }
55
+
56
+ export interface PreparedRender {
57
+ /**
58
+ * All props passed to the React component tree. For deferred renders this
59
+ * includes the Promise objects (for `<Await resolve={promise}>`) alongside
60
+ * the scalar sync fields. Never serialise this directly — use `syncData`.
61
+ */
62
+ componentProps: Record<string, unknown>;
63
+ /**
64
+ * Promise-valued fields from a `defer()` loader return. Undefined for normal
65
+ * (non-deferred) loaders. These are streamed as late `<script>` chunks after
66
+ * the React stream finishes.
67
+ */
68
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
69
+ element: ReactNode;
70
+ /** Set when the prepared element is an error UI. */
71
+ errorDigest?: string;
72
+ headData: string;
73
+ headers: Record<string, string>;
74
+ loader_ms: number;
75
+ /**
76
+ * Populated only when the loader threw `notFound()`. Mirrored into
77
+ * `__FURIN_DATA__.__furinNotFound` so the client-side can render the
78
+ * not-found UI inline on SPA navigation.
79
+ */
80
+ notFoundError?: { data?: unknown; message?: string };
81
+ ssrContext: RouterContextValue;
82
+ status: number;
83
+ /**
84
+ * JSON-serialisable subset of `componentProps`. For deferred renders this
85
+ * excludes the Promise fields (those are streamed separately).
86
+ */
87
+ syncData: Record<string, unknown>;
88
+ template: string;
89
+ }
90
+
91
+ // ── Shared helpers ───────────────────────────────────────────────────────────
92
+
93
+ export function withSSRRouterContext(
94
+ element: ReactNode,
95
+ contextValue: RouterContextValue
96
+ ): ReactNode {
97
+ return createElement(
98
+ SearchStoreContext.Provider,
99
+ { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) },
100
+ createElement(RouterContext.Provider, { value: contextValue }, element)
101
+ );
102
+ }
103
+
104
+ interface ShellFallbackResult {
105
+ /**
106
+ * Set when the primary element threw synchronously during render and a
107
+ * fallback error UI was streamed instead. Carries the digest so the caller
108
+ * can surface it in logs and the `__furinError` payload.
109
+ */
110
+ shellError: { digest: string } | undefined;
111
+ stream: Awaited<ReturnType<typeof renderToReadableStream>>;
112
+ }
113
+
114
+ /**
115
+ * Renders `element` to a React stream, recovering from a synchronous shell
116
+ * throw with a 500 error UI. The supplied error component (route-level, else
117
+ * root-level) is tried first; if it ALSO throws, the built-in error element is
118
+ * used, so a broken custom error page can never take down the whole response.
119
+ *
120
+ * Shared by SSR (which pipes the stream) and ISR/SSG non-200 (which drains it
121
+ * to a string) — both start from this same React stream and only diverge in how
122
+ * they consume it and which fields they log.
123
+ */
124
+ export async function renderElementWithShellFallback(
125
+ element: ReactNode,
126
+ errorComponent: Parameters<typeof buildErrorElement>[0],
127
+ ssrContext: RouterContextValue
128
+ ): Promise<ShellFallbackResult> {
129
+ try {
130
+ return { stream: await renderToReadableStream(element), shellError: undefined };
131
+ } catch (error) {
132
+ const digest = computeErrorDigest(error);
133
+ try {
134
+ const stream = await renderToReadableStream(
135
+ withSSRRouterContext(
136
+ buildErrorElement(errorComponent, error, digest, undefined, 500),
137
+ ssrContext
138
+ )
139
+ );
140
+ return { stream, shellError: { digest } };
141
+ } catch {
142
+ const stream = await renderToReadableStream(
143
+ withSSRRouterContext(
144
+ buildErrorElement(undefined, error, digest, undefined, 500),
145
+ ssrContext
146
+ )
147
+ );
148
+ return { stream, shellError: { digest } };
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * defer() streams data progressively — it only makes sense in SSR. In SSG/ISR
155
+ * the HTML is pre-rendered and cached, so the deferred fields would be absent
156
+ * from the embedded `__FURIN_DATA__` and the client `<Await>` would hydrate
157
+ * with `undefined`. Fail fast at the loader boundary.
158
+ */
159
+ export function assertDeferredModeAllowed(
160
+ route: ResolvedRoute,
161
+ deferredPromises: Record<string, Promise<unknown>> | undefined
162
+ ): void {
163
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
164
+ throw new Error(
165
+ `[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` +
166
+ "defer() streams data progressively and is only supported in SSR. " +
167
+ "Return the data directly (await it inside the loader) or switch the route to SSR mode."
168
+ );
169
+ }
170
+ }
171
+
172
+ function currentHrefFromContext(ctx: Context): string {
173
+ const pathUrl = new URL(ctx.path, "http://furin.local");
174
+ const requestUrl = new URL(ctx.request.url);
175
+ return normalizeHref(pathUrl.pathname) + (pathUrl.search || requestUrl.search);
176
+ }
177
+
178
+ /**
179
+ * Builds the success-path element and head injection. `head()` is user code
180
+ * that runs synchronously, outside the render pipeline's shell-error handling,
181
+ * so a throw is converted into a 500 error render that surfaces through the
182
+ * framework error UI instead of escaping `prepareRender` and crashing the
183
+ * request. Re-throws when `throwOnFailure` is set (build-time SSG) so CI fails
184
+ * loudly.
185
+ */
186
+ function buildSuccessRender(
187
+ route: ResolvedRoute,
188
+ root: RootLayout,
189
+ componentProps: Record<string, unknown>,
190
+ throwOnFailure: boolean
191
+ ): { element: ReactNode; headData: string; errorDigest: string | undefined; status: number } {
192
+ try {
193
+ const headData = buildHeadInjection(route.page?.head?.(componentProps));
194
+ const element = buildElement(route, componentProps, root.route);
195
+ return { element, headData, errorDigest: undefined, status: 200 };
196
+ } catch (headError) {
197
+ if (throwOnFailure) {
198
+ throw headError;
199
+ }
200
+ const errorDigest = computeErrorDigest(headError);
201
+ const element = buildErrorElement(
202
+ route.error ?? root.error,
203
+ headError,
204
+ errorDigest,
205
+ undefined,
206
+ 500
207
+ );
208
+ return { element, headData: "", errorDigest, status: 500 };
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Shared pipeline steps used by both `renderToHTML` (buffered) and `renderSSR`
214
+ * (streaming). Runs loaders, builds props, head injection, resolves template,
215
+ * and creates the React element.
216
+ *
217
+ * Returns the redirect Response directly when a loader redirects, so callers
218
+ * never need try/catch for redirect handling.
219
+ */
220
+ export async function prepareRender(
221
+ route: ResolvedRoute,
222
+ ctx: Context,
223
+ root: RootLayout,
224
+ basePath: string | undefined,
225
+ throwOnFailure: boolean,
226
+ precomputedLoaderResult: LoaderResult | undefined,
227
+ searchRoutes?: SearchRouteMetadata[]
228
+ ): Promise<PreparedRender | Response> {
229
+ const loaderStart = Date.now();
230
+ const loaderResult = precomputedLoaderResult ?? (await runLoaders(route, ctx));
231
+ const loader_ms = Date.now() - loaderStart;
232
+
233
+ if (loaderResult.type === "redirect") {
234
+ return loaderResult.response;
235
+ }
236
+
237
+ // Build-time paths (SSG) opt into re-throwing so CI fails loudly instead of
238
+ // silently generating a 404/500 page for buggy loaders.
239
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
240
+ throw loaderResult.error;
241
+ }
242
+
243
+ const isNotFound = loaderResult.type === "not-found";
244
+ const isError = loaderResult.type === "error";
245
+ const isFallback = isNotFound || isError;
246
+ const syncData = isFallback ? {} : loaderResult.syncData;
247
+ const deferredPromises =
248
+ !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
249
+ assertDeferredModeAllowed(route, deferredPromises);
250
+
251
+ const headers = loaderResult.headers;
252
+ const componentProps = {
253
+ ...syncData,
254
+ ...(deferredPromises ?? {}),
255
+ params: ctx.params,
256
+ query: ctx.query,
257
+ path: ctx.path,
258
+ };
259
+
260
+ const prodTemplate = getProductionTemplate();
261
+ const template =
262
+ prodTemplate ??
263
+ (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
264
+
265
+ let element: ReactNode;
266
+ let headData = "";
267
+ let status = 200;
268
+ let errorDigest: string | undefined;
269
+ let notFoundError: { data?: unknown; message?: string } | undefined;
270
+ if (loaderResult.type === "not-found") {
271
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
272
+ status = 404;
273
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
274
+ } else if (loaderResult.type === "error") {
275
+ errorDigest = computeErrorDigest(loaderResult.error);
276
+ element = buildErrorElement(
277
+ route.error ?? root.error,
278
+ loaderResult.error,
279
+ errorDigest,
280
+ loaderResult.message,
281
+ loaderResult.status
282
+ );
283
+ status = loaderResult.status;
284
+ } else {
285
+ const success = buildSuccessRender(route, root, componentProps, throwOnFailure);
286
+ element = success.element;
287
+ headData = success.headData;
288
+ errorDigest = success.errorDigest;
289
+ status = success.status;
290
+ }
291
+
292
+ const ssrContext: RouterContextValue = {
293
+ basePath: basePath ?? "",
294
+ currentHref: currentHrefFromContext(ctx),
295
+ search: (ctx.query as SearchParamsInput | undefined) ?? {},
296
+ searchRoutes: searchRoutes ?? [],
297
+ navigate: (_href, _opts) => Promise.resolve(),
298
+ prefetch: (_href, _opts) => {
299
+ /* noop */
300
+ },
301
+ invalidatePrefetch: (_path, _type) => {
302
+ /* noop */
303
+ },
304
+ refresh: (_opts) => Promise.resolve(),
305
+ isNavigating: false,
306
+ defaultPreload: "intent",
307
+ defaultPreloadDelay: 50,
308
+ defaultPreloadStaleTime: 30_000,
309
+ };
310
+ element = withSSRRouterContext(element, ssrContext);
311
+
312
+ return {
313
+ componentProps,
314
+ deferredPromises,
315
+ element,
316
+ errorDigest,
317
+ headData,
318
+ headers,
319
+ loader_ms,
320
+ notFoundError,
321
+ syncData,
322
+ ssrContext,
323
+ status,
324
+ template,
325
+ };
326
+ }
327
+
328
+ // ── Helpers ──────────────────────────────────────────────────────────────────
329
+
330
+ export function renderForPath(
331
+ route: ResolvedRoute,
332
+ params: Record<string, string>,
333
+ root: RootLayout,
334
+ origin: string,
335
+ mode: "ssg" | "isr",
336
+ basePath?: string,
337
+ searchRoutes?: SearchRouteMetadata[]
338
+ ): Promise<RenderResult | Response> {
339
+ return runInSyntheticRenderScope(
340
+ async () => {
341
+ const resolvedPath = resolvePath(route.pattern, params);
342
+ const ctx: Context = {
343
+ params,
344
+ query: {},
345
+ request: new Request(`${origin}${resolvedPath}`),
346
+ headers: {},
347
+ cookie: {},
348
+ redirect: (url: string, status: number | undefined) =>
349
+ new Response(null, { status: status ?? 302, headers: { Location: url } }),
350
+ set: { headers: {} },
351
+ path: resolvedPath,
352
+ } as Context;
353
+
354
+ const prepared = await prepareRender(
355
+ route,
356
+ ctx,
357
+ root,
358
+ basePath,
359
+ true,
360
+ undefined,
361
+ searchRoutes
362
+ );
363
+ if (prepared instanceof Response) {
364
+ return prepared;
365
+ }
366
+
367
+ useLogger().set({
368
+ furin: {
369
+ render: mode,
370
+ route: route.pattern,
371
+ cache: mode === "isr" ? "revalidated" : "miss",
372
+ loader_ms: prepared.loader_ms,
373
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
374
+ },
375
+ });
376
+
377
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
378
+ const stream = await renderToReadableStream(element);
379
+ await stream.allReady;
380
+ const reactHtml = await streamToString(stream);
381
+ return {
382
+ html: assembleHTML(template, headData, reactHtml, syncData),
383
+ headers,
384
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
385
+ status,
386
+ };
387
+ },
388
+ { route: route.pattern, render: mode }
389
+ );
390
+ }
391
+
392
+ /**
393
+ * Serialises a loader's `syncData` + `deferredPromises` into the same one-line
394
+ * NDJSON shape the live `/_furin/data` endpoint emits.
395
+ */
396
+ export async function serializeLoaderDataNdjson(
397
+ syncData: Record<string, unknown>,
398
+ deferredPromises: Record<string, Promise<unknown>> | undefined
399
+ ): Promise<string> {
400
+ const payload: Record<string, unknown> = {
401
+ ...syncData,
402
+ ...(deferredPromises ?? {}),
403
+ };
404
+ const serialized = await toCrossJSONAsync(payload);
405
+ return `${JSON.stringify(serialized)}\n`;
406
+ }
407
+
408
+ // ── Core pipeline ────────────────────────────────────────────────────────────
409
+
410
+ export async function renderToHTML(
411
+ route: ResolvedRoute,
412
+ ctx: Context,
413
+ root: RootLayout,
414
+ searchRoutes?: SearchRouteMetadata[]
415
+ ): Promise<RenderResult> {
416
+ const prepared = await prepareRender(route, ctx, root, undefined, false, undefined, searchRoutes);
417
+
418
+ if (prepared instanceof Response) {
419
+ throw prepared;
420
+ }
421
+
422
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
423
+
424
+ const stream = await renderToReadableStream(element);
425
+ await stream.allReady;
426
+ const reactHtml = await streamToString(stream);
427
+
428
+ return {
429
+ html: assembleHTML(template, headData, reactHtml, syncData),
430
+ headers,
431
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
432
+ status,
433
+ };
434
+ }
435
+
436
+ export async function renderToStream(
437
+ route: ResolvedRoute,
438
+ ctx: Context,
439
+ root: RootLayout
440
+ ): Promise<ReadableStream | Response> {
441
+ const response = await renderSSR(route, ctx, root, undefined);
442
+ if (!response.ok) {
443
+ return response;
444
+ }
445
+ return response.body ?? new ReadableStream();
446
+ }
447
+
448
+ export async function renderSSR(
449
+ route: ResolvedRoute,
450
+ ctx: Context,
451
+ root: RootLayout,
452
+ precomputedLoaderResult: LoaderResult | undefined,
453
+ searchRoutes?: SearchRouteMetadata[]
454
+ ): Promise<Response> {
455
+ const prepared = await prepareRender(
456
+ route,
457
+ ctx,
458
+ root,
459
+ undefined,
460
+ false,
461
+ precomputedLoaderResult,
462
+ searchRoutes
463
+ );
464
+
465
+ if (prepared instanceof Response) {
466
+ return prepared;
467
+ }
468
+
469
+ useLogger().set({
470
+ furin: {
471
+ render: route.mode,
472
+ route: route.pattern,
473
+ loader_ms: prepared.loader_ms,
474
+ ...(prepared.errorDigest ? { digest: prepared.errorDigest } : {}),
475
+ },
476
+ });
477
+
478
+ const { deferredPromises, element, headData, headers, syncData, template } = prepared;
479
+
480
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
481
+
482
+ const { stream: reactStream, shellError } = await renderElementWithShellFallback(
483
+ element,
484
+ route.error ?? root.error,
485
+ prepared.ssrContext
486
+ );
487
+ const shellErrored = shellError !== undefined;
488
+ let status = prepared.status;
489
+ let finalDigest = prepared.errorDigest;
490
+ if (shellError) {
491
+ status = 500;
492
+ finalDigest = shellError.digest;
493
+ useLogger().set({
494
+ furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" },
495
+ });
496
+ }
497
+
498
+ const dataPayload: Record<string, unknown> = shellErrored ? {} : { ...syncData };
499
+ if (finalDigest) {
500
+ dataPayload.__furinError = { digest: finalDigest, status };
501
+ }
502
+ if (status === 404 && !shellErrored) {
503
+ dataPayload.__furinStatus = 404;
504
+ if (prepared.notFoundError) {
505
+ dataPayload.__furinNotFound = prepared.notFoundError;
506
+ }
507
+ }
508
+ if (
509
+ process.env.NODE_ENV !== "production" &&
510
+ dataPayload.__furinError !== undefined &&
511
+ dataPayload.__furinNotFound !== undefined
512
+ ) {
513
+ throw new Error(
514
+ "[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload."
515
+ );
516
+ }
517
+
518
+ const hasDeferred = !shellErrored && deferredPromises !== undefined;
519
+
520
+ const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
521
+ const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
522
+
523
+ const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(
524
+ dataPayload
525
+ )}</script>`;
526
+ const runtimeScripts = `${buildSyncRuntimeScript()}${dataScript}`;
527
+
528
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
529
+ const writer = writable.getWriter();
530
+ const enc = new TextEncoder();
531
+
532
+ (async () => {
533
+ await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
534
+
535
+ const reader = reactStream.getReader();
536
+ for (;;) {
537
+ const { done, value } = await reader.read();
538
+ if (done) {
539
+ break;
540
+ }
541
+ await writer.write(value);
542
+ }
543
+
544
+ const [earlyBodyPost, finalBodyPost] = hasDeferred
545
+ ? splitBeforeBodyClose(bodyPost)
546
+ : ["", bodyPost];
547
+ await writer.write(enc.encode(runtimeScripts + earlyBodyPost));
548
+
549
+ if (hasDeferred) {
550
+ await Promise.all(
551
+ Object.entries(deferredPromises).map(async ([key, promise]) => {
552
+ try {
553
+ const resolvedValue = await promise;
554
+ const chunk = toCrossJSON(resolvedValue);
555
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
556
+ } catch (err) {
557
+ const normalized = await serializeDeferredRejection(err);
558
+ const chunk = toCrossJSON(normalized);
559
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
560
+ }
561
+ })
562
+ );
563
+ }
564
+
565
+ await writer.write(enc.encode(finalBodyPost));
566
+ await writer.close();
567
+ })().catch((err) => writer.abort(err));
568
+
569
+ return new Response(readable, {
570
+ status,
571
+ headers: {
572
+ "Content-Type": "text/html; charset=utf-8",
573
+ "Cache-Control": "no-store, no-cache, must-revalidate",
574
+ ...headers,
575
+ },
576
+ });
577
+ }
578
+
579
+ export function splitBeforeBodyClose(bodyPost: string): [string, string] {
580
+ const index = bodyPost.toLowerCase().lastIndexOf("</body>");
581
+ if (index === -1) {
582
+ return [bodyPost, ""];
583
+ }
584
+ return [bodyPost.slice(0, index), bodyPost.slice(index)];
585
+ }