@teyik0/furin 0.1.0-alpha.8 → 0.2.0-alpha.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/dist/adapter/bun.d.ts +2 -2
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +2 -16
  7. package/dist/build/compile-entry.ts +109 -0
  8. package/dist/build/entry-template.d.ts +24 -0
  9. package/dist/build/entry-template.ts +156 -0
  10. package/dist/build/hydrate.d.ts +3 -3
  11. package/dist/build/index.d.ts +1 -0
  12. package/dist/build/index.js +4734 -548
  13. package/dist/build/route-types.d.ts +1 -1
  14. package/dist/build/server-routes-entry.d.ts +2 -12
  15. package/dist/build/server-routes-entry.ts +36 -0
  16. package/dist/build/shared.d.ts +1 -1
  17. package/dist/build/ssg-cache.d.ts +4 -0
  18. package/dist/build/types.d.ts +5 -1
  19. package/dist/cli/index.js +4713 -549
  20. package/dist/client/boundaries.d.ts +117 -0
  21. package/dist/client/default-screens.d.ts +17 -0
  22. package/dist/client/link.d.ts +22 -0
  23. package/dist/client/link.js +3450 -0
  24. package/dist/client/router/boundary-tree.d.ts +26 -0
  25. package/dist/client/router/context.d.ts +8 -0
  26. package/dist/client/router/history.d.ts +9 -0
  27. package/dist/client/router/index.d.ts +7 -0
  28. package/dist/client/router/link-utils.d.ts +51 -0
  29. package/dist/client/router/provider.d.ts +4 -0
  30. package/dist/client/router/spa-response.d.ts +58 -0
  31. package/dist/{link.d.ts → client/router/types.d.ts} +114 -80
  32. package/dist/client/server-error.d.ts +12 -0
  33. package/dist/client.d.ts +54 -4
  34. package/dist/client.js +77 -1
  35. package/dist/config.d.ts +12 -2
  36. package/dist/config.js +1 -0
  37. package/dist/env.d.ts +50 -0
  38. package/dist/furin.d.ts +37 -2
  39. package/dist/furin.js +5288 -601
  40. package/dist/plugin/index.js +140 -48
  41. package/dist/plugin/transform-client.d.ts +2 -1
  42. package/dist/server/auto-invalidate/index.d.ts +4 -0
  43. package/dist/server/auto-invalidate/plugin.d.ts +38 -0
  44. package/dist/server/auto-invalidate/registry.d.ts +9 -0
  45. package/dist/server/auto-invalidate/runtime.d.ts +9 -0
  46. package/dist/server/auto-invalidate/types.d.ts +12 -0
  47. package/dist/server/cache/dev-loader.d.ts +28 -0
  48. package/dist/server/cache/index.d.ts +10 -0
  49. package/dist/server/cache/invalidation.d.ts +12 -0
  50. package/dist/server/cache/isr-ssg.d.ts +26 -0
  51. package/dist/server/cache/isr.d.ts +6 -0
  52. package/dist/server/cache/registry.d.ts +5 -0
  53. package/dist/server/cache/route-cache.d.ts +26 -0
  54. package/dist/server/cache/ssg.d.ts +5 -0
  55. package/dist/server/context-logger.d.ts +28 -0
  56. package/dist/server/dev-inspector.d.ts +89 -0
  57. package/dist/{internal.d.ts → server/internal.d.ts} +16 -0
  58. package/dist/server/internal.js +17 -0
  59. package/dist/server/lang-detect.d.ts +5 -0
  60. package/dist/server/render/assemble.d.ts +47 -0
  61. package/dist/server/render/element.d.ts +24 -0
  62. package/dist/server/render/index.d.ts +7 -0
  63. package/dist/server/render/index.ts +22 -0
  64. package/dist/server/render/isr.d.ts +3 -0
  65. package/dist/server/render/loaders.d.ts +64 -0
  66. package/dist/server/render/not-found.d.ts +6 -0
  67. package/dist/{render → server/render}/shell.d.ts +17 -4
  68. package/{src → dist/server}/render/shell.ts +31 -9
  69. package/dist/server/render/ssg.d.ts +8 -0
  70. package/dist/server/render/ssr.d.ts +107 -0
  71. package/dist/server/router/discovery.d.ts +16 -0
  72. package/dist/server/router/hmr.d.ts +64 -0
  73. package/dist/server/router/index.d.ts +6 -0
  74. package/dist/server/router/index.js +28 -0
  75. package/dist/server/router/index.ts +29 -0
  76. package/dist/server/router/patterns.d.ts +40 -0
  77. package/dist/server/router/plugin.d.ts +20 -0
  78. package/dist/server/router/schemas.d.ts +51 -0
  79. package/dist/server/router/types.d.ts +60 -0
  80. package/dist/server/runtime-env.js +10 -0
  81. package/dist/shared/await.d.ts +67 -0
  82. package/dist/shared/deferred-ndjson.d.ts +32 -0
  83. package/dist/shared/digest.d.ts +16 -0
  84. package/dist/shared/error.d.ts +37 -0
  85. package/dist/shared/not-found.d.ts +19 -0
  86. package/dist/shared/utils/ast-walk.d.ts +18 -0
  87. package/dist/shared/utils/index.d.ts +13 -0
  88. package/package.json +56 -25
  89. package/src/adapter/bun.ts +90 -41
  90. package/src/adapter/static.ts +83 -36
  91. package/src/build/client.ts +8 -12
  92. package/src/build/compile-entry.ts +20 -14
  93. package/src/build/entry-template.ts +90 -8
  94. package/src/build/hydrate.ts +213 -36
  95. package/src/build/index.ts +10 -9
  96. package/src/build/route-types.ts +30 -4
  97. package/src/build/scan-server.ts +52 -67
  98. package/src/build/server-routes-entry.ts +7 -11
  99. package/src/build/shared.ts +1 -1
  100. package/src/build/ssg-cache.ts +31 -0
  101. package/src/build/types.ts +5 -1
  102. package/src/cli/index.ts +1 -0
  103. package/src/client/boundaries.tsx +259 -0
  104. package/src/client/default-screens.tsx +304 -0
  105. package/src/client/link.tsx +338 -0
  106. package/src/client/router/boundary-tree.tsx +116 -0
  107. package/src/client/router/context.ts +38 -0
  108. package/src/client/router/history.ts +41 -0
  109. package/src/client/router/index.ts +47 -0
  110. package/src/client/router/link-utils.ts +180 -0
  111. package/src/client/router/provider.tsx +723 -0
  112. package/src/client/router/spa-response.ts +143 -0
  113. package/src/client/router/types.ts +263 -0
  114. package/src/client/server-error.ts +47 -0
  115. package/src/client.ts +83 -3
  116. package/src/config.ts +11 -3
  117. package/src/env.d.ts +1 -0
  118. package/src/furin.ts +104 -26
  119. package/src/plugin/index.ts +7 -8
  120. package/src/plugin/transform-client.ts +146 -120
  121. package/src/server/auto-invalidate/index.ts +10 -0
  122. package/src/server/auto-invalidate/plugin.ts +25 -0
  123. package/src/server/auto-invalidate/registry.ts +60 -0
  124. package/src/server/auto-invalidate/runtime.ts +133 -0
  125. package/src/server/auto-invalidate/types.ts +16 -0
  126. package/src/server/cache/dev-loader.ts +211 -0
  127. package/src/server/cache/index.ts +34 -0
  128. package/src/server/cache/invalidation.ts +111 -0
  129. package/src/server/cache/isr-ssg.ts +41 -0
  130. package/src/server/cache/isr.ts +17 -0
  131. package/src/server/cache/registry.ts +35 -0
  132. package/src/server/cache/route-cache.ts +124 -0
  133. package/src/server/cache/ssg.ts +15 -0
  134. package/src/server/context-logger.ts +76 -0
  135. package/src/server/dev-inspector.ts +60 -0
  136. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  137. package/src/{internal.ts → server/internal.ts} +17 -0
  138. package/src/server/lang-detect.ts +46 -0
  139. package/src/server/render/assemble.ts +133 -0
  140. package/src/server/render/element.tsx +113 -0
  141. package/src/server/render/index.ts +22 -0
  142. package/src/server/render/isr.ts +295 -0
  143. package/src/server/render/loaders.ts +328 -0
  144. package/src/server/render/not-found.ts +96 -0
  145. package/src/server/render/shell.ts +202 -0
  146. package/src/server/render/ssg.ts +137 -0
  147. package/src/server/render/ssr.ts +545 -0
  148. package/src/server/router/discovery.ts +474 -0
  149. package/src/server/router/hmr.ts +372 -0
  150. package/src/server/router/index.ts +29 -0
  151. package/src/server/router/patterns.ts +214 -0
  152. package/src/server/router/plugin.ts +401 -0
  153. package/src/server/router/schemas.ts +163 -0
  154. package/src/server/router/types.ts +59 -0
  155. package/src/shared/await.tsx +192 -0
  156. package/src/shared/deferred-ndjson.ts +244 -0
  157. package/src/shared/digest.ts +71 -0
  158. package/src/shared/error.ts +49 -0
  159. package/src/shared/not-found.ts +40 -0
  160. package/src/shared/utils/ast-walk.ts +51 -0
  161. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  162. package/dist/link.js +0 -1173
  163. package/dist/render/assemble.d.ts +0 -13
  164. package/dist/render/cache.d.ts +0 -95
  165. package/dist/render/element.d.ts +0 -4
  166. package/dist/render/index.d.ts +0 -27
  167. package/dist/render/loaders.d.ts +0 -12
  168. package/dist/router.d.ts +0 -34
  169. package/dist/router.js +0 -830
  170. package/dist/utils.d.ts +0 -6
  171. package/src/link.tsx +0 -1035
  172. package/src/render/assemble.ts +0 -64
  173. package/src/render/cache.ts +0 -241
  174. package/src/render/element.tsx +0 -28
  175. package/src/render/index.ts +0 -479
  176. package/src/render/loaders.ts +0 -113
  177. package/src/router.ts +0 -400
  178. /package/dist/{dev-page-plugin.d.ts → server/dev-page-plugin.d.ts} +0 -0
  179. /package/dist/{render → server/render}/template.d.ts +0 -0
  180. /package/dist/{runtime-env.d.ts → server/runtime-env.d.ts} +0 -0
  181. /package/src/{render → server/render}/template.ts +0 -0
  182. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,372 @@
1
+ import { existsSync } from "node:fs";
2
+ import type { Context } from "elysia";
3
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
4
+ import { collectRouteChainFromRoute, isFurinPage, isFurinRoute } from "../../shared/utils/index.ts";
5
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
6
+ import {
7
+ type DevLoaderCacheEntry,
8
+ getDevISRLoaderCache,
9
+ getDevSSGLoaderCache,
10
+ isDevLoaderCacheValid,
11
+ setDevISRLoaderCache,
12
+ setDevSSGLoaderCache,
13
+ } from "../cache/dev-loader.ts";
14
+ import { type CompileContext, getCompileContext } from "../internal.ts";
15
+ import { resolvePath } from "../render/assemble.ts";
16
+ import { type LoaderResult, renderSSR, runLoaders } from "../render/index.ts";
17
+ import { collectRouteTags, getSourceModuleCandidates, isModuleNotFoundError } from "./discovery.ts";
18
+ import { collectIntermediateLayoutDirs, resolveMode } from "./patterns.ts";
19
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
20
+
21
+ type RouteModuleImport = (specifier: string) => Promise<Record<string, unknown>>;
22
+
23
+ function isResolvedRouteModuleCandidate(
24
+ layoutPath: string,
25
+ imported: Record<string, unknown>,
26
+ ctx: CompileContext | null
27
+ ): boolean {
28
+ if (existsSync(layoutPath) || ctx?.modules[layoutPath]) {
29
+ return true;
30
+ }
31
+
32
+ return Object.keys(imported).length > 0;
33
+ }
34
+
35
+ export async function importFreshRouteModuleCandidate(
36
+ layoutPath: string,
37
+ timestamp: number,
38
+ resolveImport: RouteModuleImport,
39
+ ctx: CompileContext | null
40
+ ): Promise<Record<string, unknown> | undefined> {
41
+ try {
42
+ const imported = await resolveImport(`${layoutPath}?furin-server&t=${timestamp}`);
43
+ if (!isResolvedRouteModuleCandidate(layoutPath, imported, ctx)) {
44
+ return;
45
+ }
46
+
47
+ return imported;
48
+ } catch (err) {
49
+ // Distinguish "this layout file does not exist" (legitimate skip) from
50
+ // "this layout file's transitive imports failed" (real bug to surface).
51
+ // If the layoutPath itself is on disk or registered in the compile ctx,
52
+ // a ModuleNotFoundError must come from a sub-import — re-throw it so
53
+ // the developer sees the actual broken import instead of a silently
54
+ // ignored layout chain.
55
+ const layoutFileIsKnown = existsSync(layoutPath) || Boolean(ctx?.modules[layoutPath]);
56
+ if (!layoutFileIsKnown && isModuleNotFoundError(err)) {
57
+ return;
58
+ }
59
+ throw err;
60
+ }
61
+ }
62
+
63
+ async function importFreshLayoutRouteModule(
64
+ layoutDir: string,
65
+ timestamp: number,
66
+ resolveImport: RouteModuleImport,
67
+ ctx: CompileContext | null
68
+ ): Promise<Record<string, unknown> | undefined> {
69
+ for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
70
+ const freshMod = await importFreshRouteModuleCandidate(
71
+ layoutPath,
72
+ timestamp,
73
+ resolveImport,
74
+ ctx
75
+ );
76
+ if (freshMod) {
77
+ return freshMod;
78
+ }
79
+ }
80
+
81
+ return;
82
+ }
83
+
84
+ function patchRouteEntryFromFreshModule(
85
+ entry: RuntimeRoute | undefined,
86
+ freshMod: Record<string, unknown>
87
+ ): void {
88
+ const freshRoute = freshMod.route ?? freshMod.default;
89
+ if (!(entry && freshRoute && isFurinRoute(freshRoute))) {
90
+ return;
91
+ }
92
+
93
+ entry.layout = freshRoute.layout;
94
+ entry.loader = freshRoute.loader;
95
+ }
96
+
97
+ /**
98
+ * Re-imports intermediate layout _route.tsx files with cache-busting so that
99
+ * server-side renders reflect the latest code after an HMR edit. Bun's ESM
100
+ * cache keeps the original module alive, so we import via ?furin-server and
101
+ * patch the layout/loader references on the existing route-chain objects.
102
+ *
103
+ * The optional `importFn` parameter exists only for unit testing. In production
104
+ * it defaults to the real `import()`.
105
+ */
106
+ export async function refreshLayoutChain(
107
+ chain: RuntimeRoute[],
108
+ pagePath: string,
109
+ rootPath: string,
110
+ importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined
111
+ ): Promise<void> {
112
+ const resolveImport: RouteModuleImport =
113
+ importFn ?? ((s: string) => import(s) as Promise<Record<string, unknown>>);
114
+ const ctx = getCompileContext();
115
+ const timestamp = Date.now();
116
+ const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
117
+
118
+ // Track chainIdx independently rather than deriving it from layoutPaths
119
+ // index. Directories without a _route module produce import errors that are
120
+ // silently skipped, but those directories have no corresponding chain entry —
121
+ // so we must only advance chainIdx for directories whose _route module actually
122
+ // exists. A positional assumption (i = chainIdx - 1) drifts whenever
123
+ // isModuleNotFoundError is swallowed for a gap directory.
124
+ //
125
+ // Imports are parallelised for speed; patching stays sequential so the
126
+ // chainIdx-to-layoutDir positional mapping remains deterministic.
127
+ const freshMods = await Promise.all(
128
+ layoutDirs.map((layoutDir) =>
129
+ importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)
130
+ )
131
+ );
132
+ let chainIdx = 1; // chain[0] is the root
133
+ for (const freshMod of freshMods) {
134
+ if (chainIdx >= chain.length) {
135
+ break;
136
+ }
137
+ if (!freshMod) {
138
+ // No _route module in this directory — no chain entry to match, so
139
+ // do NOT advance chainIdx. The next deeper layoutDir may correspond
140
+ // to the current chainIdx.
141
+ continue;
142
+ }
143
+
144
+ patchRouteEntryFromFreshModule(chain[chainIdx], freshMod);
145
+ // An _route module exists at this depth — advance chainIdx regardless of
146
+ // whether the export is currently a valid route (the chain entry was
147
+ // populated by the initial import and should be revisited on the next
148
+ // successful HMR cycle).
149
+ chainIdx++;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
155
+ * `mode` reflects the CURRENT contents of the page module — not the value
156
+ * captured at scan time.
157
+ *
158
+ * In dev, `handleDevRequest` re-imports the page on every request to pick up
159
+ * source edits via the `?furin-server&t=<ts>` cache-buster. Without this
160
+ * function the spread `{ ...route, page, chain }` would carry over the stale
161
+ * `route.mode` resolved at startup, so toggling `revalidate` or removing a
162
+ * loader in source would not retake effect until a server restart.
163
+ *
164
+ * Only `mode` is recomputed: it is the only field DERIVED from page+chain.
165
+ * Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
166
+ * `notFound`) are scan-time invariants in dev and are preserved as-is.
167
+ */
168
+ export function rebuildDevRoute(
169
+ base: ResolvedRoute,
170
+ page: RuntimePage,
171
+ chain: RuntimeRoute[]
172
+ ): ResolvedRoute {
173
+ return {
174
+ ...base,
175
+ page,
176
+ routeChain: chain,
177
+ mode: resolveMode(page, chain),
178
+ tags: collectRouteTags(chain, page),
179
+ };
180
+ }
181
+
182
+ /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
183
+ export async function handleDevRequest(
184
+ route: ResolvedRoute,
185
+ ctx: Context,
186
+ root: RootLayout
187
+ ): Promise<unknown> {
188
+ // Load the page via ?furin-server virtual namespace so it stays out of
189
+ // --hot's file watcher, then hand off to renderSSR which runs loaders,
190
+ // renders React to HTML, and injects __FURIN_DATA__.
191
+ try {
192
+ let currentRoot = root;
193
+ const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
194
+ string,
195
+ unknown
196
+ >;
197
+ const rootExport = rootMod.route ?? rootMod.default;
198
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
199
+ // Preserve the RootLayout-level convention fields (error, notFound,
200
+ // errorPath, notFoundPath) populated by `scanRootLayout` from
201
+ // `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
202
+ // RootLayout with just `{ path, route }` would silently drop these
203
+ // fallbacks — `route.error ?? root.error` would resolve to `undefined`
204
+ // in dev after the first request, making custom 404/500 screens
205
+ // disappear after a HMR refresh.
206
+ currentRoot = { ...currentRoot, route: rootExport };
207
+ }
208
+
209
+ const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
210
+ const page = pageMod.default;
211
+ if (page && isFurinPage(page)) {
212
+ const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
213
+ await refreshLayoutChain(chain, route.path, root.path, undefined);
214
+
215
+ // Patch chain[0] (the root) with the freshly-imported root's loader
216
+ // and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
217
+ // because the root is already loaded separately above; without this
218
+ // patch, chain[0] points to whatever object `_route.parent` captured
219
+ // at _route's first evaluation — a STALE reference if Bun --hot
220
+ // re-evaluated root.tsx without propagating the re-evaluation to
221
+ // _route.tsx (the standard ESM behaviour). Mirroring the pattern
222
+ // used by patchRouteEntryFromFreshModule.
223
+ if (chain[0] && currentRoot.route) {
224
+ chain[0].layout = currentRoot.route.layout;
225
+ chain[0].loader = currentRoot.route.loader;
226
+ }
227
+
228
+ const refreshedRoute = rebuildDevRoute(route, page, chain);
229
+
230
+ // Live ISR — the loader chain is short-circuited by the dev cache when
231
+ // a fresh entry exists. HTML re-assembles every time so the dev shell
232
+ // chunk URL is always current.
233
+ if (refreshedRoute.mode === "isr") {
234
+ return renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot);
235
+ }
236
+
237
+ // Live SSG — same trick as Live ISR, but the cache entry is forever-fresh
238
+ // (revalidate: Infinity) so the loader runs ONCE per cache key until a
239
+ // source file in its dependency chain changes. This matches production
240
+ // SSG semantics ("loader runs once") in dev, instead of re-running the
241
+ // loader on every refresh — which would make expensive loaders (DB
242
+ // queries, MDX parsing, sitemap reads) painful in dev.
243
+ if (refreshedRoute.mode === "ssg") {
244
+ return renderDevSSGWithLoaderCache(refreshedRoute, ctx, currentRoot);
245
+ }
246
+
247
+ return renderSSR(refreshedRoute, ctx, currentRoot, undefined);
248
+ }
249
+ } catch (err) {
250
+ console.error(`[furin] Dev page load error for ${route.path}:`, err);
251
+ }
252
+ // Fallback: page couldn't load — return a clear error response rather than
253
+ // delegating to renderSSR with an undefined page.
254
+ return new Response(
255
+ `<!doctype html><html><body><h1>Page load error</h1><p>Could not load ${route.path}. Check the server console for details.</p></body></html>`,
256
+ { status: 500, headers: { "Content-Type": "text/html; charset=utf-8" } }
257
+ );
258
+ }
259
+
260
+ /**
261
+ * @internal Dev "Live ISR" — caches loader output, not assembled HTML. On a
262
+ * fresh cache hit the loader chain is skipped; the React render still runs so
263
+ * the response embeds the latest dev shell (chunk URL, HMR runtime, …). On
264
+ * miss, runs loaders normally and stores the merged data record.
265
+ */
266
+ export async function renderDevISRWithLoaderCache(
267
+ route: ResolvedRoute,
268
+ ctx: Context,
269
+ root: RootLayout
270
+ ): Promise<Response> {
271
+ const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
272
+ const cached = getDevISRLoaderCache(cacheKey);
273
+
274
+ if (cached && isDevLoaderCacheValid(cached)) {
275
+ const precomputed: LoaderResult = {
276
+ type: "data",
277
+ syncData: cached.loaderData,
278
+ deferredPromises: undefined,
279
+ headers: cached.headers,
280
+ };
281
+ return renderSSR(route, ctx, root, precomputed);
282
+ }
283
+
284
+ const result = await runLoaders(route, ctx);
285
+ if (result.type === "data") {
286
+ const revalidate = route.page._route.revalidate ?? 60;
287
+ const entry: DevLoaderCacheEntry = {
288
+ dependencies: computeRouteDependencies(route.path, root.path),
289
+ generatedAt: Date.now(),
290
+ headers: result.headers,
291
+ loaderData: result.syncData,
292
+ mode: "isr",
293
+ revalidate,
294
+ };
295
+ setDevISRLoaderCache(cacheKey, entry);
296
+ autoInvalidateRegistry.registerLoaderTags(
297
+ resolvePath(route.pattern, ctx.params ?? {}),
298
+ route.tags
299
+ );
300
+ }
301
+ return renderSSR(route, ctx, root, result);
302
+ }
303
+
304
+ /**
305
+ * @internal Dev "Live SSG" — same shape as `renderDevISRWithLoaderCache`, but
306
+ * the cached entry is tagged forever-fresh (`revalidate: Infinity`) so it
307
+ * survives indefinitely until source-aware invalidation drops it. This makes
308
+ * dev SSG behave like production SSG: the loader runs ONCE per cache key,
309
+ * not on every refresh.
310
+ */
311
+ export async function renderDevSSGWithLoaderCache(
312
+ route: ResolvedRoute,
313
+ ctx: Context,
314
+ root: RootLayout
315
+ ): Promise<Response> {
316
+ const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
317
+ const cached = getDevSSGLoaderCache(cacheKey);
318
+
319
+ if (cached && isDevLoaderCacheValid(cached)) {
320
+ const precomputed: LoaderResult = {
321
+ type: "data",
322
+ syncData: cached.loaderData,
323
+ deferredPromises: undefined,
324
+ headers: cached.headers,
325
+ };
326
+ return renderSSR(route, ctx, root, precomputed);
327
+ }
328
+
329
+ const result = await runLoaders(route, ctx);
330
+ if (result.type === "data") {
331
+ const entry: DevLoaderCacheEntry = {
332
+ dependencies: computeRouteDependencies(route.path, root.path),
333
+ generatedAt: Date.now(),
334
+ headers: result.headers,
335
+ loaderData: result.syncData,
336
+ mode: "ssg",
337
+ // SSG entries are forever-fresh — only source-aware invalidation drops them.
338
+ revalidate: Number.POSITIVE_INFINITY,
339
+ };
340
+ setDevSSGLoaderCache(cacheKey, entry);
341
+ autoInvalidateRegistry.registerLoaderTags(
342
+ resolvePath(route.pattern, ctx.params ?? {}),
343
+ route.tags
344
+ );
345
+ }
346
+ return renderSSR(route, ctx, root, result);
347
+ }
348
+
349
+ /**
350
+ * @internal Lists every source file whose contents can affect the render
351
+ * output for a given page: the page itself, every intermediate `_route.*`
352
+ * between the page and the pages root, and `root.tsx`.
353
+ *
354
+ * Only paths that EXIST on disk are returned. `isDevLoaderCacheValid` treats
355
+ * a `statSync` throw as "invalid" (conservative on missing files), so listing
356
+ * non-authored extension candidates here would force a permanent cache MISS
357
+ * for every nested route — silently disabling the dev ISR/SSG cache for any
358
+ * page in a subdirectory. Renames and deletions of TRACKED deps are still
359
+ * detected: the path that previously existed will then `statSync`-throw on
360
+ * the next read and yield the same conservative miss.
361
+ */
362
+ export function computeRouteDependencies(pagePath: string, rootPath: string): string[] {
363
+ const deps = [pagePath, rootPath];
364
+ for (const dir of collectIntermediateLayoutDirs(pagePath, rootPath)) {
365
+ for (const candidate of getSourceModuleCandidates(dir, "_route")) {
366
+ if (existsSync(candidate)) {
367
+ deps.push(candidate);
368
+ }
369
+ }
370
+ }
371
+ return deps;
372
+ }
@@ -0,0 +1,29 @@
1
+ // biome-ignore-all lint/performance/noBarrelFile: server/router barrel is the public surface of the routing module
2
+ export { collectRouteTags, loadProdRoutes, scanPages, scanRootLayout } from "./discovery.ts";
3
+ export {
4
+ computeRouteDependencies,
5
+ importFreshRouteModuleCandidate,
6
+ rebuildDevRoute,
7
+ refreshLayoutChain,
8
+ renderDevISRWithLoaderCache,
9
+ renderDevSSGWithLoaderCache,
10
+ } from "./hmr.ts";
11
+ export {
12
+ buildRouteMatcher,
13
+ buildRouteRegex,
14
+ collectIntermediateLayoutDirs,
15
+ compareRouteSpecificity,
16
+ compareRouteSpecificity as routeSpecificity,
17
+ escapeRegExpChar,
18
+ filePathToPattern,
19
+ resolveMode,
20
+ } from "./patterns.ts";
21
+ export { createDataEndpoint, createRoutePlugin } from "./plugin.ts";
22
+ export {
23
+ applySchemaDefaults,
24
+ detectQueryDefaultRedirect,
25
+ mergeRouteSchemas,
26
+ parseDataEndpointPath,
27
+ queryDefaultRedirectHook,
28
+ } from "./schemas.ts";
29
+ export type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
@@ -0,0 +1,214 @@
1
+ import { parse } from "node:path";
2
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
3
+
4
+ export function collectIntermediateLayoutDirs(pagePath: string, rootPath: string): string[] {
5
+ const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
6
+ const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
7
+ const layoutDirs: string[] = [];
8
+ let dir = pageDir;
9
+
10
+ while (dir.length > pagesDir.length) {
11
+ layoutDirs.unshift(dir);
12
+ dir = dir.slice(0, dir.lastIndexOf("/"));
13
+ }
14
+
15
+ return layoutDirs;
16
+ }
17
+
18
+ export function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr" {
19
+ const routeConfig = page._route;
20
+ const mode = routeConfig.mode ?? (page as { mode?: string }).mode;
21
+ const revalidate = routeConfig.revalidate ?? (page as { revalidate?: number }).revalidate;
22
+
23
+ if (mode) {
24
+ return mode as "ssr" | "ssg" | "isr";
25
+ }
26
+
27
+ const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
28
+
29
+ if (!hasLoader) {
30
+ return "ssg";
31
+ }
32
+
33
+ if (typeof revalidate === "number" && revalidate >= 0) {
34
+ return "isr";
35
+ }
36
+
37
+ return "ssr";
38
+ }
39
+
40
+ export function filePathToPattern(path: string): string {
41
+ const parts = path.replaceAll("\\", "/").split("/");
42
+ const segments: string[] = [];
43
+ const lastIndex = parts.length - 1;
44
+
45
+ for (let idx = 0; idx < parts.length; idx++) {
46
+ const part = parts[idx];
47
+ if (part === undefined || part.length === 0) {
48
+ continue;
49
+ }
50
+
51
+ // Only the leaf (file) segment carries an extension to strip. Directory
52
+ // segments are kept verbatim so valid folder names with dots — e.g.
53
+ // `v1.0` — are not truncated into `v1` by `parse().ext` handling.
54
+ const isFile = idx === lastIndex;
55
+ const name = isFile ? parse(part).name : part;
56
+
57
+ // `index` collapses to its parent ONLY as a leaf filename. A directory
58
+ // literally named `index` is a real route segment and must be preserved.
59
+ if (isFile && name === "index") {
60
+ continue;
61
+ }
62
+
63
+ if (name.startsWith("[") && name.endsWith("]")) {
64
+ const inner = name.slice(1, -1);
65
+
66
+ if (inner.startsWith("...")) {
67
+ segments.push("*");
68
+ continue;
69
+ }
70
+
71
+ segments.push(`:${inner}`);
72
+ continue;
73
+ }
74
+
75
+ segments.push(name);
76
+ }
77
+
78
+ return `/${segments.join("/")}`;
79
+ }
80
+
81
+ const REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
82
+
83
+ export function escapeRegExpChar(ch: string): string {
84
+ return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
85
+ }
86
+
87
+ /**
88
+ * Ranks a single route segment by how tightly it constrains a URL position:
89
+ * a literal segment outranks a `:param`, which outranks a `*` wildcard.
90
+ */
91
+ function segmentSpecificity(segment: string): number {
92
+ if (segment === "*") {
93
+ return 1;
94
+ }
95
+ if (segment.startsWith(":")) {
96
+ return 2;
97
+ }
98
+ return 3;
99
+ }
100
+
101
+ /**
102
+ * Compares two route patterns by specificity so the `/_furin/data` matcher can
103
+ * prefer the more specific of two siblings that both match a pathname.
104
+ *
105
+ * Patterns are compared segment by segment from the left; the first position
106
+ * where they differ decides (literal > `:param` > `*`). When every shared
107
+ * position ties, the pattern with more explicit segments wins over a shorter
108
+ * one whose wildcard absorbs the tail.
109
+ *
110
+ * Returns a positive number when `a` is MORE specific than `b`, negative when
111
+ * less, and `0` only when the two are indistinguishable. This lexicographic
112
+ * ranking replaces the previous summed-weight score, which produced ties such
113
+ * as `/blog/new/:section` vs `/blog/:id/edit` (both summed to 8) that resolved
114
+ * non-deterministically by scan order.
115
+ */
116
+ export function compareRouteSpecificity(a: string, b: string): number {
117
+ const aSegments = a.split("/").filter((segment) => segment.length > 0);
118
+ const bSegments = b.split("/").filter((segment) => segment.length > 0);
119
+ const length = Math.max(aSegments.length, bSegments.length);
120
+ for (let i = 0; i < length; i++) {
121
+ const aSegment = aSegments[i];
122
+ const bSegment = bSegments[i];
123
+ // The pattern that still has a segment here constrains one more position.
124
+ if (aSegment === undefined) {
125
+ return -1;
126
+ }
127
+ if (bSegment === undefined) {
128
+ return 1;
129
+ }
130
+ const diff = segmentSpecificity(aSegment) - segmentSpecificity(bSegment);
131
+ if (diff !== 0) {
132
+ return diff;
133
+ }
134
+ }
135
+ return 0;
136
+ }
137
+
138
+ /**
139
+ * Builds a regex from a route pattern, extracts named capture groups for
140
+ * each `:param` segment, and returns `{ regex, paramNames }`.
141
+ *
142
+ * Literal characters (e.g. dots in filenames like `v1.0`) are escaped so
143
+ * they are matched exactly rather than interpreted as regex syntax.
144
+ */
145
+ export function buildRouteRegex(pattern: string): { regex: RegExp; paramNames: string[] } {
146
+ const paramNames: string[] = [];
147
+ let source = "";
148
+ let i = 0;
149
+ while (i < pattern.length) {
150
+ if (pattern[i] === ":") {
151
+ const start = ++i;
152
+ while (i < pattern.length && pattern[i] !== "/") {
153
+ i++;
154
+ }
155
+ paramNames.push(pattern.slice(start, i));
156
+ source += "([^/]+)";
157
+ } else if (pattern[i] === "*") {
158
+ paramNames.push("*");
159
+ source += "(.*)";
160
+ i++;
161
+ } else {
162
+ const ch = pattern[i];
163
+ if (ch !== undefined) {
164
+ source += escapeRegExpChar(ch);
165
+ }
166
+ i++;
167
+ }
168
+ }
169
+ return { regex: new RegExp(`^${source}$`), paramNames };
170
+ }
171
+
172
+ export interface RoutePatternLike {
173
+ pattern: string;
174
+ }
175
+
176
+ export interface RouteMatch<TRoute extends RoutePatternLike> {
177
+ params: Record<string, string>;
178
+ route: TRoute;
179
+ }
180
+
181
+ interface CompiledRoutePattern<TRoute extends RoutePatternLike> {
182
+ paramNames: string[];
183
+ regex: RegExp;
184
+ route: TRoute;
185
+ }
186
+
187
+ export function buildRouteMatcher<TRoute extends RoutePatternLike>(
188
+ routes: TRoute[]
189
+ ): (pathname: string) => RouteMatch<TRoute> | null {
190
+ const compiled = routes
191
+ .map((route): CompiledRoutePattern<TRoute> => {
192
+ const { regex, paramNames } = buildRouteRegex(route.pattern);
193
+ return { paramNames, regex, route };
194
+ })
195
+ .sort((a, b) => compareRouteSpecificity(b.route.pattern, a.route.pattern));
196
+
197
+ return (pathname) => {
198
+ for (const candidate of compiled) {
199
+ const match = candidate.regex.exec(pathname);
200
+ if (!match) {
201
+ continue;
202
+ }
203
+ const params: Record<string, string> = {};
204
+ for (let i = 0; i < candidate.paramNames.length; i++) {
205
+ const name = candidate.paramNames[i];
206
+ if (name !== undefined) {
207
+ params[name] = match[i + 1] ?? "";
208
+ }
209
+ }
210
+ return { route: candidate.route, params };
211
+ }
212
+ return null;
213
+ };
214
+ }