@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.2

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 (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,317 @@
1
+ import type { Context } from "elysia";
2
+ import { renderToReadableStream } from "react-dom/server";
3
+ import { isNotFoundError } from "../../shared/not-found.ts";
4
+ import type { SearchRouteMetadata } from "../../shared/search-params.ts";
5
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
6
+ import { deleteISRCache, getISRCache, setISRCache } from "../cache/isr.ts";
7
+ import type { ISRCacheEntry } from "../cache/isr-ssg.ts";
8
+ import { createLogger, useLogger } from "../context-logger.ts";
9
+ import type { ResolvedRoute, RootLayout } from "../router/index.ts";
10
+ import { assembleHTML, type LoaderContext, resolvePath, streamToString } from "./assemble.ts";
11
+ import {
12
+ type PreparedRender,
13
+ prepareRender,
14
+ renderElementWithShellFallback,
15
+ renderForPath,
16
+ } from "./ssr.ts";
17
+
18
+ /**
19
+ * Builds the Cache-Control header value for an ISR response.
20
+ */
21
+ function isrCacheControl(isFresh: boolean, revalidate: number): string {
22
+ const sMaxAge = isFresh ? revalidate : 0;
23
+ return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
24
+ }
25
+
26
+ /**
27
+ * ETag for an ISR entry: `"buildId:generatedAt"`. Null when no build ID is
28
+ * available (dev), which disables conditional requests for that response.
29
+ */
30
+ function isrEtag(buildId: string | undefined, generatedAt: number): string | null {
31
+ return buildId ? `"${buildId}:${generatedAt}"` : null;
32
+ }
33
+
34
+ /**
35
+ * Serves a response from an existing ISR cache entry.
36
+ * Handles stale-while-revalidate background refresh and ETag conditional requests.
37
+ */
38
+ function serveISRCacheHit(
39
+ cached: ISRCacheEntry,
40
+ ctx: Context,
41
+ route: ResolvedRoute,
42
+ params: Record<string, string>,
43
+ cacheKey: string,
44
+ revalidate: number,
45
+ root: RootLayout,
46
+ buildId: string | undefined,
47
+ searchRoutes?: SearchRouteMetadata[]
48
+ ): string | undefined {
49
+ const isFresh = Date.now() - cached.generatedAt < revalidate * 1000;
50
+
51
+ if (!isFresh) {
52
+ revalidateInBackground(route, params, cacheKey, revalidate, root, ctx, searchRoutes);
53
+ }
54
+
55
+ const etag = isrEtag(buildId, cached.generatedAt);
56
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
57
+ ctx.set.status = 304;
58
+ ctx.set.headers.etag = etag;
59
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
60
+ return;
61
+ }
62
+
63
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
64
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
65
+ if (etag) {
66
+ ctx.set.headers.etag = etag;
67
+ }
68
+
69
+ useLogger().set({
70
+ furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" },
71
+ });
72
+ return cached.html;
73
+ }
74
+
75
+ /**
76
+ * Handles the ISR non-200 render path: shell-recovery with fallback error
77
+ * component, structured logging, and cache-control headers.
78
+ */
79
+ async function renderISRNon200(
80
+ prepared: PreparedRender,
81
+ route: ResolvedRoute,
82
+ ctx: Context,
83
+ root: RootLayout,
84
+ errorDigest: string | undefined,
85
+ renderStart: number,
86
+ buildId: string | undefined
87
+ ): Promise<string> {
88
+ const { componentProps, element, headData, headers, template, status, notFoundError } = prepared;
89
+ const fallbackProps: Record<string, unknown> = { ...componentProps };
90
+ if (status === 404) {
91
+ fallbackProps.__furinStatus = 404;
92
+ if (notFoundError) {
93
+ fallbackProps.__furinNotFound = notFoundError;
94
+ }
95
+ }
96
+
97
+ const { stream: reactStream, shellError } = await renderElementWithShellFallback(
98
+ element,
99
+ route.error ?? root.error,
100
+ prepared.ssrContext
101
+ );
102
+ let finalStatus = status;
103
+ let finalDigest = errorDigest;
104
+ if (shellError) {
105
+ finalStatus = 500;
106
+ finalDigest = shellError.digest;
107
+ useLogger().set({
108
+ furin: {
109
+ render: "isr",
110
+ route: route.pattern,
111
+ cache: "miss",
112
+ digest: finalDigest,
113
+ phase: "shell",
114
+ },
115
+ });
116
+ fallbackProps.__furinError = { digest: finalDigest, status: finalStatus };
117
+ fallbackProps.__furinStatus = 500;
118
+ }
119
+ if (!fallbackProps.__furinError && errorDigest) {
120
+ fallbackProps.__furinError = { digest: errorDigest, status };
121
+ }
122
+
123
+ await reactStream.allReady;
124
+ const reactHtml = await streamToString(reactStream);
125
+ const html = assembleHTML(template, headData, reactHtml, fallbackProps);
126
+ const generatedAt = Date.now();
127
+
128
+ const renderMs = generatedAt - renderStart;
129
+ useLogger().set({
130
+ furin: {
131
+ render: "isr",
132
+ route: route.pattern,
133
+ cache: "miss",
134
+ render_ms: renderMs,
135
+ ...(finalDigest ? { digest: finalDigest } : {}),
136
+ status: finalStatus,
137
+ },
138
+ });
139
+
140
+ const etag = isrEtag(buildId, generatedAt);
141
+ // Apply loader-set headers first so custom headers survive, then let the
142
+ // ISR-critical headers win (the cache contract is framework-owned).
143
+ for (const [key, value] of Object.entries(headers)) {
144
+ ctx.set.headers[key] = value;
145
+ }
146
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
147
+ ctx.set.headers["cache-control"] = "no-store";
148
+ if (etag) {
149
+ ctx.set.headers.etag = etag;
150
+ }
151
+ ctx.set.status = finalStatus;
152
+ return html;
153
+ }
154
+
155
+ export async function handleISR(
156
+ route: ResolvedRoute,
157
+ ctx: Context,
158
+ root: RootLayout,
159
+ buildId: string | undefined,
160
+ searchRoutes?: SearchRouteMetadata[]
161
+ ) {
162
+ const revalidate = route.page._route.revalidate ?? 60;
163
+ const params = ctx.params ?? {};
164
+ const cacheKey = resolvePath(route.pattern, params);
165
+
166
+ const cached = getISRCache(cacheKey);
167
+ if (cached) {
168
+ return serveISRCacheHit(
169
+ cached,
170
+ ctx,
171
+ route,
172
+ params,
173
+ cacheKey,
174
+ revalidate,
175
+ root,
176
+ buildId,
177
+ searchRoutes
178
+ );
179
+ }
180
+
181
+ const renderStart = Date.now();
182
+ const prepared = await prepareRender(route, ctx, root, undefined, false, undefined, searchRoutes);
183
+
184
+ if (prepared instanceof Response) {
185
+ return prepared;
186
+ }
187
+
188
+ const { element, headData, headers, syncData, template, status, errorDigest } = prepared;
189
+
190
+ if (status !== 200) {
191
+ return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
192
+ }
193
+
194
+ const stream = await renderToReadableStream(element);
195
+ await stream.allReady;
196
+ const reactHtml = await streamToString(stream);
197
+ const html = assembleHTML(template, headData, reactHtml, syncData);
198
+ const generatedAt = Date.now();
199
+
200
+ useLogger().set({
201
+ furin: {
202
+ render: "isr",
203
+ route: route.pattern,
204
+ cache: "miss",
205
+ render_ms: generatedAt - renderStart,
206
+ },
207
+ });
208
+
209
+ setISRCache(cacheKey, { html, generatedAt, revalidate });
210
+ autoInvalidateRegistry.registerLoaderTags(cacheKey, route.tags);
211
+
212
+ const etag = isrEtag(buildId, generatedAt);
213
+ // Apply loader-set headers first so custom headers survive, then let the
214
+ // ISR-critical headers win (the cache contract is framework-owned).
215
+ for (const [key, value] of Object.entries(headers)) {
216
+ ctx.set.headers[key] = value;
217
+ }
218
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
219
+ ctx.set.headers["cache-control"] = isrCacheControl(true, revalidate);
220
+ if (etag) {
221
+ ctx.set.headers.etag = etag;
222
+ }
223
+ return html;
224
+ }
225
+
226
+ /** Tracks in-flight ISR revalidations to prevent thundering herd. */
227
+ const pendingRevalidations = new Set<string>();
228
+
229
+ function revalidateInBackground(
230
+ route: ResolvedRoute,
231
+ params: Record<string, string>,
232
+ cacheKey: string,
233
+ revalidate: number,
234
+ root: RootLayout,
235
+ originalCtx: LoaderContext,
236
+ searchRoutes?: SearchRouteMetadata[]
237
+ ) {
238
+ if (pendingRevalidations.has(cacheKey)) {
239
+ const logger = createLogger({});
240
+ logger.set({
241
+ furin: {
242
+ render: "isr",
243
+ route: route.pattern,
244
+ cache: "revalidation_skipped",
245
+ reason: "already_in_flight",
246
+ },
247
+ });
248
+ logger.emit();
249
+ return;
250
+ }
251
+ pendingRevalidations.add(cacheKey);
252
+
253
+ renderForPath(
254
+ route,
255
+ params,
256
+ root,
257
+ new URL(originalCtx.request.url).origin,
258
+ "isr",
259
+ undefined,
260
+ searchRoutes
261
+ )
262
+ .then((result) => {
263
+ if (result instanceof Response) {
264
+ return;
265
+ }
266
+ // Only replace the cached entry with a healthy 200 render. The current
267
+ // ISR cache stores HTML only, so caching non-200 output would serve it
268
+ // back as a 200 on the next hit.
269
+ if (result.status !== 200) {
270
+ const logger = createLogger({});
271
+ logger.set({
272
+ furin: {
273
+ render: "isr",
274
+ route: route.pattern,
275
+ cache: "revalidation_skipped",
276
+ reason: "non_200_render",
277
+ status: result.status,
278
+ },
279
+ });
280
+ logger.emit();
281
+ return;
282
+ }
283
+ setISRCache(cacheKey, {
284
+ html: result.html,
285
+ generatedAt: Date.now(),
286
+ revalidate,
287
+ });
288
+ })
289
+ .catch((err: unknown) => {
290
+ const logger = createLogger({});
291
+ if (isNotFoundError(err)) {
292
+ deleteISRCache(cacheKey);
293
+ logger.set({
294
+ furin: {
295
+ render: "isr",
296
+ route: route.pattern,
297
+ cache: "revalidation_invalidated",
298
+ reason: "not_found",
299
+ },
300
+ });
301
+ logger.emit();
302
+ return;
303
+ }
304
+ logger.set({
305
+ furin: {
306
+ render: "isr",
307
+ route: route.pattern,
308
+ cache: "revalidation_failed",
309
+ },
310
+ });
311
+ logger.error(err instanceof Error ? err : new Error(String(err)));
312
+ logger.emit();
313
+ })
314
+ .finally(() => {
315
+ pendingRevalidations.delete(cacheKey);
316
+ });
317
+ }
@@ -0,0 +1,328 @@
1
+ import type { Context } from "elysia";
2
+ import { isDeferred, type RuntimeRoute } from "../../client.ts";
3
+ import { type FurinNotFoundError, isNotFoundError } from "../../shared/not-found.ts";
4
+ import { useLogger } from "../context-logger.ts";
5
+ import type { ResolvedRoute } from "../router/index.ts";
6
+
7
+ export type LoaderResult =
8
+ | {
9
+ type: "data";
10
+ /**
11
+ * Synchronous (JSON-serialisable) loader fields. Injected into the initial
12
+ * HTML shell as `__FURIN_DATA__` / the deferred registry's `_data` object.
13
+ */
14
+ syncData: Record<string, unknown>;
15
+ /**
16
+ * Promise-valued fields from a `defer()` return. `undefined` when the page
17
+ * loader did not call `defer()`. Streamed as late `<script>` resolution
18
+ * chunks (SSR) or as NDJSON chunks via `/_furin/data` (SPA nav).
19
+ */
20
+ deferredPromises: Record<string, Promise<unknown>> | undefined;
21
+ headers: Record<string, string>;
22
+ }
23
+ | { type: "redirect"; response: Response }
24
+ | { type: "not-found"; error: FurinNotFoundError; headers: Record<string, string> }
25
+ | {
26
+ type: "error";
27
+ /**
28
+ * Original thrown value, kept for digest computation and server logging.
29
+ * For thrown `Response` objects this is the Response instance whose body
30
+ * has already been consumed by `runLoaders` (do NOT read it again).
31
+ */
32
+ error: unknown;
33
+ /** HTTP status to return. Default 500; sourced from `Response.status` for thrown Response objects. */
34
+ status: number;
35
+ /**
36
+ * Safe public message extracted at the loader boundary. For thrown
37
+ * `Response` objects: response body or `statusText`. For thrown `Error`
38
+ * / non-Error values: a generic "Something went wrong" string (the raw
39
+ * error/message is never leaked here — `errorMessageOf` decides what to
40
+ * surface from the original `error` value when an `error.tsx` fallback
41
+ * exists).
42
+ */
43
+ message: string;
44
+ headers: Record<string, string>;
45
+ };
46
+
47
+ /**
48
+ * Navigation redirect status codes — the exact set `ctx.redirect()` can emit.
49
+ * Other 3xx codes (304 Not Modified, 305/306) are NOT navigation redirects and
50
+ * must not be treated as one even when they carry a `Location` header.
51
+ */
52
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
53
+
54
+ /**
55
+ * `true` only for HTTP responses that are syntactically valid redirects:
56
+ * a navigation redirect status code AND a `Location` header. A redirect status
57
+ * without `Location` is invalid HTTP and almost always a developer mistake —
58
+ * surfaced as an error so it's debuggable rather than silently redirecting to `/`.
59
+ */
60
+ function isHttpRedirect(res: Response): boolean {
61
+ return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
62
+ }
63
+
64
+ /**
65
+ * Reads the body of a thrown `Response` exactly once. Returns the body text
66
+ * if present, otherwise the response's `statusText`. The body is consumed
67
+ * destructively — callers must NOT read `res.body` / `res.text()` again.
68
+ */
69
+ async function readResponseMessage(res: Response): Promise<string> {
70
+ if (res.body === null) {
71
+ return res.statusText;
72
+ }
73
+ try {
74
+ const body = await res.text();
75
+ return body || res.statusText;
76
+ } catch {
77
+ return res.statusText;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Wraps the Elysia context so that any property NOT present on `ctx` is
83
+ * returned as an individual `Promise<value>` resolved from the accumulated
84
+ * parent data. Properties that ARE present on `ctx` (request, params, set, …)
85
+ * are returned as-is.
86
+ *
87
+ * A per-prop cache ensures the same Promise instance is returned on repeated
88
+ * access of the same field (stable reference for Promise.all etc.).
89
+ */
90
+ function createLoaderCtx(
91
+ ctx: Record<string, unknown>,
92
+ accumulatedParentPromise: Promise<Record<string, unknown>>
93
+ ): Record<string, unknown> {
94
+ const cache = new Map<string, Promise<unknown>>();
95
+ return new Proxy(ctx, {
96
+ get(target, prop: string | symbol) {
97
+ if (typeof prop !== "string") {
98
+ return Reflect.get(target, prop);
99
+ }
100
+ // Short-circuit well-known Promise/serialisation introspection keys so
101
+ // the proxy is never treated as a thenable by Promise.resolve() or
102
+ // JSON.stringify(), which would cause silent infinite loops or wrong types.
103
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
104
+ return Reflect.get(target, prop);
105
+ }
106
+ // RouteContext fields (request, params, query, set, headers, cookie,
107
+ // path, redirect) are present on target — return directly.
108
+ // Use hasOwn so prototype keys (toString, constructor, …) are not
109
+ // mistaken for context fields and incorrectly hide parent loader data.
110
+ if (Object.hasOwn(target, prop)) {
111
+ return target[prop];
112
+ }
113
+ // Everything else is a parent-data field → individual lazy Promise.
114
+ let entry = cache.get(prop);
115
+ if (!entry) {
116
+ entry = accumulatedParentPromise.then((data) => data[prop]);
117
+ cache.set(prop, entry);
118
+ }
119
+ return entry;
120
+ },
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Splits a single loader result into sync scalars and deferred Promises.
126
+ *
127
+ * A loader result is considered "deferred" only when wrapped with `defer()`
128
+ * (i.e. carries the `__isDeferred` brand). A loader that returned a plain
129
+ * object keeps all its values in sync — even if some happen to be Promises —
130
+ * preserving the long-standing semantic that only an explicit `defer()` opts
131
+ * into streaming.
132
+ */
133
+ function splitOneLoaderResult(result: Record<string, unknown>): {
134
+ sync: Record<string, unknown>;
135
+ deferred: Record<string, Promise<unknown>>;
136
+ } {
137
+ const sync: Record<string, unknown> = {};
138
+ const deferred: Record<string, Promise<unknown>> = {};
139
+ const isDef = isDeferred(result);
140
+ for (const [key, value] of Object.entries(result)) {
141
+ if (key === "__isDeferred") {
142
+ continue;
143
+ }
144
+ if (isDef && isPromiseLike(value)) {
145
+ deferred[key] = Promise.resolve(value);
146
+ } else {
147
+ sync[key] = value;
148
+ }
149
+ }
150
+ return { sync, deferred };
151
+ }
152
+
153
+ function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
154
+ return (
155
+ (typeof value === "object" || typeof value === "function") &&
156
+ value !== null &&
157
+ typeof (value as { then?: unknown }).then === "function"
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Merges per-loader results into the unified sync / deferred maps used by
163
+ * `runLoaders`. `results` is ordered ancestor-most → page, so later loaders
164
+ * overwrite earlier ones on key collision.
165
+ *
166
+ * Cross-map cleanup: when a later loader contributes a key, drop any stale
167
+ * entry from the opposite map. Without this, a key that switches between sync
168
+ * and deferred across loaders would leave both maps populated, and the wire
169
+ * would carry two contradictory values for the same field.
170
+ */
171
+ function mergeLoaderResults(results: unknown[]): {
172
+ allSync: Record<string, unknown>;
173
+ allDeferred: Record<string, Promise<unknown>>;
174
+ } {
175
+ const allSync: Record<string, unknown> = {};
176
+ const allDeferred: Record<string, Promise<unknown>> = {};
177
+ for (const result of results) {
178
+ const { sync, deferred } = splitOneLoaderResult(result as Record<string, unknown>);
179
+ for (const k of Object.keys(sync)) {
180
+ delete allDeferred[k];
181
+ }
182
+ for (const k of Object.keys(deferred)) {
183
+ delete allSync[k];
184
+ }
185
+ Object.assign(allSync, sync);
186
+ Object.assign(allDeferred, deferred);
187
+ }
188
+ return { allSync, allDeferred };
189
+ }
190
+
191
+ /**
192
+ * Normalises an error thrown inside a deferred Promise into a value that is
193
+ * safe to send through `toCrossJSON` and that preserves the original semantics
194
+ * after `fromCrossJSON` on the client.
195
+ *
196
+ * Symmetric to the rejection handling in `runLoaders` (lines 247-272) but for
197
+ * the *deferred* path, where the rejection is delivered to a client-side
198
+ * `<Await>` instead of becoming a top-level response.
199
+ *
200
+ * - `notFound()` → `Error` carrying `__furinBrand` + `data` so the
201
+ * client-side `isNotFoundError()` (duck-typed)
202
+ * recognises the rejection.
203
+ * - `Response(status, body)` → `Error` carrying `__furinStatus` and the
204
+ * body/statusText as `message`.
205
+ * - `Error` → returned unchanged.
206
+ * - anything else → wrapped in `new Error(String(value))`.
207
+ */
208
+ export async function serializeDeferredRejection(err: unknown): Promise<unknown> {
209
+ if (isNotFoundError(err)) {
210
+ const wrapped = new Error(err.message);
211
+ Object.assign(wrapped, { __furinBrand: "FURIN_NOT_FOUND", data: err.data });
212
+ return wrapped;
213
+ }
214
+ if (err instanceof Response) {
215
+ const body = await readResponseMessage(err);
216
+ const wrapped = new Error(body || err.statusText || "Something went wrong");
217
+ Object.assign(wrapped, { __furinStatus: err.status });
218
+ return wrapped;
219
+ }
220
+ if (err instanceof Error) {
221
+ return err;
222
+ }
223
+ return new Error(String(err));
224
+ }
225
+
226
+ export async function runLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult> {
227
+ try {
228
+ // Inject `log` so loaders can destructure it directly as `({ log })`.
229
+ // useLogger() resolves the correct logger for every rendering context:
230
+ // live request → evlog request-scoped logger, synthetic render → detached
231
+ // createLogger() from runInSyntheticRenderScope, outside any context → no-op.
232
+ const ctxRecord = { ...(ctx as Record<string, unknown>), log: useLogger() };
233
+ const loaderMap = new Map<RuntimeRoute, Promise<Record<string, unknown>>>();
234
+
235
+ // All loaders in the chain start immediately. Each receives a Proxy where
236
+ // parent-data fields are individually-awaitable Promises. The loader opts
237
+ // in to waiting by doing `await user` (or `Promise.all([user, org])`);
238
+ // if it never awaits a parent field it runs in full parallel.
239
+ let accumulatedParentPromise: Promise<Record<string, unknown>> = Promise.resolve({});
240
+
241
+ for (const r of route.routeChain) {
242
+ const parentAccum = accumulatedParentPromise; // capture for closure
243
+
244
+ if (r.loader) {
245
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
246
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
247
+ loaderMap.set(r, loaderPromise);
248
+
249
+ // Accumulate: previous ancestors + this loader's result.
250
+ // A void .catch() suppresses the "unhandled rejection" warning that
251
+ // fires when a sibling or child loader throws — but unlike `.catch(
252
+ // () => ({}))` it does NOT resolve the promise, so child loaders'
253
+ // field-accesses via createLoaderCtx still receive the rejection
254
+ // instead of silently resolving to undefined. The real rejection is
255
+ // re-thrown by the Promise.all below.
256
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
257
+ ...acc,
258
+ ...own,
259
+ }));
260
+ accumulatedParentPromise.catch(() => {
261
+ /* suppress unhandled-rejection warning */
262
+ });
263
+ }
264
+ }
265
+
266
+ // Page loader receives all route-chain fields as individual Promises.
267
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
268
+ const pagePromise: Promise<Record<string, unknown>> = route.page?.loader
269
+ ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {})
270
+ : Promise.resolve({});
271
+
272
+ // Await everything in parallel. `results` is ordered layout1 → … → page;
273
+ // the per-loader split preserves that order so later loaders (page last)
274
+ // overwrite earlier ones on key collision — same semantic as the previous
275
+ // non-deferred `Object.assign({}, ...results)` flat merge.
276
+ const results = await Promise.all([...loaderMap.values(), pagePromise]);
277
+ const headers: Record<string, string> = {};
278
+ Object.assign(headers, ctx.set.headers);
279
+
280
+ // Any loader wrapped with `defer()` (page OR route/layout) contributes its
281
+ // Promise-valued fields to `allDeferred` and its scalars to `allSync`.
282
+ // Non-deferred loaders keep everything in `allSync` — even Promise values,
283
+ // since only an explicit `defer()` opts into streaming.
284
+ const { allSync, allDeferred } = mergeLoaderResults(results);
285
+
286
+ // Route context is always injected into syncData so components receive
287
+ // params, query and path regardless of the serialisation path (SSR, SPA
288
+ // nav, dev cache).
289
+ const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
290
+ return {
291
+ type: "data",
292
+ syncData: { ...allSync, ...routeCtx },
293
+ deferredPromises: Object.keys(allDeferred).length > 0 ? allDeferred : undefined,
294
+ headers,
295
+ };
296
+ } catch (err) {
297
+ const headers: Record<string, string> = {};
298
+ Object.assign(headers, ctx.set.headers);
299
+ if (isNotFoundError(err)) {
300
+ return { type: "not-found", error: err, headers };
301
+ }
302
+ if (err instanceof Response) {
303
+ if (isHttpRedirect(err)) {
304
+ return { type: "redirect", response: err };
305
+ }
306
+ // Non-redirect Response → error. Read the body ONCE here so downstream
307
+ // consumers (digest, logging, error UI) all share the same extracted
308
+ // message without consuming the stream a second time.
309
+ //
310
+ // A *malformed redirect* is a redirect-status code WITHOUT a `Location`
311
+ // header (we only reach here when `isHttpRedirect` was false) — invalid
312
+ // HTTP, coerced to 500. Other 3xx codes (304/305/306) are not redirects
313
+ // at all, so they keep their own status rather than being rewritten.
314
+ const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
315
+ const status = isMalformedRedirect ? 500 : err.status;
316
+ const body = await readResponseMessage(err);
317
+ const message = body || "Something went wrong";
318
+ return { type: "error", error: err, status, message, headers };
319
+ }
320
+ return {
321
+ type: "error",
322
+ error: err,
323
+ status: 500,
324
+ message: "Something went wrong",
325
+ headers,
326
+ };
327
+ }
328
+ }