@teyik0/furin 0.3.0-alpha.1 → 0.4.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 (250) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +4 -3
  7. package/dist/build/compile-entry.ts +24 -69
  8. package/dist/build/entry-template.d.ts +8 -2
  9. package/dist/build/entry-template.ts +48 -11
  10. package/dist/build/index.d.ts +2 -2
  11. package/dist/build/index.js +11720 -7840
  12. package/dist/build/route-types.d.ts +2 -22
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +14 -1
  15. package/dist/build/types.d.ts +26 -3
  16. package/dist/build/virtual-entry.d.ts +8 -0
  17. package/dist/cache.d.ts +5 -0
  18. package/dist/cache.js +97 -0
  19. package/dist/cli/index.js +11815 -7793
  20. package/dist/cli/preview.d.ts +7 -0
  21. package/dist/client/boundaries.d.ts +3 -0
  22. package/dist/client/browser-events-runtime.d.ts +2 -0
  23. package/dist/client/browser-events.d.ts +2 -0
  24. package/dist/client/define-route.d.ts +36 -0
  25. package/dist/client/dev-error-overlay.d.ts +1 -0
  26. package/dist/client/dev-error-overlay.ts +201 -0
  27. package/dist/client/document.d.ts +27 -0
  28. package/dist/client/hmr.d.ts +12 -0
  29. package/dist/client/internal/runtime-types.d.ts +3 -1
  30. package/dist/client/link.js +1392 -940
  31. package/dist/client/router/index.d.ts +1 -1
  32. package/dist/client/router/link-utils.d.ts +9 -0
  33. package/dist/client/router/provider.d.ts +1 -1
  34. package/dist/client/router/search/index.d.ts +3 -7
  35. package/dist/client/router/sync-catch-up.d.ts +1 -1
  36. package/dist/client/router/types.d.ts +40 -34
  37. package/dist/client.d.ts +4 -159
  38. package/dist/client.js +197 -21
  39. package/dist/config.d.ts +25 -8
  40. package/dist/config.js +15 -7
  41. package/dist/define-route.d.ts +1358 -0
  42. package/dist/devtools/protocol.d.ts +2 -2
  43. package/dist/furin.d.ts +18 -34
  44. package/dist/furin.js +16038 -9395
  45. package/dist/plugin/index.js +1401 -223
  46. package/dist/plugin/route-config-autofix.d.ts +31 -0
  47. package/dist/plugin/routes.d.ts +28 -0
  48. package/dist/routes.d.ts +6 -0
  49. package/dist/routes.js +1 -0
  50. package/dist/rsc/build/index.d.ts +6 -2
  51. package/dist/rsc.js +3 -3
  52. package/dist/server/browser-events/plugin.d.ts +11 -0
  53. package/dist/server/browser-events/types.d.ts +9 -0
  54. package/dist/server/cache/invalidation.d.ts +1 -2
  55. package/dist/server/cache/isr.d.ts +1 -0
  56. package/dist/server/cache/purger.d.ts +7 -0
  57. package/dist/server/cache/runtime-cache.d.ts +21 -0
  58. package/dist/server/dev/browser-events.d.ts +4 -0
  59. package/dist/server/dev/diagnostics.d.ts +39 -0
  60. package/dist/server/dev/error.d.ts +17 -0
  61. package/dist/server/dev/graph.d.ts +86 -0
  62. package/dist/server/dev/plugin.d.ts +9 -0
  63. package/dist/server/dev/request-security.d.ts +1 -0
  64. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  65. package/dist/server/dev/runtime.production.d.ts +5 -0
  66. package/dist/server/dev/symbolicate.d.ts +11 -0
  67. package/dist/server/dev/transform-failure.d.ts +4 -0
  68. package/dist/server/dev-page-plugin.d.ts +7 -5
  69. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  70. package/dist/server/devtools/hub.d.ts +3 -2
  71. package/dist/server/devtools/instrumentation.d.ts +2 -2
  72. package/dist/server/devtools/instrumentation.production.d.ts +2 -2
  73. package/dist/server/devtools/plugin.d.ts +2 -2
  74. package/dist/server/external-prerender.d.ts +2 -0
  75. package/dist/server/instance.d.ts +2 -2
  76. package/dist/server/internal.d.ts +17 -2
  77. package/dist/server/internal.js +436 -1
  78. package/dist/server/logger.d.ts +4 -0
  79. package/dist/server/render/assemble.d.ts +0 -9
  80. package/dist/server/render/document.d.ts +4 -0
  81. package/dist/server/render/element.d.ts +3 -1
  82. package/dist/server/render/index.d.ts +2 -2
  83. package/dist/server/render/index.ts +1 -2
  84. package/dist/server/render/isr.d.ts +1 -1
  85. package/dist/server/render/loaders.d.ts +1 -1
  86. package/dist/server/render/not-found.d.ts +1 -1
  87. package/dist/server/render/ppr-document.d.ts +21 -0
  88. package/dist/server/render/ppr-request.d.ts +26 -0
  89. package/dist/server/render/ppr-route.d.ts +4 -2
  90. package/dist/server/render/shell.ts +0 -12
  91. package/dist/server/render/ssg.d.ts +3 -1
  92. package/dist/server/render/ssr.d.ts +23 -11
  93. package/dist/server/render/template.d.ts +4 -0
  94. package/dist/server/router/defined-route.d.ts +24 -0
  95. package/dist/server/router/hmr.d.ts +16 -8
  96. package/dist/server/router/hmr.production.d.ts +2 -0
  97. package/dist/server/router/patterns.d.ts +7 -0
  98. package/dist/server/router/plugin.d.ts +6 -3
  99. package/dist/server/router/schema-merge.d.ts +2 -2
  100. package/dist/server/router/schemas.d.ts +5 -5
  101. package/dist/server/router/source-version.d.ts +2 -0
  102. package/dist/server/router/types.d.ts +1 -0
  103. package/dist/server/sync/adapter.d.ts +13 -0
  104. package/dist/server/sync/config.d.ts +5 -5
  105. package/dist/server/sync/index.d.ts +6 -6
  106. package/dist/server/sync/index.js +1115 -985
  107. package/dist/server/sync/notifier.d.ts +1 -0
  108. package/dist/server/sync/postgres/index.d.ts +12 -1
  109. package/dist/server/sync/postgres/index.js +101 -6
  110. package/dist/server/sync/postgres/migrate.js +3 -2
  111. package/dist/server/sync/stream.d.ts +4 -13
  112. package/dist/shared/await.d.ts +4 -5
  113. package/dist/shared/browser-events.d.ts +22 -0
  114. package/dist/shared/compact-json.d.ts +8 -0
  115. package/dist/shared/deferred-ndjson.d.ts +6 -5
  116. package/dist/shared/dev-diagnostics.d.ts +36 -0
  117. package/dist/shared/elysia-contract.d.ts +41 -0
  118. package/dist/shared/prefix.d.ts +2 -0
  119. package/dist/shared/route-map.d.ts +5 -0
  120. package/dist/shared/utils/index.d.ts +1 -3
  121. package/package.json +55 -43
  122. package/src/adapter/README.md +45 -0
  123. package/src/adapter/bun.ts +62 -265
  124. package/src/adapter/package.ts +34 -22
  125. package/src/adapter/runtime-build.ts +375 -0
  126. package/src/adapter/static.ts +83 -5
  127. package/src/adapter/vercel.ts +857 -0
  128. package/src/build/client.ts +58 -16
  129. package/src/build/compile-entry.ts +24 -69
  130. package/src/build/entry-template.ts +48 -11
  131. package/src/build/hydrate.ts +147 -37
  132. package/src/build/index.ts +21 -7
  133. package/src/build/production-instrumentation.ts +56 -4
  134. package/src/build/route-types.ts +19 -114
  135. package/src/build/shared.ts +3 -2
  136. package/src/build/ssg-cache.ts +99 -16
  137. package/src/build/types.ts +32 -3
  138. package/src/build/virtual-entry.ts +27 -0
  139. package/src/cache.ts +14 -0
  140. package/src/cli/config.ts +3 -3
  141. package/src/cli/index.ts +62 -10
  142. package/src/cli/preview.ts +90 -0
  143. package/src/client/boundaries.tsx +19 -2
  144. package/src/client/browser-events-runtime.ts +204 -0
  145. package/src/client/browser-events.ts +22 -0
  146. package/src/client/define-route.ts +38 -0
  147. package/src/client/dev-error-overlay.ts +201 -0
  148. package/src/client/document.tsx +162 -0
  149. package/src/client/hmr.ts +63 -0
  150. package/src/client/internal/runtime-types.ts +3 -1
  151. package/src/client/link.tsx +21 -6
  152. package/src/client/router/boundary-tree.tsx +4 -4
  153. package/src/client/router/index.ts +1 -0
  154. package/src/client/router/link-utils.ts +26 -0
  155. package/src/client/router/provider.tsx +190 -65
  156. package/src/client/router/search/index.ts +4 -12
  157. package/src/client/router/sync-catch-up.ts +3 -4
  158. package/src/client/router/types.ts +56 -30
  159. package/src/client.ts +14 -316
  160. package/src/config.ts +35 -10
  161. package/src/define-route.ts +972 -0
  162. package/src/devtools/devtools-element.js +67 -87
  163. package/src/devtools/protocol.ts +2 -2
  164. package/src/furin.ts +431 -101
  165. package/src/plugin/route-config-autofix.ts +1140 -0
  166. package/src/plugin/routes.ts +1061 -0
  167. package/src/plugin/transform-client.ts +776 -228
  168. package/src/plugin/transform-isomorphic.ts +1 -1
  169. package/src/react-dom-edge.d.ts +6 -0
  170. package/src/routes.ts +6 -0
  171. package/src/rsc/build/index.ts +16 -4
  172. package/src/server/auto-invalidate/registry.ts +2 -2
  173. package/src/server/auto-invalidate/runtime.ts +5 -2
  174. package/src/server/browser-events/plugin.ts +168 -0
  175. package/src/server/browser-events/types.ts +11 -0
  176. package/src/server/cache/dev-loader.ts +30 -29
  177. package/src/server/cache/invalidation.ts +13 -22
  178. package/src/server/cache/isr.ts +9 -0
  179. package/src/server/cache/purger.ts +41 -0
  180. package/src/server/cache/runtime-cache.ts +137 -0
  181. package/src/server/dev/browser-events.ts +54 -0
  182. package/src/server/dev/diagnostics.ts +297 -0
  183. package/src/server/dev/error.ts +148 -0
  184. package/src/server/dev/graph.ts +438 -0
  185. package/src/server/dev/plugin.ts +130 -0
  186. package/src/server/dev/request-security.ts +38 -0
  187. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  188. package/src/server/dev/runtime.production.ts +24 -0
  189. package/src/server/dev/symbolicate.ts +135 -0
  190. package/src/server/dev/transform-failure.ts +8 -0
  191. package/src/server/dev-page-plugin.production.ts +3 -0
  192. package/src/server/dev-page-plugin.ts +110 -52
  193. package/src/server/devtools/hub.ts +6 -5
  194. package/src/server/devtools/instrumentation.production.ts +3 -3
  195. package/src/server/devtools/instrumentation.ts +14 -8
  196. package/src/server/devtools/plugin.ts +12 -153
  197. package/src/server/external-prerender.ts +10 -0
  198. package/src/server/instance.ts +5 -5
  199. package/src/server/internal.ts +42 -2
  200. package/src/server/logger.ts +21 -0
  201. package/src/server/render/assemble.ts +4 -45
  202. package/src/server/render/document.tsx +34 -0
  203. package/src/server/render/element.tsx +31 -15
  204. package/src/server/render/index.ts +1 -2
  205. package/src/server/render/isr.ts +70 -24
  206. package/src/server/render/loaders.ts +43 -8
  207. package/src/server/render/not-found.ts +77 -29
  208. package/src/server/render/ppr-document.ts +239 -0
  209. package/src/server/render/ppr-request.ts +104 -0
  210. package/src/server/render/ppr-route.ts +153 -32
  211. package/src/server/render/shell.ts +0 -12
  212. package/src/server/render/ssg.ts +39 -21
  213. package/src/server/render/ssr.ts +429 -143
  214. package/src/server/render/template.ts +128 -2
  215. package/src/server/router/defined-route.ts +78 -0
  216. package/src/server/router/discovery.ts +129 -29
  217. package/src/server/router/hmr.production.ts +7 -0
  218. package/src/server/router/hmr.ts +177 -67
  219. package/src/server/router/patterns.ts +45 -13
  220. package/src/server/router/plugin.ts +184 -78
  221. package/src/server/router/schema-merge.ts +4 -14
  222. package/src/server/router/schemas.ts +11 -8
  223. package/src/server/router/source-version.ts +9 -0
  224. package/src/server/router/types.ts +2 -0
  225. package/src/server/sync/adapter.ts +13 -0
  226. package/src/server/sync/config.ts +12 -12
  227. package/src/server/sync/index.ts +8 -8
  228. package/src/server/sync/notifier.ts +1 -0
  229. package/src/server/sync/plugin.ts +4 -1
  230. package/src/server/sync/postgres/index.ts +111 -5
  231. package/src/server/sync/postgres/migrate.ts +3 -2
  232. package/src/server/sync/response.ts +14 -10
  233. package/src/server/sync/runtime.ts +12 -0
  234. package/src/server/sync/stream.ts +78 -113
  235. package/src/shared/await.tsx +4 -5
  236. package/src/shared/browser-events.ts +28 -0
  237. package/src/shared/compact-json.ts +77 -0
  238. package/src/shared/deferred-ndjson.ts +20 -6
  239. package/src/shared/dev-diagnostics.ts +44 -0
  240. package/src/shared/elysia-contract.ts +63 -0
  241. package/src/shared/prefix.ts +8 -0
  242. package/src/shared/route-map.ts +46 -0
  243. package/src/shared/utils/index.ts +2 -20
  244. package/dist/build/server-routes-entry.d.ts +0 -13
  245. package/dist/build/server-routes-entry.ts +0 -30
  246. package/dist/server/router/index.d.ts +0 -7
  247. package/dist/server/router/index.js +0 -27
  248. package/dist/server/router/index.ts +0 -28
  249. package/src/build/server-routes-entry.ts +0 -30
  250. package/src/server/router/index.ts +0 -28
@@ -0,0 +1,1140 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { extname, join, relative, resolve } from "node:path";
3
+ import MagicString from "magic-string";
4
+ import { walk } from "yuku-ast";
5
+ import type { ImportDeclaration, Program } from "yuku-parser";
6
+ import { detectLangFromPath, unwrapTSExpression } from "../server/lang-detect.ts";
7
+ import { parseDynamicRouteSegment } from "../server/router/patterns.ts";
8
+ import { parseSource } from "../shared/parser.ts";
9
+ import type { AstNode } from "../shared/utils/ast-walk.ts";
10
+
11
+ /**
12
+ * Dev-time auto-fix for `config({ layout })`, mirroring how TanStack Router's
13
+ * generator rewrites `createFileRoute` ids: the watcher scans route files,
14
+ * computes the expected ancestor layout from the file system, and rewrites
15
+ * the config object (plus the import) when the declared reference is missing
16
+ * or points at the wrong module. Content edits never retrigger the watcher,
17
+ * so the rewrite cannot loop; the dev renderer re-reads the file on the next
18
+ * request through its cache-busting import.
19
+ */
20
+
21
+ const DIRECTORY_SPLIT_RE = /[\\/]/;
22
+ const NON_ALPHANUMERIC_RE = /[^a-zA-Z0-9]/g;
23
+
24
+ export interface ExpectedLayout {
25
+ /** Preferred local binding, e.g. "rootRoute". */
26
+ identifier: string;
27
+ /** Import specifier relative from the route file, e.g. "../root". */
28
+ importPath: string;
29
+ }
30
+
31
+ export type LayoutProbe = (path: string) => boolean;
32
+
33
+ function routeConfigError(filePath: string, message: string): Error {
34
+ return new Error(`[furin] ${filePath}: ${message}`);
35
+ }
36
+
37
+ function asAstNode(node: unknown): AstNode | null {
38
+ if (!node || typeof node !== "object" || !("type" in node)) {
39
+ return null;
40
+ }
41
+ return unwrapTSExpression(node as { type: string }) as AstNode;
42
+ }
43
+
44
+ function propertyName(node: unknown): string | null {
45
+ const ast = asAstNode(node);
46
+ if (ast?.type === "Identifier" && typeof ast.name === "string") {
47
+ return ast.name;
48
+ }
49
+ if (ast?.type === "Literal" && typeof ast.value === "string") {
50
+ return ast.value;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ const WITHOUT_EXTENSION_RE = /\.(ts|tsx|jsx|js|mts|cts)$/;
56
+ const NESTED_LAYOUT_FILE_NAMES = ["_route.tsx", "_route.ts", "_route.jsx", "_route.js"];
57
+ const ROOT_LAYOUT_FILE_NAMES = ["root.tsx", "root.ts"];
58
+
59
+ function withoutExtension(path: string): string {
60
+ return path.replace(WITHOUT_EXTENSION_RE, "");
61
+ }
62
+
63
+ function toImportSpecifier(fromFile: string, toFile: string): string {
64
+ const specifier = withoutExtension(relative(resolve(fromFile, ".."), toFile)).replaceAll(
65
+ "\\",
66
+ "/"
67
+ );
68
+ return specifier.startsWith(".") ? specifier : `./${specifier}`;
69
+ }
70
+
71
+ /** Deterministic binding for a layout file: `root.tsx` → `rootRoute`, `board/_route.tsx` → `boardRoute`. */
72
+ export function layoutIdentifierFor(layoutPath: string): string {
73
+ const extension = extname(layoutPath);
74
+ const stem = layoutPath.slice(0, layoutPath.length - extension.length);
75
+ const base = stem.split(DIRECTORY_SPLIT_RE).pop() ?? "";
76
+ const source =
77
+ base === "_route" ? (resolve(layoutPath, "..").split(DIRECTORY_SPLIT_RE).pop() ?? "") : base;
78
+ const name = (source || "root").replace(NON_ALPHANUMERIC_RE, "");
79
+ return `${name || "root"}Route`;
80
+ }
81
+
82
+ /**
83
+ * The layout a route file should reference: the nearest `_route.ts(x)` walking
84
+ * up from its own directory (a `_route` file looks at its PARENT directory),
85
+ * falling back to the `root.tsx` convention at the pages root. Returns null
86
+ * for the root layout itself — nothing above it exists.
87
+ */
88
+ export function expectedLayoutFor(
89
+ filePath: string,
90
+ pagesDir: string,
91
+ probe: LayoutProbe = existsSync
92
+ ): ExpectedLayout | null {
93
+ const pages = resolve(pagesDir);
94
+ const file = resolve(filePath);
95
+ const directory = resolve(file, "..");
96
+ const extension = extname(file);
97
+ const stem = file.slice(0, file.length - extension.length);
98
+ if (stem === join(pages, "root")) {
99
+ return null; // the root layout references nothing above it
100
+ }
101
+ const isLayoutFile = stem === join(directory, "_route");
102
+
103
+ let current = directory;
104
+ while (current.startsWith(pages) && current !== pages) {
105
+ if (!(isLayoutFile && current === directory)) {
106
+ for (const candidate of NESTED_LAYOUT_FILE_NAMES) {
107
+ const layoutPath = join(current, candidate);
108
+ if (probe(layoutPath)) {
109
+ return {
110
+ identifier: layoutIdentifierFor(layoutPath),
111
+ importPath: toImportSpecifier(file, layoutPath),
112
+ };
113
+ }
114
+ }
115
+ }
116
+ current = resolve(current, "..");
117
+ }
118
+
119
+ for (const candidate of ROOT_LAYOUT_FILE_NAMES) {
120
+ const layoutPath = join(pages, candidate);
121
+ if (probe(layoutPath)) {
122
+ return {
123
+ identifier: layoutIdentifierFor(layoutPath),
124
+ importPath: toImportSpecifier(file, layoutPath),
125
+ };
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+
131
+ interface LayoutImport {
132
+ binding: string;
133
+ resolvedPath: string;
134
+ }
135
+
136
+ interface CollectedImports {
137
+ /** Every local import binding (collision detection for injected imports). */
138
+ allBindings: Set<string>;
139
+ imports: LayoutImport[];
140
+ /** End offset of the last import statement (import insertion point). */
141
+ lastImportEnd: number;
142
+ /** Local binding of the `t` TypeBox import, when present. */
143
+ tBinding: string | null;
144
+ }
145
+
146
+ const LEADING_SLASH_RE = /^\//;
147
+
148
+ function collectLayoutImports(program: Program, filePath: string): CollectedImports {
149
+ const imports: LayoutImport[] = [];
150
+ const allBindings = new Set<string>();
151
+ let lastImportEnd = 0;
152
+ let tBinding: string | null = null;
153
+ for (const statement of program.body) {
154
+ if (statement.type !== "ImportDeclaration") {
155
+ continue;
156
+ }
157
+ const declaration = statement as unknown as ImportDeclaration;
158
+ if (declaration.importKind === "type") {
159
+ continue;
160
+ }
161
+ const end = typeof declaration.end === "number" ? declaration.end : 0;
162
+ if (end > lastImportEnd) {
163
+ lastImportEnd = end;
164
+ }
165
+ const collected = collectImportBinding(declaration, filePath, imports, allBindings);
166
+ if (collected !== null && tBinding === null) {
167
+ tBinding = collected;
168
+ }
169
+ }
170
+ return { allBindings, imports, lastImportEnd, tBinding };
171
+ }
172
+
173
+ function collectImportBinding(
174
+ declaration: ImportDeclaration,
175
+ filePath: string,
176
+ imports: LayoutImport[],
177
+ allBindings: Set<string>
178
+ ): string | null {
179
+ const specifierValue = declaration.source?.value;
180
+ if (typeof specifierValue !== "string") {
181
+ return null;
182
+ }
183
+ const resolvedPath = withoutExtension(resolve(filePath, "..", specifierValue));
184
+ let tBinding: string | null = null;
185
+ for (const specifier of declaration.specifiers as unknown as AstNode[]) {
186
+ if (specifier.type !== "ImportSpecifier") {
187
+ continue;
188
+ }
189
+ const imported = asAstNode(specifier.imported);
190
+ const local = asAstNode(specifier.local);
191
+ if (
192
+ imported?.type !== "Identifier" ||
193
+ typeof imported.name !== "string" ||
194
+ local?.type !== "Identifier" ||
195
+ typeof local.name !== "string"
196
+ ) {
197
+ continue;
198
+ }
199
+ allBindings.add(local.name);
200
+ if (imported.name === "route") {
201
+ imports.push({ binding: local.name, resolvedPath });
202
+ }
203
+ if (imported.name === "t" && specifierValue === "elysia") {
204
+ tBinding = local.name;
205
+ }
206
+ }
207
+ return tBinding;
208
+ }
209
+
210
+ function belongsToBuilderChain(node: unknown, bindings: BuilderBindings): boolean {
211
+ const expression = asAstNode(node);
212
+ if (expression?.type !== "CallExpression") {
213
+ return false;
214
+ }
215
+ const callee = asAstNode(expression.callee);
216
+ if (callee?.type === "Identifier" && typeof callee.name === "string") {
217
+ return bindings.rootBindings.has(callee.name) || bindings.routeBindings.has(callee.name);
218
+ }
219
+ if (callee?.type !== "MemberExpression") {
220
+ return false;
221
+ }
222
+ return belongsToBuilderChain(callee.object, bindings);
223
+ }
224
+
225
+ function collectConfigObjects(program: Program, bindings: BuilderBindings): AstNode[] {
226
+ const objects: AstNode[] = [];
227
+ walk(program as never, {
228
+ CallExpression(call) {
229
+ const callee = asAstNode(call.callee);
230
+ if (callee?.type !== "MemberExpression" || typeof callee.property !== "object") {
231
+ return;
232
+ }
233
+ const property = asAstNode(callee.property);
234
+ if (property?.type !== "Identifier" || property.name !== "config") {
235
+ return;
236
+ }
237
+ if (!belongsToBuilderChain(callee.object, bindings)) {
238
+ return;
239
+ }
240
+ const argument = Array.isArray(call.arguments) ? asAstNode(call.arguments[0]) : null;
241
+ if (argument?.type === "ObjectExpression") {
242
+ objects.push(argument);
243
+ }
244
+ },
245
+ });
246
+ return objects;
247
+ }
248
+
249
+ function builderChainHasMethod(
250
+ program: Program,
251
+ bindings: BuilderBindings,
252
+ methodName: string
253
+ ): boolean {
254
+ let found = false;
255
+ walk(program as never, {
256
+ CallExpression(call) {
257
+ const callee = asAstNode(call.callee);
258
+ if (callee?.type !== "MemberExpression") {
259
+ return;
260
+ }
261
+ const property = asAstNode(callee.property);
262
+ if (
263
+ property?.type === "Identifier" &&
264
+ property.name === methodName &&
265
+ belongsToBuilderChain(callee.object, bindings)
266
+ ) {
267
+ found = true;
268
+ }
269
+ },
270
+ });
271
+ return found;
272
+ }
273
+
274
+ interface BuilderBindings {
275
+ documentBindings: Set<string>;
276
+ rootBindings: Set<string>;
277
+ routeBindings: Set<string>;
278
+ routeSpecifiers: Map<string, { end: number; start: number }>;
279
+ }
280
+
281
+ const FURIN_BUILDER_MODULES = new Set([
282
+ "@teyik0/furin",
283
+ "furin",
284
+ "@teyik0/furin/client",
285
+ "furin/client",
286
+ ]);
287
+
288
+ function collectDocumentBinding(
289
+ importedName: string,
290
+ localName: string,
291
+ bindings: BuilderBindings
292
+ ): void {
293
+ if (
294
+ (importedName === "HeadContent" || importedName === "Scripts") &&
295
+ localName === importedName
296
+ ) {
297
+ bindings.documentBindings.add(importedName);
298
+ }
299
+ }
300
+
301
+ function collectBindingsFromDeclaration(
302
+ declaration: ImportDeclaration,
303
+ bindings: BuilderBindings
304
+ ): void {
305
+ const specifierValue = declaration.source?.value;
306
+ if (typeof specifierValue !== "string" || !FURIN_BUILDER_MODULES.has(specifierValue)) {
307
+ return;
308
+ }
309
+ for (const specifier of declaration.specifiers as unknown as AstNode[]) {
310
+ if (specifier.type !== "ImportSpecifier") {
311
+ continue;
312
+ }
313
+ const imported = asAstNode(specifier.imported);
314
+ const local = asAstNode(specifier.local);
315
+ if (imported?.type !== "Identifier" || typeof imported.name !== "string") {
316
+ continue;
317
+ }
318
+ if (local?.type !== "Identifier" || typeof local.name !== "string") {
319
+ continue;
320
+ }
321
+ if (imported.name === "defineRoute") {
322
+ bindings.routeBindings.add(local.name);
323
+ if (typeof specifier.start === "number" && typeof specifier.end === "number") {
324
+ bindings.routeSpecifiers.set(local.name, {
325
+ end: specifier.end,
326
+ start: specifier.start,
327
+ });
328
+ }
329
+ }
330
+ if (imported.name === "defineRootRoute") {
331
+ bindings.rootBindings.add(local.name);
332
+ }
333
+ collectDocumentBinding(imported.name, local.name, bindings);
334
+ }
335
+ }
336
+
337
+ function collectBuilderBindings(program: Program): BuilderBindings {
338
+ const bindings: BuilderBindings = {
339
+ documentBindings: new Set(),
340
+ rootBindings: new Set(),
341
+ routeBindings: new Set(),
342
+ routeSpecifiers: new Map(),
343
+ };
344
+ for (const statement of program.body) {
345
+ if (statement.type === "ImportDeclaration") {
346
+ collectBindingsFromDeclaration(statement as unknown as ImportDeclaration, bindings);
347
+ }
348
+ }
349
+ return bindings;
350
+ }
351
+
352
+ function prependMissingDocumentImports(bindings: BuilderBindings, magic: MagicString): void {
353
+ const missing = ["HeadContent", "Scripts"].filter(
354
+ (binding) => !bindings.documentBindings.has(binding)
355
+ );
356
+ if (missing.length > 0) {
357
+ magic.prepend(`import { ${missing.join(", ")} } from "@teyik0/furin";\n`);
358
+ }
359
+ }
360
+
361
+ interface ChainHead {
362
+ binding: string;
363
+ builderEnd: number;
364
+ chainEnd: number;
365
+ end: number;
366
+ exportedAsRoute: boolean;
367
+ isRoot: boolean;
368
+ start: number;
369
+ terminal: string | null;
370
+ }
371
+
372
+ function terminalName(node: unknown): string | null {
373
+ const expression = asAstNode(node);
374
+ if (expression?.type !== "CallExpression") {
375
+ return null;
376
+ }
377
+ const callee = asAstNode(expression.callee);
378
+ if (callee?.type !== "MemberExpression") {
379
+ return null;
380
+ }
381
+ const property = asAstNode(callee.property);
382
+ return property?.type === "Identifier" && typeof property.name === "string"
383
+ ? property.name
384
+ : null;
385
+ }
386
+
387
+ /** `defineRoute()` / `defineRootRoute()` calls and their observable chain terminal. */
388
+ function collectChainHeads(program: Program, bindings: BuilderBindings): ChainHead[] {
389
+ const heads: ChainHead[] = [];
390
+ walk(program as never, {
391
+ CallExpression(call, context) {
392
+ const callee = asAstNode(call.callee);
393
+ if (callee?.type !== "Identifier" || typeof callee.name !== "string") {
394
+ return;
395
+ }
396
+ const callEnd = typeof call.end === "number" ? call.end : 0;
397
+ const calleeStart = typeof callee.start === "number" ? callee.start : 0;
398
+ const calleeEnd = typeof callee.end === "number" ? callee.end : 0;
399
+ const ancestors = context.ancestors() as AstNode[];
400
+ const declaration = ancestors.find((ancestor) => ancestor.type === "VariableDeclarator");
401
+ const identifier = asAstNode(declaration?.id);
402
+ const chain = asAstNode(declaration?.init);
403
+ const variableDeclaration = ancestors.find(
404
+ (ancestor) => ancestor.type === "VariableDeclaration"
405
+ );
406
+ const exportedAsRoute =
407
+ identifier?.type === "Identifier" &&
408
+ identifier.name === "route" &&
409
+ variableDeclaration?.kind === "const" &&
410
+ ancestors.some((ancestor) => ancestor.type === "ExportNamedDeclaration");
411
+ const terminal = terminalName(declaration?.init);
412
+ if (bindings.rootBindings.has(callee.name)) {
413
+ heads.push({
414
+ binding: callee.name,
415
+ builderEnd: calleeEnd,
416
+ chainEnd: typeof chain?.end === "number" ? chain.end : callEnd,
417
+ end: callEnd,
418
+ exportedAsRoute,
419
+ isRoot: true,
420
+ start: calleeStart,
421
+ terminal,
422
+ });
423
+ return;
424
+ }
425
+ if (bindings.routeBindings.has(callee.name)) {
426
+ heads.push({
427
+ binding: callee.name,
428
+ builderEnd: calleeEnd,
429
+ chainEnd: typeof chain?.end === "number" ? chain.end : callEnd,
430
+ end: callEnd,
431
+ exportedAsRoute,
432
+ isRoot: false,
433
+ start: calleeStart,
434
+ terminal,
435
+ });
436
+ }
437
+ },
438
+ });
439
+ return heads;
440
+ }
441
+
442
+ interface FixContext {
443
+ allBindings: Set<string>;
444
+ ancestorHasLoader: boolean;
445
+ ancestorHasQuery: boolean;
446
+ dynamicParams: string[];
447
+ expected: ExpectedLayout | null;
448
+ expectedResolvedPath: string;
449
+ filePath: string;
450
+ hasLoader: boolean;
451
+ imports: LayoutImport[];
452
+ isRootLayout: boolean;
453
+ lastImportEnd: number;
454
+ magic: MagicString;
455
+ source: string;
456
+ tBinding: string | null;
457
+ }
458
+
459
+ type InferredRenderingMode = "isr" | "ssg" | "ssr";
460
+
461
+ function inferRenderingMode({
462
+ hasLoader,
463
+ hasQuery,
464
+ hasRevalidate,
465
+ isRootLayout,
466
+ }: {
467
+ hasLoader: boolean;
468
+ hasQuery: boolean;
469
+ hasRevalidate: boolean;
470
+ isRootLayout: boolean;
471
+ }): InferredRenderingMode {
472
+ if (isRootLayout || hasQuery) {
473
+ return "ssr";
474
+ }
475
+ if (!hasLoader) {
476
+ return "ssg";
477
+ }
478
+ return hasRevalidate ? "isr" : "ssr";
479
+ }
480
+
481
+ function findSourceFile(
482
+ directory: string,
483
+ fileNames: readonly string[],
484
+ probe: LayoutProbe
485
+ ): string | null {
486
+ for (const fileName of fileNames) {
487
+ const candidate = join(directory, fileName);
488
+ if (probe(candidate)) {
489
+ return candidate;
490
+ }
491
+ }
492
+ return null;
493
+ }
494
+
495
+ function ancestorLayoutPaths(filePath: string, pagesDir: string, probe: LayoutProbe): string[] {
496
+ const pages = resolve(pagesDir);
497
+ const file = resolve(filePath);
498
+ const directory = resolve(file, "..");
499
+ const isLayoutFile = withoutExtension(file) === join(directory, "_route");
500
+ const paths: string[] = [];
501
+ let current = isLayoutFile ? resolve(directory, "..") : directory;
502
+
503
+ while (current.startsWith(pages) && current !== pages) {
504
+ const layoutPath = findSourceFile(current, NESTED_LAYOUT_FILE_NAMES, probe);
505
+ if (layoutPath) {
506
+ paths.push(layoutPath);
507
+ }
508
+ current = resolve(current, "..");
509
+ }
510
+
511
+ const rootPath = findSourceFile(pages, ROOT_LAYOUT_FILE_NAMES, probe);
512
+ if (rootPath) {
513
+ paths.push(rootPath);
514
+ }
515
+ return paths;
516
+ }
517
+
518
+ interface AncestorRenderingRequirements {
519
+ hasLoader: boolean;
520
+ hasQuery: boolean;
521
+ }
522
+
523
+ function layoutRenderingRequirements(filePath: string): AncestorRenderingRequirements {
524
+ try {
525
+ const source = readFileSync(filePath, "utf8");
526
+ const parsed = parseSource(source, detectLangFromPath(filePath));
527
+ const bindings = collectBuilderBindings(parsed.program);
528
+ return {
529
+ hasLoader: builderChainHasMethod(parsed.program, bindings, "loader"),
530
+ hasQuery: collectConfigObjects(parsed.program, bindings).some(
531
+ (object) => collectConfigProperties(object).query !== undefined
532
+ ),
533
+ };
534
+ } catch {
535
+ return { hasLoader: false, hasQuery: true };
536
+ }
537
+ }
538
+
539
+ function ancestorRenderingRequirements(
540
+ filePath: string,
541
+ pagesDir: string,
542
+ probe: LayoutProbe
543
+ ): AncestorRenderingRequirements {
544
+ return ancestorLayoutPaths(filePath, pagesDir, probe).reduce<AncestorRenderingRequirements>(
545
+ (requirements, layoutPath) => {
546
+ const current = layoutRenderingRequirements(layoutPath);
547
+ return {
548
+ hasLoader: requirements.hasLoader || current.hasLoader,
549
+ hasQuery: requirements.hasQuery || current.hasQuery,
550
+ };
551
+ },
552
+ { hasLoader: false, hasQuery: false }
553
+ );
554
+ }
555
+
556
+ const wordBoundaryRe = (binding: string): RegExp => new RegExp(`\\b${binding}\\b`);
557
+
558
+ function resolveBinding(ctx: FixContext, insertionOffset: number): string {
559
+ const existing = ctx.imports.find(
560
+ (candidate) => candidate.resolvedPath === ctx.expectedResolvedPath
561
+ );
562
+ if (existing) {
563
+ return existing.binding;
564
+ }
565
+ const expected = ctx.expected as ExpectedLayout;
566
+ const taken = new Set(ctx.imports.map((candidate) => candidate.binding));
567
+ let binding = expected.identifier;
568
+ let suffix = 2;
569
+ while (taken.has(binding) || wordBoundaryRe(binding).test(ctx.source)) {
570
+ binding = `${expected.identifier}${suffix}`;
571
+ suffix += 1;
572
+ }
573
+ ctx.magic.appendRight(
574
+ insertionOffset,
575
+ `\nimport { route as ${binding} } from "${expected.importPath}";${
576
+ ctx.source[insertionOffset] === "\n" || ctx.source[insertionOffset] === "\r" ? "" : "\n"
577
+ }`
578
+ );
579
+ ctx.imports.push({ binding, resolvedPath: ctx.expectedResolvedPath });
580
+ return binding;
581
+ }
582
+
583
+ function removeObjectProperties(
584
+ object: AstNode,
585
+ properties: AstNode[],
586
+ removed: Set<AstNode>,
587
+ magic: MagicString
588
+ ): void {
589
+ if (removed.size === 0) {
590
+ return;
591
+ }
592
+ if (
593
+ removed.size === properties.length &&
594
+ typeof object.start === "number" &&
595
+ typeof object.end === "number"
596
+ ) {
597
+ magic.remove(object.start + 1, object.end - 1);
598
+ return;
599
+ }
600
+
601
+ let firstRemovedIndex: number | null = null;
602
+ for (let index = 0; index <= properties.length; index += 1) {
603
+ const property = properties[index];
604
+ if (property && removed.has(property)) {
605
+ firstRemovedIndex ??= index;
606
+ continue;
607
+ }
608
+ if (firstRemovedIndex === null) {
609
+ continue;
610
+ }
611
+ const first = properties[firstRemovedIndex];
612
+ const last = properties[index - 1];
613
+ const previous = properties[firstRemovedIndex - 1];
614
+ if (!(first && last && typeof first.start === "number" && typeof last.end === "number")) {
615
+ firstRemovedIndex = null;
616
+ continue;
617
+ }
618
+ if (property && typeof property.start === "number") {
619
+ magic.remove(first.start, property.start);
620
+ } else if (previous && typeof previous.end === "number") {
621
+ magic.remove(previous.end, last.end);
622
+ } else {
623
+ magic.remove(first.start, last.end);
624
+ }
625
+ firstRemovedIndex = null;
626
+ }
627
+ }
628
+
629
+ interface ConfigProperties {
630
+ all: AstNode[];
631
+ layout: AstNode | undefined;
632
+ mode: AstNode | undefined;
633
+ params: AstNode | undefined;
634
+ query: AstNode | undefined;
635
+ revalidate: AstNode | undefined;
636
+ staticParams: AstNode | undefined;
637
+ }
638
+
639
+ function collectConfigProperties(object: AstNode): ConfigProperties {
640
+ const propertyValues: unknown[] = Array.isArray(object.properties) ? object.properties : [];
641
+ const all = propertyValues
642
+ .map((property) => asAstNode(property))
643
+ .filter((property): property is AstNode => property !== null);
644
+ const findProperty = (name: string) =>
645
+ all.find((property) => property.type === "Property" && propertyName(property.key) === name);
646
+ return {
647
+ all,
648
+ layout: findProperty("layout"),
649
+ mode: findProperty("mode"),
650
+ params: findProperty("params"),
651
+ query: findProperty("query"),
652
+ revalidate: findProperty("revalidate"),
653
+ staticParams: findProperty("staticParams"),
654
+ };
655
+ }
656
+
657
+ function validateConfigProperties(
658
+ properties: ConfigProperties,
659
+ ctx: FixContext
660
+ ): { inferredMode: InferredRenderingMode | null; layoutValue: AstNode | null } {
661
+ const layoutValue = properties.layout ? asAstNode(properties.layout.value) : null;
662
+ if (!ctx.isRootLayout && properties.layout && layoutValue?.type !== "Identifier") {
663
+ throw routeConfigError(ctx.filePath, "use a static layout route reference");
664
+ }
665
+ const modeValue = properties.mode ? asAstNode(properties.mode.value) : null;
666
+ if (
667
+ properties.revalidate &&
668
+ modeValue?.type === "Literal" &&
669
+ (modeValue.value === "ssg" || modeValue.value === "ssr")
670
+ ) {
671
+ throw routeConfigError(ctx.filePath, "revalidate requires mode isr");
672
+ }
673
+ if (properties.staticParams && modeValue?.type === "Literal" && modeValue.value === "ssr") {
674
+ throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
675
+ }
676
+ if (!properties.revalidate && modeValue?.type === "Literal" && modeValue.value === "isr") {
677
+ throw routeConfigError(ctx.filePath, "isr requires revalidate > 0 (or use ssg/ssr)");
678
+ }
679
+
680
+ const inferredMode = properties.mode
681
+ ? null
682
+ : inferRenderingMode({
683
+ hasLoader: ctx.hasLoader || ctx.ancestorHasLoader,
684
+ hasQuery: Boolean(properties.query) || ctx.ancestorHasQuery,
685
+ hasRevalidate: Boolean(properties.revalidate),
686
+ isRootLayout: ctx.isRootLayout,
687
+ });
688
+ if (properties.staticParams && inferredMode === "ssr") {
689
+ throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
690
+ }
691
+ return { inferredMode, layoutValue };
692
+ }
693
+
694
+ function removeInvalidConfigProperties(
695
+ object: AstNode,
696
+ properties: ConfigProperties,
697
+ inferredMode: InferredRenderingMode | null,
698
+ ctx: FixContext
699
+ ): Set<AstNode> {
700
+ const removed = new Set<AstNode>();
701
+ if (ctx.isRootLayout && properties.layout) {
702
+ removed.add(properties.layout);
703
+ }
704
+ if (properties.revalidate && inferredMode !== null && inferredMode !== "isr") {
705
+ removed.add(properties.revalidate);
706
+ }
707
+ removeObjectProperties(object, properties.all, removed, ctx.magic);
708
+ return removed;
709
+ }
710
+
711
+ function repointLayout(layoutValue: AstNode | null, ctx: FixContext): boolean {
712
+ if (layoutValue?.type === "Identifier" && ctx.expected) {
713
+ const binding = resolveBinding(ctx, Math.max(ctx.lastImportEnd, 0));
714
+ if (
715
+ binding !== layoutValue.name &&
716
+ typeof layoutValue.start === "number" &&
717
+ typeof layoutValue.end === "number"
718
+ ) {
719
+ ctx.magic.update(layoutValue.start, layoutValue.end, binding);
720
+ return true;
721
+ }
722
+ }
723
+ return false;
724
+ }
725
+
726
+ function missingConfigEntries(
727
+ properties: ConfigProperties,
728
+ inferredMode: InferredRenderingMode | null,
729
+ ctx: FixContext
730
+ ): string[] {
731
+ const missing: string[] = [];
732
+ if (!(properties.layout || ctx.isRootLayout) && ctx.expected) {
733
+ const binding = resolveBinding(ctx, Math.max(ctx.lastImportEnd, 0));
734
+ missing.push(`layout: ${binding}`);
735
+ }
736
+ if (!properties.mode) {
737
+ missing.push(`mode: "${inferredMode}"`);
738
+ }
739
+ if (!properties.params && ctx.dynamicParams.length > 0) {
740
+ const typeBoxBinding = ensureTImport(ctx);
741
+ const body = ctx.dynamicParams
742
+ .map((name) => `${paramKey(name)}: ${typeBoxBinding}.String()`)
743
+ .join(", ");
744
+ missing.push(`params: ${typeBoxBinding}.Object({ ${body} })`);
745
+ }
746
+ return missing;
747
+ }
748
+
749
+ /** Dynamic param names derived from the file path segments (`[id]` → id, `[...all]` → "*"). */
750
+ export function dynamicParamsFor(filePath: string, pagesDir: string): string[] {
751
+ const relativePath = withoutExtension(relative(resolve(pagesDir), resolve(filePath)))
752
+ .replaceAll("\\", "/")
753
+ .replace(LEADING_SLASH_RE, "");
754
+ const params = new Set<string>();
755
+ for (const segment of relativePath.split("/")) {
756
+ if (segment.length === 0) {
757
+ continue;
758
+ }
759
+ const dynamic = parseDynamicRouteSegment(segment, filePath);
760
+ if (!dynamic) {
761
+ continue;
762
+ }
763
+ params.add(dynamic.catchAll ? "*" : dynamic.name);
764
+ }
765
+ return [...params];
766
+ }
767
+
768
+ const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
769
+
770
+ const paramKey = (name: string): string => (IDENTIFIER_RE.test(name) ? name : JSON.stringify(name));
771
+
772
+ function ensureTImport(ctx: FixContext): string {
773
+ if (ctx.tBinding) {
774
+ return ctx.tBinding;
775
+ }
776
+ const offset = Math.max(ctx.lastImportEnd, 0);
777
+ let binding = "t";
778
+ let suffix = 2;
779
+ while (ctx.allBindings.has(binding)) {
780
+ binding = `t${suffix}`;
781
+ suffix += 1;
782
+ }
783
+ ctx.magic.appendRight(offset, `\nimport { ${binding} } from "elysia";`);
784
+ ctx.tBinding = binding;
785
+ return binding;
786
+ }
787
+
788
+ function insertConfigEntries(
789
+ object: AstNode,
790
+ entries: string[],
791
+ properties: ConfigProperties,
792
+ removed: Set<AstNode>,
793
+ ctx: FixContext
794
+ ): boolean {
795
+ if (entries.length === 0) {
796
+ return false;
797
+ }
798
+ const first = properties.all.find(
799
+ (property) => !removed.has(property) && typeof property.start === "number"
800
+ );
801
+ if (first && typeof first.start === "number") {
802
+ ctx.magic.appendRight(first.start, `${entries.join(", ")}, `);
803
+ return true;
804
+ }
805
+ if (typeof object.start === "number") {
806
+ ctx.magic.appendRight(object.start + 1, ` ${entries.join(", ")} `);
807
+ return true;
808
+ }
809
+ return false;
810
+ }
811
+
812
+ function injectMissingConfigKeys(object: AstNode, ctx: FixContext): boolean {
813
+ const properties = collectConfigProperties(object);
814
+ const { inferredMode, layoutValue } = validateConfigProperties(properties, ctx);
815
+ const removed = removeInvalidConfigProperties(object, properties, inferredMode, ctx);
816
+ const layoutRepointed = repointLayout(layoutValue, ctx);
817
+ const missing = missingConfigEntries(properties, inferredMode, ctx);
818
+ const entriesInserted = insertConfigEntries(object, missing, properties, removed, ctx);
819
+ return removed.size > 0 || layoutRepointed || entriesInserted;
820
+ }
821
+
822
+ interface RouteFileConvention {
823
+ dynamicParams: string[];
824
+ expected: ExpectedLayout | null;
825
+ fileName: string | undefined;
826
+ filePath: string;
827
+ isNestedLayout: boolean;
828
+ isRootLayout: boolean;
829
+ }
830
+
831
+ function routeFileConvention(
832
+ filePath: string,
833
+ pagesDir: string,
834
+ probe: LayoutProbe
835
+ ): RouteFileConvention {
836
+ const pages = resolve(pagesDir);
837
+ const file = resolve(filePath);
838
+ const extensionlessFile = withoutExtension(file);
839
+ return {
840
+ dynamicParams: dynamicParamsFor(filePath, pagesDir),
841
+ expected: expectedLayoutFor(filePath, pagesDir, probe),
842
+ fileName: extensionlessFile.split(DIRECTORY_SPLIT_RE).pop(),
843
+ filePath,
844
+ isNestedLayout: extensionlessFile === join(resolve(file, ".."), "_route"),
845
+ isRootLayout: extensionlessFile === join(pages, "root"),
846
+ };
847
+ }
848
+
849
+ /** `, params: t.Object({ … })` fragment for scaffolds — empty when no dynamic segment. */
850
+ function scaffoldParamsDeclaration(dynamicParams: string[]): string {
851
+ if (dynamicParams.length === 0) {
852
+ return "";
853
+ }
854
+ const body = dynamicParams.map((name) => `${paramKey(name)}: t.String()`).join(", ");
855
+ return `, params: t.Object({ ${body} })`;
856
+ }
857
+
858
+ function scaffoldEmptyRoute(convention: RouteFileConvention): string | null {
859
+ const { dynamicParams, expected, fileName, filePath, isNestedLayout, isRootLayout } = convention;
860
+ if (isRootLayout) {
861
+ return `import { defineRootRoute, HeadContent, Scripts } from "@teyik0/furin";
862
+
863
+ export const route = defineRootRoute()
864
+ .config({ mode: "ssr" })
865
+ .layout(({ children }) => (
866
+ <html lang="en">
867
+ <head>
868
+ <HeadContent />
869
+ </head>
870
+ <body>
871
+ {children}
872
+ <Scripts />
873
+ </body>
874
+ </html>
875
+ ));
876
+ `;
877
+ }
878
+ if (isNestedLayout && expected) {
879
+ const tImport = dynamicParams.length > 0 ? `\nimport { t } from "elysia"` : "";
880
+ return `import { defineRoute } from "@teyik0/furin";${tImport}
881
+ import { route as ${expected.identifier} } from "${expected.importPath}";
882
+
883
+ export const route = defineRoute()
884
+ .config({ layout: ${expected.identifier}, mode: "ssr"${scaffoldParamsDeclaration(dynamicParams)} })
885
+ .layout(({ children }) => children);
886
+ `;
887
+ }
888
+ if (fileName === "error" || fileName === "not-found") {
889
+ return null;
890
+ }
891
+ if (!expected) {
892
+ throw routeConfigError(filePath, "no ancestor layout found; create pages/root.tsx");
893
+ }
894
+ const tImport = dynamicParams.length > 0 ? `\nimport { t } from "elysia"` : "";
895
+ return `import { defineRoute } from "@teyik0/furin";${tImport}
896
+ import { route as ${expected.identifier} } from "${expected.importPath}";
897
+
898
+ export const route = defineRoute()
899
+ .config({ layout: ${expected.identifier}, mode: "ssg"${scaffoldParamsDeclaration(dynamicParams)} })
900
+ .page(() => null);
901
+ `;
902
+ }
903
+
904
+ function validateRouteChain(heads: ChainHead[], convention: RouteFileConvention): ChainHead | null {
905
+ if (heads.length === 0) {
906
+ return null;
907
+ }
908
+ if (heads.length > 1) {
909
+ throw routeConfigError(convention.filePath, "one route per file");
910
+ }
911
+ const [routeHead] = heads;
912
+ if (!routeHead) {
913
+ return null;
914
+ }
915
+ if (!convention.isRootLayout && routeHead.isRoot) {
916
+ throw routeConfigError(
917
+ convention.filePath,
918
+ "use defineRoute + config({ layout }) outside pages/root.tsx"
919
+ );
920
+ }
921
+ if (!(convention.isRootLayout || convention.expected)) {
922
+ throw routeConfigError(convention.filePath, "no ancestor layout found; create pages/root.tsx");
923
+ }
924
+ if ((convention.isRootLayout || convention.isNestedLayout) && routeHead.terminal === "page") {
925
+ throw routeConfigError(convention.filePath, "layout files must end with .layout()");
926
+ }
927
+ if (!(convention.isRootLayout || convention.isNestedLayout) && routeHead.terminal !== "page") {
928
+ throw routeConfigError(convention.filePath, "page files must end with .page()");
929
+ }
930
+ if (!routeHead.exportedAsRoute) {
931
+ throw routeConfigError(
932
+ convention.filePath,
933
+ "route files must export a route terminal as export const route"
934
+ );
935
+ }
936
+ return routeHead;
937
+ }
938
+
939
+ function rewriteRootBuilder(
940
+ routeHead: ChainHead,
941
+ bindings: BuilderBindings,
942
+ isRootLayout: boolean,
943
+ magic: MagicString
944
+ ): boolean {
945
+ if (!(isRootLayout && !routeHead.isRoot)) {
946
+ return false;
947
+ }
948
+ const existingRootBinding = bindings.rootBindings.values().next().value as string | undefined;
949
+ const replacement = existingRootBinding ?? "defineRootRoute";
950
+ if (!existingRootBinding) {
951
+ const specifier = bindings.routeSpecifiers.get(routeHead.binding);
952
+ if (specifier) {
953
+ magic.update(specifier.start, specifier.end, "defineRootRoute");
954
+ }
955
+ }
956
+ magic.update(routeHead.start, routeHead.builderEnd, replacement);
957
+ return true;
958
+ }
959
+
960
+ function insertCompleteConfig(routeHead: ChainHead, ctx: FixContext): void {
961
+ const binding =
962
+ ctx.expected && !ctx.isRootLayout ? resolveBinding(ctx, Math.max(ctx.lastImportEnd, 0)) : null;
963
+ const entries: string[] = [];
964
+ if (binding && !ctx.isRootLayout) {
965
+ entries.push(`layout: ${binding}`);
966
+ }
967
+ const mode = inferRenderingMode({
968
+ hasLoader: ctx.hasLoader || ctx.ancestorHasLoader,
969
+ hasQuery: ctx.ancestorHasQuery,
970
+ hasRevalidate: false,
971
+ isRootLayout: ctx.isRootLayout,
972
+ });
973
+ entries.push(`mode: "${mode}"`);
974
+ if (ctx.dynamicParams.length > 0) {
975
+ const typeBoxBinding = ensureTImport(ctx);
976
+ const params = ctx.dynamicParams
977
+ .map((name) => `${paramKey(name)}: ${typeBoxBinding}.String()`)
978
+ .join(", ");
979
+ entries.push(`params: ${typeBoxBinding}.Object({ ${params} })`);
980
+ }
981
+ ctx.magic.appendRight(routeHead.end, `.config({ ${entries.join(", ")} })`);
982
+ }
983
+
984
+ function insertMissingLayoutTerminal(
985
+ routeHead: ChainHead,
986
+ bindings: BuilderBindings,
987
+ convention: RouteFileConvention,
988
+ magic: MagicString
989
+ ): boolean {
990
+ if (!(convention.isRootLayout || convention.isNestedLayout) || routeHead.terminal === "layout") {
991
+ return false;
992
+ }
993
+ if (convention.isRootLayout) {
994
+ prependMissingDocumentImports(bindings, magic);
995
+ }
996
+ const layout = convention.isRootLayout
997
+ ? '(\n <html lang="en">\n <head>\n <HeadContent />\n </head>\n <body>\n {children}\n <Scripts />\n </body>\n </html>\n )'
998
+ : "children";
999
+ magic.appendRight(routeHead.chainEnd, `.layout(({ children }) => ${layout})`);
1000
+ return true;
1001
+ }
1002
+
1003
+ function legacyRootLayoutBody(node: unknown): AstNode | null {
1004
+ const callback = asAstNode(node);
1005
+ if (callback?.type !== "ArrowFunctionExpression") {
1006
+ return null;
1007
+ }
1008
+ const params = Array.isArray(callback.params) ? callback.params : [];
1009
+ const pattern = asAstNode(params[0]);
1010
+ const properties = Array.isArray(pattern?.properties) ? pattern.properties : [];
1011
+ const property = properties.length === 1 ? asAstNode(properties[0]) : null;
1012
+ const value = asAstNode(property?.value);
1013
+ const body = asAstNode(callback.body);
1014
+ if (
1015
+ pattern?.type !== "ObjectPattern" ||
1016
+ property?.type !== "Property" ||
1017
+ propertyName(property.key) !== "children" ||
1018
+ value?.type !== "Identifier" ||
1019
+ value.name !== "children" ||
1020
+ body?.type !== "Identifier" ||
1021
+ body.name !== "children"
1022
+ ) {
1023
+ return null;
1024
+ }
1025
+ return body;
1026
+ }
1027
+
1028
+ function rewriteLegacyRootLayout(
1029
+ program: Program,
1030
+ bindings: BuilderBindings,
1031
+ convention: RouteFileConvention,
1032
+ magic: MagicString
1033
+ ): boolean {
1034
+ if (!convention.isRootLayout) {
1035
+ return false;
1036
+ }
1037
+ let touched = false;
1038
+ walk(program as never, {
1039
+ CallExpression(call) {
1040
+ const callee = asAstNode(call.callee);
1041
+ if (callee?.type !== "MemberExpression" || !belongsToBuilderChain(callee.object, bindings)) {
1042
+ return;
1043
+ }
1044
+ const property = asAstNode(callee.property);
1045
+ if (property?.type !== "Identifier" || property.name !== "layout") {
1046
+ return;
1047
+ }
1048
+ const argument = Array.isArray(call.arguments) ? call.arguments[0] : null;
1049
+ const body = legacyRootLayoutBody(argument);
1050
+ if (typeof body?.start === "number" && typeof body.end === "number") {
1051
+ prependMissingDocumentImports(bindings, magic);
1052
+ magic.update(
1053
+ body.start,
1054
+ body.end,
1055
+ '(\n <html lang="en">\n <head>\n <HeadContent />\n </head>\n <body>\n {children}\n <Scripts />\n </body>\n </html>\n )'
1056
+ );
1057
+ touched = true;
1058
+ }
1059
+ },
1060
+ });
1061
+ return touched;
1062
+ }
1063
+
1064
+ /**
1065
+ * Rewrites `defineRoute()` chains so every route file declares a full
1066
+ * `config({ layout, mode, ... })`:
1067
+ * - chain without `config()` → inserts `.config({ layout, mode })`
1068
+ * - `config()` without `layout` → injects the expected ancestor layout
1069
+ * - `config()` with a WRONG layout → repoints the reference (and its import)
1070
+ * - `config()` without `mode` → infers the mode using the runtime cascade
1071
+ * - layout file without `layout()` → appends an identity layout terminal
1072
+ * The root layout (`pages/root.tsx`, built with `defineRootRoute()`) never
1073
+ * receives a parent `layout` config entry. Returns the new source, or null when unchanged
1074
+ * (idempotent — running the fix twice returns null on the second pass).
1075
+ */
1076
+ export function fixRouteConfigLayout(
1077
+ source: string,
1078
+ filePath: string,
1079
+ pagesDir: string,
1080
+ probe: LayoutProbe = existsSync
1081
+ ): string | null {
1082
+ const convention = routeFileConvention(filePath, pagesDir, probe);
1083
+ if (source.trim().length === 0) {
1084
+ return scaffoldEmptyRoute(convention);
1085
+ }
1086
+ if (!(source.includes("defineRoute") || source.includes("defineRootRoute"))) {
1087
+ return null;
1088
+ }
1089
+ const parsed = parseSource(source, detectLangFromPath(filePath));
1090
+ const magic = new MagicString(source);
1091
+ const expectedResolvedPath = convention.expected
1092
+ ? withoutExtension(resolve(filePath, "..", convention.expected.importPath))
1093
+ : "";
1094
+ const { imports, lastImportEnd, allBindings, tBinding } = collectLayoutImports(
1095
+ parsed.program,
1096
+ filePath
1097
+ );
1098
+ const bindings = collectBuilderBindings(parsed.program);
1099
+ const hasLoader = builderChainHasMethod(parsed.program, bindings, "loader");
1100
+ const heads = collectChainHeads(parsed.program, bindings).filter(
1101
+ (candidate) => candidate.end !== 0
1102
+ );
1103
+ const routeHead = validateRouteChain(heads, convention);
1104
+ if (!routeHead) {
1105
+ return null;
1106
+ }
1107
+ let touched = rewriteRootBuilder(routeHead, bindings, convention.isRootLayout, magic);
1108
+ const configObjects = collectConfigObjects(parsed.program, bindings);
1109
+ const ancestorRequirements = ancestorRenderingRequirements(filePath, pagesDir, probe);
1110
+ const ctx: FixContext = {
1111
+ allBindings,
1112
+ ancestorHasLoader: ancestorRequirements.hasLoader,
1113
+ ancestorHasQuery: ancestorRequirements.hasQuery,
1114
+ dynamicParams: dynamicParamsFor(filePath, pagesDir),
1115
+ expected: convention.expected,
1116
+ expectedResolvedPath,
1117
+ filePath,
1118
+ hasLoader,
1119
+ imports,
1120
+ isRootLayout: convention.isRootLayout,
1121
+ lastImportEnd,
1122
+ magic,
1123
+ source,
1124
+ tBinding,
1125
+ };
1126
+ if (configObjects.length === 0) {
1127
+ insertCompleteConfig(routeHead, ctx);
1128
+ touched = true;
1129
+ }
1130
+ for (const object of configObjects) {
1131
+ touched = injectMissingConfigKeys(object, ctx) || touched;
1132
+ }
1133
+ touched = insertMissingLayoutTerminal(routeHead, bindings, convention, magic) || touched;
1134
+ touched = rewriteLegacyRootLayout(parsed.program, bindings, convention, magic) || touched;
1135
+
1136
+ const output = magic.toString();
1137
+ // Structural idempotence: a rewrite that produces the exact input is no
1138
+ // change at all (protects every future branch from breaking the contract).
1139
+ return output === source ? null : output;
1140
+ }