@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,401 +1,384 @@
1
- import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
- import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
- import { computeErrorDigest } from "../../shared/digest.ts";
5
- import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
6
- import { useLogger } from "../context-logger.ts";
7
- import { resolvePath } from "../render/assemble.ts";
8
- import {
9
- handleISR,
10
- prerenderSSG,
11
- renderSSR,
12
- runLoaders,
13
- serializeDeferredRejection,
14
- } from "../render/index.ts";
15
- import { extractTitle } from "../render/shell.ts";
16
- import { IS_DEV } from "../runtime-env.ts";
17
- import { handleDevRequest } from "./hmr.ts";
18
- import { buildRouteMatcher } from "./patterns.ts";
19
- import {
20
- applySchemaDefaults,
21
- detectQueryDefaultRedirect,
22
- mergeRouteSchemas,
23
- parseDataEndpointPath,
24
- queryDefaultRedirectHook,
25
- } from "./schemas.ts";
26
- import type { ResolvedRoute, RootLayout } from "./types.ts";
27
-
28
- /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
29
- async function handleSSGRequest(
30
- route: ResolvedRoute,
31
- ctx: Context,
32
- root: RootLayout,
33
- buildId: string
34
- ): Promise<unknown> {
35
- const origin = new URL(ctx.request.url).origin;
36
- const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
37
-
38
- // Loader issued a redirect — forward it directly to the client.
39
- if (entry instanceof Response) {
40
- return entry;
41
- }
42
-
43
- const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
44
-
45
- // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
46
- const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
47
- if (etag && ctx.request.headers.get("if-none-match") === etag) {
48
- ctx.set.status = 304;
49
- return;
50
- }
51
-
52
- ctx.set.headers["content-type"] = "text/html; charset=utf-8";
53
- // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
54
- // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
55
- ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
56
- if (etag) {
57
- ctx.set.headers.etag = etag;
58
- }
59
- ctx.set.headers["cache-tag"] = resolvedPath;
60
- return entry.html;
61
- }
62
-
63
- export function createRoutePlugin(
64
- route: ResolvedRoute,
65
- root: RootLayout,
66
- buildId?: string
67
- ): AnyElysia {
68
- const resolvedBuildId = buildId ?? "";
69
- const { pattern, routeChain } = route;
70
-
71
- const allParams = mergeRouteSchemas(routeChain, "params");
72
- const allQuery = mergeRouteSchemas(routeChain, "query");
73
- const hasQuerySchema = !!allQuery;
74
-
75
- // Guard and handler MUST live in the same Elysia scope so that validation
76
- // (including default-filling) applies to the route handler's ctx.query.
77
- const plugin = new Elysia();
78
-
79
- if (allParams || allQuery) {
80
- plugin.guard({
81
- params: allParams as AnySchema,
82
- query: allQuery as AnySchema,
83
- });
84
- }
85
-
86
- plugin.get(pattern, (ctx) => {
87
- // Redirect when Elysia applied query defaults (validator-agnostic)
88
- if (hasQuerySchema) {
89
- const redirect = queryDefaultRedirectHook(ctx);
90
- if (redirect) {
91
- return redirect;
92
- }
93
- }
94
-
95
- // Dev mode: re-imports page + layouts on every request via the
96
- // ?furin-server cache-buster, then dispatches into one of:
97
- // - renderDevISRWithLoaderCache (mode === "isr")
98
- // - renderDevSSGWithLoaderCache (mode === "ssg")
99
- // - renderSSR (otherwise)
100
- //
101
- // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
102
- // fresh so the response always embeds the latest Bun client chunk URL.
103
- // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
104
- // HTML response held an OLD chunk URL after Bun rebundled. The dev
105
- // cache is invalidated source-aware via `isDevLoaderCacheValid`
106
- // (mtime-checked dependency walk on every read).
107
- if (IS_DEV) {
108
- return handleDevRequest(route, ctx, root);
109
- }
110
-
111
- if (route.mode === "ssg") {
112
- return handleSSGRequest(route, ctx, root, resolvedBuildId);
113
- }
114
-
115
- if (route.mode === "isr") {
116
- ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
117
- return handleISR(route, ctx, root, resolvedBuildId);
118
- }
119
-
120
- return renderSSR(route, ctx, root, undefined);
121
- });
122
-
123
- return plugin;
124
- }
125
-
126
- /**
127
- * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
128
- *
129
- * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
130
- * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
131
- *
132
- * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
133
- * serialising, so the client receives all data resolved in one round-trip.
134
- * SPA navigation calls this endpoint via `parseDeferredNdjson` in
135
- * `router-provider.tsx`.
136
- *
137
- * Special fields emitted alongside data:
138
- * - `__furinStatus: 404` — when the loader called `notFound()`
139
- * - `__furinNotFound` — not-found payload
140
- * - `__furinRedirect` — logical path after a server-side redirect
141
- */
142
- export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
143
- const plugin = new Elysia();
144
- const matchRoute = buildRouteMatcher(routes);
145
-
146
- plugin.get(
147
- "/_furin/data",
148
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: data endpoint handler validates path, resolves loaders, handles deferred/SPA/ISR modes — each branch is a distinct protocol case; splitting would spread context across many functions
149
- async (ctx) => {
150
- const rawPath = ctx.query.path;
151
- if (!rawPath || typeof rawPath !== "string") {
152
- return new Response("Missing required query param: path", { status: 400 });
153
- }
154
-
155
- const parsed = parseDataEndpointPath(rawPath);
156
- if (!parsed) {
157
- return new Response("Invalid path", { status: 400 });
158
- }
159
- const { url, pathname } = parsed;
160
-
161
- // Rewrite the request-scoped wide event so logs / drains report the
162
- // *logical* path the user navigated to (e.g. "/board/123/card/456")
163
- // instead of the technical "/_furin/data" transport URL. We set this
164
- // before the route-match check so 404s also surface the attempted path
165
- // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
166
- const wideEventLog = useLogger();
167
- wideEventLog.set({ path: rawPath });
168
-
169
- // Precompiled at plugin creation: route regexes are built once, sorted
170
- // most-specific first, then the hot path only executes regex matches.
171
- const matched = matchRoute(pathname);
172
-
173
- if (!matched) {
174
- return new Response("Route not found", { status: 404 });
175
- }
176
-
177
- // Now that we know the matched pattern, add it as a stable aggregation
178
- // key for drains (e.g. "p99 latency by route").
179
- wideEventLog.set({ routePattern: matched.route.pattern });
180
-
181
- // Build a synthetic Elysia-compatible context for the matched route.
182
- // Loaders receive request, params, query, set, headers, and cookie.
183
- // Build the synthetic URL from the parsed `pathname + search` only —
184
- // never from `rawPath` directly — so an attacker cannot smuggle a
185
- // foreign origin into `syntheticRequest.url`.
186
- const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
187
- const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
188
- const syntheticCtx = {
189
- request: syntheticRequest,
190
- params: matched.params,
191
- query: Object.fromEntries(url.searchParams),
192
- set: syntheticSet,
193
- headers: ctx.headers,
194
- cookie: ctx.cookie,
195
- path: pathname,
196
- // Loader-emitted redirects flow through `runLoaders` → `result.type
197
- // === "redirect"` and are converted to NDJSON below. The Response we
198
- // return here only has to be detectable by that pipeline.
199
- redirect: (location: string, status?: number) =>
200
- new Response(null, { status: status ?? 302, headers: { location } }),
201
- // Synthetic `status` helper: numeric codes only. Callers that reach
202
- // this endpoint never dispatch a string-keyed status; rejecting them
203
- // is safer than coercing via `Number(code)` and silently producing
204
- // `NaN`. Query-default redirects no longer flow through this helper —
205
- // they are detected via `detectQueryDefaultRedirect` below.
206
- status: (code: number) => new Response(null, { status: code }),
207
- } as unknown as Context;
208
-
209
- // Normalize params and query through the same merged schemas used by
210
- // createRoutePlugin so loaders see identical typed/defaulted inputs.
211
- const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
212
- const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
213
- syntheticCtx.params = applySchemaDefaults(
214
- mergedParams as Record<string, unknown> | undefined,
215
- syntheticCtx.params as Record<string, unknown>
216
- ) as Record<string, string>;
217
- syntheticCtx.query = applySchemaDefaults(
218
- mergedQuery as Record<string, unknown> | undefined,
219
- syntheticCtx.query as Record<string, unknown>
220
- ) as Record<string, string>;
221
-
222
- // Query-default redirect: detect via the pure helper so we can emit the
223
- // NDJSON `__furinRedirect` sentinel (the SPA client cannot parse a real
224
- // HTTP 302 — it never sees one because `parseDeferredNdjson` reads the
225
- // body, not the redirect chain).
226
- if (mergedQuery) {
227
- const redirectLocation = detectQueryDefaultRedirect(
228
- syntheticRequest,
229
- syntheticCtx.query as Record<string, unknown>
230
- );
231
- if (redirectLocation) {
232
- const serialized = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
233
- return new Response(`${JSON.stringify(serialized)}\n`, {
234
- headers: { "content-type": "application/x-ndjson" },
235
- });
236
- }
237
- }
238
-
239
- const result = await runLoaders(matched.route, syntheticCtx);
240
-
241
- // Keep the auto-invalidate registry in sync with whatever path was just
242
- // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
243
- // afterHandle) can still find this URL by tag. Without this, a SPA-only
244
- // navigation path (which never goes through the full-HTML render that
245
- // also registers tags) would silently fall off the registry — the first
246
- // mutation invalidates and unregisters via the cache `onDelete` hook,
247
- // the next SPA fetch re-loads but does not re-register, and from then
248
- // on `revalidateTag` finds no path to invalidate.
249
- if (result.type === "data") {
250
- autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
251
- }
252
-
253
- if (result.type === "redirect") {
254
- // Encode the redirect target as a special field for the client to follow
255
- const redirectUrl = new URL(
256
- result.response.headers.get("location") ?? "/",
257
- ctx.request.url
258
- );
259
- const serialized = await toCrossJSONAsync({
260
- __furinRedirect: redirectUrl.pathname + redirectUrl.search,
261
- });
262
- return new Response(`${JSON.stringify(serialized)}\n`, {
263
- headers: { "content-type": "application/x-ndjson" },
264
- });
265
- }
266
-
267
- if (result.type === "not-found") {
268
- const serialized = await toCrossJSONAsync({
269
- __furinStatus: 404,
270
- __furinNotFound: { message: result.error.message, data: result.error.data },
271
- });
272
- return new Response(`${JSON.stringify(serialized)}\n`, {
273
- status: 200,
274
- headers: { "content-type": "application/x-ndjson" },
275
- });
276
- }
277
-
278
- if (result.type === "error") {
279
- // Compute the digest server-side ONCE so:
280
- // 1. The HTTP response body carries it (client error UI displays the
281
- // same id the server logs).
282
- // 2. The server-log line below uses the SAME digest a user would see
283
- // on screen, enabling support correlation.
284
- // Recomputing client-side from a synthetic message + stack would yield
285
- // a different hash — see boundaries.tsx for the digest precedence.
286
- const digest = computeErrorDigest(result.error);
287
- const serialized = await toCrossJSONAsync({
288
- __furinError: {
289
- digest,
290
- message: result.message,
291
- status: result.status,
292
- },
293
- });
294
- return new Response(`${JSON.stringify(serialized)}\n`, {
295
- status: result.status,
296
- headers: { "content-type": "application/x-ndjson" },
297
- });
298
- }
299
-
300
- // Resolve the page title server-side: head() never runs in the browser,
301
- // so SPA navigation depends on the endpoint shipping it as __furinTitle.
302
- const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
303
-
304
- if (result.deferredPromises) {
305
- return new Response(
306
- createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
307
- {
308
- // Loader headers first so custom headers survive; the NDJSON
309
- // content-type is framework-owned and must win — a loader cannot be
310
- // allowed to mislabel the data-endpoint payload.
311
- headers: {
312
- ...result.headers,
313
- "content-type": "application/x-ndjson",
314
- },
315
- }
316
- );
317
- }
318
-
319
- // No deferred fields: emit the single-line payload used by the legacy path.
320
- const serialized = await toCrossJSONAsync(syncDataWithTitle);
321
- return new Response(`${JSON.stringify(serialized)}\n`, {
322
- headers: {
323
- ...result.headers,
324
- "content-type": "application/x-ndjson",
325
- },
326
- });
327
- },
328
- {
329
- query: t.Object({ path: t.Optional(t.String()) }),
330
- }
331
- );
332
-
333
- return plugin;
334
- }
335
-
336
- /**
337
- * Runs the matched page's `head()` against the resolved sync data and, when it
338
- * yields a title, returns a copy of `syncData` carrying the reserved
339
- * `__furinTitle` field. `head()` never executes in the browser, so this is the
340
- * only channel through which SPA navigation can learn the new document title.
341
- *
342
- * Deferred fields are absent from `syncData` (they are still Promises), so a
343
- * `head()` that reads one sees `undefined` — titles should be derived from
344
- * synchronous loader data. A throwing `head()` is swallowed: a missing title
345
- * must never break the data response.
346
- */
347
- function withResolvedTitle(
348
- route: ResolvedRoute,
349
- syncData: Record<string, unknown>
350
- ): Record<string, unknown> {
351
- const head = route.page.head;
352
- if (!head) {
353
- return syncData;
354
- }
355
- let title: string | undefined;
356
- try {
357
- title = extractTitle(head(syncData).meta);
358
- } catch {
359
- return syncData;
360
- }
361
- if (title === undefined) {
362
- return syncData;
363
- }
364
- return { ...syncData, __furinTitle: title };
365
- }
366
-
367
- function createDeferredNdjsonStream(
368
- syncData: Record<string, unknown>,
369
- deferredPromises: Record<string, Promise<unknown>>
370
- ): ReadableStream<Uint8Array> {
371
- const enc = new TextEncoder();
372
- const entries = Object.entries(deferredPromises);
373
-
374
- return new ReadableStream<Uint8Array>({
375
- async start(controller) {
376
- const initial = toCrossJSON({
377
- ...syncData,
378
- __furinDeferredKeys: entries.map(([key]) => key),
379
- });
380
- controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
381
-
382
- await Promise.all(
383
- entries.map(async ([key, promise]) => {
384
- try {
385
- const value = await promise;
386
- controller.enqueue(
387
- enc.encode(
388
- `${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
389
- )
390
- );
391
- } catch (err) {
392
- const normalized = await serializeDeferredRejection(err);
393
- const value = toCrossJSON(normalized);
394
- controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
395
- }
396
- })
397
- );
398
- controller.close();
399
- },
400
- });
401
- }
1
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
+ import type { AnySchema } from "elysia/types";
3
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
+ import { computeErrorDigest } from "../../shared/digest.ts";
5
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
7
+ import { useLogger } from "../context-logger.ts";
8
+ import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
9
+ import {
10
+ handleISR,
11
+ prerenderSSG,
12
+ renderSSR,
13
+ runLoaders,
14
+ serializeDeferredRejection,
15
+ } from "../render/index.ts";
16
+ import { extractTitle } from "../render/shell.ts";
17
+ import { IS_DEV } from "../runtime-env.ts";
18
+ import { handleDevRequest } from "./hmr.ts";
19
+ import { buildRouteMatcher } from "./patterns.ts";
20
+ import {
21
+ applySchemaDefaults,
22
+ mergeRouteSchemas,
23
+ parseDataEndpointPath,
24
+ parseRouteQuery,
25
+ } from "./schemas.ts";
26
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
27
+
28
+ type SyntheticDataContext = Omit<Context, "params" | "query"> & {
29
+ params: Record<string, string>;
30
+ query: SearchParamsInput;
31
+ };
32
+
33
+ /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
34
+ async function handleSSGRequest(
35
+ route: ResolvedRoute,
36
+ ctx: Context,
37
+ root: RootLayout,
38
+ buildId: string,
39
+ searchRoutes: SearchRouteMetadata[] | undefined
40
+ ): Promise<unknown> {
41
+ const origin = new URL(ctx.request.url).origin;
42
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined, searchRoutes);
43
+
44
+ // Loader issued a redirect — forward it directly to the client.
45
+ if (entry instanceof Response) {
46
+ return entry;
47
+ }
48
+
49
+ const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
50
+
51
+ // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
52
+ const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
53
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
54
+ ctx.set.status = 304;
55
+ return;
56
+ }
57
+
58
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
59
+ // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
60
+ // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
61
+ ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
62
+ if (etag) {
63
+ ctx.set.headers.etag = etag;
64
+ }
65
+ ctx.set.headers["cache-tag"] = resolvedPath;
66
+ return injectSyncRuntimeScript(entry.html);
67
+ }
68
+
69
+ export function createRoutePlugin(
70
+ route: ResolvedRoute,
71
+ root: RootLayout,
72
+ buildId?: string,
73
+ searchRoutes?: SearchRouteMetadata[]
74
+ ): AnyElysia {
75
+ const resolvedBuildId = buildId ?? "";
76
+ const { pattern, routeChain } = route;
77
+
78
+ const allParams = mergeRouteSchemas(routeChain, "params");
79
+ const allQuery = mergeRouteSchemas(routeChain, "query");
80
+
81
+ // Guard and handler MUST live in the same Elysia scope so that validation
82
+ // (including default-filling) applies to the route handler's ctx.query.
83
+ const plugin = new Elysia();
84
+
85
+ if (allParams || allQuery) {
86
+ plugin.guard({
87
+ params: allParams as AnySchema,
88
+ query: allQuery as AnySchema,
89
+ });
90
+ }
91
+
92
+ plugin.get(pattern, (ctx) => {
93
+ // Dev mode: re-imports page + layouts on every request via the
94
+ // ?furin-server cache-buster, then dispatches into one of:
95
+ // - renderDevISRWithLoaderCache (mode === "isr")
96
+ // - renderDevSSGWithLoaderCache (mode === "ssg")
97
+ // - renderSSR (otherwise)
98
+ //
99
+ // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
100
+ // fresh so the response always embeds the latest Bun client chunk URL.
101
+ // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
102
+ // HTML response held an OLD chunk URL after Bun rebundled. The dev
103
+ // cache is invalidated source-aware via `isDevLoaderCacheValid`
104
+ // (mtime-checked dependency walk on every read).
105
+ if (IS_DEV) {
106
+ return handleDevRequest(route, ctx, root, searchRoutes);
107
+ }
108
+
109
+ if (route.mode === "ssg") {
110
+ return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
111
+ }
112
+
113
+ if (route.mode === "isr") {
114
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
115
+ return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
116
+ }
117
+
118
+ return renderSSR(route, ctx, root, undefined, searchRoutes);
119
+ });
120
+
121
+ return plugin;
122
+ }
123
+
124
+ /**
125
+ * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
126
+ *
127
+ * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
128
+ * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
129
+ *
130
+ * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
131
+ * serialising, so the client receives all data resolved in one round-trip.
132
+ * SPA navigation calls this endpoint via `parseDeferredNdjson` in
133
+ * `router-provider.tsx`.
134
+ *
135
+ * Special fields emitted alongside data:
136
+ * - `__furinStatus: 404` — when the loader called `notFound()`
137
+ * - `__furinNotFound` — not-found payload
138
+ * - `__furinRedirect` — logical path after a server-side redirect
139
+ */
140
+ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
141
+ const plugin = new Elysia();
142
+ const matchRoute = buildRouteMatcher(routes);
143
+
144
+ plugin.get(
145
+ "/_furin/data",
146
+ async (ctx) => {
147
+ const rawPath = ctx.query.path;
148
+ if (!rawPath || typeof rawPath !== "string") {
149
+ return new Response("Missing required query param: path", { status: 400 });
150
+ }
151
+
152
+ const parsed = parseDataEndpointPath(rawPath);
153
+ if (!parsed) {
154
+ return new Response("Invalid path", { status: 400 });
155
+ }
156
+ const { url, pathname } = parsed;
157
+
158
+ // Rewrite the request-scoped wide event so logs / drains report the
159
+ // *logical* path the user navigated to (e.g. "/board/123/card/456")
160
+ // instead of the technical "/_furin/data" transport URL. We set this
161
+ // before the route-match check so 404s also surface the attempted path
162
+ // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
163
+ const wideEventLog = useLogger();
164
+ wideEventLog.set({ path: rawPath });
165
+
166
+ // Precompiled at plugin creation: route regexes are built once, sorted
167
+ // most-specific first, then the hot path only executes regex matches.
168
+ const matched = matchRoute(pathname);
169
+
170
+ if (!matched) {
171
+ return new Response("Route not found", { status: 404 });
172
+ }
173
+
174
+ // Now that we know the matched pattern, add it as a stable aggregation
175
+ // key for drains (e.g. "p99 latency by route").
176
+ wideEventLog.set({ routePattern: matched.route.pattern });
177
+
178
+ // Build a synthetic Elysia-compatible context for the matched route.
179
+ // Loaders receive request, params, query, set, headers, and cookie.
180
+ // Build the synthetic URL from the parsed `pathname + search` only —
181
+ // never from `rawPath` directly — so an attacker cannot smuggle a
182
+ // foreign origin into `syntheticRequest.url`.
183
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
184
+ const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
185
+ const syntheticCtx: SyntheticDataContext = {
186
+ request: syntheticRequest,
187
+ params: matched.params,
188
+ query: Object.fromEntries(url.searchParams),
189
+ set: syntheticSet,
190
+ headers: ctx.headers,
191
+ cookie: ctx.cookie,
192
+ path: pathname,
193
+ // Loader-emitted redirects flow through `runLoaders` → `result.type
194
+ // === "redirect"` and are converted to NDJSON below. The Response we
195
+ // return here only has to be detectable by that pipeline.
196
+ redirect: (location: string, status?: number) =>
197
+ new Response(null, { status: status ?? 302, headers: { location } }),
198
+ // Synthetic `status` helper: numeric codes only. Callers that reach
199
+ // this endpoint never dispatch a string-keyed status; rejecting them
200
+ // is safer than coercing via `Number(code)` and silently producing
201
+ // `NaN`.
202
+ status: (code: number) => new Response(null, { status: code }),
203
+ } as unknown as SyntheticDataContext;
204
+
205
+ // Normalize params and query through the same merged schemas used by
206
+ // createRoutePlugin so loaders see identical typed/defaulted inputs.
207
+ const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
208
+ const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
209
+ const parsedQuery = await parseRouteQuery(url, mergedQuery);
210
+ if (!parsedQuery.ok) {
211
+ return Response.json(
212
+ { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
213
+ { status: 422 }
214
+ );
215
+ }
216
+ syntheticCtx.params = applySchemaDefaults(
217
+ mergedParams as Record<string, unknown> | undefined,
218
+ syntheticCtx.params as Record<string, unknown>
219
+ ) as Record<string, string>;
220
+ syntheticCtx.query = parsedQuery.query as SearchParamsInput;
221
+
222
+ const result = await runLoaders(matched.route, syntheticCtx as unknown as Context);
223
+
224
+ // Keep the auto-invalidate registry in sync with whatever path was just
225
+ // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
226
+ // afterHandle) can still find this URL by tag. Without this, a SPA-only
227
+ // navigation path (which never goes through the full-HTML render that
228
+ // also registers tags) would silently fall off the registry — the first
229
+ // mutation invalidates and unregisters via the cache `onDelete` hook,
230
+ // the next SPA fetch re-loads but does not re-register, and from then
231
+ // on `revalidateTag` finds no path to invalidate.
232
+ if (result.type === "data") {
233
+ autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
234
+ }
235
+
236
+ if (result.type === "redirect") {
237
+ // Encode the redirect target as a special field for the client to follow
238
+ const redirectUrl = new URL(
239
+ result.response.headers.get("location") ?? "/",
240
+ ctx.request.url
241
+ );
242
+ const serialized = await toCrossJSONAsync({
243
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search,
244
+ });
245
+ return new Response(`${JSON.stringify(serialized)}\n`, {
246
+ headers: { "content-type": "application/x-ndjson" },
247
+ });
248
+ }
249
+
250
+ if (result.type === "not-found") {
251
+ const serialized = await toCrossJSONAsync({
252
+ __furinStatus: 404,
253
+ __furinNotFound: { message: result.error.message, data: result.error.data },
254
+ });
255
+ return new Response(`${JSON.stringify(serialized)}\n`, {
256
+ status: 200,
257
+ headers: { "content-type": "application/x-ndjson" },
258
+ });
259
+ }
260
+
261
+ if (result.type === "error") {
262
+ // Compute the digest server-side ONCE so:
263
+ // 1. The HTTP response body carries it (client error UI displays the
264
+ // same id the server logs).
265
+ // 2. The server-log line below uses the SAME digest a user would see
266
+ // on screen, enabling support correlation.
267
+ // Recomputing client-side from a synthetic message + stack would yield
268
+ // a different hash — see boundaries.tsx for the digest precedence.
269
+ const digest = computeErrorDigest(result.error);
270
+ const serialized = await toCrossJSONAsync({
271
+ __furinError: {
272
+ digest,
273
+ message: result.message,
274
+ status: result.status,
275
+ },
276
+ });
277
+ return new Response(`${JSON.stringify(serialized)}\n`, {
278
+ status: result.status,
279
+ headers: { "content-type": "application/x-ndjson" },
280
+ });
281
+ }
282
+
283
+ // Resolve the page title server-side: head() never runs in the browser,
284
+ // so SPA navigation depends on the endpoint shipping it as __furinTitle.
285
+ const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
286
+
287
+ if (result.deferredPromises) {
288
+ return new Response(
289
+ createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
290
+ {
291
+ // Loader headers first so custom headers survive; the NDJSON
292
+ // content-type is framework-owned and must win — a loader cannot be
293
+ // allowed to mislabel the data-endpoint payload.
294
+ headers: {
295
+ ...result.headers,
296
+ "content-type": "application/x-ndjson",
297
+ },
298
+ }
299
+ );
300
+ }
301
+
302
+ // No deferred fields: emit the single-line payload used by the legacy path.
303
+ const serialized = await toCrossJSONAsync(syncDataWithTitle);
304
+ return new Response(`${JSON.stringify(serialized)}\n`, {
305
+ headers: {
306
+ ...result.headers,
307
+ "content-type": "application/x-ndjson",
308
+ },
309
+ });
310
+ },
311
+ {
312
+ query: t.Object({ path: t.Optional(t.String()) }),
313
+ }
314
+ );
315
+
316
+ return plugin;
317
+ }
318
+
319
+ /**
320
+ * Runs the matched page's `head()` against the resolved sync data and, when it
321
+ * yields a title, returns a copy of `syncData` carrying the reserved
322
+ * `__furinTitle` field. `head()` never executes in the browser, so this is the
323
+ * only channel through which SPA navigation can learn the new document title.
324
+ *
325
+ * Deferred fields are absent from `syncData` (they are still Promises), so a
326
+ * `head()` that reads one sees `undefined` — titles should be derived from
327
+ * synchronous loader data. A throwing `head()` is swallowed: a missing title
328
+ * must never break the data response.
329
+ */
330
+ function withResolvedTitle(
331
+ route: ResolvedRoute,
332
+ syncData: Record<string, unknown>
333
+ ): Record<string, unknown> {
334
+ const head = route.page.head;
335
+ if (!head) {
336
+ return syncData;
337
+ }
338
+ let title: string | undefined;
339
+ try {
340
+ title = extractTitle(head(syncData).meta);
341
+ } catch {
342
+ return syncData;
343
+ }
344
+ if (title === undefined) {
345
+ return syncData;
346
+ }
347
+ return { ...syncData, __furinTitle: title };
348
+ }
349
+
350
+ function createDeferredNdjsonStream(
351
+ syncData: Record<string, unknown>,
352
+ deferredPromises: Record<string, Promise<unknown>>
353
+ ): ReadableStream<Uint8Array> {
354
+ const enc = new TextEncoder();
355
+ const entries = Object.entries(deferredPromises);
356
+
357
+ return new ReadableStream<Uint8Array>({
358
+ async start(controller) {
359
+ const initial = toCrossJSON({
360
+ ...syncData,
361
+ __furinDeferredKeys: entries.map(([key]) => key),
362
+ });
363
+ controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
364
+
365
+ await Promise.all(
366
+ entries.map(async ([key, promise]) => {
367
+ try {
368
+ const value = await promise;
369
+ controller.enqueue(
370
+ enc.encode(
371
+ `${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
372
+ )
373
+ );
374
+ } catch (err) {
375
+ const normalized = await serializeDeferredRejection(err);
376
+ const value = toCrossJSON(normalized);
377
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
378
+ }
379
+ })
380
+ );
381
+ controller.close();
382
+ },
383
+ });
384
+ }