@teyik0/furin 0.4.0-alpha.2 → 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 (100) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +24 -5
  6. package/dist/build/index.js +753 -453
  7. package/dist/build/server-app-entry.d.ts +12 -0
  8. package/dist/cache.d.ts +1 -0
  9. package/dist/cache.js +185 -0
  10. package/dist/cli/index.js +766 -466
  11. package/dist/client/internal/runtime-types.d.ts +8 -1
  12. package/dist/client/link.js +221 -11
  13. package/dist/client/sync.d.ts +1 -0
  14. package/dist/config.d.ts +22 -21
  15. package/dist/config.js +1 -1
  16. package/dist/define-route.d.ts +273 -1009
  17. package/dist/furin.d.ts +20 -5
  18. package/dist/furin.js +6222 -5383
  19. package/dist/plugin/routes.d.ts +6 -0
  20. package/dist/server/assets/production.d.ts +3 -0
  21. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  22. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  23. package/dist/server/cache/invalidation.d.ts +1 -1
  24. package/dist/server/cache/page-cache-state.d.ts +5 -0
  25. package/dist/server/cache/page-cache.d.ts +53 -0
  26. package/dist/server/cache/redis/index.d.ts +39 -0
  27. package/dist/server/cache/redis/index.js +396 -0
  28. package/dist/server/cache/redis/scripts.d.ts +6 -0
  29. package/dist/server/context-logger.d.ts +2 -2
  30. package/dist/server/dev/runtime.production.d.ts +1 -0
  31. package/dist/server/dev-page-plugin.d.ts +7 -0
  32. package/dist/server/evlog.d.ts +14 -0
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +2537 -0
  35. package/dist/server/render/not-found.d.ts +1 -1
  36. package/dist/server/render/ssg.d.ts +5 -0
  37. package/dist/server/render/static-params.d.ts +4 -0
  38. package/dist/server/router/defined-route.d.ts +1 -1
  39. package/dist/server/router/schemas.d.ts +1 -0
  40. package/dist/server/sync/index.js +794 -116
  41. package/dist/server/sync/plugin.d.ts +31 -158
  42. package/dist/server/sync/stream.d.ts +34 -49
  43. package/dist/shared/elysia-contract.d.ts +8 -14
  44. package/package.json +13 -7
  45. package/src/adapter/README.md +9 -2
  46. package/src/adapter/bun.ts +73 -27
  47. package/src/adapter/package.ts +6 -2
  48. package/src/adapter/runtime-build.ts +11 -4
  49. package/src/adapter/static.ts +8 -6
  50. package/src/adapter/vercel.ts +49 -30
  51. package/src/build/client.ts +18 -1
  52. package/src/build/compile-entry.ts +17 -13
  53. package/src/build/elysia-aot.ts +102 -0
  54. package/src/build/entry-template.ts +24 -5
  55. package/src/build/index.ts +0 -5
  56. package/src/build/production-instrumentation.ts +2 -2
  57. package/src/build/server-app-entry.ts +60 -0
  58. package/src/build/shared.ts +3 -1
  59. package/src/build/ssg-cache.ts +5 -10
  60. package/src/build/virtual-entry.ts +5 -4
  61. package/src/cache.ts +12 -0
  62. package/src/cli/config.ts +3 -3
  63. package/src/cli/index.ts +5 -2
  64. package/src/client/internal/runtime-types.ts +10 -1
  65. package/src/client/sync.ts +1 -0
  66. package/src/config.ts +3 -2
  67. package/src/define-route.ts +266 -128
  68. package/src/furin.ts +138 -149
  69. package/src/plugin/route-config-autofix.ts +11 -2
  70. package/src/plugin/routes.ts +85 -29
  71. package/src/server/assets/production.ts +99 -0
  72. package/src/server/auto-invalidate/plugin.ts +4 -4
  73. package/src/server/auto-invalidate/runtime.ts +74 -42
  74. package/src/server/browser-events/plugin.ts +6 -1
  75. package/src/server/cache/invalidation.ts +61 -20
  76. package/src/server/cache/page-cache-state.ts +22 -0
  77. package/src/server/cache/page-cache.ts +300 -0
  78. package/src/server/cache/redis/index.ts +350 -0
  79. package/src/server/cache/redis/scripts.ts +160 -0
  80. package/src/server/context-logger.ts +5 -5
  81. package/src/server/dev/runtime.production.ts +4 -0
  82. package/src/server/dev-page-plugin.ts +54 -10
  83. package/src/server/evlog.ts +99 -0
  84. package/src/server/internal.ts +7 -0
  85. package/src/server/render/isr.ts +480 -132
  86. package/src/server/render/loaders.ts +18 -12
  87. package/src/server/render/not-found.ts +4 -4
  88. package/src/server/render/ppr-document.ts +2 -2
  89. package/src/server/render/ppr-route.ts +193 -7
  90. package/src/server/render/ssg.ts +148 -4
  91. package/src/server/render/ssr.ts +4 -6
  92. package/src/server/render/static-params.ts +174 -0
  93. package/src/server/router/defined-route.ts +2 -1
  94. package/src/server/router/hmr.ts +2 -0
  95. package/src/server/router/plugin.ts +44 -35
  96. package/src/server/router/schema-merge.ts +1 -1
  97. package/src/server/router/schemas.ts +174 -61
  98. package/src/server/sync/plugin.ts +14 -10
  99. package/src/server/sync/response.ts +3 -3
  100. package/src/shared/elysia-contract.ts +23 -25
@@ -1,5 +1,5 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, join, relative, resolve } from "node:path";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { buildClient } from "../build/client.ts";
5
5
  import type { BuildEntryOptions, EntryAppContext } from "../build/entry-template.ts";
@@ -11,7 +11,7 @@ import {
11
11
  type SSGCacheSnapshot,
12
12
  } from "../build/ssg-cache.ts";
13
13
  import type { BuildAppOptions } from "../build/types.ts";
14
- import { routeModuleSpecifier, routeSourcePaths } from "../plugin/routes.ts";
14
+ import { composableRouteModuleSpecifier, routeSourcePaths } from "../plugin/routes.ts";
15
15
  import { buildRscGraph } from "../rsc/build/index.ts";
16
16
  import { ssgRouteCache } from "../server/cache/ssg.ts";
17
17
  import { hasRequestLoader } from "../server/render/loaders.ts";
@@ -138,11 +138,17 @@ export async function createBuildFingerprint(
138
138
 
139
139
  function stableFingerprintPath(path: string, projectRoot: string): string {
140
140
  const projectPath = relative(projectRoot, path);
141
- if (projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
141
+ if (
142
+ !isAbsolute(projectPath) &&
143
+ projectPath !== ".." &&
144
+ !projectPath.startsWith("../") &&
145
+ !projectPath.startsWith("..\\")
146
+ ) {
142
147
  return `app/${toPosixPath(projectPath)}`;
143
148
  }
144
149
  const frameworkPath = relative(_pkgRoot, path);
145
150
  if (
151
+ !isAbsolute(frameworkPath) &&
146
152
  frameworkPath !== ".." &&
147
153
  !frameworkPath.startsWith("../") &&
148
154
  !frameworkPath.startsWith("..\\")
@@ -316,9 +322,10 @@ export async function buildRuntimeApp(
316
322
  entryApp: {
317
323
  buildId,
318
324
  clientLogging: options.clientLogging ?? false,
325
+ deploymentTarget: targetName === "vercel" ? "vercel" : undefined,
319
326
  embed: options.compile === "embed" ? { clientDir } : undefined,
320
327
  modulePaths,
321
- nativeRoutes: routeModuleSpecifier(app),
328
+ nativeRoutes: composableRouteModuleSpecifier(app),
322
329
  prefix,
323
330
  rootConventions,
324
331
  rootPath: root.path,
@@ -1,6 +1,6 @@
1
1
  // biome-ignore-all lint/performance/noAwaitInLoops: static build emits routes in sequence to keep output deterministic
2
2
  import { cpSync, existsSync, rmSync, writeFileSync } from "node:fs";
3
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep, win32 } from "node:path";
4
4
  import { toCrossJSONAsync } from "seroval";
5
5
  import { buildClient } from "../build/client.ts";
6
6
  import { ensureDir, toPosixPath } from "../build/shared.ts";
@@ -10,6 +10,7 @@ import type { StaticExportConfig } from "../config.ts";
10
10
  import { resolvePath } from "../server/render/assemble.ts";
11
11
  import { generateProdIndexHtml } from "../server/render/shell.ts";
12
12
  import { prerenderSSG } from "../server/render/ssg.ts";
13
+ import { hasStaticParams, resolveStaticParams } from "../server/render/static-params.ts";
13
14
  import { setProductionTemplateContent } from "../server/render/template.ts";
14
15
  import { createSearchRouteMetadata } from "../server/router/schemas.ts";
15
16
  import type { ResolvedRoute, RootLayout } from "../server/router/types.ts";
@@ -271,7 +272,7 @@ async function buildTaskQueue(
271
272
  if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
272
273
  return { paramSets: [{}], route };
273
274
  }
274
- if (!route.page.staticParams) {
275
+ if (!hasStaticParams(route)) {
275
276
  console.warn(
276
277
  `[furin] static: skipping dynamic route "${route.pattern}" — no staticParams() defined.`
277
278
  );
@@ -279,7 +280,7 @@ async function buildTaskQueue(
279
280
  return { paramSets: null, route };
280
281
  }
281
282
  try {
282
- const paramSets = (await route.page.staticParams()) ?? [];
283
+ const paramSets = (await resolveStaticParams(route, STATIC_RENDER_ORIGIN)) ?? [];
283
284
  return { paramSets, route };
284
285
  } catch (err) {
285
286
  return { error: err, paramSets: null, route };
@@ -394,7 +395,8 @@ export async function buildStaticTarget(
394
395
  );
395
396
  }
396
397
 
397
- const outDir = resolve(rootDir, staticConfig.outDir ?? "dist");
398
+ const rawOutDir = staticConfig.outDir ?? "dist";
399
+ const outDir = resolve(rootDir, rawOutDir);
398
400
 
399
401
  // Guard against destructive rmSync on obviously wrong output directories.
400
402
  const normalizedRoot = resolve(rootDir);
@@ -402,8 +404,8 @@ export async function buildStaticTarget(
402
404
  if (
403
405
  outDir === normalizedRoot ||
404
406
  outDir === normalizedBuildRoot ||
405
- outDir === "/" ||
406
- outDir === "."
407
+ outDir === parse(outDir).root ||
408
+ rawOutDir === win32.parse(rawOutDir).root
407
409
  ) {
408
410
  throw new Error(
409
411
  `[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` +
@@ -1,17 +1,10 @@
1
- import {
2
- cpSync,
3
- existsSync,
4
- readFileSync,
5
- rmSync,
6
- statSync,
7
- symlinkSync,
8
- writeFileSync,
9
- } from "node:fs";
1
+ import { cpSync, existsSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
10
2
  import { basename, dirname, extname, join, relative } from "node:path";
11
3
  import { fileURLToPath, pathToFileURL } from "node:url";
12
4
  import { runBunBuild } from "../build/bun-build.ts";
13
- import { buildEntrySource } from "../build/entry-template.ts";
5
+ import { elysiaAot } from "../build/elysia-aot.ts";
14
6
  import { productionInstrumentationPlugin } from "../build/production-instrumentation.ts";
7
+ import { materializeServerAppEntry } from "../build/server-app-entry.ts";
15
8
  import { ensureDir, toPosixPath } from "../build/shared.ts";
16
9
  import type { RoutePrerender } from "../build/ssg-cache.ts";
17
10
  import type { BuildAppOptions, VercelTargetBuildManifest } from "../build/types.ts";
@@ -32,7 +25,7 @@ import {
32
25
 
33
26
  const ISR_PATH_PARAM = "__furin_path";
34
27
  const DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
35
- const ELYSIA_STATIC_IMPORT_RE = /^@elysiajs\/static$/;
28
+ const ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
36
29
  const MATCH_ALL_RE = /.*/;
37
30
  const REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
38
31
  const UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
@@ -95,12 +88,12 @@ function vercelRuntimePlugin(): Bun.BunPlugin {
95
88
  build.onResolve({ filter: ELYSIA_STATIC_IMPORT_RE }, ({ importer }) => {
96
89
  if (!isFurinRuntimeImporter(importer)) {
97
90
  throw new Error(
98
- "[furin] Application @elysiajs/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead."
91
+ "[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead."
99
92
  );
100
93
  }
101
94
  return {
102
95
  namespace: VERCEL_RUNTIME_STUB_NAMESPACE,
103
- path: "@elysiajs/static",
96
+ path: "@elysia/static",
104
97
  };
105
98
  });
106
99
  build.onLoad({ filter: MATCH_ALL_RE, namespace: VERCEL_RUNTIME_STUB_NAMESPACE }, () => ({
@@ -137,13 +130,23 @@ function serverEntryLoader(serverEntry: string): "js" | "jsx" | "ts" | "tsx" {
137
130
 
138
131
  function assertDefaultServerExport(serverEntry: string): void {
139
132
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
140
- const { exports } = transpiler.scan(readFileSync(serverEntry, "utf8"));
133
+ const { exports, imports } = transpiler.scan(readFileSync(serverEntry, "utf8"));
141
134
  if (!exports.includes("default")) {
142
135
  throw new Error(
143
136
  `[furin] Vercel server entry "${toPosixPath(serverEntry)}" must export the Elysia app as default. ` +
144
137
  "Guard app.listen() with `if (import.meta.main)` so the same entry also runs locally."
145
138
  );
146
139
  }
140
+ if (imports.some(({ path }) => ELYSIA_STATIC_IMPORT_RE.test(path))) {
141
+ throw new AggregateError(
142
+ [
143
+ new Error(
144
+ "[furin] Application @elysia/static mounts are not supported by the Vercel target. Put CDN assets under public/ instead."
145
+ ),
146
+ ],
147
+ "[furin] Vercel build rejected application static mounts."
148
+ );
149
+ }
147
150
  }
148
151
 
149
152
  function escapeRegex(value: string): string {
@@ -367,7 +370,7 @@ function vercelEntrySource(
367
370
  apps: RuntimeTargetApp[],
368
371
  builds: RuntimeAppBuild[],
369
372
  prerenderSpecs: PrerenderSpec[],
370
- serverEntry: string,
373
+ appEntry: string,
371
374
  pprResumeKey: string
372
375
  ): string {
373
376
  const routeCount = builds.reduce((count, build) => count + build.entryApp.routes.length, 0);
@@ -395,15 +398,6 @@ function vercelEntrySource(
395
398
  )
396
399
  .sort((left, right) => compareRouteSpecificity(right.pattern, left.pattern))
397
400
  .map(({ source, tags }) => [source, tags]);
398
- const contextSource = buildEntrySource({
399
- apps: builds.map(({ entryApp, indexHtml }) => ({
400
- ...entryApp,
401
- embed: undefined,
402
- serveAssets: false,
403
- templateHtml: indexHtml,
404
- })),
405
- headerComment: "// Auto-generated by `furin build --target vercel` — do not edit",
406
- });
407
401
  return `import {
408
402
  addCacheTag,
409
403
  getCache as getVercelCache,
@@ -416,12 +410,11 @@ import {
416
410
  markExternalPrerenderRequest,
417
411
  restorePprResumeRequest,
418
412
  setCacheTagPurger,
413
+ setRuntimeEvlogWaitUntil,
419
414
  setRuntimeCacheProvider,
420
415
  waitForPendingISRRevalidations,
421
416
  } from "@teyik0/furin/internal";
422
417
 
423
- ${contextSource}
424
-
425
418
  const prerenderAliases = new Map(
426
419
  ${JSON.stringify(prerenderAliases)}.map(([alias, source]) => [alias, new RegExp(source)])
427
420
  );
@@ -445,6 +438,7 @@ function encodeCacheTag(value) {
445
438
  setRuntimeCacheProvider({
446
439
  getCache: (options) => getVercelCache(options),
447
440
  });
441
+ setRuntimeEvlogWaitUntil(waitUntil);
448
442
 
449
443
  async function purgeCacheTags(paths) {
450
444
  const purge = Promise.all([
@@ -458,7 +452,7 @@ setCachePurger(purgeCacheTags);
458
452
  setCacheTagPurger(purgeCacheTags);
459
453
 
460
454
  const serverInitStartedAt = performance.now();
461
- const serverModule = await import(${JSON.stringify(toPosixPath(serverEntry))});
455
+ const serverModule = await import(${JSON.stringify(toPosixPath(appEntry))});
462
456
  const app = serverModule.default;
463
457
  if (!app || typeof app.handle !== "function") {
464
458
  throw new TypeError("[furin] Vercel server entry must export the Elysia app as default.");
@@ -677,6 +671,7 @@ async function handle(request) {
677
671
  \`furin_server_init;dur=\${initialization.server_init_ms}\`,
678
672
  \`furin_handler_wait;dur=\${requestWaitMs}\`,
679
673
  \`furin_handler;dur=\${handlerMs}\`,
674
+ ...(isFirstRequest ? ["furin_instance_first_request"] : []),
680
675
  ].join(", ");
681
676
  return appendServerTiming(response, serverTiming);
682
677
  }
@@ -719,6 +714,15 @@ export async function buildVercelTarget(
719
714
  const publicDir = join(rootDir, "public");
720
715
  if (existsSync(publicDir)) {
721
716
  cpSync(publicDir, staticDir, { recursive: true });
717
+ for (const app of apps) {
718
+ const appStaticDir = join(staticDir, app.prefix.slice(1));
719
+ const appPublicDir = join(appStaticDir, "public");
720
+ cpSync(publicDir, appPublicDir, { recursive: true });
721
+ const favicon = join(publicDir, "favicon.ico");
722
+ if (app.prefix !== "" && existsSync(favicon)) {
723
+ cpSync(favicon, join(appStaticDir, "favicon.ico"));
724
+ }
725
+ }
722
726
  }
723
727
  for (let appIndex = 0; appIndex < apps.length; appIndex += 1) {
724
728
  const app = apps[appIndex] as RuntimeTargetApp;
@@ -729,10 +733,22 @@ export async function buildVercelTarget(
729
733
 
730
734
  const pprResumeKey = crypto.randomUUID();
731
735
  const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
736
+ const appEntry = await materializeServerAppEntry({
737
+ apps: builds.map(({ entryApp, indexHtml }) => ({
738
+ ...entryApp,
739
+ embed: undefined,
740
+ serveAssets: false,
741
+ templateHtml: indexHtml,
742
+ })),
743
+ headerComment: "// Auto-generated by `furin build --target vercel` — do not edit",
744
+ instances: apps,
745
+ outDir: serverFunctionDir,
746
+ serverEntry,
747
+ });
732
748
  const entryPath = join(serverFunctionDir, "_vercel-handler.ts");
733
749
  const entry = createVirtualBuildEntry(
734
750
  entryPath,
735
- vercelEntrySource(apps, builds, prerenderSpecs, serverEntry, pprResumeKey),
751
+ vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey),
736
752
  "ts"
737
753
  );
738
754
  const serverBuild = await runBunBuild({
@@ -753,8 +769,10 @@ export async function buildVercelTarget(
753
769
  createRoutesPlugin({ instances: apps, target: "server" }),
754
770
  isomorphicTransformPlugin("server"),
755
771
  environmentGuardPlugin("ssr"),
772
+ elysiaAot(appEntry),
756
773
  ],
757
774
  sourcemap: "none",
775
+ splitting: true,
758
776
  target: "bun",
759
777
  });
760
778
  if (options.analyze) {
@@ -766,8 +784,9 @@ export async function buildVercelTarget(
766
784
  writeFileSync(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}\n`);
767
785
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
768
786
  }
769
- const handlerPath = join(serverFunctionDir, "handler.js");
770
- const serverBundleBytes = existsSync(handlerPath) ? statSync(handlerPath).size : 0;
787
+ const serverBundleBytes = serverBuild.outputs
788
+ .filter((output) => output.path.endsWith(".js"))
789
+ .reduce((total, output) => total + output.size, 0);
771
790
  writeFileSync(join(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
772
791
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
773
792
 
@@ -1,5 +1,5 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, 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";
@@ -12,6 +12,7 @@ import type { BuildClientOptions, BunBuildAliasConfig } from "./types";
12
12
  import { createVirtualBuildEntry } from "./virtual-entry.ts";
13
13
 
14
14
  const SCRIPT_FILE_FILTER = /\.(tsx?|jsx?)$/;
15
+ const ROUTER_PROVIDER_PATH = resolve(import.meta.dir, "../client/router/provider.tsx");
15
16
 
16
17
  function resolveClientModuleSpecifiers(code: string): string {
17
18
  return code
@@ -109,6 +110,21 @@ export async function buildClient(
109
110
  },
110
111
  };
111
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
+
112
128
  const clientBuildConfig: BunBuildAliasConfig = {
113
129
  // Use the JS file as entrypoint — NOT an HTML file. Bun's HTML bundler
114
130
  // with code-splitting incorrectly references a leaf chunk in the output
@@ -141,6 +157,7 @@ export async function buildClient(
141
157
  plugins: [
142
158
  hydrateEntry.plugin,
143
159
  ...(plugins ?? []),
160
+ ...(!clientLogging ? [routerLoggerPlugin] : []),
144
161
  ...(pagesDir
145
162
  ? [createRoutesPlugin({ instances: [{ pagesDir, prefix: basePath }], target: "client" })]
146
163
  : []),
@@ -33,18 +33,8 @@ function buildEmbeddedContext(
33
33
  ];
34
34
  }
35
35
 
36
- /**
37
- * Generates a virtual `_compile-entry.ts` that:
38
- * 1. Statically imports every page module of every app so Bun bundles them
39
- * 2. Points embed-mode contexts at Bun's `compile.assets` directories
40
- * 3. Sets production mode and registers one CompileContext PER APP
41
- * 4. Dynamically imports server.ts to boot the composed app
42
- */
43
- export function generateCompileEntry(options: BuildEntryOptions): VirtualBuildEntry {
44
- const { apps, outDir, serverEntry, publicDir } = options;
45
- ensureDir(outDir);
46
-
47
- const preparedApps: EntryAppContext[] = apps.map((app) => {
36
+ export function prepareCompileEntryApps(options: BuildEntryOptions): EntryAppContext[] {
37
+ return options.apps.map((app) => {
48
38
  const { embed, ...context } = app;
49
39
  if (!embed) {
50
40
  return context;
@@ -53,10 +43,24 @@ export function generateCompileEntry(options: BuildEntryOptions): VirtualBuildEn
53
43
  ...context,
54
44
  extraContext: [
55
45
  ...(context.extraContext ?? []),
56
- ...buildEmbeddedContext(embed.clientDir, publicDir),
46
+ ...buildEmbeddedContext(embed.clientDir, options.publicDir),
57
47
  ],
58
48
  };
59
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);
60
64
 
61
65
  const source = buildEntrySource({
62
66
  apps: preparedApps,
@@ -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,6 +22,8 @@ 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
29
  /** Additional route modules such as filesystem-derived `_route` layouts. */
@@ -57,13 +59,15 @@ export interface EntryTemplateOptions {
57
59
  /**
58
60
  * - "boot" (default): forces production mode and dynamically imports the
59
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.
60
64
  * - "register": ONLY registers contexts. Emitted by `--target package` as a
61
65
  * side-effect module the HOST app imports; it must not touch dev mode or
62
66
  * NODE_ENV (the host decides), and it imports furin internals via the
63
67
  * package specifier so the host and the register module share ONE copy of
64
68
  * the context registry (`packages: "external"` keeps it unbundled).
65
69
  */
66
- mode?: "boot" | "register";
70
+ mode?: "app" | "boot" | "register";
67
71
  /**
68
72
  * Server entry to boot after context registration. Omitted in package
69
73
  * (register-module) mode where the entry only registers contexts.
@@ -152,6 +156,10 @@ function buildAppContextBlock(
152
156
  const routeMetadataLine = app.routeMetadata
153
157
  ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},`
154
158
  : "";
159
+ const deploymentTargetLine =
160
+ app.deploymentTarget === undefined
161
+ ? ""
162
+ : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
155
163
  const serveAssetsLine =
156
164
  app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
157
165
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
@@ -162,6 +170,7 @@ function buildAppContextBlock(
162
170
  "__setCompileContext({",
163
171
  ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
164
172
  ` clientLogging: ${JSON.stringify(app.clientLogging ?? false)},`,
173
+ deploymentTargetLine,
165
174
  ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
166
175
  ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
167
176
  app.nativeRoutes ? ` nativeRoutes: ${nativeRoutesVar},` : "",
@@ -188,6 +197,7 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
188
197
  const mode = options.mode ?? "boot";
189
198
  const internalSpecifier =
190
199
  mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
200
+ const productionMode = mode !== "register";
191
201
 
192
202
  const importLines: string[] = [];
193
203
  const contextBlocks: string[] = [];
@@ -205,11 +215,11 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
205
215
  const lines = [
206
216
  headerComment,
207
217
  `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
208
- ...(mode === "boot"
218
+ ...(productionMode
209
219
  ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`]
210
220
  : []),
211
221
  ...importLines,
212
- ...(mode === "boot"
222
+ ...(productionMode
213
223
  ? [
214
224
  "",
215
225
  "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
@@ -219,7 +229,7 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
219
229
  : []),
220
230
  ...contextBlocks,
221
231
  "",
222
- ...(serverEntry
232
+ ...(serverEntry && mode === "boot"
223
233
  ? [
224
234
  `const __serverModule = await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
225
235
  "if (typeof __serverModule.startServer === \"function\") {",
@@ -239,7 +249,16 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
239
249
  "}",
240
250
  "",
241
251
  ]
242
- : []),
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
+ : []),
243
262
  ];
244
263
 
245
264
  return lines.join("\n");
@@ -230,11 +230,6 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
230
230
  options
231
231
  );
232
232
  break;
233
- case "node":
234
- case "cloudflare":
235
- throw new Error(
236
- `[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`
237
- );
238
233
  default:
239
234
  throw new Error(`[furin] Unsupported build target "${target}"`);
240
235
  }
@@ -3,12 +3,12 @@ import { dirname, relative, resolve } from "node:path";
3
3
  const INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
4
4
  const DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
5
5
  const DEV_RUNTIME_IMPORT =
6
- /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|plugin)(?:\.ts|\.js)?$/;
6
+ /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
7
7
  const DEV_BUILD_IMPORT =
8
8
  /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
9
9
  const HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
10
10
  const PRODUCTION_BOUNDARY_IMPORT =
11
- /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
11
+ /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
12
12
  const PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
13
13
  const FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
14
14
 
@@ -0,0 +1,60 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ materializedRouteModuleSource,
5
+ type RouteInstanceSpec,
6
+ } from "../plugin/routes.ts";
7
+ import { buildEntrySource, type EntryAppContext } from "./entry-template.ts";
8
+ import { ensureDir, toPosixPath } from "./shared.ts";
9
+
10
+ interface MaterializeServerAppEntryOptions {
11
+ apps: EntryAppContext[];
12
+ headerComment: string;
13
+ instances: RouteInstanceSpec[];
14
+ outDir: string;
15
+ serverEntry: string;
16
+ }
17
+
18
+ export async function materializeServerAppEntry(
19
+ options: MaterializeServerAppEntryOptions
20
+ ): Promise<string> {
21
+ ensureDir(options.outDir);
22
+ const apps = await Promise.all(
23
+ options.apps.map(async (app, index): Promise<EntryAppContext> => {
24
+ const instance = options.instances[index];
25
+ if (!instance) {
26
+ throw new Error(`[furin] Missing route instance for server app ${index}.`);
27
+ }
28
+ const routePath = join(options.outDir, `_furin-routes-${index}.ts`);
29
+ writeFileSync(routePath, await materializedRouteModuleSource(instance));
30
+ return { ...app, nativeRoutes: toPosixPath(routePath) };
31
+ })
32
+ );
33
+ const entryPath = join(options.outDir, "_furin-app.ts");
34
+ writeFileSync(
35
+ entryPath,
36
+ buildEntrySource({
37
+ apps,
38
+ headerComment: options.headerComment,
39
+ mode: "app",
40
+ serverEntry: options.serverEntry,
41
+ })
42
+ );
43
+ return entryPath;
44
+ }
45
+
46
+ export function serverBootSource(appEntry: string): string {
47
+ return `// Auto-generated by furin build - do not edit
48
+ import app, { port, startServer } from ${JSON.stringify(toPosixPath(appEntry))};
49
+
50
+ if (typeof startServer === "function") {
51
+ await startServer();
52
+ } else if (app && typeof app.listen === "function" && !app.server) {
53
+ const serverPort = process.env.PORT === undefined
54
+ ? typeof port === "number" ? port : 3000
55
+ : Number(process.env.PORT);
56
+ app.listen(serverPort);
57
+ console.log(\`[furin] Server running at http://localhost:\${app.server?.port}\`);
58
+ }
59
+ `;
60
+ }