@teyik0/furin 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
@@ -0,0 +1,153 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { transformForClient } from "../plugin/transform-client";
4
+ import type { ResolvedRoute } from "../router";
5
+ import { generateHydrateEntry } from "./hydrate";
6
+ import { CLIENT_MODULE_PATH, LINK_MODULE_PATH } from "./shared";
7
+ import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
+
9
+ const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
+ const REACT_IMPORT_RE = /import\s+React\b/;
11
+
12
+ export interface BuildClientResult {
13
+ /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
14
+ cssChunks: string[];
15
+ /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
16
+ entryChunk: string;
17
+ }
18
+
19
+ /**
20
+ * Builds the production client bundle via Bun.build() using _hydrate.tsx as
21
+ * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
22
+ * <outDir>/client/chunk-*.js — code-split bundles
23
+ * <outDir>/client/chunk-*.css — extracted CSS (if imported)
24
+ *
25
+ * Returns the chunk paths so the caller can compute a `buildId` and write
26
+ * `index.html` with the correct meta tag. Using an HTML entrypoint with
27
+ * code-splitting causes a Bun bug where the output index.html references a
28
+ * leaf chunk instead of the actual entry chunk, preventing React from mounting
29
+ * in production.
30
+ *
31
+ * The output index.html is NOT served to browsers directly. The server reads
32
+ * it as an SSR template, injects the pre-rendered React HTML into
33
+ * <!--ssr-outlet-->, and sends the complete page.
34
+ */
35
+ export async function buildClient(
36
+ routes: ResolvedRoute[],
37
+ { outDir, rootLayout, plugins, publicPath, basePath }: BuildClientOptions
38
+ ): Promise<BuildClientResult> {
39
+ const clientDir = join(outDir, "client");
40
+
41
+ if (!existsSync(outDir)) {
42
+ mkdirSync(outDir, { recursive: true });
43
+ }
44
+ if (!existsSync(clientDir)) {
45
+ mkdirSync(clientDir, { recursive: true });
46
+ }
47
+
48
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
49
+ const hydratePath = join(outDir, "_hydrate.tsx");
50
+ writeFileSync(hydratePath, hydrateCode);
51
+
52
+ console.log("[furin] Building production client bundle…");
53
+
54
+ const transformPlugin: Bun.BunPlugin = {
55
+ name: "furin-transform-client",
56
+ setup(build) {
57
+ build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
58
+ const { path } = args;
59
+ if (path.includes("node_modules")) {
60
+ return;
61
+ }
62
+
63
+ const code = await Bun.file(path).text();
64
+ try {
65
+ 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
73
+ .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
74
+ .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
75
+ .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
76
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
77
+
78
+ return {
79
+ contents: transformed,
80
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
81
+ };
82
+ } catch (error) {
83
+ console.error(`[furin] Transform error for ${path}:`, error);
84
+ return;
85
+ }
86
+ });
87
+ },
88
+ };
89
+
90
+ const clientBuildConfig: BunBuildAliasConfig = {
91
+ // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
92
+ // with code-splitting incorrectly references a leaf chunk in the output
93
+ // index.html instead of the actual entry chunk, preventing React from
94
+ // mounting. We write index.html ourselves after the build.
95
+ entrypoints: [hydratePath],
96
+ outdir: clientDir,
97
+ target: "browser",
98
+ format: "esm",
99
+ splitting: true,
100
+ minify: true,
101
+ sourcemap: "linked",
102
+ // Hash the entry point name so it gets immutable caching like chunks.
103
+ // Without this, _hydrate.js keeps the same name across builds and browsers
104
+ // serve stale versions that reference old chunk hashes → dynamic import 404.
105
+ naming: {
106
+ entry: "[dir]/[name]-[hash].[ext]",
107
+ chunk: "[name]-[hash].[ext]",
108
+ },
109
+ // Absolute public path so SSR template asset URLs resolve on any route.
110
+ // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
111
+ publicPath,
112
+ // User plugins run before the internal transform so they pre-process files first
113
+ plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
114
+ alias: {
115
+ "@teyik0/furin/client": CLIENT_MODULE_PATH,
116
+ "@teyik0/furin/link": LINK_MODULE_PATH,
117
+ },
118
+ define: {
119
+ "process.env.NODE_ENV": JSON.stringify("production"),
120
+ },
121
+ };
122
+
123
+ const result = await Bun.build(clientBuildConfig);
124
+ for (const output of result.outputs) {
125
+ console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
126
+ }
127
+
128
+ // Build index.html (SSR template) with correct chunk references.
129
+ // We derive these from result.outputs rather than letting Bun write the HTML,
130
+ // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
131
+ const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
132
+ const cssOutputs = result.outputs.filter(
133
+ (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
134
+ );
135
+ if (!entryOutput) {
136
+ throw new Error("[furin] client build did not emit entry chunk");
137
+ }
138
+
139
+ // Normalise: ensure publicPath ends with exactly one "/".
140
+ // Preserve an empty publicPath ("") as-is so callers that want
141
+ // relative chunk URLs don't get an unintended root-absolute "/".
142
+ let publicPrefix: string;
143
+ if (publicPath === "") {
144
+ publicPrefix = "";
145
+ } else {
146
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
147
+ }
148
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
149
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
150
+
151
+ console.log("[furin] Production client build complete");
152
+ return { entryChunk, cssChunks };
153
+ }
@@ -0,0 +1,129 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import { buildEntrySource } from "./entry-template";
4
+ import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
5
+
6
+ export interface CompileEntryOptions {
7
+ buildId: string | undefined;
8
+ embed: { clientDir: string } | undefined;
9
+ outDir: string;
10
+ publicDir: string | undefined;
11
+ rootConventions: { errorPath: string | undefined; notFoundPath: string | undefined } | undefined;
12
+ rootPath: string;
13
+ routeMetadata:
14
+ | Record<
15
+ string,
16
+ {
17
+ segmentBoundaries: Array<{
18
+ depth: number;
19
+ path: string;
20
+ errorPath: string | undefined;
21
+ notFoundPath: string | undefined;
22
+ }>;
23
+ }
24
+ >
25
+ | undefined;
26
+ routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
27
+ serverEntry: string;
28
+ }
29
+
30
+ /**
31
+ * Generates a single `_compile-entry.ts` that:
32
+ * 1. Statically imports every page module so Bun bundles them into the binary
33
+ * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
34
+ * 3. Sets production mode and registers everything in a single CompileContext
35
+ * 4. Dynamically imports server.ts to boot the app
36
+ */
37
+ export function generateCompileEntry(options: CompileEntryOptions): string {
38
+ const {
39
+ buildId,
40
+ outDir,
41
+ rootPath,
42
+ routes,
43
+ serverEntry,
44
+ embed,
45
+ publicDir,
46
+ rootConventions,
47
+ routeMetadata,
48
+ } = options;
49
+ ensureDir(outDir);
50
+
51
+ // Build embedded asset imports if embed mode
52
+ const assetImports: string[] = [];
53
+ let embeddedBlock: string[] = [];
54
+ if (embed) {
55
+ if (!existsSync(embed.clientDir)) {
56
+ throw new Error(
57
+ `[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`
58
+ );
59
+ }
60
+ const clientFiles = collectFilesRecursive(embed.clientDir);
61
+ const assetEntries: string[] = [];
62
+ let templateVarName: string | null = null;
63
+
64
+ let assetIndex = 0;
65
+ for (const file of clientFiles) {
66
+ const varName = `_asset${assetIndex++}`;
67
+ const relPath = toPosixPath(relative(outDir, file));
68
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
69
+
70
+ assetImports.push(
71
+ `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
72
+ );
73
+
74
+ const clientRelativePath = toPosixPath(relative(embed.clientDir, file));
75
+ if (clientRelativePath === "index.html") {
76
+ templateVarName = varName;
77
+ } else {
78
+ assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
79
+ }
80
+ }
81
+
82
+ if (templateVarName === null) {
83
+ throw new Error(
84
+ `[furin] Embed mode requires a client index.html at ${join(embed.clientDir, "index.html")}. Run the client build first.`
85
+ );
86
+ }
87
+
88
+ if (publicDir && existsSync(publicDir)) {
89
+ const publicFiles = collectFilesRecursive(publicDir);
90
+ for (const file of publicFiles) {
91
+ const varName = `_asset${assetIndex++}`;
92
+ const relPath = toPosixPath(relative(outDir, file));
93
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
94
+
95
+ assetImports.push(
96
+ `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
97
+ );
98
+
99
+ const publicRelativePath = toPosixPath(relative(publicDir, file));
100
+ assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
101
+ }
102
+ }
103
+
104
+ embeddedBlock = [
105
+ " embedded: {",
106
+ ` template: ${templateVarName},`,
107
+ " assets: {",
108
+ ...assetEntries,
109
+ " },",
110
+ " },",
111
+ ];
112
+ }
113
+
114
+ const source = buildEntrySource({
115
+ buildId,
116
+ headerComment: "// Auto-generated by furin compile — do not edit",
117
+ rootPath,
118
+ routes,
119
+ serverEntry,
120
+ extraImports: assetImports,
121
+ extraContext: embeddedBlock,
122
+ rootConventions,
123
+ routeMetadata,
124
+ });
125
+
126
+ const entryPath = join(outDir, "_compile-entry.ts");
127
+ writeFileSync(entryPath, source);
128
+ return entryPath;
129
+ }
@@ -0,0 +1,126 @@
1
+ import { dirname } from "node:path";
2
+
3
+ // 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`;
9
+
10
+ export interface EntryTemplateOptions {
11
+ buildId?: string;
12
+ extraContext?: string[];
13
+ extraImports?: string[];
14
+ headerComment: string;
15
+ rootConventions?: { errorPath?: string; notFoundPath?: string };
16
+ rootPath: string;
17
+ routeMetadata?: Record<
18
+ string,
19
+ {
20
+ segmentBoundaries: Array<{
21
+ depth: number;
22
+ path: string;
23
+ errorPath?: string;
24
+ notFoundPath?: string;
25
+ }>;
26
+ }
27
+ >;
28
+ routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
29
+ serverEntry: string;
30
+ }
31
+
32
+ function collectConventionPaths(
33
+ rootConventions: EntryTemplateOptions["rootConventions"],
34
+ routeMetadata: EntryTemplateOptions["routeMetadata"]
35
+ ): string[] {
36
+ const paths: string[] = [];
37
+ if (rootConventions?.errorPath) {
38
+ paths.push(rootConventions.errorPath);
39
+ }
40
+ if (rootConventions?.notFoundPath) {
41
+ paths.push(rootConventions.notFoundPath);
42
+ }
43
+ if (routeMetadata) {
44
+ for (const meta of Object.values(routeMetadata)) {
45
+ for (const seg of meta.segmentBoundaries) {
46
+ if (seg.errorPath) {
47
+ paths.push(seg.errorPath);
48
+ }
49
+ if (seg.notFoundPath) {
50
+ paths.push(seg.notFoundPath);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return [...new Set(paths)];
56
+ }
57
+
58
+ export function buildEntrySource(options: EntryTemplateOptions): string {
59
+ const { buildId, headerComment, rootPath, routes, serverEntry, rootConventions, routeMetadata } =
60
+ options;
61
+ let { extraImports, extraContext } = options;
62
+ if (extraImports === undefined) {
63
+ extraImports = [];
64
+ }
65
+ if (extraContext === undefined) {
66
+ extraContext = [];
67
+ }
68
+
69
+ const allModulePaths = [
70
+ rootPath,
71
+ ...routes.map((r) => r.path),
72
+ ...collectConventionPaths(rootConventions, routeMetadata),
73
+ ];
74
+ const moduleImports: string[] = [];
75
+ const moduleEntries: string[] = [];
76
+
77
+ for (let i = 0; i < allModulePaths.length; i++) {
78
+ const absPath = (allModulePaths[i] as string).replace(/\\/g, "/");
79
+ const varName = `_mod${i}`;
80
+ moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
81
+ moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
82
+ }
83
+
84
+ const routeEntries = routes.map(
85
+ (r) =>
86
+ ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`
87
+ );
88
+
89
+ const rootConventionsLine = rootConventions
90
+ ? ` rootConventions: ${JSON.stringify(rootConventions)},`
91
+ : "";
92
+ const routeMetadataLine = routeMetadata
93
+ ? ` routeMetadata: ${JSON.stringify(routeMetadata)},`
94
+ : "";
95
+
96
+ const lines = [
97
+ headerComment,
98
+ `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
99
+ `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
100
+ ...moduleImports,
101
+ ...(extraImports.length > 0 ? ["", ...extraImports] : []),
102
+ "",
103
+ "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
104
+ "__setDevMode(false);",
105
+ 'process.env.NODE_ENV = "production";',
106
+ "",
107
+ "__setCompileContext({",
108
+ ` buildId: ${JSON.stringify(buildId ?? "")},`,
109
+ ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
110
+ rootConventionsLine,
111
+ " modules: {",
112
+ ...moduleEntries,
113
+ " },",
114
+ " routes: [",
115
+ ...routeEntries,
116
+ " ],",
117
+ routeMetadataLine,
118
+ ...extraContext,
119
+ "});",
120
+ "",
121
+ `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
122
+ "",
123
+ ];
124
+
125
+ return lines.join("\n");
126
+ }
@@ -0,0 +1,250 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { generateIndexHtml } from "../render/shell";
4
+ import type { ResolvedRoute } from "../router";
5
+ import { writeRouteTypes } from "./route-types";
6
+ import type { BuildClientOptions } from "./types";
7
+
8
+ /**
9
+ * Generates the client hydration entry.
10
+ *
11
+ * Renders into <div id="root"> (the SSR outlet element) and retains the React
12
+ * root across hot reloads via import.meta.hot.data.root so React Fast Refresh
13
+ * applies in-place instead of remounting.
14
+ *
15
+ * @param routes - Resolved routes to include in the hydration manifest.
16
+ * @param rootLayout - Absolute path to the root layout module.
17
+ * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
18
+ * When set, the generated code strips the prefix from `window.location.pathname`
19
+ * before matching routes, and passes `basePath` to `RouterProvider` so SPA
20
+ * navigation uses the correct physical URLs.
21
+ */
22
+ export function generateHydrateEntry(
23
+ routes: ResolvedRoute[],
24
+ rootLayout: string,
25
+ basePath: string
26
+ ): string {
27
+ // Deduplicate convention-file paths across all routes so each physical file
28
+ // produces ONE static import, even when shared by many routes (e.g. the
29
+ // pages-dir-level error.tsx covers every page at depth 0).
30
+ const conventionIdents = new Map<string, string>();
31
+ const getIdent = (filePath: string | undefined): string | undefined => {
32
+ if (!filePath) {
33
+ return;
34
+ }
35
+ const existing = conventionIdents.get(filePath);
36
+ if (existing) {
37
+ return existing;
38
+ }
39
+ const ident = `__furin_bnd_${conventionIdents.size}`;
40
+ conventionIdents.set(filePath, ident);
41
+ return ident;
42
+ };
43
+
44
+ const routeEntries: string[] = [];
45
+
46
+ for (const route of routes) {
47
+ const resolvedPage = route.path.replace(/\\/g, "/");
48
+ const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
49
+
50
+ // Emit one boundary literal per segment that actually carries a convention
51
+ // file — segments that only declare one of the two are emitted with the
52
+ // missing field omitted entirely (keeps the generated JS tidy).
53
+ const boundaryLiterals: string[] = [];
54
+ for (const seg of route.segmentBoundaries ?? []) {
55
+ const errorIdent = getIdent(seg.errorPath);
56
+ const notFoundIdent = getIdent(seg.notFoundPath);
57
+ if (!(errorIdent || notFoundIdent)) {
58
+ continue;
59
+ }
60
+ const parts = [`depth: ${seg.depth}`];
61
+ if (errorIdent) {
62
+ parts.push(`error: ${errorIdent}`);
63
+ }
64
+ if (notFoundIdent) {
65
+ parts.push(`notFound: ${notFoundIdent}`);
66
+ }
67
+ boundaryLiterals.push(`{ ${parts.join(", ")} }`);
68
+ }
69
+ const boundariesField =
70
+ boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
71
+
72
+ routeEntries.push(
73
+ ` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}")${boundariesField} }`
74
+ );
75
+ }
76
+
77
+ // Collect all deduplicated convention-file imports. Emitted BEFORE the
78
+ // route array so the idents are in scope when the array literal is built.
79
+ const conventionImportLines = [...conventionIdents.entries()]
80
+ .map(([filePath, ident]) => `import ${ident} from "${filePath.replace(/\\/g, "/")}";`)
81
+ .join("\n");
82
+
83
+ // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
84
+ // prefix before route matching so patterns like /docs/routing still work.
85
+ const basePathLiteral = JSON.stringify(basePath);
86
+ // Strip basePath only when it matches on a path boundary (prevents "/furin" from
87
+ // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
88
+ // at the prefix length OR the next character is "/".
89
+ const pathnameExpr = basePath
90
+ ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()`
91
+ : "window.location.pathname";
92
+
93
+ // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
94
+ const logEndpoint = basePath
95
+ ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
96
+ : `"/_furin/ingest"`;
97
+
98
+ // RouterProvider receives basePath so navigate() / Link push physical paths.
99
+ const basePathProp = basePath ? `\n basePath: ${basePathLiteral},` : "";
100
+
101
+ const conventionImportsBlock = conventionImportLines ? `\n${conventionImportLines}` : "";
102
+
103
+ return `import { hydrateRoot, createRoot } from "react-dom/client";
104
+ import { createElement } from "react";
105
+ import { initLogger, log } from "evlog";
106
+ import { createHttpLogDrain } from "evlog/http";
107
+ import { RouterProvider } from "@teyik0/furin/link";
108
+ import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
109
+
110
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
111
+
112
+ const routes = [
113
+ ${routeEntries.join(",\n")}
114
+ ];
115
+
116
+ const pathname = ${pathnameExpr};
117
+ const _match = routes.find((r) => r.regex.test(pathname));
118
+
119
+ // Parse the server-embedded loader payload up front. It carries:
120
+ // - normal loader props under arbitrary keys,
121
+ // - __furinError.digest when SSR caught an error,
122
+ // - __furinStatus: 404 when the server rendered the catch-all not-found
123
+ // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
124
+ // a matched loader threw notFound(). The latter still has a _match; the
125
+ // former does not — so the two cases fork on _match below.
126
+ const dataEl = document.getElementById("__FURIN_DATA__");
127
+ const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
128
+ const rootEl = document.getElementById("root") as HTMLElement;
129
+
130
+ // Eagerly load only the current page module for initial hydration.
131
+ // All other pages are loaded on demand when the user navigates to them.
132
+ // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
133
+ // bundler to misidentify which chunk to reference as the entry in index.html.
134
+ (async () => {
135
+ let app;
136
+ if (_match) {
137
+ const _mod = await _match.load();
138
+ const match = { ..._match, component: _mod.default.component, pageRoute: _mod.default._route };
139
+
140
+ const isNotFound = loaderData.__furinStatus === 404;
141
+
142
+ app = createElement(RouterProvider, {
143
+ routes,
144
+ root,
145
+ initialMatch: match,
146
+ initialData: loaderData,
147
+ initialDigest: loaderData.__furinError?.digest,
148
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${basePathProp}
149
+ } as any);
150
+ } else if (loaderData.__furinStatus === 404) {
151
+ // Direct load to an unknown URL. The server sent the root not-found UI
152
+ // already rendered into the DOM. Mount RouterProvider with a null match
153
+ // so the provider boots into its not-found branch, hydrating that exact
154
+ // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
155
+ // (e.g. the default screen's "Go Home" button) hit the useRouter()
156
+ // fallback that does a full window.location assignment — a jarring reload.
157
+ // Strip the server-only signal keys before handing data to components.
158
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
159
+ app = createElement(RouterProvider, {
160
+ routes,
161
+ root,
162
+ initialMatch: null,
163
+ initialData: cleanData,
164
+ initialDigest: loaderData.__furinError?.digest,
165
+ initialNotFound: loaderData.__furinNotFound ?? {},${basePathProp}
166
+ } as any);
167
+ } else {
168
+ // No match and no 404 signal — either the client bundle is out of sync
169
+ // with the server (stale deploy) or the server returned something we
170
+ // don't know how to hydrate. Bail loudly; the page stays static.
171
+ log.error({ action: "hydrate_no_match", pathname });
172
+ return;
173
+ }
174
+
175
+ if (import.meta.hot) {
176
+ // Dev mode — preserve root across HMR using a window global.
177
+ // window is the only object that survives Bun's module re-evaluation.
178
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
179
+ const existingRoot = (window as any).__FURIN_ROOT__;
180
+ if (existingRoot) {
181
+ // Already mounted — reconciliation, NOT hydration. React Fast Refresh
182
+ // patched the component in-place, now re-render with the new module.
183
+ existingRoot.render(app);
184
+ // The initialData embedded in the DOM is stale (from the original SSR).
185
+ // Trigger a loader-data refresh so the component renders with fresh
186
+ // server state, avoiding hydration mismatches after a _route.tsx edit.
187
+ const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
188
+ if (hmrRefresh) {
189
+ requestAnimationFrame(() => hmrRefresh());
190
+ }
191
+ } else if (rootEl.innerHTML.trim()) {
192
+ // First load with SSR content — hydrateRoot renders on construction
193
+ const root = hydrateRoot(rootEl, app);
194
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
195
+ (window as any).__FURIN_ROOT__ = root;
196
+ } else {
197
+ // First load without SSR content — createRoot requires explicit .render()
198
+ const root = createRoot(rootEl);
199
+ root.render(app);
200
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
201
+ (window as any).__FURIN_ROOT__ = root;
202
+ }
203
+ } else if (rootEl.innerHTML.trim()) {
204
+ hydrateRoot(rootEl, app);
205
+ } else {
206
+ createRoot(rootEl).render(app);
207
+ }
208
+
209
+ log.info({ action: "hydrate_complete", pathname });
210
+ })().catch((err: unknown) => {
211
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
212
+ });
213
+ `;
214
+ }
215
+
216
+ /**
217
+ * Writes _hydrate.tsx + index.html to outDir for dev (Bun HMR) mode.
218
+ *
219
+ * Only rewrites a file when its content has actually changed so Bun's --hot
220
+ * watcher does not trigger a spurious reload on every server restart.
221
+ */
222
+ export function writeDevFiles(
223
+ routes: ResolvedRoute[],
224
+ { outDir, rootLayout, basePath }: BuildClientOptions,
225
+ projectRoot: string
226
+ ): void {
227
+ if (!existsSync(outDir)) {
228
+ mkdirSync(outDir, { recursive: true });
229
+ }
230
+
231
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
232
+ const hydratePath = join(outDir, "_hydrate.tsx");
233
+ const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
234
+ if (hydrateCode !== existingHydrate) {
235
+ writeFileSync(hydratePath, hydrateCode);
236
+ }
237
+
238
+ const indexHtml = generateIndexHtml();
239
+ const indexPath = join(outDir, "index.html");
240
+ const existingIndex = existsSync(indexPath) ? readFileSync(indexPath, "utf8") : "";
241
+ if (indexHtml !== existingIndex) {
242
+ writeFileSync(indexPath, indexHtml);
243
+ }
244
+
245
+ writeRouteTypes(routes, projectRoot);
246
+
247
+ console.log(
248
+ "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
249
+ );
250
+ }