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

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 (84) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/compile-entry.ts +109 -109
  5. package/dist/build/entry-template.ts +156 -156
  6. package/dist/build/index.js +1724 -687
  7. package/dist/build/route-types.d.ts +3 -1
  8. package/dist/build/server-routes-entry.ts +36 -36
  9. package/dist/build/shared.d.ts +1 -0
  10. package/dist/build/ssg-cache.d.ts +1 -1
  11. package/dist/cli/index.js +1673 -658
  12. package/dist/client/link.js +883 -89
  13. package/dist/client/router/index.d.ts +4 -0
  14. package/dist/client/router/link-utils.d.ts +3 -1
  15. package/dist/client/router/navigation.d.ts +10 -0
  16. package/dist/client/router/provider.d.ts +1 -1
  17. package/dist/client/router/search/index.d.ts +18 -0
  18. package/dist/client/router/search-store.d.ts +21 -0
  19. package/dist/client/router/types.d.ts +14 -1
  20. package/dist/client/sync.d.ts +25 -0
  21. package/dist/client.d.ts +1 -0
  22. package/dist/client.js +44 -0
  23. package/dist/furin.d.ts +9 -1
  24. package/dist/furin.js +1578 -258
  25. package/dist/server/auto-invalidate/runtime.d.ts +1 -1
  26. package/dist/server/dev-page-plugin.d.ts +3 -0
  27. package/dist/server/render/assemble.d.ts +2 -0
  28. package/dist/server/render/isr.d.ts +2 -1
  29. package/dist/server/render/ssg.d.ts +3 -2
  30. package/dist/server/render/ssr.d.ts +5 -4
  31. package/dist/server/router/hmr.d.ts +4 -3
  32. package/dist/server/router/index.d.ts +1 -1
  33. package/dist/server/router/index.js +1 -2
  34. package/dist/server/router/index.ts +1 -2
  35. package/dist/server/router/plugin.d.ts +2 -1
  36. package/dist/server/router/schemas.d.ts +25 -17
  37. package/dist/server/sync/config.d.ts +6 -0
  38. package/dist/server/sync/index.d.ts +4 -0
  39. package/dist/server/sync/plugin.d.ts +369 -0
  40. package/dist/server/sync/stream.d.ts +47 -0
  41. package/dist/shared/search-params.d.ts +17 -0
  42. package/package.json +10 -5
  43. package/src/adapter/README.md +13 -13
  44. package/src/adapter/static.ts +23 -6
  45. package/src/build/client.ts +152 -149
  46. package/src/build/compile-entry.ts +109 -109
  47. package/src/build/entry-template.ts +156 -156
  48. package/src/build/hydrate.ts +340 -331
  49. package/src/build/index.ts +152 -152
  50. package/src/build/route-types.ts +145 -115
  51. package/src/build/scan-server.ts +95 -95
  52. package/src/build/server-routes-entry.ts +36 -36
  53. package/src/build/shared.ts +80 -78
  54. package/src/build/ssg-cache.ts +32 -31
  55. package/src/build/types.ts +89 -89
  56. package/src/client/link.tsx +13 -4
  57. package/src/client/router/context.ts +2 -0
  58. package/src/client/router/index.ts +9 -0
  59. package/src/client/router/link-utils.ts +184 -180
  60. package/src/client/router/navigation.ts +61 -0
  61. package/src/client/router/provider.tsx +804 -723
  62. package/src/client/router/search/index.ts +99 -0
  63. package/src/client/router/search-store.ts +86 -0
  64. package/src/client/router/types.ts +276 -263
  65. package/src/client/sync.ts +98 -0
  66. package/src/client.ts +369 -355
  67. package/src/furin.ts +465 -437
  68. package/src/server/auto-invalidate/runtime.ts +134 -133
  69. package/src/server/dev-page-plugin.ts +454 -449
  70. package/src/server/render/assemble.ts +160 -133
  71. package/src/server/render/isr.ts +323 -295
  72. package/src/server/render/not-found.ts +2 -0
  73. package/src/server/render/ssg.ts +15 -4
  74. package/src/server/render/ssr.ts +585 -545
  75. package/src/server/router/hmr.ts +14 -10
  76. package/src/server/router/index.ts +1 -2
  77. package/src/server/router/patterns.ts +5 -0
  78. package/src/server/router/plugin.ts +384 -401
  79. package/src/server/router/schemas.ts +172 -57
  80. package/src/server/sync/config.ts +29 -0
  81. package/src/server/sync/index.ts +14 -0
  82. package/src/server/sync/plugin.ts +108 -0
  83. package/src/server/sync/stream.ts +144 -0
  84. package/src/shared/search-params.ts +182 -0
@@ -0,0 +1,47 @@
1
+ import { Elysia } from "elysia";
2
+ export interface SyncInvalidationEvent {
3
+ invalidations: readonly string[];
4
+ }
5
+ export declare function publishSyncInvalidation(invalidations: readonly string[]): void;
6
+ export declare function createSyncStreamPlugin(path?: string): Elysia<"", {
7
+ decorator: {};
8
+ store: {};
9
+ derive: {};
10
+ resolve: {};
11
+ }, {
12
+ typebox: {};
13
+ error: {};
14
+ }, {
15
+ schema: {};
16
+ standaloneSchema: {};
17
+ macro: {};
18
+ macroFn: {};
19
+ parser: {};
20
+ response: {};
21
+ }, {
22
+ [x: string]: {
23
+ get: {
24
+ body: unknown;
25
+ params: {};
26
+ query: unknown;
27
+ headers: unknown;
28
+ response: {
29
+ 200: Response;
30
+ };
31
+ };
32
+ };
33
+ }, {
34
+ derive: {};
35
+ resolve: {};
36
+ schema: {};
37
+ standaloneSchema: {};
38
+ response: {};
39
+ }, {
40
+ derive: {};
41
+ resolve: {};
42
+ schema: {};
43
+ standaloneSchema: {};
44
+ response: {};
45
+ }>;
46
+ /** @internal — resets process-local stream subscribers between tests. */
47
+ export declare function __resetSyncState(): void;
@@ -0,0 +1,17 @@
1
+ export type SearchParamValue = string | number | boolean | null | undefined | SearchParamValue[] | {
2
+ [key: string]: SearchParamValue;
3
+ };
4
+ export interface SearchParamsInput {
5
+ [key: string]: SearchParamValue;
6
+ }
7
+ export interface SearchRouteMetadata {
8
+ pattern: string;
9
+ regex: RegExp;
10
+ searchDefaults?: SearchParamsInput;
11
+ }
12
+ export declare function stripSearchDefaults(search: SearchParamsInput, defaults: SearchParamsInput | undefined): SearchParamsInput;
13
+ export declare function appendSearchParamValue(params: URLSearchParams, key: string, value: unknown): void;
14
+ export declare function buildSearchParams(search: SearchParamsInput, defaults?: SearchParamsInput): URLSearchParams;
15
+ export declare function collectSearchDefaults(schema: unknown): SearchParamsInput | undefined;
16
+ export declare function findSearchDefaults(pathname: string, routes: readonly SearchRouteMetadata[]): SearchParamsInput | undefined;
17
+ export declare function findSearchDefaultsForRouteTarget(to: string, routes: readonly SearchRouteMetadata[]): SearchParamsInput | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.2.0-alpha.1",
3
+ "version": "0.2.0-alpha.3",
4
4
  "description": "React meta-framework powered by Elysia and Bun with file-based routing, SSR, SSG, and ISR.",
5
5
  "license": "MIT",
6
6
  "author": "teyik0",
@@ -76,6 +76,11 @@
76
76
  "bun": "./src/client/link.tsx",
77
77
  "import": "./dist/client/link.js"
78
78
  },
79
+ "./search": {
80
+ "types": "./dist/client/router/search/index.d.ts",
81
+ "bun": "./src/client/router/search/index.ts",
82
+ "import": "./dist/client/router/search/index.js"
83
+ },
79
84
  "./env": {
80
85
  "types": "./dist/env.d.ts",
81
86
  "bun": "./src/env.d.ts"
@@ -92,16 +97,16 @@
92
97
  "@elysiajs/static": "^1.4.10",
93
98
  "magic-string": "^0.30.21",
94
99
  "seroval": "^1.5.4",
95
- "yuku-parser": "^0.5.31"
100
+ "yuku-parser": "^0.5.43"
96
101
  },
97
102
  "devDependencies": {
98
103
  "@types/react": "^19.2.17",
99
104
  "@types/react-dom": "^19.2.3",
100
- "expect-type": "^1.3.0"
105
+ "expect-type": "^1.4.0"
101
106
  },
102
107
  "peerDependencies": {
103
- "elysia": "^1.4.28",
104
- "evlog": "^2.18.1",
108
+ "elysia": "^1.4.29",
109
+ "evlog": "^2.19.2",
105
110
  "react": "^19.2.7",
106
111
  "react-dom": "^19.2.7"
107
112
  }
@@ -1,13 +1,13 @@
1
- ## Bun adapter
2
-
3
- Goal is having 3 modes:
4
-
5
- - generate server.js + client/
6
- - generate server (compiled to binary) + client/
7
- - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
-
9
- All should be portable.
10
-
11
- ## Cloudflare adapter
12
-
13
- ## Vercel adapter
1
+ ## Bun adapter
2
+
3
+ Goal is having 3 modes:
4
+
5
+ - generate server.js + client/
6
+ - generate server (compiled to binary) + client/
7
+ - generate server (compiled to binary with client/ [embeded](https://bun.com/docs/bundler/executables.md))
8
+
9
+ All should be portable.
10
+
11
+ ## Cloudflare adapter
12
+
13
+ ## Vercel adapter
@@ -8,7 +8,12 @@ import { resolvePath } from "../server/render/assemble.ts";
8
8
  import { prerenderSSG } from "../server/render/index.ts";
9
9
  import { generateProdIndexHtml } from "../server/render/shell.ts";
10
10
  import { setProductionTemplateContent } from "../server/render/template.ts";
11
- import type { ResolvedRoute, RootLayout } from "../server/router/index.ts";
11
+ import {
12
+ createSearchRouteMetadata,
13
+ type ResolvedRoute,
14
+ type RootLayout,
15
+ } from "../server/router/index.ts";
16
+ import type { SearchRouteMetadata } from "../shared/search-params.ts";
12
17
  import { mapWithConcurrency } from "../shared/utils/index.ts";
13
18
 
14
19
  /** Maximum concurrent pre-render calls (mirrors warmSSGCache). */
@@ -55,14 +60,22 @@ async function prerenderAndWrite(
55
60
  outDir: string,
56
61
  renderedRoutes: string[],
57
62
  skippedRoutes: string[],
58
- basePath: string
63
+ basePath: string,
64
+ searchRoutes: SearchRouteMetadata[]
59
65
  ): Promise<void> {
60
66
  const urlPath = resolvePath(route.pattern, params);
61
67
  const htmlOutputFile = pathToOutputFile(urlPath, outDir, "index.html");
62
68
  const dataOutputFile = pathToOutputFile(urlPath, outDir, "__furin_data.ndjson");
63
69
 
64
70
  try {
65
- const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
71
+ const entry = await prerenderSSG(
72
+ route,
73
+ params,
74
+ root,
75
+ "http://localhost",
76
+ basePath,
77
+ searchRoutes
78
+ );
66
79
 
67
80
  if (entry instanceof Response) {
68
81
  console.warn(
@@ -138,7 +151,8 @@ async function buildTaskQueue(
138
151
  outDir: string,
139
152
  renderedRoutes: string[],
140
153
  skippedRoutes: string[],
141
- basePath: string
154
+ basePath: string,
155
+ searchRoutes: SearchRouteMetadata[]
142
156
  ): Promise<Array<() => Promise<void>>> {
143
157
  const tasks: Array<() => Promise<void>> = [];
144
158
 
@@ -200,7 +214,8 @@ async function buildTaskQueue(
200
214
  outDir,
201
215
  renderedRoutes,
202
216
  skippedRoutes,
203
- basePath
217
+ basePath,
218
+ searchRoutes
204
219
  )
205
220
  );
206
221
  }
@@ -294,6 +309,7 @@ export async function buildStaticTarget(
294
309
 
295
310
  // ── 1. Validate SSR/ISR routes before doing any work ─────────────────────
296
311
  const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
312
+ const searchRoutes = createSearchRouteMetadata(ssgRoutes);
297
313
 
298
314
  // ── 2. Clean & create output directories ─────────────────────────────────
299
315
  rmSync(outDir, { force: true, recursive: true });
@@ -345,7 +361,8 @@ export async function buildStaticTarget(
345
361
  outDir,
346
362
  renderedRoutes,
347
363
  skippedRoutes,
348
- basePath
364
+ basePath,
365
+ searchRoutes
349
366
  );
350
367
  // Snapshot after queue-building: routes skipped due to missing staticParams() are
351
368
  // already recorded; only routes added during task execution are prerender failures.
@@ -1,149 +1,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 } 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
-
74
- return {
75
- contents: transformed,
76
- loader: path.endsWith(".tsx") ? "tsx" : "ts",
77
- };
78
- } catch (error) {
79
- console.error(`[furin] Transform error for ${path}:`, error);
80
- return;
81
- }
82
- });
83
- },
84
- };
85
-
86
- const clientBuildConfig: BunBuildAliasConfig = {
87
- // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
88
- // with code-splitting incorrectly references a leaf chunk in the output
89
- // index.html instead of the actual entry chunk, preventing React from
90
- // mounting. We write index.html ourselves after the build.
91
- entrypoints: [hydratePath],
92
- outdir: clientDir,
93
- target: "browser",
94
- format: "esm",
95
- splitting: true,
96
- minify: true,
97
- sourcemap: "none",
98
- // Hash the entry point name so it gets immutable caching like chunks.
99
- // Without this, _hydrate.js keeps the same name across builds and browsers
100
- // serve stale versions that reference old chunk hashes → dynamic import 404.
101
- naming: {
102
- entry: "[dir]/[name]-[hash].[ext]",
103
- chunk: "[name]-[hash].[ext]",
104
- },
105
- // Absolute public path so SSR template asset URLs resolve on any route.
106
- // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
107
- publicPath,
108
- // User plugins run before the internal transform so they pre-process files first
109
- plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
110
- alias: {
111
- "@teyik0/furin/client": CLIENT_MODULE_PATH,
112
- "@teyik0/furin/link": LINK_MODULE_PATH,
113
- },
114
- define: {
115
- "process.env.NODE_ENV": JSON.stringify("production"),
116
- },
117
- };
118
-
119
- const result = await Bun.build(clientBuildConfig);
120
- for (const output of result.outputs) {
121
- console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
122
- }
123
-
124
- // Build index.html (SSR template) with correct chunk references.
125
- // We derive these from result.outputs rather than letting Bun write the HTML,
126
- // because Bun's HTML entrypoint + code-splitting produces the wrong entry chunk.
127
- const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
128
- const cssOutputs = result.outputs.filter(
129
- (o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map")
130
- );
131
- if (!entryOutput) {
132
- throw new Error("[furin] client build did not emit entry chunk");
133
- }
134
-
135
- // Normalise: ensure publicPath ends with exactly one "/".
136
- // Preserve an empty publicPath ("") as-is so callers that want
137
- // relative chunk URLs don't get an unintended root-absolute "/".
138
- let publicPrefix: string;
139
- if (publicPath === "") {
140
- publicPrefix = "";
141
- } else {
142
- publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
143
- }
144
- const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
145
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
146
-
147
- console.log("[furin] Production client build complete");
148
- return { entryChunk, cssChunks };
149
- }
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
+ }