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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -1,13 +1,12 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { transformForClient } from "../plugin/transform-client";
4
- import type { ResolvedRoute } from "../router";
4
+ import type { ResolvedRoute } from "../server/router/index.ts";
5
5
  import { generateHydrateEntry } from "./hydrate";
6
- import { CLIENT_MODULE_PATH, LINK_MODULE_PATH } from "./shared";
6
+ import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
7
  import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
8
 
9
9
  const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
- const REACT_IMPORT_RE = /import\s+React\b/;
11
10
 
12
11
  export interface BuildClientResult {
13
12
  /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
@@ -34,7 +33,7 @@ export interface BuildClientResult {
34
33
  */
35
34
  export async function buildClient(
36
35
  routes: ResolvedRoute[],
37
- { outDir, rootLayout, plugins, publicPath, basePath }: BuildClientOptions
36
+ { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions
38
37
  ): Promise<BuildClientResult> {
39
38
  const clientDir = join(outDir, "client");
40
39
 
@@ -45,7 +44,7 @@ export async function buildClient(
45
44
  mkdirSync(clientDir, { recursive: true });
46
45
  }
47
46
 
48
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
47
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
49
48
  const hydratePath = join(outDir, "_hydrate.tsx");
50
49
  writeFileSync(hydratePath, hydrateCode);
51
50
 
@@ -63,17 +62,16 @@ export async function buildClient(
63
62
  const code = await Bun.file(path).text();
64
63
  try {
65
64
  const result = transformForClient(code, path);
66
- let transformed = result.code;
67
-
68
- if (transformed.includes("React.createElement") && !REACT_IMPORT_RE.test(transformed)) {
69
- transformed = `import React from "react";\n${transformed}`;
70
- }
71
-
72
- transformed = transformed
65
+ // transformForClient now emits TS/TSX directly (no pre-transpile),
66
+ // so JSX → React handling is delegated to Bun.build's loader, which
67
+ // applies the project tsconfig's automatic runtime by default.
68
+ const transformed = result.code
73
69
  .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
74
70
  .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
75
71
  .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
76
- .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
72
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
73
+ .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
74
+ .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
77
75
 
78
76
  return {
79
77
  contents: transformed,
@@ -98,7 +96,7 @@ export async function buildClient(
98
96
  format: "esm",
99
97
  splitting: true,
100
98
  minify: true,
101
- sourcemap: "linked",
99
+ sourcemap: "none",
102
100
  // Hash the entry point name so it gets immutable caching like chunks.
103
101
  // Without this, _hydrate.js keeps the same name across builds and browsers
104
102
  // serve stale versions that reference old chunk hashes → dynamic import 404.
@@ -114,6 +112,7 @@ export async function buildClient(
114
112
  alias: {
115
113
  "@teyik0/furin/client": CLIENT_MODULE_PATH,
116
114
  "@teyik0/furin/link": LINK_MODULE_PATH,
115
+ "@teyik0/furin/search": SEARCH_MODULE_PATH,
117
116
  },
118
117
  define: {
119
118
  "process.env.NODE_ENV": JSON.stringify("production"),
@@ -1,18 +1,8 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
- import { buildEntrySource } from "./entry-template";
3
+ import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
4
4
  import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
5
5
 
6
- export interface CompileEntryOptions {
7
- buildId?: string;
8
- embed?: { clientDir: string };
9
- outDir: string;
10
- publicDir?: string;
11
- rootPath: string;
12
- routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
13
- serverEntry: string;
14
- }
15
-
16
6
  /**
17
7
  * Generates a single `_compile-entry.ts` that:
18
8
  * 1. Statically imports every page module so Bun bundles them into the binary
@@ -20,8 +10,19 @@ export interface CompileEntryOptions {
20
10
  * 3. Sets production mode and registers everything in a single CompileContext
21
11
  * 4. Dynamically imports server.ts to boot the app
22
12
  */
23
- export function generateCompileEntry(options: CompileEntryOptions): string {
24
- const { buildId, outDir, rootPath, routes, serverEntry, embed, publicDir } = options;
13
+ export function generateCompileEntry(options: BuildEntryOptions): string {
14
+ const {
15
+ buildId,
16
+ outDir,
17
+ rootPath,
18
+ routes,
19
+ serverEntry,
20
+ embed,
21
+ publicDir,
22
+ rootConventions,
23
+ routeMetadata,
24
+ ssgCache,
25
+ } = options;
25
26
  ensureDir(outDir);
26
27
 
27
28
  // Build embedded asset imports if embed mode
@@ -33,7 +34,9 @@ export function generateCompileEntry(options: CompileEntryOptions): string {
33
34
  `[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`
34
35
  );
35
36
  }
36
- const clientFiles = collectFilesRecursive(embed.clientDir);
37
+ const clientFiles = collectFilesRecursive(embed.clientDir).filter(
38
+ (file) => !file.endsWith(".map")
39
+ );
37
40
  const assetEntries: string[] = [];
38
41
  let templateVarName: string | null = null;
39
42
 
@@ -95,6 +98,9 @@ export function generateCompileEntry(options: CompileEntryOptions): string {
95
98
  serverEntry,
96
99
  extraImports: assetImports,
97
100
  extraContext: embeddedBlock,
101
+ rootConventions,
102
+ routeMetadata,
103
+ ssgCache,
98
104
  });
99
105
 
100
106
  const entryPath = join(outDir, "_compile-entry.ts");
@@ -1,24 +1,91 @@
1
- import { dirname } from "node:path";
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { SsgCacheEntry } from "../server/cache/index.ts";
2
5
 
3
6
  // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
4
- // through package exports, and is the Web-standard API. The "bun" condition
5
- // on "." resolves to src/furin.ts, so dirname gives us the src/ dir.
6
- const _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
7
- const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
8
- const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
7
+ // through package exports, and is the Web-standard API. The main entry is
8
+ // `src/furin.ts` (or `dist/furin.js`), so we strip two path segments to reach
9
+ // the package root.
10
+ const _pkgRoot = dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin"))));
11
+ const _pkgSrcDirRaw = existsSync(join(_pkgRoot, "src", "furin.ts"))
12
+ ? join(_pkgRoot, "src")
13
+ : join(_pkgRoot, "dist");
14
+ // Normalize to forward slashes so endsWith checks and template paths work on Windows.
15
+ const _pkgSrcDir = _pkgSrcDirRaw.replace(/\\/g, "/");
16
+ const _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
17
+ const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
18
+ const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/server/runtime-env${_ext}`;
9
19
 
10
20
  export interface EntryTemplateOptions {
11
21
  buildId?: string;
12
22
  extraContext?: string[];
13
23
  extraImports?: string[];
14
24
  headerComment: string;
25
+ rootConventions?: { errorPath?: string; notFoundPath?: string };
15
26
  rootPath: string;
27
+ routeMetadata?: Record<
28
+ string,
29
+ {
30
+ segmentBoundaries: Array<{
31
+ depth: number;
32
+ path: string;
33
+ errorPath?: string;
34
+ notFoundPath?: string;
35
+ }>;
36
+ }
37
+ >;
16
38
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
17
39
  serverEntry: string;
40
+ ssgCache?: Record<string, SsgCacheEntry>;
41
+ }
42
+
43
+ /** Unified options for generating a build entry (compile or disk-based). */
44
+ export interface BuildEntryOptions extends Omit<EntryTemplateOptions, "headerComment"> {
45
+ outDir: string;
46
+ headerComment?: string;
47
+ /** Embed mode: bundles client assets into the binary via `with { type: "file" }`. */
48
+ embed?: { clientDir: string };
49
+ publicDir?: string;
50
+ }
51
+
52
+ function collectConventionPaths(
53
+ rootConventions: EntryTemplateOptions["rootConventions"],
54
+ routeMetadata: EntryTemplateOptions["routeMetadata"]
55
+ ): string[] {
56
+ const paths: string[] = [];
57
+ if (rootConventions?.errorPath) {
58
+ paths.push(rootConventions.errorPath);
59
+ }
60
+ if (rootConventions?.notFoundPath) {
61
+ paths.push(rootConventions.notFoundPath);
62
+ }
63
+ if (routeMetadata) {
64
+ for (const meta of Object.values(routeMetadata)) {
65
+ for (const seg of meta.segmentBoundaries) {
66
+ if (seg.errorPath) {
67
+ paths.push(seg.errorPath);
68
+ }
69
+ if (seg.notFoundPath) {
70
+ paths.push(seg.notFoundPath);
71
+ }
72
+ }
73
+ }
74
+ }
75
+ return [...new Set(paths)];
18
76
  }
19
77
 
20
78
  export function buildEntrySource(options: EntryTemplateOptions): string {
21
- const { buildId, headerComment, rootPath, routes, serverEntry } = options;
79
+ const {
80
+ buildId,
81
+ headerComment,
82
+ rootPath,
83
+ routes,
84
+ serverEntry,
85
+ rootConventions,
86
+ routeMetadata,
87
+ ssgCache,
88
+ } = options;
22
89
  let { extraImports, extraContext } = options;
23
90
  if (extraImports === undefined) {
24
91
  extraImports = [];
@@ -27,7 +94,11 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
27
94
  extraContext = [];
28
95
  }
29
96
 
30
- const allModulePaths = [rootPath, ...routes.map((r) => r.path)];
97
+ const allModulePaths = [
98
+ rootPath,
99
+ ...routes.map((r) => r.path),
100
+ ...collectConventionPaths(rootConventions, routeMetadata),
101
+ ];
31
102
  const moduleImports: string[] = [];
32
103
  const moduleEntries: string[] = [];
33
104
 
@@ -43,6 +114,14 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
43
114
  ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`
44
115
  );
45
116
 
117
+ const rootConventionsLine = rootConventions
118
+ ? ` rootConventions: ${JSON.stringify(rootConventions)},`
119
+ : "";
120
+ const routeMetadataLine = routeMetadata
121
+ ? ` routeMetadata: ${JSON.stringify(routeMetadata)},`
122
+ : "";
123
+ const ssgCacheLine = ssgCache ? ` ssgCache: ${JSON.stringify(ssgCache)},` : "";
124
+
46
125
  const lines = [
47
126
  headerComment,
48
127
  `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
@@ -57,12 +136,15 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
57
136
  "__setCompileContext({",
58
137
  ` buildId: ${JSON.stringify(buildId ?? "")},`,
59
138
  ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
139
+ rootConventionsLine,
60
140
  " modules: {",
61
141
  ...moduleEntries,
62
142
  " },",
63
143
  " routes: [",
64
144
  ...routeEntries,
65
145
  " ],",
146
+ routeMetadataLine,
147
+ ssgCacheLine,
66
148
  ...extraContext,
67
149
  "});",
68
150
  "",
@@ -1,7 +1,10 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { generateIndexHtml } from "../render/shell";
4
- import type { ResolvedRoute } from "../router";
3
+ import { generateIndexHtml } from "../server/render/shell.ts";
4
+ import { mergeRouteSchemas } from "../server/router/index.ts";
5
+ import { buildRouteRegex } from "../server/router/patterns.ts";
6
+ import type { ResolvedRoute } from "../server/router/index.ts";
7
+ import { collectSearchDefaults } from "../shared/search-params.ts";
5
8
  import { writeRouteTypes } from "./route-types";
6
9
  import type { BuildClientOptions } from "./types";
7
10
 
@@ -22,16 +25,66 @@ import type { BuildClientOptions } from "./types";
22
25
  export function generateHydrateEntry(
23
26
  routes: ResolvedRoute[],
24
27
  rootLayout: string,
25
- basePath: string
28
+ basePath: string,
29
+ clientLogging: boolean
26
30
  ): string {
31
+ const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
32
+ if (!filePath) {
33
+ return;
34
+ }
35
+ const existing = idents.get(filePath);
36
+ if (existing) {
37
+ return existing;
38
+ }
39
+ const ident = `__furin_bnd_${idents.size}`;
40
+ idents.set(filePath, ident);
41
+ return ident;
42
+ };
43
+
27
44
  const routeEntries: string[] = [];
28
45
 
29
46
  for (const route of routes) {
30
47
  const resolvedPage = route.path.replace(/\\/g, "/");
31
- const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
48
+ const regexPattern = buildRouteRegex(route.pattern).regex.source;
49
+ const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
50
+ const boundaryIdents = new Map<string, string>();
51
+
52
+ // Emit one boundary literal per segment that actually carries a convention
53
+ // file — segments that only declare one of the two are emitted with the
54
+ // missing field omitted entirely (keeps the generated JS tidy).
55
+ const boundaryLiterals: string[] = [];
56
+ for (const seg of route.segmentBoundaries ?? []) {
57
+ const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
58
+ const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
59
+ if (!(errorIdent || notFoundIdent)) {
60
+ continue;
61
+ }
62
+ const parts = [`depth: ${seg.depth}`];
63
+ if (errorIdent) {
64
+ parts.push(`error: ${errorIdent}.default`);
65
+ }
66
+ if (notFoundIdent) {
67
+ parts.push(`notFound: ${notFoundIdent}.default`);
68
+ }
69
+ boundaryLiterals.push(`{ ${parts.join(", ")} }`);
70
+ }
32
71
 
72
+ const lazyImports = [
73
+ `import("${resolvedPage}")`,
74
+ ...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`),
75
+ ];
76
+ const loadBody =
77
+ boundaryLiterals.length > 0
78
+ ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
79
+ ...boundaryIdents.values(),
80
+ ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
81
+ : `import("${resolvedPage}")`;
82
+
83
+ const searchDefaultsEntry = searchDefaults
84
+ ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
85
+ : "";
33
86
  routeEntries.push(
34
- ` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`
87
+ ` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`
35
88
  );
36
89
  }
37
90
 
@@ -41,26 +94,38 @@ export function generateHydrateEntry(
41
94
  // Strip basePath only when it matches on a path boundary (prevents "/furin" from
42
95
  // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
43
96
  // at the prefix length OR the next character is "/".
97
+ // Trailing slashes are also stripped so "/docs/routing/" matches the route
98
+ // pattern "/docs/routing" — GitHub Pages and many static hosts append them.
44
99
  const pathnameExpr = basePath
45
- ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()`
46
- : "window.location.pathname";
100
+ ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()`
101
+ : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
47
102
 
48
103
  // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
49
104
  const logEndpoint = basePath
50
105
  ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
51
106
  : `"/_furin/ingest"`;
52
107
 
108
+ // Client-side HTTP draining is opt-in (config `clientLogging`). When disabled
109
+ // we emit neither the hydrate-entry evlog imports nor initLogger, and define a
110
+ // no-op `log` shim so the hydration body's log.* calls stay valid.
111
+ const loggingImports = clientLogging
112
+ ? 'import { initLogger, log } from "evlog";\nimport { createHttpLogDrain } from "evlog/http";\n'
113
+ : "";
114
+ const loggerSetup = clientLogging
115
+ ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });`
116
+ : "const log = { error() {}, info() {} };";
117
+
53
118
  // RouterProvider receives basePath so navigate() / Link push physical paths.
54
- const basePathProp = basePath ? `\n basePath: ${basePathLiteral},` : "";
119
+ const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,`;
55
120
 
56
121
  return `import { hydrateRoot, createRoot } from "react-dom/client";
57
122
  import { createElement } from "react";
58
- import { initLogger, log } from "evlog";
59
- import { createHttpLogDrain } from "evlog/http";
60
- import { RouterProvider } from "@teyik0/furin/link";
123
+ ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
124
+ import { fromCrossJSON } from "@teyik0/furin/link";
125
+ import type { SerovalNode } from "seroval";
61
126
  import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
62
127
 
63
- initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
128
+ ${loggerSetup}
64
129
 
65
130
  const routes = [
66
131
  ${routeEntries.join(",\n")}
@@ -69,48 +134,166 @@ ${routeEntries.join(",\n")}
69
134
  const pathname = ${pathnameExpr};
70
135
  const _match = routes.find((r) => r.regex.test(pathname));
71
136
 
137
+ // Parse the server-embedded loader payload up front. It carries:
138
+ // - normal loader props under arbitrary keys,
139
+ // - __furinError.digest when SSR caught an error,
140
+ // - __furinStatus: 404 when the server rendered the catch-all not-found
141
+ // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
142
+ // a matched loader threw notFound(). The latter still has a _match; the
143
+ // former does not — so the two cases fork on _match below.
144
+ const dataEl = document.getElementById("__FURIN_DATA__");
145
+ const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
146
+
147
+ // ── Deferred data hydration ─────────────────────────────────────────────────
148
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
149
+ // defer(). It carries:
150
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
151
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
152
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
153
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
154
+ interface FurinDeferredRegistry {
155
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
156
+ _deferredKeys: string[];
157
+ _resolvers: Record<string, {
158
+ promise: Promise<unknown>;
159
+ reject: (reason: unknown) => void;
160
+ resolve: (value: unknown) => void;
161
+ }>;
162
+ getPromise: (key: string) => Promise<unknown>;
163
+ reject: (key: string, chunk: SerovalNode) => void;
164
+ resolve: (key: string, chunk: SerovalNode) => void;
165
+ }
166
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
167
+ .__FURIN_DEFERRED__;
168
+ const deferredData: Record<string, Promise<unknown>> = {};
169
+ if (__deferred && __deferred._chunks) {
170
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
171
+ // settle immediately. The previous version stored late chunks in _chunks
172
+ // when no resolver was registered yet, but the drain loop below only runs
173
+ // ONCE at hydrate time — so any chunk landing after the drain would stay
174
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
175
+ // the resolver via getPromise() fixes the race.
176
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
177
+ __deferred.getPromise(key);
178
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
179
+ };
180
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
181
+ __deferred.getPromise(key);
182
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
183
+ };
184
+ for (const key of Object.keys(__deferred._chunks)) {
185
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
186
+ const p = __deferred.getPromise(key) as Promise<unknown>;
187
+ const resolver = __deferred._resolvers[key];
188
+ const value = fromCrossJSON(entry.v, {});
189
+ if (entry.a === 0) {
190
+ resolver.resolve(value);
191
+ } else {
192
+ resolver.reject(value);
193
+ }
194
+ deferredData[key] = p;
195
+ }
196
+ for (const key of __deferred._deferredKeys ?? []) {
197
+ if (!(key in deferredData)) {
198
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
199
+ }
200
+ }
201
+ // Keys that have a resolver (getPromise was called by <Await>) but no
202
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
203
+ // so the hydration data record is complete.
204
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
205
+ if (!(key in deferredData)) {
206
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
207
+ }
208
+ }
209
+ }
210
+ const rootEl = document.getElementById("root") as HTMLElement;
211
+
72
212
  // Eagerly load only the current page module for initial hydration.
73
213
  // All other pages are loaded on demand when the user navigates to them.
74
214
  // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
75
215
  // bundler to misidentify which chunk to reference as the entry in index.html.
76
216
  (async () => {
217
+ let app;
77
218
  if (_match) {
78
219
  const _mod = await _match.load();
79
- const match = { ..._match, component: _mod.default.component, pageRoute: _mod.default._route };
220
+ const match = {
221
+ ..._match,
222
+ component: _mod.default.component,
223
+ pageRoute: _mod.default._route,
224
+ segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
225
+ };
80
226
 
81
- const dataEl = document.getElementById("__FURIN_DATA__");
82
- const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
83
- const rootEl = document.getElementById("root") as HTMLElement;
227
+ const isNotFound = loaderData.__furinStatus === 404;
84
228
 
85
- const app = createElement(RouterProvider, {
229
+ app = createElement(RouterProvider, {
86
230
  routes,
87
231
  root,
88
232
  initialMatch: match,
89
- initialData: loaderData,${basePathProp}
233
+ initialData: { ...loaderData, ...deferredData },
234
+ initialDigest: loaderData.__furinError?.digest,
235
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
90
236
  } as any);
237
+ } else if (loaderData.__furinStatus === 404) {
238
+ // Direct load to an unknown URL. The server sent the root not-found UI
239
+ // already rendered into the DOM. Mount RouterProvider with a null match
240
+ // so the provider boots into its not-found branch, hydrating that exact
241
+ // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
242
+ // (e.g. the default screen's "Go Home" button) hit the useRouter()
243
+ // fallback that does a full window.location assignment — a jarring reload.
244
+ // Strip the server-only signal keys before handing data to components.
245
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
246
+ app = createElement(RouterProvider, {
247
+ routes,
248
+ root,
249
+ initialMatch: null,
250
+ initialData: cleanData,
251
+ initialDigest: loaderData.__furinError?.digest,
252
+ initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
253
+ } as any);
254
+ } else {
255
+ // No match and no 404 signal — either the client bundle is out of sync
256
+ // with the server (stale deploy) or the server returned something we
257
+ // don't know how to hydrate. Bail loudly; the page stays static.
258
+ log.error({ action: "hydrate_no_match", pathname });
259
+ return;
260
+ }
91
261
 
92
- if (import.meta.hot) {
93
- if (import.meta.hot.data.root) {
94
- // HMR re-render — update in place without remounting
95
- import.meta.hot.data.root.render(app);
96
- } else if (rootEl.innerHTML.trim()) {
97
- // First load with SSR content — hydrateRoot renders on construction
98
- import.meta.hot.data.root = hydrateRoot(rootEl, app);
99
- } else {
100
- // First load without SSR content — createRoot requires explicit .render()
101
- const freshRoot = createRoot(rootEl);
102
- freshRoot.render(app);
103
- import.meta.hot.data.root = freshRoot;
262
+ if (import.meta.hot) {
263
+ // Dev mode — preserve root across HMR using a window global.
264
+ // window is the only object that survives Bun's module re-evaluation.
265
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
266
+ const existingRoot = (window as any).__FURIN_ROOT__;
267
+ if (existingRoot) {
268
+ // Already mounted — reconciliation, NOT hydration. React Fast Refresh
269
+ // patched the component in-place, now re-render with the new module.
270
+ existingRoot.render(app);
271
+ // The initialData embedded in the DOM is stale (from the original SSR).
272
+ // Trigger a loader-data refresh so the component renders with fresh
273
+ // server state, avoiding hydration mismatches after a _route.tsx edit.
274
+ const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
275
+ if (hmrRefresh) {
276
+ requestAnimationFrame(() => hmrRefresh());
104
277
  }
105
278
  } else if (rootEl.innerHTML.trim()) {
106
- hydrateRoot(rootEl, app);
279
+ // First load with SSR content — hydrateRoot renders on construction
280
+ const root = hydrateRoot(rootEl, app);
281
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
282
+ (window as any).__FURIN_ROOT__ = root;
107
283
  } else {
108
- createRoot(rootEl).render(app);
284
+ // First load without SSR content — createRoot requires explicit .render()
285
+ const root = createRoot(rootEl);
286
+ root.render(app);
287
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
288
+ (window as any).__FURIN_ROOT__ = root;
109
289
  }
110
- log.info({ action: "hydrate_complete", pathname });
290
+ } else if (rootEl.innerHTML.trim()) {
291
+ hydrateRoot(rootEl, app);
111
292
  } else {
112
- log.error({ action: "hydrate_no_match", pathname });
293
+ createRoot(rootEl).render(app);
113
294
  }
295
+
296
+ log.info({ action: "hydrate_complete", pathname });
114
297
  })().catch((err: unknown) => {
115
298
  log.error({ action: "hydrate_failed", pathname, error: String(err) });
116
299
  });
@@ -125,14 +308,14 @@ const _match = routes.find((r) => r.regex.test(pathname));
125
308
  */
126
309
  export function writeDevFiles(
127
310
  routes: ResolvedRoute[],
128
- { outDir, rootLayout, basePath }: BuildClientOptions,
311
+ { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
129
312
  projectRoot: string
130
313
  ): void {
131
314
  if (!existsSync(outDir)) {
132
315
  mkdirSync(outDir, { recursive: true });
133
316
  }
134
317
 
135
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
318
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
136
319
  const hydratePath = join(outDir, "_hydrate.tsx");
137
320
  const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
138
321
  if (hydrateCode !== existingHydrate) {
@@ -2,8 +2,8 @@ import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative, resolve } from "node:path";
3
3
  import { buildBunTarget } from "../adapter/bun";
4
4
  import { buildStaticTarget } from "../adapter/static";
5
- import { BUILD_TARGETS, type BuildTarget } from "../config";
6
- import { scanPages } from "../router";
5
+ import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
6
+ import { scanPages } from "../server/router/index.ts";
7
7
  import { scanFurinInstances } from "./scan-server";
8
8
  import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
9
  import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
@@ -12,6 +12,7 @@ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
12
12
  export { buildClient } from "./client";
13
13
  export { writeDevFiles } from "./hydrate";
14
14
  export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
15
+ export { buildSSGCacheSnapshot, type SSGCacheSnapshot } from "./ssg-cache";
15
16
  export type {
16
17
  BuildAppOptions,
17
18
  BuildAppResult,
@@ -68,14 +69,14 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
68
69
  // doesn't exist in the runtime context) are skipped silently — they only
69
70
  // affect the Bun.build() client bundle, not server-side rendering.
70
71
  for (const plugin of options.plugins ?? []) {
72
+ const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
73
+ if (buildOnly) {
74
+ continue;
75
+ }
71
76
  try {
72
- Bun.plugin(plugin);
77
+ Bun.plugin(runtimePlugin);
73
78
  } catch (err) {
74
- // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
75
- // does not exist in the runtime context) are expected to throw here —
76
- // they only affect the Bun.build() client bundle, not server-side rendering.
77
- // Log at debug level so genuine plugin registration errors remain visible.
78
- console.debug("[furin] Skipped build-only plugin at runtime:", err);
79
+ console.debug("[furin] Skipped plugin at runtime:", err);
79
80
  }
80
81
  }
81
82
 
@@ -117,7 +118,7 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
117
118
  routes,
118
119
  rootDir,
119
120
  buildRoot,
120
- root.path,
121
+ root,
121
122
  serverEntry,
122
123
  options
123
124
  );