@teyik0/furin 0.1.0-alpha.10

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 (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
package/src/router.ts ADDED
@@ -0,0 +1,779 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { join, parse } from "node:path";
4
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
5
+ import type { AnySchema } from "elysia/types";
6
+ import type { RuntimePage, RuntimeRoute } from "./client.ts";
7
+ import type { ErrorComponent } from "./error.ts";
8
+ import { type CompileContext, getCompileContext } from "./internal.ts";
9
+ import type { NotFoundComponent } from "./not-found.ts";
10
+ import { resolvePath } from "./render/assemble.ts";
11
+ import { handleISR, prerenderSSG, renderSSR } from "./render/index.ts";
12
+ import { IS_DEV } from "./runtime-env.ts";
13
+ import {
14
+ collectRouteChainFromRoute,
15
+ isFurinPage,
16
+ isFurinRoute,
17
+ validateRouteChain,
18
+ } from "./utils.ts";
19
+
20
+ function isModuleNotFoundError(err: unknown): boolean {
21
+ if (!(err instanceof Error)) {
22
+ return false;
23
+ }
24
+ const msg = err.message.toLowerCase();
25
+ const code = (err as { code?: string }).code;
26
+ return (
27
+ code === "ENOENT" ||
28
+ code === "ERR_MODULE_NOT_FOUND" ||
29
+ code === "MODULE_NOT_FOUND" ||
30
+ msg.includes("cannot find module") ||
31
+ msg.includes("module not found") ||
32
+ msg.includes("no such file or directory")
33
+ );
34
+ }
35
+
36
+ /**
37
+ * A single directory-scoped boundary declaration.
38
+ *
39
+ * Each entry represents ONE directory on the path from `pagesDir` to the page
40
+ * file. `error` / `notFound` hold the components defined IN THAT DIRECTORY
41
+ * only — never inherited from a parent. This 1:1 tie between directory and
42
+ * entry is what lets the render layer insert React error boundaries at the
43
+ * exact nesting level where the user authored them (Next.js app-router model).
44
+ */
45
+ export interface SegmentBoundary {
46
+ /** 0 = `pagesDir`; increments with each nested subdirectory. */
47
+ depth: number;
48
+ error?: ErrorComponent;
49
+ /**
50
+ * Absolute path to the `error.tsx` module, when present. Carried alongside
51
+ * the component so the client hydrate entry can emit a static `import`
52
+ * statement for each unique convention file — a component reference alone
53
+ * can't survive the server→client boundary.
54
+ */
55
+ errorPath?: string;
56
+ notFound?: NotFoundComponent;
57
+ /** Absolute path to the `not-found.tsx` module, when present. */
58
+ notFoundPath?: string;
59
+ /** Absolute directory path. */
60
+ path: string;
61
+ }
62
+
63
+ export interface ResolvedRoute {
64
+ error?: ErrorComponent;
65
+ isrCache?: { html: string; generatedAt: number; revalidate: number };
66
+ mode: "ssr" | "ssg" | "isr";
67
+ notFound?: NotFoundComponent;
68
+ page: RuntimePage;
69
+ path: string;
70
+ pattern: string;
71
+ routeChain: RuntimeRoute[];
72
+ /**
73
+ * Per-directory boundary chain, ordered shallow → deep. Only directories
74
+ * that DECLARE at least one of `error.tsx` / `not-found.tsx` are included;
75
+ * directories without conventions are skipped. Empty when no conventions
76
+ * exist anywhere in the path.
77
+ */
78
+ segmentBoundaries: SegmentBoundary[];
79
+ ssgHtml?: string;
80
+ }
81
+
82
+ export interface RootLayout {
83
+ error?: ErrorComponent;
84
+ errorPath?: string;
85
+ notFound?: NotFoundComponent;
86
+ notFoundPath?: string;
87
+ path: string;
88
+ route: RuntimeRoute;
89
+ }
90
+
91
+ export function loadProdRoutes(ctx: CompileContext): {
92
+ root: RootLayout;
93
+ routes: ResolvedRoute[];
94
+ } {
95
+ const rootMod = ctx.modules[ctx.rootPath] as Record<string, unknown>;
96
+ const rootExport = rootMod.route ?? rootMod.default;
97
+ if (!(rootExport && isFurinRoute(rootExport) && rootExport.layout)) {
98
+ throw new Error("[furin] root.tsx: createRoute() with layout not found in CompileContext.");
99
+ }
100
+
101
+ function resolveModuleComponent<T>(modPath: string | undefined): T | undefined {
102
+ if (!modPath) {
103
+ return;
104
+ }
105
+ const mod = ctx.modules[modPath] as { default?: T } | undefined;
106
+ return mod?.default;
107
+ }
108
+
109
+ const root: RootLayout = {
110
+ path: ctx.rootPath,
111
+ route: rootExport,
112
+ error: resolveModuleComponent(ctx.rootConventions?.errorPath),
113
+ notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
114
+ };
115
+
116
+ const routes: ResolvedRoute[] = [];
117
+ for (const { pattern, path, mode } of ctx.routes) {
118
+ const pageMod = ctx.modules[path] as { default: RuntimePage };
119
+ const page: RuntimePage = pageMod.default;
120
+ if (!isFurinPage(page)) {
121
+ throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
122
+ }
123
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
124
+ validateRouteChain(routeChain, root.route, path);
125
+ const meta = ctx.routeMetadata?.[path];
126
+ const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
127
+ ...b,
128
+ error: resolveModuleComponent(b.errorPath),
129
+ notFound: resolveModuleComponent(b.notFoundPath),
130
+ })) as SegmentBoundary[];
131
+
132
+ const error = boundaries.findLast((b) => b.error)?.error;
133
+ const notFound = boundaries.findLast((b) => b.notFound)?.notFound;
134
+
135
+ // Note: In production we store only the nearest segment-level convention
136
+ // (error / notFound) and do NOT fall back to root.error / root.notFound here.
137
+ // The dev-mode resolveNearestConvention() does include the root fallback,
138
+ // and the render layer applies the runtime fallback (route.error ?? root.error)
139
+ // when building the React element tree. This asymmetry is intentional:
140
+ // loadProdRoutes records the static wiring so buildElement can place React
141
+ // boundaries at the correct nesting depth, while the runtime fallback ensures
142
+ // every route always has a safety-net component even if no boundary was
143
+ // declared at any segment level.
144
+
145
+ routes.push({
146
+ pattern,
147
+ page,
148
+ path,
149
+ routeChain,
150
+ mode,
151
+ segmentBoundaries: boundaries,
152
+ error,
153
+ notFound,
154
+ });
155
+ }
156
+
157
+ return { root, routes };
158
+ }
159
+
160
+ export async function scanPages(pagesDir: string): Promise<{
161
+ root: RootLayout;
162
+ routes: ResolvedRoute[];
163
+ }> {
164
+ const root = await scanRootLayout(pagesDir);
165
+ const routes = await scanPageFiles(pagesDir, root);
166
+ return { root, routes };
167
+ }
168
+
169
+ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
170
+ const rootPath = `${pagesDir}/root.tsx`;
171
+ const ctx = getCompileContext();
172
+ if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
173
+ throw new Error("[furin] root.tsx: not found.");
174
+ }
175
+
176
+ const mod = (ctx?.modules[rootPath] ?? (await import(rootPath))) as Record<string, unknown>;
177
+ const rootExport = mod.route ?? mod.default;
178
+ if (!(rootExport && isFurinRoute(rootExport))) {
179
+ throw new Error("[furin] root.tsx: createRoute() export not found.");
180
+ }
181
+
182
+ if (!rootExport.layout) {
183
+ throw new Error("[furin] root.tsx: createRoute() has no layout.");
184
+ }
185
+
186
+ const notFoundEntry = await loadConventionComponent<NotFoundComponent>(pagesDir, "not-found");
187
+ const errorEntry = await loadConventionComponent<ErrorComponent>(pagesDir, "error");
188
+ return {
189
+ path: rootPath,
190
+ route: rootExport,
191
+ notFound: notFoundEntry?.component,
192
+ notFoundPath: notFoundEntry?.path,
193
+ error: errorEntry?.component,
194
+ errorPath: errorEntry?.path,
195
+ };
196
+ }
197
+
198
+ const CONVENTION_FILE_NAMES = ["not-found", "error"] as const;
199
+
200
+ function isConventionFileName(name: string): boolean {
201
+ return (CONVENTION_FILE_NAMES as readonly string[]).includes(name);
202
+ }
203
+
204
+ /**
205
+ * Result of a convention-file lookup. The `path` is the absolute module path
206
+ * — callers that only care about the component discard it, but the hydrate
207
+ * emission pipeline needs it to generate static `import` statements.
208
+ */
209
+ interface ConventionLookup<T> {
210
+ component: T;
211
+ path: string;
212
+ }
213
+
214
+ async function loadConventionComponent<T>(
215
+ dir: string,
216
+ name: string
217
+ ): Promise<ConventionLookup<T> | undefined> {
218
+ const ctx = getCompileContext();
219
+ for (const ext of [".tsx", ".ts", ".jsx", ".js"]) {
220
+ const filePath = `${dir}/${name}${ext}`;
221
+ if (existsSync(filePath) || ctx?.modules[filePath]) {
222
+ const mod = (ctx?.modules[filePath] ?? (await import(filePath))) as {
223
+ default?: T;
224
+ };
225
+ if (mod.default) {
226
+ return { component: mod.default, path: filePath };
227
+ }
228
+ }
229
+ }
230
+ return;
231
+ }
232
+
233
+ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<ResolvedRoute[]> {
234
+ const routes: ResolvedRoute[] = [];
235
+ const notFoundCache = new Map<string, ConventionLookup<NotFoundComponent> | undefined>();
236
+ const errorCache = new Map<string, ConventionLookup<ErrorComponent> | undefined>();
237
+
238
+ for (const absolutePath of await collectPageFilePaths(pagesDir)) {
239
+ if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
240
+ continue;
241
+ }
242
+
243
+ const relativePath = absolutePath.replace(`${pagesDir}/`, "");
244
+ const fileName = parse(relativePath).name;
245
+
246
+ // Skip root.tsx, convention files (not-found, error), and files starting with _
247
+ if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
248
+ continue;
249
+ }
250
+
251
+ const notFound = await resolveNearestConvention<NotFoundComponent>(
252
+ absolutePath,
253
+ pagesDir,
254
+ "not-found",
255
+ notFoundCache,
256
+ root.notFound
257
+ );
258
+
259
+ const errorComponent = await resolveNearestConvention<ErrorComponent>(
260
+ absolutePath,
261
+ pagesDir,
262
+ "error",
263
+ errorCache,
264
+ root.error
265
+ );
266
+
267
+ const segmentBoundaries = await collectSegmentBoundaries(
268
+ absolutePath,
269
+ pagesDir,
270
+ notFoundCache,
271
+ errorCache
272
+ );
273
+
274
+ if (IS_DEV) {
275
+ const devRoute = await buildDevRoute(absolutePath, relativePath, root);
276
+ devRoute.notFound = notFound;
277
+ devRoute.error = errorComponent;
278
+ devRoute.segmentBoundaries = segmentBoundaries;
279
+ routes.push(devRoute);
280
+ continue;
281
+ }
282
+
283
+ const ctx = getCompileContext();
284
+ const pageMod = (ctx?.modules[absolutePath] ?? (await import(absolutePath))) as {
285
+ default: RuntimePage;
286
+ };
287
+ const page: RuntimePage = pageMod.default;
288
+ if (!isFurinPage(page)) {
289
+ throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
290
+ }
291
+
292
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
293
+
294
+ validateRouteChain(routeChain, root.route, relativePath);
295
+
296
+ routes.push({
297
+ pattern: filePathToPattern(relativePath),
298
+ page,
299
+ path: absolutePath,
300
+ routeChain,
301
+ mode: resolveMode(page, routeChain),
302
+ notFound,
303
+ error: errorComponent,
304
+ segmentBoundaries,
305
+ });
306
+ }
307
+
308
+ return routes;
309
+ }
310
+
311
+ /**
312
+ * Walks every directory from `pagesDir` down to the directory containing
313
+ * `pageAbsolutePath` and records the OWN (not inherited) error.tsx /
314
+ * not-found.tsx declared there. Directories without any convention file are
315
+ * omitted so consumers can treat each entry as "a place where the user
316
+ * authored a boundary on purpose".
317
+ *
318
+ * Uses the shared per-directory caches so sibling pages don't re-import the
319
+ * same convention modules.
320
+ */
321
+ async function collectSegmentBoundaries(
322
+ pageAbsolutePath: string,
323
+ pagesDir: string,
324
+ notFoundCache: Map<string, ConventionLookup<NotFoundComponent> | undefined>,
325
+ errorCache: Map<string, ConventionLookup<ErrorComponent> | undefined>
326
+ ): Promise<SegmentBoundary[]> {
327
+ const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
328
+
329
+ // Accumulate directories from shallow → deep starting at pagesDir.
330
+ const dirs: string[] = [pagesDir];
331
+ if (pageDir.length > pagesDir.length) {
332
+ const relativeTail = pageDir.slice(pagesDir.length + 1); // skip leading "/"
333
+ const parts = relativeTail.split("/");
334
+ let acc = pagesDir;
335
+ for (const part of parts) {
336
+ acc = `${acc}/${part}`;
337
+ dirs.push(acc);
338
+ }
339
+ }
340
+
341
+ const boundaries: SegmentBoundary[] = [];
342
+ for (let depth = 0; depth < dirs.length; depth++) {
343
+ const dir = dirs[depth] as string;
344
+
345
+ if (!errorCache.has(dir)) {
346
+ errorCache.set(dir, await loadConventionComponent<ErrorComponent>(dir, "error"));
347
+ }
348
+ if (!notFoundCache.has(dir)) {
349
+ notFoundCache.set(dir, await loadConventionComponent<NotFoundComponent>(dir, "not-found"));
350
+ }
351
+
352
+ const errorEntry = errorCache.get(dir);
353
+ const notFoundEntry = notFoundCache.get(dir);
354
+ if (errorEntry || notFoundEntry) {
355
+ boundaries.push({
356
+ path: dir,
357
+ depth,
358
+ error: errorEntry?.component,
359
+ errorPath: errorEntry?.path,
360
+ notFound: notFoundEntry?.component,
361
+ notFoundPath: notFoundEntry?.path,
362
+ });
363
+ }
364
+ }
365
+
366
+ return boundaries;
367
+ }
368
+
369
+ async function resolveNearestConvention<T>(
370
+ pageAbsolutePath: string,
371
+ pagesDir: string,
372
+ conventionName: string,
373
+ cache: Map<string, ConventionLookup<T> | undefined>,
374
+ rootFallback: T | undefined
375
+ ): Promise<T | undefined> {
376
+ // Walk from the page's directory up to pagesDir looking for the convention file.
377
+ // Cached per directory so repeated scans for sibling pages don't re-import.
378
+ let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
379
+ while (dir.length >= pagesDir.length) {
380
+ if (!cache.has(dir)) {
381
+ cache.set(dir, await loadConventionComponent<T>(dir, conventionName));
382
+ }
383
+ const found = cache.get(dir);
384
+ if (found) {
385
+ return found.component;
386
+ }
387
+ if (dir === pagesDir) {
388
+ break;
389
+ }
390
+ dir = dir.slice(0, dir.lastIndexOf("/"));
391
+ }
392
+ return rootFallback;
393
+ }
394
+
395
+ async function buildDevRoute(
396
+ absolutePath: string,
397
+ relativePath: string,
398
+ root: RootLayout
399
+ ): Promise<ResolvedRoute> {
400
+ // Import via the virtual namespace (registerDevPagePlugin must be called first)
401
+ // so page files stay out of --hot's module graph. We still extract the route
402
+ // chain at startup for type generation, guards, and mode resolution — matching
403
+ // prod behavior exactly.
404
+ let page: RuntimePage | undefined;
405
+ let routeChain: RuntimeRoute[] = [];
406
+
407
+ try {
408
+ const pageMod = (await import(`${absolutePath}?furin-server&t=${Date.now()}`)) as {
409
+ default: RuntimePage;
410
+ };
411
+ if (isFurinPage(pageMod.default)) {
412
+ page = pageMod.default;
413
+ routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
414
+ validateRouteChain(routeChain, root.route, relativePath);
415
+ }
416
+ } catch {
417
+ // Page will be loaded on first request in createRoutePlugin as fallback
418
+ }
419
+
420
+ // Dev stub: a minimal RuntimePage that passes isFurinPage() but is never
421
+ // actually rendered — createRoutePlugin always re-imports from disk in dev mode.
422
+ const devStubPage: RuntimePage = {
423
+ __type: "FURIN_PAGE",
424
+ _route: { __type: "FURIN_ROUTE" },
425
+ component: () => null,
426
+ };
427
+
428
+ return {
429
+ pattern: filePathToPattern(relativePath),
430
+ path: absolutePath,
431
+ mode: page ? resolveMode(page, routeChain) : "ssr",
432
+ // Still lazily re-imported on each request in createRoutePlugin for fresh code
433
+ page: page ?? devStubPage,
434
+ routeChain,
435
+ // scanPageFiles() overwrites this with the real chain before the route
436
+ // is pushed — present here to satisfy the ResolvedRoute required shape.
437
+ segmentBoundaries: [],
438
+ };
439
+ }
440
+
441
+ // ── Query-default redirect ──────────────────────────────────────────────────
442
+ // Validator-agnostic: after Elysia applies defaults (TypeBox, Zod, Valibot…),
443
+ // compare the raw URL query keys with the resolved ctx.query keys. If ctx.query
444
+ // contains keys absent from the URL, defaults were applied → 302 redirect to
445
+ // the canonical URL so the address bar always reflects the actual app state.
446
+
447
+ /** @internal Exported for unit testing. */
448
+ export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
449
+ const resolvedQuery = query as Record<string, unknown>;
450
+ const queryKeys = Object.keys(resolvedQuery);
451
+ if (queryKeys.length === 0) {
452
+ return;
453
+ }
454
+
455
+ const rawParams = new URL(request.url).searchParams;
456
+
457
+ let needsRedirect = false;
458
+ for (const key of queryKeys) {
459
+ if (!rawParams.has(key) && resolvedQuery[key] != null) {
460
+ needsRedirect = true;
461
+ break;
462
+ }
463
+ }
464
+ if (!needsRedirect) {
465
+ return;
466
+ }
467
+
468
+ const url = new URL(request.url);
469
+ for (const [k, v] of Object.entries(resolvedQuery)) {
470
+ if (v != null) {
471
+ url.searchParams.set(k, String(v));
472
+ }
473
+ }
474
+
475
+ set.headers.location = url.pathname + url.search;
476
+ return status("Found");
477
+ }
478
+
479
+ /**
480
+ * Re-imports intermediate layout _route.tsx files with cache-busting so that
481
+ * server-side renders reflect the latest code after an HMR edit. Bun's ESM
482
+ * cache keeps the original module alive, so we import via ?furin-server and
483
+ * patch the layout/loader references on the existing route-chain objects.
484
+ *
485
+ * The optional `importFn` parameter exists only for unit testing. In production
486
+ * it defaults to the real `import()`.
487
+ */
488
+ export async function refreshLayoutChain(
489
+ chain: RuntimeRoute[],
490
+ pagePath: string,
491
+ rootPath: string,
492
+ importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined
493
+ ): Promise<void> {
494
+ const resolveImport = importFn ?? ((s: string) => import(s) as Promise<Record<string, unknown>>);
495
+
496
+ const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
497
+ const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
498
+ const layoutPaths: string[] = [];
499
+ let dir = pageDir;
500
+ while (dir.length > pagesDir.length) {
501
+ layoutPaths.unshift(`${dir}/_route.tsx`);
502
+ dir = dir.slice(0, dir.lastIndexOf("/"));
503
+ }
504
+
505
+ // Track chainIdx independently rather than deriving it from layoutPaths
506
+ // index. Directories without a _route.tsx produce import errors that are
507
+ // silently skipped, but those directories have no corresponding chain entry —
508
+ // so we must only advance chainIdx for directories whose _route.tsx actually
509
+ // exists. A positional assumption (i = chainIdx - 1) drifts whenever
510
+ // isModuleNotFoundError is swallowed for a gap directory.
511
+ let chainIdx = 1; // chain[0] is the root
512
+ for (const layoutPath of layoutPaths) {
513
+ if (chainIdx >= chain.length) {
514
+ break;
515
+ }
516
+ try {
517
+ const freshMod = await resolveImport(`${layoutPath}?furin-server&t=${Date.now()}`);
518
+ const freshRoute = freshMod.route ?? freshMod.default;
519
+ if (freshRoute && isFurinRoute(freshRoute)) {
520
+ const entry = chain[chainIdx];
521
+ if (entry) {
522
+ entry.layout = freshRoute.layout;
523
+ entry.loader = freshRoute.loader;
524
+ }
525
+ }
526
+ // _route.tsx exists at this depth — advance chainIdx regardless of
527
+ // whether the export is currently a valid route (the chain entry was
528
+ // populated by the initial import and should be revisited on the next
529
+ // successful HMR cycle).
530
+ chainIdx++;
531
+ } catch (err) {
532
+ if (!isModuleNotFoundError(err)) {
533
+ throw err;
534
+ }
535
+ // No _route.tsx in this directory — no chain entry to match, so
536
+ // do NOT advance chainIdx. The next deeper layoutPath may correspond
537
+ // to the current chainIdx.
538
+ }
539
+ }
540
+ }
541
+
542
+ /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
543
+ async function handleDevRequest(
544
+ route: ResolvedRoute,
545
+ ctx: Context,
546
+ root: RootLayout
547
+ ): Promise<unknown> {
548
+ // Load the page via ?furin-server virtual namespace so it stays out of
549
+ // --hot's file watcher, then hand off to renderSSR which runs loaders,
550
+ // renders React to HTML, and injects __FURIN_DATA__.
551
+ try {
552
+ let currentRoot = root;
553
+ const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
554
+ string,
555
+ unknown
556
+ >;
557
+ const rootExport = rootMod.route ?? rootMod.default;
558
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
559
+ currentRoot = { path: root.path, route: rootExport };
560
+ }
561
+
562
+ const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
563
+ const page = pageMod.default;
564
+ if (page && isFurinPage(page)) {
565
+ const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
566
+ await refreshLayoutChain(chain, route.path, root.path, undefined);
567
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
568
+ }
569
+ } catch (err) {
570
+ console.error(`[furin] Dev page load error for ${route.path}:`, err);
571
+ }
572
+ // Fallback: page couldn't load — return a clear error response rather than
573
+ // delegating to renderSSR with an undefined page.
574
+ return new Response(
575
+ `<!doctype html><html><body><h1>Page load error</h1><p>Could not load ${route.path}. Check the server console for details.</p></body></html>`,
576
+ { status: 500, headers: { "Content-Type": "text/html; charset=utf-8" } }
577
+ );
578
+ }
579
+
580
+ /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
581
+ async function handleSSGRequest(
582
+ route: ResolvedRoute,
583
+ ctx: Context,
584
+ root: RootLayout,
585
+ buildId: string
586
+ ): Promise<unknown> {
587
+ const origin = new URL(ctx.request.url).origin;
588
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
589
+
590
+ // Loader issued a redirect — forward it directly to the client.
591
+ if (entry instanceof Response) {
592
+ return entry;
593
+ }
594
+
595
+ const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
596
+
597
+ // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
598
+ const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
599
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
600
+ ctx.set.status = 304;
601
+ return;
602
+ }
603
+
604
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
605
+ // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
606
+ // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
607
+ ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
608
+ if (etag) {
609
+ ctx.set.headers.etag = etag;
610
+ }
611
+ ctx.set.headers["cache-tag"] = resolvedPath;
612
+ return entry.html;
613
+ }
614
+
615
+ // Standard structural keys on a TObject — everything else is a user-supplied option
616
+ // (e.g. additionalProperties, $id, description, title) and must be preserved.
617
+ const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
618
+
619
+ /**
620
+ * Merges TObject schemas from all routeChain entries for a given key.
621
+ * Properties are spread left-to-right (leaf wins on key conflict).
622
+ * Object-level options (additionalProperties, $id, description, …) are also
623
+ * merged with the same leaf-wins semantics so they are not silently dropped.
624
+ * Returns undefined when no entry in the chain defines the key.
625
+ *
626
+ * @internal Exported for unit testing.
627
+ */
628
+ export function mergeRouteSchemas(
629
+ routeChain: RuntimeRoute[],
630
+ key: "params" | "query"
631
+ ): AnySchema | undefined {
632
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean) as Record<string, unknown>[];
633
+
634
+ if (schemas.length === 0) {
635
+ return;
636
+ }
637
+ if (schemas.length === 1) {
638
+ return schemas[0] as AnySchema;
639
+ }
640
+
641
+ const mergedProperties = Object.assign(
642
+ {},
643
+ ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
644
+ );
645
+
646
+ const mergedOptions = Object.assign(
647
+ {},
648
+ ...schemas.map((s) =>
649
+ Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
650
+ )
651
+ );
652
+
653
+ return t.Object(mergedProperties, mergedOptions) as AnySchema;
654
+ }
655
+
656
+ export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId = ""): AnyElysia {
657
+ const { pattern, routeChain } = route;
658
+
659
+ const allParams = mergeRouteSchemas(routeChain, "params");
660
+ const allQuery = mergeRouteSchemas(routeChain, "query");
661
+ const hasQuerySchema = !!allQuery;
662
+
663
+ // Guard and handler MUST live in the same Elysia scope so that validation
664
+ // (including default-filling) applies to the route handler's ctx.query.
665
+ const plugin = new Elysia();
666
+
667
+ if (allParams || allQuery) {
668
+ plugin.guard({
669
+ params: allParams as AnySchema,
670
+ query: allQuery as AnySchema,
671
+ });
672
+ }
673
+
674
+ plugin.get(pattern, (ctx) => {
675
+ // Redirect when Elysia applied query defaults (validator-agnostic)
676
+ if (hasQuerySchema) {
677
+ const redirect = queryDefaultRedirectHook(ctx);
678
+ if (redirect) {
679
+ return redirect;
680
+ }
681
+ }
682
+
683
+ if (IS_DEV) {
684
+ return handleDevRequest(route, ctx, root);
685
+ }
686
+
687
+ if (route.mode === "ssg") {
688
+ return handleSSGRequest(route, ctx, root, buildId);
689
+ }
690
+
691
+ if (route.mode === "isr") {
692
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
693
+ return handleISR(route, ctx, root, buildId);
694
+ }
695
+
696
+ return renderSSR(route, ctx, root);
697
+ });
698
+
699
+ return plugin;
700
+ }
701
+
702
+ async function collectPageFilePaths(dir: string): Promise<string[]> {
703
+ const files: string[] = [];
704
+
705
+ // Sort by name so route order is reproducible across platforms / restarts.
706
+ // readdir is hash-based on Linux ext4, alphabetical on macOS APFS — without
707
+ // this sort, two pages that compile to the same URL pattern would resolve
708
+ // non-deterministically depending on host. Sorting also makes the eventual
709
+ // "duplicate route pattern" error reproducible (always the same winner).
710
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) =>
711
+ a.name.localeCompare(b.name)
712
+ );
713
+
714
+ for (const entry of entries) {
715
+ const absolutePath = join(dir, entry.name);
716
+
717
+ if (entry.isDirectory()) {
718
+ files.push(...(await collectPageFilePaths(absolutePath)));
719
+ continue;
720
+ }
721
+
722
+ if (entry.isFile()) {
723
+ files.push(absolutePath);
724
+ }
725
+ }
726
+
727
+ return files;
728
+ }
729
+
730
+ export function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr" {
731
+ const routeConfig = page._route;
732
+ const mode = routeConfig.mode ?? (page as { mode?: string }).mode;
733
+ const revalidate = routeConfig.revalidate ?? (page as { revalidate?: number }).revalidate;
734
+
735
+ if (mode) {
736
+ return mode as "ssr" | "ssg" | "isr";
737
+ }
738
+
739
+ const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
740
+
741
+ if (!hasLoader) {
742
+ return "ssg";
743
+ }
744
+
745
+ if (typeof revalidate === "number" && revalidate >= 0) {
746
+ return "isr";
747
+ }
748
+
749
+ return "ssr";
750
+ }
751
+
752
+ export function filePathToPattern(path: string): string {
753
+ const parts = path.replaceAll("\\", "/").split("/");
754
+ const segments: string[] = [];
755
+
756
+ for (const part of parts) {
757
+ const name = parse(part).name;
758
+
759
+ if (name === "index") {
760
+ continue;
761
+ }
762
+
763
+ if (name.startsWith("[") && name.endsWith("]")) {
764
+ const inner = name.slice(1, -1);
765
+
766
+ if (inner.startsWith("...")) {
767
+ segments.push("*");
768
+ continue;
769
+ }
770
+
771
+ segments.push(`:${inner}`);
772
+ continue;
773
+ }
774
+
775
+ segments.push(name);
776
+ }
777
+
778
+ return `/${segments.join("/")}`;
779
+ }