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

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 (129) 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 +27 -6
  6. package/dist/build/index.js +969 -528
  7. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  8. package/dist/build/server-app-entry.d.ts +12 -0
  9. package/dist/build/types.d.ts +2 -0
  10. package/dist/cache.d.ts +1 -0
  11. package/dist/cache.js +185 -0
  12. package/dist/cli/index.js +983 -541
  13. package/dist/client/document.d.ts +2 -0
  14. package/dist/client/internal/runtime-types.d.ts +8 -1
  15. package/dist/client/link.js +232 -11
  16. package/dist/client/sync.d.ts +1 -0
  17. package/dist/client.js +11 -0
  18. package/dist/config.d.ts +28 -22
  19. package/dist/config.js +25 -2
  20. package/dist/define-route.d.ts +273 -1009
  21. package/dist/furin.d.ts +20 -5
  22. package/dist/furin.js +6431 -5457
  23. package/dist/plugin/routes.d.ts +6 -0
  24. package/dist/rsc-client.js +9 -1
  25. package/dist/rsc.js +19 -7
  26. package/dist/server/assets/production.d.ts +3 -0
  27. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  28. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  29. package/dist/server/browser-events/shutdown.d.ts +3 -0
  30. package/dist/server/cache/invalidation.d.ts +1 -1
  31. package/dist/server/cache/page-cache-state.d.ts +5 -0
  32. package/dist/server/cache/page-cache.d.ts +53 -0
  33. package/dist/server/cache/redis/index.d.ts +41 -0
  34. package/dist/server/cache/redis/index.js +451 -0
  35. package/dist/server/cache/redis/scripts.d.ts +6 -0
  36. package/dist/server/context-logger.d.ts +2 -2
  37. package/dist/server/dev/plugin.d.ts +1 -0
  38. package/dist/server/dev/runtime.production.d.ts +1 -0
  39. package/dist/server/dev-page-plugin.d.ts +7 -0
  40. package/dist/server/evlog.d.ts +14 -0
  41. package/dist/server/internal.d.ts +6 -0
  42. package/dist/server/internal.js +2539 -0
  43. package/dist/server/production-server.d.ts +13 -0
  44. package/dist/server/production-server.js +2906 -0
  45. package/dist/server/render/not-found.d.ts +1 -1
  46. package/dist/server/render/ssg.d.ts +5 -0
  47. package/dist/server/render/static-params.d.ts +4 -0
  48. package/dist/server/router/defined-route.d.ts +1 -1
  49. package/dist/server/router/hmr.d.ts +6 -0
  50. package/dist/server/router/hmr.production.d.ts +5 -0
  51. package/dist/server/router/plugin.d.ts +5 -1
  52. package/dist/server/router/schemas.d.ts +1 -0
  53. package/dist/server/sync/index.js +798 -117
  54. package/dist/server/sync/plugin.d.ts +31 -158
  55. package/dist/server/sync/stream.d.ts +38 -49
  56. package/dist/shared/elysia-contract.d.ts +8 -14
  57. package/dist/shared/production-build.d.ts +2 -0
  58. package/package.json +19 -8
  59. package/src/adapter/README.md +9 -2
  60. package/src/adapter/bun.ts +146 -41
  61. package/src/adapter/package.ts +6 -2
  62. package/src/adapter/runtime-build.ts +11 -4
  63. package/src/adapter/static.ts +8 -6
  64. package/src/adapter/vercel.ts +64 -31
  65. package/src/build/client.ts +18 -1
  66. package/src/build/compile-entry.ts +17 -13
  67. package/src/build/elysia-aot.ts +102 -0
  68. package/src/build/entry-template.ts +27 -6
  69. package/src/build/hydrate.ts +5 -1
  70. package/src/build/index.ts +5 -5
  71. package/src/build/private-server-sourcemaps.ts +20 -0
  72. package/src/build/production-instrumentation.ts +2 -2
  73. package/src/build/server-app-entry.ts +61 -0
  74. package/src/build/shared.ts +3 -1
  75. package/src/build/ssg-cache.ts +5 -10
  76. package/src/build/types.ts +2 -0
  77. package/src/build/virtual-entry.ts +5 -4
  78. package/src/cache.ts +12 -0
  79. package/src/cli/config.ts +3 -3
  80. package/src/cli/index.ts +6 -2
  81. package/src/client/document.tsx +19 -0
  82. package/src/client/internal/runtime-types.ts +10 -1
  83. package/src/client/sync.ts +1 -0
  84. package/src/config.ts +33 -4
  85. package/src/define-route.ts +266 -128
  86. package/src/furin.ts +168 -154
  87. package/src/plugin/route-config-autofix.ts +11 -2
  88. package/src/plugin/routes.ts +85 -29
  89. package/src/rsc/codec.ts +11 -6
  90. package/src/rsc/render-error.ts +3 -1
  91. package/src/server/assets/production.ts +99 -0
  92. package/src/server/auto-invalidate/plugin.ts +4 -4
  93. package/src/server/auto-invalidate/runtime.ts +74 -42
  94. package/src/server/browser-events/plugin.ts +13 -1
  95. package/src/server/browser-events/shutdown.ts +32 -0
  96. package/src/server/cache/invalidation.ts +61 -20
  97. package/src/server/cache/page-cache-state.ts +22 -0
  98. package/src/server/cache/page-cache.ts +300 -0
  99. package/src/server/cache/redis/index.ts +367 -0
  100. package/src/server/cache/redis/scripts.ts +200 -0
  101. package/src/server/context-logger.ts +5 -5
  102. package/src/server/dev/plugin.ts +10 -1
  103. package/src/server/dev/runtime.production.ts +4 -0
  104. package/src/server/dev-page-plugin.ts +54 -10
  105. package/src/server/evlog.ts +106 -0
  106. package/src/server/internal.ts +7 -0
  107. package/src/server/production-server.ts +135 -0
  108. package/src/server/render/document.tsx +7 -1
  109. package/src/server/render/isr.ts +480 -132
  110. package/src/server/render/loaders.ts +18 -12
  111. package/src/server/render/not-found.ts +4 -4
  112. package/src/server/render/ppr-document.ts +2 -2
  113. package/src/server/render/ppr-route.ts +193 -7
  114. package/src/server/render/ssg.ts +148 -4
  115. package/src/server/render/ssr.ts +6 -7
  116. package/src/server/render/static-params.ts +174 -0
  117. package/src/server/render/template.ts +5 -1
  118. package/src/server/router/defined-route.ts +2 -1
  119. package/src/server/router/discovery.ts +3 -1
  120. package/src/server/router/hmr.production.ts +11 -0
  121. package/src/server/router/hmr.ts +85 -76
  122. package/src/server/router/plugin.ts +118 -50
  123. package/src/server/router/schema-merge.ts +10 -3
  124. package/src/server/router/schemas.ts +174 -61
  125. package/src/server/sync/plugin.ts +14 -10
  126. package/src/server/sync/response.ts +3 -3
  127. package/src/server/sync/stream.ts +43 -2
  128. package/src/shared/elysia-contract.ts +23 -25
  129. package/src/shared/production-build.ts +20 -0
package/src/furin.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { basename, dirname, join, resolve } from "node:path";
2
+ import { basename, delimiter, dirname, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysiajs/static";
5
- import { type AnyElysia, Elysia, file } from "elysia";
4
+ import { staticPlugin } from "@elysia/static";
5
+ import { type AnyElysia, Elysia, file, NotFound, problem } from "elysia";
6
6
  import type { DrainContext, LoggerConfig } from "evlog";
7
- import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
7
  import { FURIN_RENDER_DECORATOR, type FurinRouteDispatcher } from "./define-route.ts";
9
- import { createBrowserEventsPlugin } from "./server/browser-events/plugin.ts";
8
+ import { createProductionAssetsPlugin } from "./server/assets/production.ts";
10
9
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
10
+ import type { PageCacheAdapter } from "./server/cache/page-cache.ts";
11
+ import { setPageCacheAdapter } from "./server/cache/page-cache-state.ts";
11
12
  import { setSSGCache } from "./server/cache/ssg.ts";
12
13
  import type { DevelopmentRouteSnapshot, DevGraph } from "./server/dev/graph.ts";
13
14
  import {
@@ -16,6 +17,7 @@ import {
16
17
  runWithRequestInstrumentation,
17
18
  shouldInstrumentRequest,
18
19
  } from "./server/devtools/instrumentation.ts";
20
+ import { createFurinEvlog, type FurinEvlogOptions } from "./server/evlog.ts";
19
21
  import {
20
22
  assertPrefixAvailable,
21
23
  createInstance,
@@ -38,7 +40,7 @@ import {
38
40
  setProductionTemplatePath,
39
41
  } from "./server/render/template.ts";
40
42
  import { loadProdRoutes } from "./server/router/discovery.ts";
41
- import { invalidateStampedRouteModules } from "./server/router/hmr.ts";
43
+ import { invalidateStampedRouteModules, resolveCurrentDevRoute } from "./server/router/hmr.ts";
42
44
  import { buildRouteMatcher } from "./server/router/patterns.ts";
43
45
  import { createDataEndpoint, renderResolvedRoute } from "./server/router/plugin.ts";
44
46
  import { mergeRouteSchemas } from "./server/router/schema-merge.ts";
@@ -50,15 +52,18 @@ import {
50
52
  import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
51
53
  import { IS_DEV } from "./server/runtime-env.ts";
52
54
  import { type FurinSyncOption, resolveSyncPath } from "./server/sync/config.ts";
53
- import { createSyncChangesPlugin } from "./server/sync/stream.ts";
54
55
 
55
56
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
56
57
  export interface FurinCacheTags {}
57
58
 
58
59
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
59
60
 
60
- function createProductionBrowserEventsPlugin(sync: FurinSyncOption | undefined): AnyElysia {
61
- return sync ? createBrowserEventsPlugin({ sync }) : new Elysia();
61
+ async function createProductionBrowserEventsPlugin(
62
+ sync: FurinSyncOption | undefined
63
+ ): Promise<AnyElysia> {
64
+ return sync
65
+ ? (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({ sync })
66
+ : new Elysia();
62
67
  }
63
68
 
64
69
  function repairedDevelopmentRoutes(
@@ -177,7 +182,10 @@ function resolveClientDirFromCandidate(candidate: string, dirName: string): stri
177
182
 
178
183
  const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
179
184
  if (existsSync(absolute)) {
180
- return join(dirname(absolute), dirName);
185
+ const clientDir = join(dirname(absolute), dirName);
186
+ if (existsSync(join(clientDir, "index.html"))) {
187
+ return clientDir;
188
+ }
181
189
  }
182
190
 
183
191
  if (!candidate.includes("/")) {
@@ -188,11 +196,14 @@ function resolveClientDirFromCandidate(candidate: string, dirName: string): stri
188
196
  }
189
197
 
190
198
  function resolveClientDirFromPath(candidate: string, dirName: string): string | null {
191
- const pathEntries = process.env.PATH?.split(":") ?? [];
199
+ const pathEntries = process.env.PATH?.split(delimiter) ?? [];
192
200
  for (const dir of pathEntries) {
193
201
  const fullPath = join(dir, candidate);
194
202
  if (existsSync(fullPath)) {
195
- return join(dirname(fullPath), dirName);
203
+ const clientDir = join(dirname(fullPath), dirName);
204
+ if (existsSync(join(clientDir, "index.html"))) {
205
+ return clientDir;
206
+ }
196
207
  }
197
208
  }
198
209
  return null;
@@ -310,12 +321,12 @@ async function readBrowserIngest(request: Request): Promise<BrowserIngestRead> {
310
321
  function createLoggerPlugin(
311
322
  prefix: string,
312
323
  syncPath: string | undefined,
313
- logger: EvlogElysiaOptions | undefined,
324
+ logger: FurinEvlogOptions | undefined,
314
325
  clientLogging: boolean
315
- ): Elysia {
326
+ ) {
316
327
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
317
328
  const app = new Elysia().use(
318
- evlog({
329
+ createFurinEvlog({
319
330
  ...evlogOptions,
320
331
  // Exclude patterns match the PHYSICAL request path — prefix them.
321
332
  exclude: [
@@ -326,7 +337,7 @@ function createLoggerPlugin(
326
337
  ...instrumentationLoggerExclusions(prefix),
327
338
  ...(syncPath ? [`${prefix}${syncPath}/**`] : []),
328
339
  // Note: /_furin/data is logged with the *logical* path rewritten by
329
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
340
+ // createDataEndpoint via getLogger().set({ path }), so SPA navigations
330
341
  // appear as "GET /board/123 200" — same shape as a normal SSR nav.
331
342
  // /_furin/ingest remains loggable when browser logging is explicitly
332
343
  // enabled so browser-side events show up.
@@ -338,50 +349,46 @@ function createLoggerPlugin(
338
349
  );
339
350
 
340
351
  if (!clientLogging) {
341
- return app as unknown as Elysia;
352
+ return app;
342
353
  }
343
354
 
344
- return app.post(
345
- "/_furin/ingest",
346
- async ({ log, request, status }) => {
347
- const parsed = await readBrowserIngest(request);
348
- if (parsed.kind === "oversized") {
349
- return status(413);
350
- }
351
- if (parsed.kind === "invalid") {
352
- return status("Bad Request");
353
- }
354
- const { body } = parsed;
355
- if (!Array.isArray(body)) {
356
- return status("Bad Request");
355
+ return app.post("/_furin/ingest", { parse: "none" }, async ({ log, request, status }) => {
356
+ const parsed = await readBrowserIngest(request);
357
+ if (parsed.kind === "oversized") {
358
+ return problem(413, { detail: "Browser event payload exceeds 64 KiB." });
359
+ }
360
+ if (parsed.kind === "invalid") {
361
+ return problem("Bad Request", { detail: "Browser event payload must be valid JSON." });
362
+ }
363
+ const { body } = parsed;
364
+ if (!Array.isArray(body)) {
365
+ return problem("Bad Request", { detail: "Browser event payload must be a JSON array." });
366
+ }
367
+ const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
368
+ for (const entry of batch) {
369
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
370
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
371
+ continue;
357
372
  }
358
- const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
359
- for (const entry of batch) {
360
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
361
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
362
- continue;
363
- }
364
- // Pick only safe, known fields from the event to prevent prototype pollution
365
- const event = entry.event as FurinBrowserEvent | undefined;
366
- if (!event || typeof event !== "object") {
367
- continue;
368
- }
369
- const {
370
- __proto__,
371
- constructor: _ctor,
372
- prototype,
373
- environment: _browserEnv,
374
- ...safeEvent
375
- } = event;
376
- log.set({ ...safeEvent, service: "furin:browser" });
373
+ // Pick only safe, known fields from the event to prevent prototype pollution
374
+ const event = entry.event as FurinBrowserEvent | undefined;
375
+ if (!event || typeof event !== "object") {
376
+ continue;
377
377
  }
378
- return status("No Content");
379
- },
380
- { parse: "none" }
381
- ) as unknown as Elysia;
378
+ const {
379
+ __proto__,
380
+ constructor: _ctor,
381
+ prototype,
382
+ environment: _browserEnv,
383
+ ...safeEvent
384
+ } = event;
385
+ log.set({ ...safeEvent, service: "furin:browser" });
386
+ }
387
+ return status("No Content");
388
+ }) as unknown as Elysia;
382
389
  }
383
390
 
384
- function initializeLogger(logger: FurinLoggerOptions | undefined): EvlogElysiaOptions {
391
+ function initializeLogger(logger: FurinLoggerOptions | undefined): FurinEvlogOptions {
385
392
  const { sampling, ...elysiaLoggerOptions } = logger ?? {};
386
393
  initializeFurinLogger({
387
394
  env: { service: "furin" },
@@ -409,31 +416,43 @@ function initializeLogger(logger: FurinLoggerOptions | undefined): EvlogElysiaOp
409
416
  * closure — which wrap executes first is therefore irrelevant.
410
417
  */
411
418
  function wrapWithRequestScope(app: AnyElysia): Elysia {
412
- return app.wrap((handler, request) => (ctx: unknown) => {
419
+ return app.wrap((fetch) => (request, ...rest) => {
413
420
  if (hasRequestScope()) {
414
- return handler(ctx);
421
+ return fetch(request, ...rest);
415
422
  }
416
423
  markTraffic();
417
- const req = request ?? (ctx as { request?: Request } | undefined)?.request;
418
- const pathname = req ? new URL(req.url).pathname : "/";
424
+ const { pathname } = new URL(request.url);
419
425
  const instance = resolveInstanceByPath(pathname);
420
426
  return runWithInstanceScope(instance, () => {
421
- if (!(req && shouldInstrumentRequest(pathname, instance.prefix))) {
422
- return handler(ctx);
427
+ if (!shouldInstrumentRequest(pathname, instance.prefix)) {
428
+ return fetch(request, ...rest);
423
429
  }
424
- return runWithRequestInstrumentation(req, () => handler(ctx));
430
+ return runWithRequestInstrumentation(request, () => fetch(request, ...rest));
425
431
  });
426
432
  });
427
433
  }
428
434
 
429
- function createFurinPlugin(
430
- app: AnyElysia,
431
- prepareParent: ((parentApp: AnyElysia) => void) | undefined
432
- ) {
435
+ function createFurinPlugin(app: AnyElysia, hmrPrefix: string | undefined) {
433
436
  const scopedApp = wrapWithRequestScope(app);
434
437
  return <ParentApp extends AnyElysia>(parentApp: ParentApp) => {
435
- prepareParent?.(parentApp);
436
- return parentApp.use(scopedApp);
438
+ const mounted = parentApp.use(scopedApp);
439
+ if (hmrPrefix !== undefined) {
440
+ const parentConfig = Reflect.get(parentApp, "~config") as { prefix?: string } | undefined;
441
+ const entryPath = `${parentConfig?.prefix ?? ""}${hmrPrefix}/_bun_hmr_entry`;
442
+ const routes = Reflect.get(mounted, "~routes") as
443
+ | [string, string, unknown, unknown, unknown, unknown, unknown?][]
444
+ | undefined;
445
+ for (const route of routes ?? []) {
446
+ if (
447
+ route[0] === "GET" &&
448
+ (route[1] === entryPath || route[1] === `${entryPath}/index.html`)
449
+ ) {
450
+ // Bun serves these HTML bundles natively; inherited Elysia hooks cannot run.
451
+ route[6] = undefined;
452
+ }
453
+ }
454
+ }
455
+ return mounted;
437
456
  };
438
457
  }
439
458
 
@@ -469,20 +488,14 @@ function createNativeRouteRenderer(
469
488
  mergeRouteSchemas(matched.route.routeChain, "params")
470
489
  );
471
490
  if (!parsedParams.ok) {
472
- return Response.json(
473
- { errors: parsedParams.errors, message: "Invalid params", type: "validation" },
474
- { status: 422 }
475
- );
491
+ return problem(422, { detail: "Invalid params", errors: parsedParams.errors });
476
492
  }
477
493
  const parsedQuery = await parseRouteQuery(
478
494
  requestUrl,
479
495
  mergeRouteSchemas(matched.route.routeChain, "query")
480
496
  );
481
497
  if (!parsedQuery.ok) {
482
- return Response.json(
483
- { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
484
- { status: 422 }
485
- );
498
+ return problem(422, { detail: "Invalid query", errors: parsedQuery.errors });
486
499
  }
487
500
  context.params = parsedParams.params;
488
501
  context.query = parsedQuery.query;
@@ -530,7 +543,7 @@ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
530
543
  }
531
544
 
532
545
  /** Options for the {@link furin} plugin. */
533
- export type FurinLoggerOptions = EvlogElysiaOptions & Pick<LoggerConfig, "sampling">;
546
+ export type FurinLoggerOptions = FurinEvlogOptions & Pick<LoggerConfig, "sampling">;
534
547
 
535
548
  export interface FurinOptions {
536
549
  /**
@@ -548,6 +561,12 @@ export interface FurinOptions {
548
561
  */
549
562
  clientLogging?: boolean;
550
563
  logger?: FurinLoggerOptions;
564
+ /**
565
+ * Cache for public page artifacts. Use a distributed adapter when several
566
+ * replicas serve the same application. When omitted, Furin keeps its
567
+ * process-local cache.
568
+ */
569
+ pageCache?: PageCacheAdapter;
551
570
  pagesDir?: string;
552
571
  /**
553
572
  * Mount prefix for this app, e.g. `"/admin"`. All pages, framework
@@ -564,6 +583,21 @@ export interface FurinOptions {
564
583
  sync?: FurinSyncOption;
565
584
  }
566
585
 
586
+ function configurePageCache(
587
+ instance: FurinInstance,
588
+ ctx: CompileContext | null,
589
+ pageCache: PageCacheAdapter | undefined
590
+ ): void {
591
+ if (pageCache !== undefined && ctx?.deploymentTarget === "vercel") {
592
+ throw new Error(
593
+ "[furin] pageCache cannot be configured with the Vercel target. Vercel owns SSG, ISR, and PPR public caching."
594
+ );
595
+ }
596
+ if (pageCache !== undefined) {
597
+ setPageCacheAdapter(instance, pageCache);
598
+ }
599
+ }
600
+
567
601
  /**
568
602
  * Main Furin plugin.
569
603
  *
@@ -586,6 +620,7 @@ export async function furin({
586
620
  clientDir: explicitClientDir,
587
621
  logger,
588
622
  clientLogging,
623
+ pageCache,
589
624
  sync,
590
625
  }: FurinOptions = {}) {
591
626
  const prefix = normalizePrefix(rawPrefix);
@@ -618,6 +653,7 @@ export async function furin({
618
653
  assertPrefixAvailable(prefix, normalizedPagesDir);
619
654
  const instance = createInstance(prefix, normalizedPagesDir);
620
655
  instance.syncPath = syncPath;
656
+ configurePageCache(instance, ctx, pageCache);
621
657
 
622
658
  // ── Dev: Bun native HMR ────────────────────────────────────────────────
623
659
  if (IS_DEV) {
@@ -705,6 +741,7 @@ export async function furin({
705
741
  };
706
742
  writeCurrentDevFiles(initialSnapshot);
707
743
  graph.commit(initialSnapshot);
744
+ const hmrEntry = (await import(join(furinDir, "index.html"))).default;
708
745
  const refreshDevelopmentRoutes = (changedSources: readonly string[]): Promise<void> =>
709
746
  withInstance(instance, async () => {
710
747
  invalidateStampedRouteModules();
@@ -733,10 +770,8 @@ export async function furin({
733
770
  throw error;
734
771
  }
735
772
  });
736
- const devHtmlBundle = (await import(join(furinDir, "index.html"))).default;
737
773
  const publicDir = resolve(cwd, "public");
738
774
  const publicExists = existsSync(publicDir);
739
- const hmrEntryPath = `${prefix}/_bun_hmr_entry`;
740
775
  let routeTopologyWatcher: ReturnType<typeof registerDevRouteTopologyWatcher> | undefined;
741
776
 
742
777
  // Routes registered below are LOGICAL — Elysia's `prefix` makes them
@@ -747,7 +782,7 @@ export async function furin({
747
782
  prefix: prefix || undefined,
748
783
  seed: resolvedPagesDir,
749
784
  })
750
- .onStart(() => {
785
+ .setup(() => {
751
786
  routeTopologyWatcher = registerDevRouteTopologyWatcher({
752
787
  instance: routeInstance,
753
788
  onRouteFilesTouched: async (sourcePaths) => {
@@ -777,22 +812,19 @@ export async function furin({
777
812
  },
778
813
  });
779
814
  })
780
- .onStop(() => {
815
+ .cleanup(() => {
781
816
  routeTopologyWatcher?.close();
782
817
  routeTopologyWatcher = undefined;
783
818
  })
784
- // Elysia 1.4.30 only preserves Bun's native HTMLBundle handler when the
785
- // bundle is also present in serve.routes once request hooks are installed.
786
- .use(await staticPlugin({ assets: furinDir, bunFullstack: true, prefix: "/_bun_hmr_entry" }))
819
+ .get("/_bun_hmr_entry/index.html", hmrEntry)
820
+ .get("/_bun_hmr_entry", hmrEntry)
787
821
  .use(loggerPlugin)
788
822
  // Local scope (default) — a global hook would leak onto sibling furin
789
823
  // instances mounted on the same parent app.
790
- .onError(async ({ code, request, server }) => {
791
- if (code === "NOT_FOUND") {
792
- return await renderRootNotFound(currentSnapshot().root, request, server?.url.origin);
793
- }
794
- })
795
- .onAfterHandle(({ set }) => {
824
+ .error(NotFound, async ({ request, server }) =>
825
+ renderRootNotFound(currentSnapshot().root, request, server?.url.origin)
826
+ )
827
+ .afterHandle(({ set }) => {
796
828
  // Forward pending revalidation paths so the client can bust its prefetch cache
797
829
  const pending = consumePendingInvalidations();
798
830
  if (pending.length > 0) {
@@ -809,7 +841,7 @@ export async function furin({
809
841
  : () => new Response(null, { status: 404 })
810
842
  )
811
843
  .use(
812
- createBrowserEventsPlugin({
844
+ (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({
813
845
  sources: createDevelopmentBrowserEventSources(instance, devDiagnosticStore(instance)),
814
846
  sync: sync || undefined,
815
847
  })
@@ -820,14 +852,22 @@ export async function furin({
820
852
  })
821
853
  )
822
854
  .use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
823
- .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
824
855
  .use(
825
- createDataEndpoint(async (request) => {
826
- if (request.headers.get("x-furin-hmr-refresh") === "1") {
827
- await routeTopologyWatcher?.refresh();
828
- }
829
- return currentSnapshot().routes;
830
- })
856
+ sync
857
+ ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync)
858
+ : new Elysia()
859
+ )
860
+ .use(
861
+ createDataEndpoint(
862
+ async (request) => {
863
+ if (request.headers.get("x-furin-hmr-refresh") === "1") {
864
+ await routeTopologyWatcher?.refresh();
865
+ }
866
+ return currentSnapshot().routes;
867
+ },
868
+ undefined,
869
+ (route) => resolveCurrentDevRoute(route, currentSnapshot().root)
870
+ )
831
871
  )
832
872
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
833
873
  .use(nativeRoutesApp)
@@ -846,15 +886,7 @@ export async function furin({
846
886
  })
847
887
  );
848
888
  registerInstance(instance);
849
- return createFurinPlugin(devApp, (parentApp) => {
850
- parentApp.config.serve = {
851
- ...parentApp.config.serve,
852
- routes: {
853
- ...parentApp.config.serve?.routes,
854
- [hmrEntryPath]: devHtmlBundle,
855
- },
856
- };
857
- });
889
+ return createFurinPlugin(devApp, prefix);
858
890
  }
859
891
 
860
892
  // ── Production ──────────────────────────────────────────────────────────
@@ -883,7 +915,8 @@ export async function furin({
883
915
  });
884
916
 
885
917
  const embedded = ctx?.embedded;
886
- const clientDir = embedded?.clientDir ?? explicitClientDir ?? resolveClientDirFromArgv(prefix);
918
+ const clientDir =
919
+ embedded?.clientDir ?? explicitClientDir ?? ctx.clientDir ?? resolveClientDirFromArgv(prefix);
887
920
  await setupCompiledTemplate(ctx, embedded, clientDir, instance);
888
921
 
889
922
  const prodApp = new Elysia({
@@ -894,12 +927,10 @@ export async function furin({
894
927
  .use(loggerPlugin)
895
928
  // Local scope (default) — a global hook would leak onto sibling furin
896
929
  // instances mounted on the same parent app.
897
- .onError(async ({ code, request, server }) => {
898
- if (code === "NOT_FOUND") {
899
- return await renderRootNotFound(root, request, server?.url.origin);
900
- }
901
- })
902
- .onAfterHandle(({ set }) => {
930
+ .error(NotFound, async ({ request, server }) =>
931
+ renderRootNotFound(root, request, server?.url.origin)
932
+ )
933
+ .afterHandle(({ set }) => {
903
934
  // Forward pending revalidation paths so the client can bust its prefetch cache
904
935
  const pending = consumePendingInvalidations();
905
936
  if (pending.length > 0) {
@@ -910,7 +941,7 @@ export async function furin({
910
941
  set.headers["x-furin-build-id"] = instance.buildId;
911
942
  }
912
943
  })
913
- .onStart(async ({ server }) => {
944
+ .setup(async ({ server }) => {
914
945
  if (ctx.ssgCache) {
915
946
  return;
916
947
  }
@@ -919,32 +950,11 @@ export async function furin({
919
950
  // render pipeline resolves its template/caches, not a sibling's.
920
951
  await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
921
952
  })
953
+ .use(await createProductionAssetsPlugin(ctx, embedded, clientDir))
954
+ .use(await createProductionBrowserEventsPlugin(sync))
922
955
  .use(
923
- await (async () => {
924
- if (ctx.serveAssets === false) {
925
- return new Elysia();
926
- }
927
- const publicDir = embedded?.publicDir ?? join(dirname(clientDir), "public");
928
- const app = new Elysia();
929
- if (existsSync(publicDir)) {
930
- app
931
- .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
932
- .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
933
- }
934
- app.use(
935
- await staticPlugin({
936
- assets: clientDir,
937
- headers: {
938
- "Cache-Control": "public, max-age=31536000, immutable",
939
- },
940
- prefix: "/_client",
941
- })
942
- );
943
- return app;
944
- })()
956
+ sync ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync) : new Elysia()
945
957
  )
946
- .use(createProductionBrowserEventsPlugin(sync))
947
- .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
948
958
  .use(createDataEndpoint(routes, root))
949
959
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
950
960
  .use(ctx.nativeRoutes)
@@ -956,8 +966,8 @@ export async function furin({
956
966
  /**
957
967
  * 404 handling per mount position:
958
968
  *
959
- * - ROOT instance (`prefix === ""`): the historical `{as:"global"}`
960
- * onError(NOT_FOUND) hook — it owns the root scope, and a parent `.onError`
969
+ * - ROOT instance (`prefix === ""`): a global `NotFound` handler owns the root
970
+ * scope, and a parent `.error()`
961
971
  * registered BEFORE `.use(furin)` still wins (documented escape hatch for
962
972
  * JSON API 404s).
963
973
  * - PREFIXED instance: a global hook would leak onto sibling apps, and a
@@ -974,16 +984,23 @@ function createNotFoundHandling(
974
984
  tryNativeDispatch?: (context: { request: Request }) => Promise<unknown>
975
985
  ): Elysia {
976
986
  const app = new Elysia();
987
+ const dispatch =
988
+ tryNativeDispatch ??
989
+ (routes.some((route) => route.pattern === "/*")
990
+ ? async (context: { request: Request }): Promise<unknown> => {
991
+ if (context.request.method !== "GET") {
992
+ return;
993
+ }
994
+ return await dispatchNativeRoute(context as Parameters<FurinRouteDispatcher>[0]);
995
+ }
996
+ : undefined);
977
997
  if (prefix === "") {
978
- app.onError({ as: "global" }, async (context) => {
979
- if (context.code !== "NOT_FOUND") {
980
- return;
981
- }
998
+ app.error("global", NotFound, async (context) => {
982
999
  // Dev topology: the native renderer is rebuilt by the watcher on route
983
1000
  // add/remove, so a hot-added route (no mounted Elysia route yet) can
984
- // still be served here. `tryNativeDispatch` is undefined in production.
985
- if (tryNativeDispatch) {
986
- const rendered = await tryNativeDispatch(context);
1001
+ // still be served here. Production also renders root catch-all pages here.
1002
+ if (dispatch) {
1003
+ const rendered = await dispatch(context);
987
1004
  if (rendered !== undefined && rendered !== null) {
988
1005
  return rendered;
989
1006
  }
@@ -992,17 +1009,14 @@ function createNotFoundHandling(
992
1009
  });
993
1010
  return app;
994
1011
  }
995
- if (routes.some((route) => route.pattern === "/*")) {
996
- return app;
997
- }
998
- app.get("/*", async ({ request, server }) => {
999
- if (tryNativeDispatch) {
1000
- const rendered = await tryNativeDispatch({ request });
1012
+ app.get("/*", async (context) => {
1013
+ if (dispatch) {
1014
+ const rendered = await dispatch(context);
1001
1015
  if (rendered !== undefined && rendered !== null) {
1002
1016
  return rendered;
1003
1017
  }
1004
1018
  }
1005
- return renderRootNotFound(root, request, server?.url.origin);
1019
+ return renderRootNotFound(root, context.request, context.server?.url.origin);
1006
1020
  });
1007
1021
  return app;
1008
1022
  }
@@ -448,6 +448,7 @@ interface FixContext {
448
448
  expectedResolvedPath: string;
449
449
  filePath: string;
450
450
  hasLoader: boolean;
451
+ hasStaticParams: boolean;
451
452
  imports: LayoutImport[];
452
453
  isRootLayout: boolean;
453
454
  lastImportEnd: number;
@@ -659,6 +660,9 @@ function validateConfigProperties(
659
660
  ctx: FixContext
660
661
  ): { inferredMode: InferredRenderingMode | null; layoutValue: AstNode | null } {
661
662
  const layoutValue = properties.layout ? asAstNode(properties.layout.value) : null;
663
+ if (properties.staticParams) {
664
+ throw routeConfigError(ctx.filePath, "staticParams must be chained after config");
665
+ }
662
666
  if (!ctx.isRootLayout && properties.layout && layoutValue?.type !== "Identifier") {
663
667
  throw routeConfigError(ctx.filePath, "use a static layout route reference");
664
668
  }
@@ -670,7 +674,7 @@ function validateConfigProperties(
670
674
  ) {
671
675
  throw routeConfigError(ctx.filePath, "revalidate requires mode isr");
672
676
  }
673
- if (properties.staticParams && modeValue?.type === "Literal" && modeValue.value === "ssr") {
677
+ if (ctx.hasStaticParams && modeValue?.type === "Literal" && modeValue.value === "ssr") {
674
678
  throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
675
679
  }
676
680
  if (!properties.revalidate && modeValue?.type === "Literal" && modeValue.value === "isr") {
@@ -685,7 +689,7 @@ function validateConfigProperties(
685
689
  hasRevalidate: Boolean(properties.revalidate),
686
690
  isRootLayout: ctx.isRootLayout,
687
691
  });
688
- if (properties.staticParams && inferredMode === "ssr") {
692
+ if (ctx.hasStaticParams && inferredMode === "ssr") {
689
693
  throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
690
694
  }
691
695
  return { inferredMode, layoutValue };
@@ -970,6 +974,9 @@ function insertCompleteConfig(routeHead: ChainHead, ctx: FixContext): void {
970
974
  hasRevalidate: false,
971
975
  isRootLayout: ctx.isRootLayout,
972
976
  });
977
+ if (ctx.hasStaticParams && mode === "ssr") {
978
+ throw routeConfigError(ctx.filePath, "staticParams requires mode ssg or isr");
979
+ }
973
980
  entries.push(`mode: "${mode}"`);
974
981
  if (ctx.dynamicParams.length > 0) {
975
982
  const typeBoxBinding = ensureTImport(ctx);
@@ -1097,6 +1104,7 @@ export function fixRouteConfigLayout(
1097
1104
  );
1098
1105
  const bindings = collectBuilderBindings(parsed.program);
1099
1106
  const hasLoader = builderChainHasMethod(parsed.program, bindings, "loader");
1107
+ const hasStaticParams = builderChainHasMethod(parsed.program, bindings, "staticParams");
1100
1108
  const heads = collectChainHeads(parsed.program, bindings).filter(
1101
1109
  (candidate) => candidate.end !== 0
1102
1110
  );
@@ -1116,6 +1124,7 @@ export function fixRouteConfigLayout(
1116
1124
  expectedResolvedPath,
1117
1125
  filePath,
1118
1126
  hasLoader,
1127
+ hasStaticParams,
1119
1128
  imports,
1120
1129
  isRootLayout: convention.isRootLayout,
1121
1130
  lastImportEnd,