@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.5

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -0,0 +1,206 @@
1
+ import { existsSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import { type BunTargetApp, createBuildFingerprint } from "../adapter/bun.ts";
4
+ import { buildClient } from "../build/client.ts";
5
+ import { buildEntrySource } from "../build/entry-template.ts";
6
+ import { copyDirRecursive, ensureDir, toPosixPath } from "../build/shared.ts";
7
+ import { buildSSGCacheSnapshot } from "../build/ssg-cache.ts";
8
+ import type { BuildAppOptions, PackageTargetBuildManifest } from "../build/types.ts";
9
+ import { ssgRouteCache } from "../server/cache/ssg.ts";
10
+ import { generateProdIndexHtml } from "../server/render/shell.ts";
11
+ import { setProductionTemplateContent } from "../server/render/template.ts";
12
+
13
+ /**
14
+ * `--target package` — builds a furin app as a PUBLISHABLE Elysia plugin
15
+ * instead of a bootable server. Output (`.furin/build/package/`):
16
+ *
17
+ * - `client/` content-hashed chunks + index.html SSR template
18
+ * - `register.js` side-effect module registering the app's CompileContext;
19
+ * page modules are bundled in, but everything from
20
+ * node_modules (incl. @teyik0/furin itself) stays external so
21
+ * the host and the register module share ONE furin runtime
22
+ * - `index.js` `createFurinApp()` factory the host `.use()`es
23
+ * - `index.d.ts` minimal typings for the factory
24
+ *
25
+ * The host composes it like any Elysia plugin:
26
+ *
27
+ * ```ts
28
+ * import { createFurinApp as admin } from "@org/admin/furin";
29
+ * new Elysia().use(await furin({...})).use(await admin()).listen(3000)
30
+ * ```
31
+ *
32
+ * In a monorepo the baked relative `pagesDir` still points at real sources,
33
+ * so the same factory works under `bun --hot` (dev scans live). A published
34
+ * package without sources is production-only; its context is found by prefix.
35
+ */
36
+ export async function buildPackageTarget(
37
+ app: BunTargetApp,
38
+ rootDir: string,
39
+ buildRoot: string,
40
+ options: BuildAppOptions
41
+ ): Promise<PackageTargetBuildManifest> {
42
+ const { prefix, root, routes, pagesDir } = app;
43
+ const targetDir = join(buildRoot, "package");
44
+
45
+ rmSync(targetDir, { force: true, recursive: true });
46
+ ensureDir(targetDir);
47
+
48
+ const { entryChunk, cssChunks } = await buildClient(routes, {
49
+ outDir: targetDir,
50
+ rootLayout: root.path,
51
+ plugins: options.plugins,
52
+ publicPath: `${prefix}/_client/`,
53
+ basePath: prefix,
54
+ clientLogging: options.clientLogging ?? false,
55
+ });
56
+
57
+ // Same fingerprint as the Bun target: hashing only the client chunks would
58
+ // keep the old build ID across SSR-only changes (page/loader code that never
59
+ // reaches the client bundle), defeating stale-deploy detection. The package
60
+ // target has no server entry, hence `null`.
61
+ const buildFingerprint = await createBuildFingerprint(
62
+ `${prefix}\n${entryChunk}`,
63
+ cssChunks,
64
+ routes,
65
+ root,
66
+ null
67
+ );
68
+ const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
69
+
70
+ const clientDir = join(targetDir, "client");
71
+
72
+ // At runtime furin() derives publicDir next to the baked clientDir
73
+ // (join(dirname(clientDir), "public")), so the project's public/ assets must
74
+ // ship inside the artifact or /public/* and /favicon.ico 404 in production.
75
+ const publicDir = join(rootDir, "public");
76
+ if (existsSync(publicDir)) {
77
+ copyDirRecursive(publicDir, join(targetDir, "public"));
78
+ }
79
+
80
+ const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
81
+ writeFileSync(join(clientDir, "index.html"), indexHtml);
82
+
83
+ // SSG snapshot renders through the build-time default state bucket. The
84
+ // mount prefix is passed explicitly — no instance scope exists at build time.
85
+ setProductionTemplateContent(indexHtml);
86
+ ssgRouteCache().clear();
87
+ const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
88
+
89
+ const rootConventions =
90
+ root.errorPath || root.notFoundPath
91
+ ? {
92
+ errorPath: root.errorPath ? toPosixPath(root.errorPath) : undefined,
93
+ notFoundPath: root.notFoundPath ? toPosixPath(root.notFoundPath) : undefined,
94
+ }
95
+ : undefined;
96
+ const routeMetadata: Record<
97
+ string,
98
+ {
99
+ segmentBoundaries: Array<{
100
+ depth: number;
101
+ path: string;
102
+ errorPath?: string;
103
+ notFoundPath?: string;
104
+ }>;
105
+ }
106
+ > = {};
107
+ for (const route of routes) {
108
+ routeMetadata[toPosixPath(route.path)] = {
109
+ segmentBoundaries: route.segmentBoundaries.map((b) => ({
110
+ depth: b.depth,
111
+ path: toPosixPath(b.path),
112
+ errorPath: b.errorPath ? toPosixPath(b.errorPath) : undefined,
113
+ notFoundPath: b.notFoundPath ? toPosixPath(b.notFoundPath) : undefined,
114
+ })),
115
+ };
116
+ }
117
+
118
+ // 1. register.ts — context registration side-effect module.
119
+ const registerSource = buildEntrySource({
120
+ apps: [
121
+ {
122
+ buildId,
123
+ prefix,
124
+ rootPath: root.path,
125
+ routes: routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode })),
126
+ rootConventions,
127
+ routeMetadata,
128
+ ssgCache,
129
+ },
130
+ ],
131
+ headerComment: "// Auto-generated by `furin build --target package` — do not edit",
132
+ mode: "register",
133
+ });
134
+ const registerEntry = join(targetDir, "register.ts");
135
+ writeFileSync(registerEntry, registerSource);
136
+
137
+ const result = await Bun.build({
138
+ entrypoints: [registerEntry],
139
+ outdir: targetDir,
140
+ target: "bun",
141
+ // Keep EVERY dependency external (incl. @teyik0/furin): the host must
142
+ // share one copy of the furin runtime with this register module — only
143
+ // the package's own page sources get bundled in.
144
+ packages: "external",
145
+ naming: { entry: "[name].[ext]", chunk: "[name]-[hash].[ext]" },
146
+ sourcemap: "none",
147
+ minify: false,
148
+ plugins: options.plugins,
149
+ });
150
+ if (!result.success) {
151
+ throw new AggregateError(result.logs, "[furin] package register build failed");
152
+ }
153
+ rmSync(registerEntry, { force: true });
154
+ rmSync(join(targetDir, "_hydrate.tsx"), { force: true });
155
+
156
+ // 2. index.js — the factory the host mounts. The baked relative pagesDir
157
+ // keeps monorepo dev working; in a published package the compile context is
158
+ // resolved by prefix instead.
159
+ const relativePagesDir = toPosixPath(relative(targetDir, resolve(rootDir, pagesDir)));
160
+ const factorySource = `// Auto-generated by \`furin build --target package\` — do not edit
161
+ import { fileURLToPath } from "node:url";
162
+ import { furin } from "@teyik0/furin";
163
+ import "./register.js";
164
+
165
+ const PAGES_DIR = fileURLToPath(new URL(${JSON.stringify(`./${relativePagesDir}`)}, import.meta.url));
166
+ const CLIENT_DIR = fileURLToPath(new URL("./client", import.meta.url));
167
+
168
+ /**
169
+ * Mounts this packaged furin app as an Elysia plugin.
170
+ *
171
+ * @param {object} [options] Extra furin() options (logger, sync, ...) —
172
+ * pagesDir/prefix/clientDir are baked into the package and cannot be overridden.
173
+ * @returns {Promise<import("elysia").Elysia>}
174
+ */
175
+ export function createFurinApp(options = {}) {
176
+ return furin({
177
+ ...options,
178
+ pagesDir: PAGES_DIR,
179
+ prefix: ${JSON.stringify(prefix)},
180
+ clientDir: CLIENT_DIR,
181
+ });
182
+ }
183
+
184
+ export const prefix = ${JSON.stringify(prefix)};
185
+ `;
186
+ writeFileSync(join(targetDir, "index.js"), factorySource);
187
+
188
+ const dtsSource = `import type { Elysia } from "elysia";
189
+ import type { FurinOptions } from "@teyik0/furin";
190
+
191
+ /** Extra furin() options — pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
192
+ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "clientDir">;
193
+ export declare function createFurinApp(options?: CreateFurinAppOptions): Promise<Elysia>;
194
+ export declare const prefix: string;
195
+ `;
196
+ writeFileSync(join(targetDir, "index.d.ts"), dtsSource);
197
+
198
+ console.log(`[furin] Package artifact: ${toPosixPath(relative(rootDir, targetDir))}`);
199
+
200
+ return {
201
+ buildId,
202
+ generatedAt: new Date().toISOString(),
203
+ prefix,
204
+ targetDir: toPosixPath(relative(rootDir, targetDir)),
205
+ };
206
+ }
@@ -1,152 +1,158 @@
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 "../server/router/index.ts";
5
- import { generateHydrateEntry } from "./hydrate";
6
- import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
- import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
-
9
- const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
-
11
- export interface BuildClientResult {
12
- /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
13
- cssChunks: string[];
14
- /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
15
- entryChunk: string;
16
- }
17
-
18
- /**
19
- * Builds the production client bundle via Bun.build() using _hydrate.tsx as
20
- * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
21
- * <outDir>/client/chunk-*.js — code-split bundles
22
- * <outDir>/client/chunk-*.css — extracted CSS (if imported)
23
- *
24
- * Returns the chunk paths so the caller can compute a `buildId` and write
25
- * `index.html` with the correct meta tag. Using an HTML entrypoint with
26
- * code-splitting causes a Bun bug where the output index.html references a
27
- * leaf chunk instead of the actual entry chunk, preventing React from mounting
28
- * in production.
29
- *
30
- * The output index.html is NOT served to browsers directly. The server reads
31
- * it as an SSR template, injects the pre-rendered React HTML into
32
- * <!--ssr-outlet-->, and sends the complete page.
33
- */
34
- export async function buildClient(
35
- routes: ResolvedRoute[],
36
- { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions
37
- ): Promise<BuildClientResult> {
38
- const clientDir = join(outDir, "client");
39
-
40
- if (!existsSync(outDir)) {
41
- mkdirSync(outDir, { recursive: true });
42
- }
43
- if (!existsSync(clientDir)) {
44
- mkdirSync(clientDir, { recursive: true });
45
- }
46
-
47
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
48
- const hydratePath = join(outDir, "_hydrate.tsx");
49
- writeFileSync(hydratePath, hydrateCode);
50
-
51
- console.log("[furin] Building production client bundle…");
52
-
53
- const transformPlugin: Bun.BunPlugin = {
54
- name: "furin-transform-client",
55
- setup(build) {
56
- build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
57
- const { path } = args;
58
- if (path.includes("node_modules")) {
59
- return;
60
- }
61
-
62
- const code = await Bun.file(path).text();
63
- try {
64
- const result = transformForClient(code, path);
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
69
- .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
70
- .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
71
- .replaceAll(`"@teyik0/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));
75
-
76
- return {
77
- contents: transformed,
78
- loader: path.endsWith(".tsx") ? "tsx" : "ts",
79
- };
80
- } catch (error) {
81
- console.error(`[furin] Transform error for ${path}:`, error);
82
- return;
83
- }
84
- });
85
- },
86
- };
87
-
88
- const clientBuildConfig: BunBuildAliasConfig = {
89
- // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
90
- // with code-splitting incorrectly references a leaf chunk in the output
91
- // index.html instead of the actual entry chunk, preventing React from
92
- // mounting. We write index.html ourselves after the build.
93
- entrypoints: [hydratePath],
94
- outdir: clientDir,
95
- target: "browser",
96
- format: "esm",
97
- splitting: true,
98
- minify: true,
99
- sourcemap: "none",
100
- // Hash the entry point name so it gets immutable caching like chunks.
101
- // Without this, _hydrate.js keeps the same name across builds and browsers
102
- // serve stale versions that reference old chunk hashes → dynamic import 404.
103
- naming: {
104
- entry: "[dir]/[name]-[hash].[ext]",
105
- chunk: "[name]-[hash].[ext]",
106
- },
107
- // Absolute public path so SSR template asset URLs resolve on any route.
108
- // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
109
- publicPath,
110
- // User plugins run before the internal transform so they pre-process files first
111
- plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
112
- alias: {
113
- "@teyik0/furin/client": CLIENT_MODULE_PATH,
114
- "@teyik0/furin/link": LINK_MODULE_PATH,
115
- "@teyik0/furin/search": SEARCH_MODULE_PATH,
116
- },
117
- define: {
118
- "process.env.NODE_ENV": JSON.stringify("production"),
119
- },
120
- };
121
-
122
- const result = await Bun.build(clientBuildConfig);
123
- for (const output of result.outputs) {
124
- console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
125
- }
126
-
127
- // Build index.html (SSR template) with correct chunk references.
128
- // We derive these from result.outputs rather than letting Bun write the HTML,
129
- // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
130
- const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
131
- const cssOutputs = result.outputs.filter(
132
- (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
133
- );
134
- if (!entryOutput) {
135
- throw new Error("[furin] client build did not emit entry chunk");
136
- }
137
-
138
- // Normalise: ensure publicPath ends with exactly one "/".
139
- // Preserve an empty publicPath ("") as-is so callers that want
140
- // relative chunk URLs don't get an unintended root-absolute "/".
141
- let publicPrefix: string;
142
- if (publicPath === "") {
143
- publicPrefix = "";
144
- } else {
145
- publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
146
- }
147
- const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
148
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
149
-
150
- console.log("[furin] Production client build complete");
151
- return { entryChunk, cssChunks };
152
- }
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 "../server/router/index.ts";
5
+ import { generateHydrateEntry } from "./hydrate";
6
+ import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
7
+ import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
8
+
9
+ const TS_FILE_FILTER = /\.(tsx|ts)$/;
10
+
11
+ export interface BuildClientResult {
12
+ /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
13
+ cssChunks: string[];
14
+ /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
15
+ entryChunk: string;
16
+ }
17
+
18
+ /**
19
+ * Builds the production client bundle via Bun.build() using _hydrate.tsx as
20
+ * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
21
+ * <outDir>/client/chunk-*.js — code-split bundles
22
+ * <outDir>/client/chunk-*.css — extracted CSS (if imported)
23
+ *
24
+ * Returns the chunk paths so the caller can compute a `buildId` and write
25
+ * `index.html` with the correct meta tag. Using an HTML entrypoint with
26
+ * code-splitting causes a Bun bug where the output index.html references a
27
+ * leaf chunk instead of the actual entry chunk, preventing React from mounting
28
+ * in production.
29
+ *
30
+ * The output index.html is NOT served to browsers directly. The server reads
31
+ * it as an SSR template, injects the pre-rendered React HTML into
32
+ * <!--ssr-outlet-->, and sends the complete page.
33
+ */
34
+ export async function buildClient(
35
+ routes: ResolvedRoute[],
36
+ { outDir, rootLayout, plugins, publicPath, basePath, clientLogging, clientDirName }: BuildClientOptions
37
+ ): Promise<BuildClientResult> {
38
+ // Per-app client dir so several mounted apps build side by side
39
+ // ("client", "client-admin", …) without clobbering each other.
40
+ const dirName = clientDirName ?? "client";
41
+ const clientDir = join(outDir, dirName);
42
+
43
+ if (!existsSync(outDir)) {
44
+ mkdirSync(outDir, { recursive: true });
45
+ }
46
+ if (!existsSync(clientDir)) {
47
+ mkdirSync(clientDir, { recursive: true });
48
+ }
49
+
50
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
51
+ const hydratePath = join(
52
+ outDir,
53
+ dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`
54
+ );
55
+ writeFileSync(hydratePath, hydrateCode);
56
+
57
+ console.log("[furin] Building production client bundle…");
58
+
59
+ const transformPlugin: Bun.BunPlugin = {
60
+ name: "furin-transform-client",
61
+ setup(build) {
62
+ build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
63
+ const { path } = args;
64
+ if (path.includes("node_modules")) {
65
+ return;
66
+ }
67
+
68
+ const code = await Bun.file(path).text();
69
+ try {
70
+ const result = transformForClient(code, path);
71
+ // transformForClient now emits TS/TSX directly (no pre-transpile),
72
+ // so JSX → React handling is delegated to Bun.build's loader, which
73
+ // applies the project tsconfig's automatic runtime by default.
74
+ const transformed = result.code
75
+ .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
76
+ .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
77
+ .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
78
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
79
+ .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
80
+ .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
81
+
82
+ return {
83
+ contents: transformed,
84
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
85
+ };
86
+ } catch (error) {
87
+ console.error(`[furin] Transform error for ${path}:`, error);
88
+ return;
89
+ }
90
+ });
91
+ },
92
+ };
93
+
94
+ const clientBuildConfig: BunBuildAliasConfig = {
95
+ // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
96
+ // with code-splitting incorrectly references a leaf chunk in the output
97
+ // index.html instead of the actual entry chunk, preventing React from
98
+ // mounting. We write index.html ourselves after the build.
99
+ entrypoints: [hydratePath],
100
+ outdir: clientDir,
101
+ target: "browser",
102
+ format: "esm",
103
+ splitting: true,
104
+ minify: true,
105
+ sourcemap: "none",
106
+ // Hash the entry point name so it gets immutable caching like chunks.
107
+ // Without this, _hydrate.js keeps the same name across builds and browsers
108
+ // serve stale versions that reference old chunk hashes → dynamic import 404.
109
+ naming: {
110
+ entry: "[dir]/[name]-[hash].[ext]",
111
+ chunk: "[name]-[hash].[ext]",
112
+ },
113
+ // Absolute public path so SSR template asset URLs resolve on any route.
114
+ // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
115
+ publicPath,
116
+ // User plugins run before the internal transform so they pre-process files first
117
+ plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
118
+ alias: {
119
+ "@teyik0/furin/client": CLIENT_MODULE_PATH,
120
+ "@teyik0/furin/link": LINK_MODULE_PATH,
121
+ "@teyik0/furin/search": SEARCH_MODULE_PATH,
122
+ },
123
+ define: {
124
+ "process.env.NODE_ENV": JSON.stringify("production"),
125
+ },
126
+ };
127
+
128
+ const result = await Bun.build(clientBuildConfig);
129
+ for (const output of result.outputs) {
130
+ console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
131
+ }
132
+
133
+ // Build index.html (SSR template) with correct chunk references.
134
+ // We derive these from result.outputs rather than letting Bun write the HTML,
135
+ // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
136
+ const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
137
+ const cssOutputs = result.outputs.filter(
138
+ (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
139
+ );
140
+ if (!entryOutput) {
141
+ throw new Error("[furin] client build did not emit entry chunk");
142
+ }
143
+
144
+ // Normalise: ensure publicPath ends with exactly one "/".
145
+ // Preserve an empty publicPath ("") as-is so callers that want
146
+ // relative chunk URLs don't get an unintended root-absolute "/".
147
+ let publicPrefix: string;
148
+ if (publicPath === "") {
149
+ publicPrefix = "";
150
+ } else {
151
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
152
+ }
153
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
154
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
155
+
156
+ console.log("[furin] Production client build complete");
157
+ return { entryChunk, cssChunks };
158
+ }