@teyik0/furin 0.4.0-alpha.1 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +6 -4
  7. package/dist/build/compile-entry.ts +36 -77
  8. package/dist/build/elysia-aot.d.ts +9 -0
  9. package/dist/build/entry-template.d.ts +9 -3
  10. package/dist/build/entry-template.ts +55 -13
  11. package/dist/build/index.d.ts +1 -1
  12. package/dist/build/index.js +8912 -6391
  13. package/dist/build/server-app-entry.d.ts +12 -0
  14. package/dist/build/ssg-cache.d.ts +13 -0
  15. package/dist/build/types.d.ts +25 -2
  16. package/dist/build/virtual-entry.d.ts +8 -0
  17. package/dist/cache.d.ts +6 -0
  18. package/dist/cache.js +282 -0
  19. package/dist/cli/index.js +8936 -6308
  20. package/dist/cli/preview.d.ts +7 -0
  21. package/dist/client/boundaries.d.ts +1 -0
  22. package/dist/client/browser-events-runtime.d.ts +2 -0
  23. package/dist/client/browser-events.d.ts +2 -0
  24. package/dist/client/define-route.d.ts +9 -8
  25. package/dist/client/dev-error-overlay.d.ts +1 -0
  26. package/dist/client/dev-error-overlay.ts +201 -0
  27. package/dist/client/document.d.ts +1 -0
  28. package/dist/client/hmr.d.ts +4 -2
  29. package/dist/client/internal/runtime-types.d.ts +8 -1
  30. package/dist/client/link.js +465 -86
  31. package/dist/client/router/provider.d.ts +1 -1
  32. package/dist/client/router/sync-catch-up.d.ts +1 -1
  33. package/dist/client/router/types.d.ts +8 -10
  34. package/dist/client/sync.d.ts +1 -0
  35. package/dist/client.js +37 -23
  36. package/dist/config.d.ts +35 -17
  37. package/dist/config.js +10 -2
  38. package/dist/define-route.d.ts +282 -1015
  39. package/dist/devtools/protocol.d.ts +2 -2
  40. package/dist/furin.d.ts +21 -6
  41. package/dist/furin.js +12823 -8484
  42. package/dist/plugin/index.js +476 -7
  43. package/dist/plugin/routes.d.ts +10 -3
  44. package/dist/rsc/build/index.d.ts +5 -1
  45. package/dist/server/assets/production.d.ts +3 -0
  46. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  47. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  48. package/dist/server/browser-events/plugin.d.ts +11 -0
  49. package/dist/server/browser-events/types.d.ts +9 -0
  50. package/dist/server/cache/invalidation.d.ts +2 -3
  51. package/dist/server/cache/isr.d.ts +1 -0
  52. package/dist/server/cache/page-cache-state.d.ts +5 -0
  53. package/dist/server/cache/page-cache.d.ts +53 -0
  54. package/dist/server/cache/purger.d.ts +7 -0
  55. package/dist/server/cache/redis/index.d.ts +39 -0
  56. package/dist/server/cache/redis/index.js +396 -0
  57. package/dist/server/cache/redis/scripts.d.ts +6 -0
  58. package/dist/server/cache/runtime-cache.d.ts +21 -0
  59. package/dist/server/context-logger.d.ts +2 -2
  60. package/dist/server/dev/browser-events.d.ts +4 -0
  61. package/dist/server/dev/diagnostics.d.ts +39 -0
  62. package/dist/server/dev/error.d.ts +17 -0
  63. package/dist/server/dev/graph.d.ts +86 -0
  64. package/dist/server/dev/plugin.d.ts +9 -0
  65. package/dist/server/dev/request-security.d.ts +1 -0
  66. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  67. package/dist/server/dev/runtime.production.d.ts +6 -0
  68. package/dist/server/dev/symbolicate.d.ts +11 -0
  69. package/dist/server/dev/transform-failure.d.ts +4 -0
  70. package/dist/server/dev-page-plugin.d.ts +7 -0
  71. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  72. package/dist/server/devtools/hub.d.ts +3 -2
  73. package/dist/server/devtools/instrumentation.d.ts +1 -1
  74. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  75. package/dist/server/devtools/plugin.d.ts +1 -1
  76. package/dist/server/evlog.d.ts +14 -0
  77. package/dist/server/external-prerender.d.ts +2 -0
  78. package/dist/server/instance.d.ts +2 -2
  79. package/dist/server/internal.d.ts +20 -2
  80. package/dist/server/internal.js +2973 -1
  81. package/dist/server/render/element.d.ts +1 -0
  82. package/dist/server/render/index.d.ts +1 -1
  83. package/dist/server/render/index.ts +1 -1
  84. package/dist/server/render/not-found.d.ts +1 -1
  85. package/dist/server/render/ppr-document.d.ts +21 -0
  86. package/dist/server/render/ppr-request.d.ts +26 -0
  87. package/dist/server/render/ppr-route.d.ts +3 -1
  88. package/dist/server/render/shell.ts +0 -12
  89. package/dist/server/render/ssg.d.ts +7 -0
  90. package/dist/server/render/ssr.d.ts +17 -6
  91. package/dist/server/render/static-params.d.ts +4 -0
  92. package/dist/server/router/defined-route.d.ts +1 -1
  93. package/dist/server/router/hmr.production.d.ts +2 -0
  94. package/dist/server/router/patterns.d.ts +1 -0
  95. package/dist/server/router/plugin.d.ts +3 -1
  96. package/dist/server/router/schemas.d.ts +1 -0
  97. package/dist/server/sync/adapter.d.ts +13 -0
  98. package/dist/server/sync/config.d.ts +5 -5
  99. package/dist/server/sync/index.d.ts +6 -6
  100. package/dist/server/sync/index.js +1252 -599
  101. package/dist/server/sync/notifier.d.ts +1 -0
  102. package/dist/server/sync/plugin.d.ts +31 -158
  103. package/dist/server/sync/postgres/index.d.ts +12 -1
  104. package/dist/server/sync/postgres/index.js +101 -6
  105. package/dist/server/sync/stream.d.ts +37 -61
  106. package/dist/shared/await.d.ts +3 -3
  107. package/dist/shared/browser-events.d.ts +22 -0
  108. package/dist/shared/compact-json.d.ts +8 -0
  109. package/dist/shared/deferred-ndjson.d.ts +6 -5
  110. package/dist/shared/dev-diagnostics.d.ts +36 -0
  111. package/dist/shared/elysia-contract.d.ts +8 -14
  112. package/dist/shared/prefix.d.ts +2 -0
  113. package/package.json +26 -11
  114. package/src/adapter/README.md +53 -1
  115. package/src/adapter/bun.ts +106 -283
  116. package/src/adapter/package.ts +21 -11
  117. package/src/adapter/runtime-build.ts +382 -0
  118. package/src/adapter/static.ts +87 -8
  119. package/src/adapter/vercel.ts +876 -0
  120. package/src/build/client.ts +55 -13
  121. package/src/build/compile-entry.ts +36 -77
  122. package/src/build/elysia-aot.ts +102 -0
  123. package/src/build/entry-template.ts +55 -13
  124. package/src/build/hydrate.ts +60 -20
  125. package/src/build/index.ts +17 -8
  126. package/src/build/production-instrumentation.ts +56 -4
  127. package/src/build/server-app-entry.ts +60 -0
  128. package/src/build/shared.ts +5 -2
  129. package/src/build/ssg-cache.ts +93 -12
  130. package/src/build/types.ts +31 -2
  131. package/src/build/virtual-entry.ts +28 -0
  132. package/src/cache.ts +26 -0
  133. package/src/cli/config.ts +3 -3
  134. package/src/cli/index.ts +58 -3
  135. package/src/cli/preview.ts +90 -0
  136. package/src/client/boundaries.tsx +10 -1
  137. package/src/client/browser-events-runtime.ts +204 -0
  138. package/src/client/browser-events.ts +22 -0
  139. package/src/client/define-route.ts +7 -17
  140. package/src/client/dev-error-overlay.ts +201 -0
  141. package/src/client/document.tsx +4 -7
  142. package/src/client/hmr.ts +26 -3
  143. package/src/client/internal/runtime-types.ts +10 -1
  144. package/src/client/router/boundary-tree.tsx +4 -4
  145. package/src/client/router/provider.tsx +165 -63
  146. package/src/client/router/sync-catch-up.ts +3 -4
  147. package/src/client/router/types.ts +6 -6
  148. package/src/client/sync.ts +1 -0
  149. package/src/config.ts +28 -2
  150. package/src/define-route.ts +285 -134
  151. package/src/devtools/devtools-element.js +56 -77
  152. package/src/devtools/protocol.ts +2 -2
  153. package/src/furin.ts +272 -203
  154. package/src/plugin/route-config-autofix.ts +11 -2
  155. package/src/plugin/routes.ts +291 -65
  156. package/src/plugin/transform-client.ts +685 -3
  157. package/src/react-dom-edge.d.ts +6 -0
  158. package/src/rsc/build/index.ts +15 -3
  159. package/src/server/assets/production.ts +99 -0
  160. package/src/server/auto-invalidate/plugin.ts +4 -4
  161. package/src/server/auto-invalidate/runtime.ts +76 -41
  162. package/src/server/browser-events/plugin.ts +173 -0
  163. package/src/server/browser-events/types.ts +11 -0
  164. package/src/server/cache/dev-loader.ts +30 -29
  165. package/src/server/cache/invalidation.ts +67 -35
  166. package/src/server/cache/isr.ts +9 -0
  167. package/src/server/cache/page-cache-state.ts +22 -0
  168. package/src/server/cache/page-cache.ts +300 -0
  169. package/src/server/cache/purger.ts +41 -0
  170. package/src/server/cache/redis/index.ts +350 -0
  171. package/src/server/cache/redis/scripts.ts +160 -0
  172. package/src/server/cache/runtime-cache.ts +137 -0
  173. package/src/server/context-logger.ts +5 -5
  174. package/src/server/dev/browser-events.ts +54 -0
  175. package/src/server/dev/diagnostics.ts +297 -0
  176. package/src/server/dev/error.ts +148 -0
  177. package/src/server/dev/graph.ts +438 -0
  178. package/src/server/dev/plugin.ts +130 -0
  179. package/src/server/dev/request-security.ts +38 -0
  180. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  181. package/src/server/dev/runtime.production.ts +28 -0
  182. package/src/server/dev/symbolicate.ts +135 -0
  183. package/src/server/dev/transform-failure.ts +8 -0
  184. package/src/server/dev-page-plugin.production.ts +3 -0
  185. package/src/server/dev-page-plugin.ts +136 -53
  186. package/src/server/devtools/hub.ts +6 -5
  187. package/src/server/devtools/instrumentation.production.ts +1 -1
  188. package/src/server/devtools/instrumentation.ts +12 -6
  189. package/src/server/devtools/plugin.ts +7 -150
  190. package/src/server/evlog.ts +99 -0
  191. package/src/server/external-prerender.ts +10 -0
  192. package/src/server/instance.ts +3 -3
  193. package/src/server/internal.ts +46 -2
  194. package/src/server/render/assemble.ts +4 -4
  195. package/src/server/render/document.tsx +13 -4
  196. package/src/server/render/element.tsx +18 -14
  197. package/src/server/render/index.ts +1 -1
  198. package/src/server/render/isr.ts +509 -136
  199. package/src/server/render/loaders.ts +31 -15
  200. package/src/server/render/not-found.ts +32 -8
  201. package/src/server/render/ppr-document.ts +239 -0
  202. package/src/server/render/ppr-request.ts +104 -0
  203. package/src/server/render/ppr-route.ts +335 -28
  204. package/src/server/render/shell.ts +0 -12
  205. package/src/server/render/ssg.ts +186 -24
  206. package/src/server/render/ssr.ts +215 -89
  207. package/src/server/render/static-params.ts +174 -0
  208. package/src/server/render/template.ts +47 -11
  209. package/src/server/router/defined-route.ts +9 -40
  210. package/src/server/router/hmr.production.ts +7 -0
  211. package/src/server/router/hmr.ts +108 -67
  212. package/src/server/router/patterns.ts +5 -1
  213. package/src/server/router/plugin.ts +164 -66
  214. package/src/server/router/schema-merge.ts +1 -1
  215. package/src/server/router/schemas.ts +174 -61
  216. package/src/server/router/source-version.ts +3 -10
  217. package/src/server/sync/adapter.ts +13 -0
  218. package/src/server/sync/config.ts +12 -12
  219. package/src/server/sync/index.ts +8 -8
  220. package/src/server/sync/notifier.ts +1 -0
  221. package/src/server/sync/plugin.ts +18 -11
  222. package/src/server/sync/postgres/index.ts +111 -5
  223. package/src/server/sync/response.ts +3 -3
  224. package/src/server/sync/runtime.ts +12 -0
  225. package/src/server/sync/stream.ts +78 -113
  226. package/src/shared/await.tsx +3 -3
  227. package/src/shared/browser-events.ts +28 -0
  228. package/src/shared/compact-json.ts +77 -0
  229. package/src/shared/deferred-ndjson.ts +20 -6
  230. package/src/shared/dev-diagnostics.ts +44 -0
  231. package/src/shared/elysia-contract.ts +23 -25
  232. package/src/shared/prefix.ts +8 -0
  233. package/src/shared/route-map.ts +10 -1
@@ -1,5 +1,5 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { basename, join } from "node:path";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { transformForClient } from "../plugin/transform-client";
4
4
  import { createRoutesPlugin } from "../plugin/routes.ts";
5
5
  import { environmentGuardPlugin } from "../rsc/build/environment.ts";
@@ -9,8 +9,20 @@ import { runBunBuild } from "./bun-build.ts";
9
9
  import { generateHydrateEntry } from "./hydrate";
10
10
  import { CLIENT_MODULE_PATH, LINK_MODULE_PATH, SEARCH_MODULE_PATH } from "./shared";
11
11
  import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
12
+ import { createVirtualBuildEntry } from "./virtual-entry.ts";
12
13
 
13
14
  const SCRIPT_FILE_FILTER = /\.(tsx?|jsx?)$/;
15
+ const ROUTER_PROVIDER_PATH = resolve(import.meta.dir, "../client/router/provider.tsx");
16
+
17
+ function resolveClientModuleSpecifiers(code: string): string {
18
+ return code
19
+ .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
20
+ .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
21
+ .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
22
+ .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
23
+ .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
24
+ .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
25
+ }
14
26
 
15
27
  export interface BuildClientResult {
16
28
  /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
@@ -45,6 +57,9 @@ export async function buildClient(
45
57
  basePath,
46
58
  clientLogging,
47
59
  clientDirName,
60
+ metafilePath,
61
+ optimizeImports,
62
+ reactCompiler,
48
63
  pagesDir,
49
64
  }: BuildClientOptions
50
65
  ): Promise<BuildClientResult> {
@@ -60,12 +75,14 @@ export async function buildClient(
60
75
  mkdirSync(clientDir, { recursive: true });
61
76
  }
62
77
 
63
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
78
+ const hydrateCode = resolveClientModuleSpecifiers(
79
+ generateHydrateEntry(routes, rootLayout, basePath, clientLogging)
80
+ );
64
81
  const hydratePath = join(
65
82
  outDir,
66
83
  dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`
67
84
  );
68
- writeFileSync(hydratePath, hydrateCode);
85
+ const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
69
86
 
70
87
  console.log("[furin] Building production client bundle…");
71
88
 
@@ -83,13 +100,7 @@ export async function buildClient(
83
100
  // transformForClient now emits TS/TSX directly (no pre-transpile),
84
101
  // so JSX → React handling is delegated to Bun.build's loader, which
85
102
  // applies the project tsconfig's automatic runtime by default.
86
- const transformed = result.code
87
- .replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH))
88
- .replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH))
89
- .replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH))
90
- .replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH))
91
- .replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH))
92
- .replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
103
+ const transformed = resolveClientModuleSpecifiers(result.code);
93
104
 
94
105
  return {
95
106
  contents: transformed,
@@ -99,31 +110,54 @@ export async function buildClient(
99
110
  },
100
111
  };
101
112
 
113
+ const routerLoggerPlugin: Bun.BunPlugin = {
114
+ name: "furin-client-router-logger",
115
+ setup(build) {
116
+ build.onResolve({ filter: /^evlog$/ }, ({ importer }) => {
117
+ if (importer === ROUTER_PROVIDER_PATH) {
118
+ return { namespace: "furin-client-router-logger", path: "router-logger" };
119
+ }
120
+ });
121
+ build.onLoad({ filter: /.*/, namespace: "furin-client-router-logger" }, () => ({
122
+ contents: "export const log = { warn: console.warn, error: console.error };",
123
+ loader: "js",
124
+ }));
125
+ },
126
+ };
127
+
102
128
  const clientBuildConfig: BunBuildAliasConfig = {
103
129
  // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
104
130
  // with code-splitting incorrectly references a leaf chunk in the output
105
131
  // index.html instead of the actual entry chunk, preventing React from
106
132
  // mounting. We write index.html ourselves after the build.
107
- entrypoints: [hydratePath],
133
+ entrypoints: [hydrateEntry.entrypoint],
134
+ files: hydrateEntry.files,
108
135
  outdir: clientDir,
109
136
  target: "browser",
110
137
  format: "esm",
111
138
  splitting: true,
139
+ optimizeImports,
140
+ reactCompiler: reactCompiler ?? true,
141
+ reactCompilerOutputMode: "client",
112
142
  minify: true,
113
143
  sourcemap: "none",
144
+ metafile: metafilePath !== undefined,
114
145
  // Hash the entry point name so it gets immutable caching like chunks.
115
146
  // Without this, _hydrate.js keeps the same name across builds and browsers
116
147
  // serve stale versions that reference old chunk hashes → dynamic import 404.
117
148
  naming: {
118
- entry: "[dir]/[name]-[hash].[ext]",
149
+ entry: "[name]-[hash].[ext]",
119
150
  chunk: "[name]-[hash].[ext]",
120
151
  },
121
152
  // Absolute public path so SSR template asset URLs resolve on any route.
122
153
  // Overridable via the `publicPath` option (e.g. "/furin/_client/" for basePath builds).
123
154
  publicPath,
124
- // User plugins run before the internal transform so they pre-process files first
155
+ // Resolve the in-memory entry first. User plugins still run before Furin's
156
+ // transforms for every imported application module.
125
157
  plugins: [
158
+ hydrateEntry.plugin,
126
159
  ...(plugins ?? []),
160
+ ...(!clientLogging ? [routerLoggerPlugin] : []),
127
161
  ...(pagesDir
128
162
  ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })]
129
163
  : []),
@@ -141,6 +175,14 @@ export async function buildClient(
141
175
  };
142
176
 
143
177
  const result = await runBunBuild(clientBuildConfig);
178
+ if (metafilePath !== undefined) {
179
+ if (result.metafile === undefined) {
180
+ throw new Error("[furin] client build did not produce the requested metafile");
181
+ }
182
+ mkdirSync(dirname(metafilePath), { recursive: true });
183
+ writeFileSync(metafilePath, `${JSON.stringify(result.metafile, null, 2)}\n`);
184
+ console.log(`[furin] Client metafile: ${metafilePath}`);
185
+ }
144
186
  for (const output of result.outputs) {
145
187
  console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
146
188
  }
@@ -1,106 +1,66 @@
1
- import { existsSync, writeFileSync } from "node:fs";
2
- import { join, relative } from "node:path";
1
+ import { existsSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
3
  import { buildEntrySource, type BuildEntryOptions, type EntryAppContext } from "./entry-template";
4
- import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
4
+ import { ensureDir } from "./shared";
5
+ import { createVirtualBuildEntry, type VirtualBuildEntry } from "./virtual-entry.ts";
5
6
 
6
7
  /**
7
- * Builds one app's embedded-asset import lines + `embedded:` context block.
8
- * Asset keys stay UNPREFIXED (`/_client/...`) — the instance's Elysia prefix
9
- * strips the mount path before lookup at runtime.
8
+ * Builds one app's embedded directory context. Bun places each directory from
9
+ * `compile.assets` below `import.meta.dir` in the standalone executable.
10
10
  */
11
- function buildEmbeddedAssets(
12
- outDir: string,
11
+ function buildEmbeddedContext(
13
12
  clientDir: string,
14
- publicDir: string | undefined,
15
- varPrefix: string
16
- ): { extraContext: string[]; extraImports: string[] } {
13
+ publicDir: string | undefined
14
+ ): string[] {
17
15
  if (!existsSync(clientDir)) {
18
16
  throw new Error(
19
17
  `[furin] Client directory not found: ${clientDir}. Run the client build first.`
20
18
  );
21
19
  }
22
- const clientFiles = collectFilesRecursive(clientDir).filter((file) => !file.endsWith(".map"));
23
- const assetImports: string[] = [];
24
- const assetEntries: string[] = [];
25
- let templateVarName: string | null = null;
26
-
27
- let assetIndex = 0;
28
- const importAsset = (file: string): string => {
29
- const varName = `${varPrefix}asset${assetIndex++}`;
30
- const relPath = toPosixPath(relative(outDir, file));
31
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
32
- assetImports.push(
33
- `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
34
- );
35
- return varName;
36
- };
37
-
38
- for (const file of clientFiles) {
39
- const varName = importAsset(file);
40
- const clientRelativePath = toPosixPath(relative(clientDir, file));
41
- if (clientRelativePath === "index.html") {
42
- templateVarName = varName;
43
- } else {
44
- assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
45
- }
46
- }
47
-
48
- if (templateVarName === null) {
20
+ if (!existsSync(join(clientDir, "index.html"))) {
49
21
  throw new Error(
50
22
  `[furin] Embed mode requires a client index.html at ${join(clientDir, "index.html")}. Run the client build first.`
51
23
  );
52
24
  }
53
25
 
54
- if (publicDir && existsSync(publicDir)) {
55
- const publicFiles = collectFilesRecursive(publicDir);
56
- for (const file of publicFiles) {
57
- const varName = importAsset(file);
58
- const publicRelativePath = toPosixPath(relative(publicDir, file));
59
- assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
60
- }
61
- }
62
-
63
- const extraContext = [
26
+ return [
64
27
  " embedded: {",
65
- ` template: ${templateVarName},`,
66
- " assets: {",
67
- ...assetEntries,
68
- " },",
28
+ ` clientDir: import.meta.dir + ${JSON.stringify(`/${basename(clientDir)}`)},`,
29
+ ...(publicDir && existsSync(publicDir)
30
+ ? [` publicDir: import.meta.dir + ${JSON.stringify(`/${basename(publicDir)}`)},`]
31
+ : []),
69
32
  " },",
70
33
  ];
71
-
72
- return { extraContext, extraImports: assetImports };
73
34
  }
74
35
 
75
- /**
76
- * Generates a single `_compile-entry.ts` that:
77
- * 1. Statically imports every page module of every app so Bun bundles them
78
- * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
79
- * 3. Sets production mode and registers one CompileContext PER APP
80
- * 4. Dynamically imports server.ts to boot the composed app
81
- */
82
- export function generateCompileEntry(options: BuildEntryOptions): string {
83
- const { apps, outDir, serverEntry, publicDir } = options;
84
- ensureDir(outDir);
85
-
86
- const preparedApps: EntryAppContext[] = apps.map((app, appIndex) => {
36
+ export function prepareCompileEntryApps(options: BuildEntryOptions): EntryAppContext[] {
37
+ return options.apps.map((app) => {
87
38
  const { embed, ...context } = app;
88
39
  if (!embed) {
89
40
  return context;
90
41
  }
91
- const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
92
- // Every app gets the project-level public/ dir: each instance serves only
93
- // from its own `embedded.assets`, so `/public/*` (and `/favicon.ico`) would
94
- // 404 on non-first apps otherwise. This only duplicates the string keys —
95
- // each app imports the same file via the same relative path, and Bun
96
- // dedupes identical `with { type: "file" }` modules into one embedded blob.
97
- const embedded = buildEmbeddedAssets(outDir, embed.clientDir, publicDir, varPrefix);
98
42
  return {
99
43
  ...context,
100
- extraContext: [...(context.extraContext ?? []), ...embedded.extraContext],
101
- extraImports: [...(context.extraImports ?? []), ...embedded.extraImports],
44
+ extraContext: [
45
+ ...(context.extraContext ?? []),
46
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir),
47
+ ],
102
48
  };
103
49
  });
50
+ }
51
+
52
+ /**
53
+ * Generates a virtual `_compile-entry.ts` that:
54
+ * 1. Statically imports every page module of every app so Bun bundles them
55
+ * 2. Points embed-mode contexts at Bun's `compile.assets` directories
56
+ * 3. Sets production mode and registers one CompileContext PER APP
57
+ * 4. Dynamically imports server.ts to boot the composed app
58
+ */
59
+ export function generateCompileEntry(options: BuildEntryOptions): VirtualBuildEntry {
60
+ const { outDir, serverEntry } = options;
61
+ ensureDir(outDir);
62
+
63
+ const preparedApps = prepareCompileEntryApps(options);
104
64
 
105
65
  const source = buildEntrySource({
106
66
  apps: preparedApps,
@@ -109,6 +69,5 @@ export function generateCompileEntry(options: BuildEntryOptions): string {
109
69
  });
110
70
 
111
71
  const entryPath = join(outDir, "_compile-entry.ts");
112
- writeFileSync(entryPath, source);
113
- return entryPath;
72
+ return createVirtualBuildEntry(entryPath, source, "ts");
114
73
  }
@@ -0,0 +1,102 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3
+
4
+ const AOT_NAMESPACE = "furin-elysia-aot";
5
+ const ELYSIA_RESOLVE_DIR = dirname(Bun.resolveSync("elysia", import.meta.dir));
6
+ const SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
7
+ const WEBSOCKET_STUB_MARKER =
8
+ "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
9
+
10
+ function loaderFor(path: string): Bun.Loader {
11
+ const extension = path.slice(path.lastIndexOf("."));
12
+ if (extension === ".jsx") {
13
+ return "jsx";
14
+ }
15
+ if (extension === ".tsx") {
16
+ return "tsx";
17
+ }
18
+ if (extension === ".ts" || extension === ".mts" || extension === ".cts") {
19
+ return "ts";
20
+ }
21
+ return "js";
22
+ }
23
+
24
+ /**
25
+ * Kiana strips the WebSocket route module when an app has no WS route,
26
+ * but its capability plugin still imports four helpers omitted by that stub.
27
+ * Keep the upstream failure semantics while restoring the complete export
28
+ * surface. Remove this compatibility shim when Elysia ships the full stub.
29
+ */
30
+ export function patchElysiaWebSocketStub(source: string): string {
31
+ if (!source.includes(WEBSOCKET_STUB_MARKER) || source.includes("accumulateWSOptions")) {
32
+ return source;
33
+ }
34
+ return `${source}
35
+ export function accumulateWSOptions(){return e()}
36
+ export function resolveWSOptions(){return e()}
37
+ export function drainWaiters(){return e()}
38
+ export function handleWSResponse(){return e()}
39
+ `;
40
+ }
41
+
42
+ /** Elysia AOT plugin with the no-WebSocket stub compatibility fix. */
43
+ export function elysiaAot(entry: string): Bun.BunPlugin {
44
+ const entryPath = resolve(entry);
45
+ const hooks = aotFactory({ entry, strip: "auto", target: "bun" });
46
+ return {
47
+ name: "elysia-aot",
48
+ async setup(build) {
49
+ try {
50
+ await hooks.buildStart?.();
51
+ } catch (error) {
52
+ if (
53
+ error instanceof Error &&
54
+ error.message.startsWith("[elysia-aot]") &&
55
+ error.message.includes("mounts a sub-app")
56
+ ) {
57
+ console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
58
+ return;
59
+ }
60
+ throw error;
61
+ }
62
+ const entrySource = await Bun.file(entryPath).text();
63
+ const transformedEntry = await hooks.transform?.(entrySource, entryPath);
64
+ if (transformedEntry !== undefined) {
65
+ await Bun.write(entryPath, transformedEntry);
66
+ }
67
+ build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
68
+ path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR),
69
+ }));
70
+ build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
71
+ const resolved = hooks.resolveId?.(path);
72
+ return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
73
+ });
74
+ build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
75
+ const contents = hooks.load?.(path);
76
+ return contents === undefined
77
+ ? undefined
78
+ : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
79
+ });
80
+ build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
81
+ if (resolve(path) === entryPath) {
82
+ return;
83
+ }
84
+ if (hooks.transformInclude?.(path) === false) {
85
+ return;
86
+ }
87
+ const original = await Bun.file(path).text();
88
+ const transformed = await hooks.transform?.(original, path);
89
+ if (transformed === undefined) {
90
+ return;
91
+ }
92
+ return {
93
+ contents: patchElysiaWebSocketStub(transformed),
94
+ loader: loaderFor(path),
95
+ };
96
+ });
97
+ build.onEnd(() => {
98
+ hooks.buildEnd?.();
99
+ });
100
+ },
101
+ };
102
+ }
@@ -22,10 +22,10 @@ export interface EntryAppContext {
22
22
  buildId?: string;
23
23
  /** Whether the emitted hydration client sends browser log batches. */
24
24
  clientLogging?: boolean;
25
+ /** Deployment adapter that owns public page caching for this build. */
26
+ deploymentTarget?: "vercel";
25
27
  /** Extra lines injected inside this app's `__setCompileContext({...})` call. */
26
28
  extraContext?: string[];
27
- /** Extra import lines this app needs (embedded asset imports). */
28
- extraImports?: string[];
29
29
  /** Additional route modules such as filesystem-derived `_route` layouts. */
30
30
  modulePaths?: string[];
31
31
  /** Virtual module specifier exporting this app's composed Elysia route tree. */
@@ -46,7 +46,11 @@ export interface EntryAppContext {
46
46
  }
47
47
  >;
48
48
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
49
+ /** False when the deployment platform serves client/public assets itself. */
50
+ serveAssets?: boolean;
49
51
  ssgCache?: Record<string, SsgCacheEntry>;
52
+ /** In-memory production document template for filesystem-free runtimes. */
53
+ templateHtml?: string;
50
54
  }
51
55
 
52
56
  export interface EntryTemplateOptions {
@@ -55,13 +59,15 @@ export interface EntryTemplateOptions {
55
59
  /**
56
60
  * - "boot" (default): forces production mode and dynamically imports the
57
61
  * server entry after registering contexts — the whole app's entrypoint.
62
+ * - "app": registers contexts and exports the user's Elysia app without
63
+ * starting a listener, so build-time tooling can safely import it.
58
64
  * - "register": ONLY registers contexts. Emitted by `--target package` as a
59
65
  * side-effect module the HOST app imports; it must not touch dev mode or
60
66
  * NODE_ENV (the host decides), and it imports furin internals via the
61
67
  * package specifier so the host and the register module share ONE copy of
62
68
  * the context registry (`packages: "external"` keeps it unbundled).
63
69
  */
64
- mode?: "boot" | "register";
70
+ mode?: "app" | "boot" | "register";
65
71
  /**
66
72
  * Server entry to boot after context registration. Omitted in package
67
73
  * (register-module) mode where the entry only registers contexts.
@@ -150,12 +156,21 @@ function buildAppContextBlock(
150
156
  const routeMetadataLine = app.routeMetadata
151
157
  ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},`
152
158
  : "";
159
+ const deploymentTargetLine =
160
+ app.deploymentTarget === undefined
161
+ ? ""
162
+ : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
163
+ const serveAssetsLine =
164
+ app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
153
165
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
166
+ const templateHtmlLine =
167
+ app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
154
168
 
155
169
  const contextLines = [
156
170
  "__setCompileContext({",
157
171
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
158
172
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
173
+ deploymentTargetLine,
159
174
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
160
175
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
161
176
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -167,7 +182,9 @@ function buildAppContextBlock(
167
182
  ...routeEntries,
168
183
  " ],",
169
184
  routeMetadataLine,
185
+ serveAssetsLine,
170
186
  ssgCacheLine,
187
+ templateHtmlLine,
171
188
  ...(app.extraContext ?? []),
172
189
  "});",
173
190
  ];
@@ -180,31 +197,29 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
180
197
  const mode = options.mode ?? "boot";
181
198
  const internalSpecifier =
182
199
  mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
200
+ const productionMode = mode !== "register";
183
201
 
184
202
  const importLines: string[] = [];
185
203
  const contextBlocks: string[] = [];
186
204
 
187
205
  for (let appIndex = 0; appIndex < apps.length; appIndex++) {
188
206
  const app = apps[appIndex] as EntryAppContext;
189
- // Per-app variable namespace so several apps' module/asset imports never
190
- // collide inside the single generated entry.
207
+ // Per-app variable namespace so several apps' module imports never collide
208
+ // inside the single generated entry.
191
209
  const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
192
210
  const block = buildAppContextBlock(app, varPrefix);
193
211
  importLines.push(...block.importLines);
194
- if (app.extraImports && app.extraImports.length > 0) {
195
- importLines.push("", ...app.extraImports);
196
- }
197
212
  contextBlocks.push("", ...block.contextLines);
198
213
  }
199
214
 
200
215
  const lines = [
201
216
  headerComment,
202
217
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
203
- ...(mode === "boot"
218
+ ...(productionMode
204
219
  ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`]
205
220
  : []),
206
221
  ...importLines,
207
- ...(mode === "boot"
222
+ ...(productionMode
208
223
  ? [
209
224
  "",
210
225
  "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
@@ -214,9 +229,36 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
214
229
  : []),
215
230
  ...contextBlocks,
216
231
  "",
217
- ...(serverEntry
218
- ? [`await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`, ""]
219
- : []),
232
+ ...(serverEntry && mode === "boot"
233
+ ? [
234
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
235
+ "if (typeof __serverModule.startServer === \"function\") {",
236
+ " await __serverModule.startServer();",
237
+ "} else {",
238
+ " const __app = __serverModule.default;",
239
+ " if (__app && typeof __app.listen === \"function\" && !__app.server) {",
240
+ " const __port =",
241
+ " process.env.PORT === undefined",
242
+ " ? typeof __serverModule.port === \"number\"",
243
+ " ? __serverModule.port",
244
+ " : 3000",
245
+ " : Number(process.env.PORT);",
246
+ " __app.listen(__port);",
247
+ " console.log(`[furin] Server running at http://localhost:${__app.server?.port}`);",
248
+ " }",
249
+ "}",
250
+ "",
251
+ ]
252
+ : serverEntry && mode === "app"
253
+ ? [
254
+ `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
255
+ "export const app = __serverModule.default;",
256
+ "export const port = __serverModule.port;",
257
+ "export const startServer = __serverModule.startServer;",
258
+ "export default __serverModule.default;",
259
+ "",
260
+ ]
261
+ : []),
220
262
  ];
221
263
 
222
264
  return lines.join("\n");