@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
@@ -16,10 +16,12 @@ import { parseDynamicRouteSegment, routeSegmentToPattern } from "../server/route
16
16
 
17
17
  const ROUTES_NAMESPACE_PREFIX = "furin-routes";
18
18
  const ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry";
19
- const ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry$/;
19
+ const COMPOSABLE_ROUTES_REGISTRY_SPECIFIER = "furin/routes?registry=composable";
20
+ const ROUTES_REGISTRY_FILTER = /^furin\/routes\?registry(?:=composable)?$/;
20
21
  const ROUTE_FILE_FILTER = /^furin-route-file:.+$/;
21
22
  const ROUTE_FILES_NAMESPACE = "furin-route-files";
22
- const ROUTES_REGISTRY_FILE_FILTER = /[\\/]\.furin-routes-registry\.ts\?furin-virtual$/;
23
+ const ROUTES_REGISTRY_FILE_FILTER =
24
+ /[\\/]\.furin-routes-registry(?:-composable)?\.ts\?furin-virtual$/;
23
25
  const CLIENT_ROUTES_NAMESPACE = "furin-routes-client";
24
26
  const CLIENT_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes$/;
25
27
  const SERVER_ROUTES_FILTER = /^(?:@teyik0\/furin|furin)\/routes\?instance=.+$/;
@@ -82,6 +84,10 @@ export function routeModuleSpecifier(instance: RouteInstanceSpec): string {
82
84
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
83
85
  }
84
86
 
87
+ export function composableRouteModuleSpecifier(instance: RouteInstanceSpec): string {
88
+ return `${routeModuleSpecifier(instance)}&composable`;
89
+ }
90
+
85
91
  function instanceNamespace(instance: RouteInstanceSpec): string {
86
92
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
87
93
  }
@@ -534,7 +540,11 @@ export function registerDevRouteTopologyWatcher(
534
540
  };
535
541
  }
536
542
 
537
- function emitRouteNode(node: RouteTreeNode, indentation: string): string {
543
+ function emitRouteNode(
544
+ node: RouteTreeNode,
545
+ indentation: string,
546
+ includeRootCatchAll: boolean
547
+ ): string {
538
548
  const childIndentation = `${indentation} `;
539
549
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
540
550
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
@@ -544,7 +554,7 @@ function emitRouteNode(node: RouteTreeNode, indentation: string): string {
544
554
  `${childIndentation}.use(new Elysia({ prefix: "" }).use(${node.indexRoute.id}.elysia))`
545
555
  );
546
556
  }
547
- for (const route of node.fileRoutes) {
557
+ for (const route of node.fileRoutes.filter((file) => includeRootCatchAll || file.path !== "/*")) {
548
558
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
549
559
  content.push(
550
560
  `${childIndentation}.use(new Elysia({ prefix: ${JSON.stringify(`/${segment}`)} }).use(${route.id}.elysia))`
@@ -552,7 +562,7 @@ function emitRouteNode(node: RouteTreeNode, indentation: string): string {
552
562
  }
553
563
  for (const child of node.children) {
554
564
  content.push(`${childIndentation}.use(`);
555
- content.push(emitRouteNode(child, `${childIndentation} `));
565
+ content.push(emitRouteNode(child, `${childIndentation} `, includeRootCatchAll));
556
566
  content.push(`${childIndentation})`);
557
567
  }
558
568
  if (node.layout) {
@@ -604,7 +614,9 @@ async function retainComposableRoutes(node: RouteTreeNode): Promise<void> {
604
614
 
605
615
  async function generateServerInstance(
606
616
  instance: RouteInstanceSpec,
607
- routeFilesBySpecifier: Map<string, RouteModuleInfo>
617
+ routeFilesBySpecifier: Map<string, RouteModuleInfo>,
618
+ materialized: boolean,
619
+ includeRootCatchAll: boolean
608
620
  ): Promise<GeneratedServerInstance> {
609
621
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
610
622
  const tree = buildRouteTree(instance.pagesDir, instanceId);
@@ -612,7 +624,9 @@ async function generateServerInstance(
612
624
  const imports = collectRouteFiles(tree)
613
625
  .sort((left, right) => left.sourcePath.localeCompare(right.sourcePath))
614
626
  .map((route) => {
615
- const specifier = routeFileSpecifier(route);
627
+ const specifier = materialized
628
+ ? resolve(route.sourcePath).replaceAll("\\", "/")
629
+ : routeFileSpecifier(route);
616
630
  routeFilesBySpecifier.set(specifier, {
617
631
  routePath: route.path,
618
632
  sourcePath: resolve(route.sourcePath),
@@ -621,7 +635,7 @@ async function generateServerInstance(
621
635
  })
622
636
  .join("\n");
623
637
  return {
624
- appExpression: emitRouteNode(tree, ""),
638
+ appExpression: emitRouteNode(tree, "", includeRootCatchAll),
625
639
  exportName: `furinApp_${instanceId}`,
626
640
  imports,
627
641
  };
@@ -629,11 +643,15 @@ async function generateServerInstance(
629
643
 
630
644
  async function serverRegistrySource(
631
645
  instances: RouteInstanceSpec[],
632
- routeFilesBySpecifier: Map<string, RouteModuleInfo>
646
+ routeFilesBySpecifier: Map<string, RouteModuleInfo>,
647
+ materialized: boolean,
648
+ includeRootCatchAll: boolean
633
649
  ): Promise<string> {
634
650
  routeFilesBySpecifier.clear();
635
651
  const generated = await Promise.all(
636
- instances.map((instance) => generateServerInstance(instance, routeFilesBySpecifier))
652
+ instances.map((instance) =>
653
+ generateServerInstance(instance, routeFilesBySpecifier, materialized, includeRootCatchAll)
654
+ )
637
655
  );
638
656
  return `import { Elysia } from "elysia";
639
657
  ${generated.map(({ imports }) => imports).join("\n")}
@@ -644,6 +662,18 @@ ${generated
644
662
  `;
645
663
  }
646
664
 
665
+ /**
666
+ * Emits a real server route module for build-time consumers such as Elysia's
667
+ * AOT plugin, which imports the application outside Bun's virtual module graph.
668
+ */
669
+ export async function materializedRouteModuleSource(instance: RouteInstanceSpec): Promise<string> {
670
+ const routeFilesBySpecifier = new Map<string, RouteModuleInfo>();
671
+ const source = await serverRegistrySource([instance], routeFilesBySpecifier, true, false);
672
+ await validateRouteModules(routeFilesBySpecifier.values());
673
+ const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
674
+ return `${source}\nexport { ${exportName} as furinApp };\n`;
675
+ }
676
+
647
677
  export function validateRouteParams(
648
678
  path: string,
649
679
  schemas: { params?: { properties?: object } } | undefined
@@ -867,10 +897,11 @@ async function composableRouteApps(route: RouteFile): Promise<DevRoutesApps | un
867
897
 
868
898
  async function composeRuntimeNode(node: RouteTreeNode): Promise<DevRoutesApps> {
869
899
  const prefix = node.name ? `/${segmentPath(node.name)}` : "";
900
+ const { fileRoutes } = node;
870
901
  const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
871
902
  node.layout ? composableRouteApps(node.layout) : undefined,
872
903
  node.indexRoute ? composableRouteApps(node.indexRoute) : undefined,
873
- Promise.all(node.fileRoutes.map((route) => composableRouteApps(route))),
904
+ Promise.all(fileRoutes.map((route) => composableRouteApps(route))),
874
905
  Promise.all(node.children.map((child) => composeRuntimeNode(child))),
875
906
  ]);
876
907
  const appScope = layoutApps?.app ?? new Elysia();
@@ -880,12 +911,14 @@ async function composeRuntimeNode(node: RouteTreeNode): Promise<DevRoutesApps> {
880
911
  appScope.use(new Elysia({ prefix: "" }).use(indexRouteApps.app));
881
912
  shellScope.use(new Elysia({ prefix: "" }).use(indexRouteApps.shell));
882
913
  }
883
- for (const [index, route] of node.fileRoutes.entries()) {
914
+ for (const [index, route] of fileRoutes.entries()) {
884
915
  const routeApps = fileRouteApps[index];
885
916
  if (routeApps) {
886
917
  const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
887
918
  appScope.use(new Elysia({ prefix: `/${segment}` }).use(routeApps.app));
888
- shellScope.use(new Elysia({ prefix: `/${segment}` }).use(routeApps.shell));
919
+ if (route.path !== "/*") {
920
+ shellScope.use(new Elysia({ prefix: `/${segment}` }).use(routeApps.shell));
921
+ }
889
922
  }
890
923
  }
891
924
  for (const child of childApps) {
@@ -974,9 +1007,12 @@ function primaryInstance(instances: RouteInstanceSpec[]): RouteInstanceSpec {
974
1007
  return instance;
975
1008
  }
976
1009
 
977
- function serverProxySource(instance: RouteInstanceSpec): string {
1010
+ function serverProxySource(instance: RouteInstanceSpec, includeRootCatchAll: boolean): string {
978
1011
  const exportName = `furinApp_${Bun.hash(instanceKey(instance)).toString(16)}`;
979
- return `export { ${exportName} as furinApp } from ${JSON.stringify(ROUTES_REGISTRY_SPECIFIER)};\n`;
1012
+ const registry = includeRootCatchAll
1013
+ ? ROUTES_REGISTRY_SPECIFIER
1014
+ : COMPOSABLE_ROUTES_REGISTRY_SPECIFIER;
1015
+ return `export { ${exportName} as furinApp } from ${JSON.stringify(registry)};\n`;
980
1016
  }
981
1017
 
982
1018
  export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunPlugin {
@@ -986,14 +1022,28 @@ export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunP
986
1022
  resolve(primaryInstance(options.instances).pagesDir),
987
1023
  ".furin-routes-registry.ts?furin-virtual"
988
1024
  );
989
- const instancesBySpecifier = new Map(
990
- options.instances.map(
991
- (instance) =>
992
- [
993
- routeModuleSpecifier(instance),
994
- { instance, namespace: instanceNamespace(instance) },
995
- ] as const
996
- )
1025
+ const composableRegistryVirtualPath = join(
1026
+ resolve(primaryInstance(options.instances).pagesDir),
1027
+ ".furin-routes-registry-composable.ts?furin-virtual"
1028
+ );
1029
+ const instancesBySpecifier = new Map<
1030
+ string,
1031
+ { instance: RouteInstanceSpec; namespace: string; includeRootCatchAll: boolean }
1032
+ >(
1033
+ options.instances.flatMap((instance) => [
1034
+ [
1035
+ routeModuleSpecifier(instance),
1036
+ { includeRootCatchAll: true, instance, namespace: instanceNamespace(instance) },
1037
+ ] as const,
1038
+ [
1039
+ composableRouteModuleSpecifier(instance),
1040
+ {
1041
+ includeRootCatchAll: false,
1042
+ instance,
1043
+ namespace: `${instanceNamespace(instance)}-composable`,
1044
+ },
1045
+ ] as const,
1046
+ ])
997
1047
  );
998
1048
 
999
1049
  return {
@@ -1018,12 +1068,18 @@ export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunP
1018
1068
  }
1019
1069
  return { namespace: registered.namespace, path };
1020
1070
  });
1021
- build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, () => ({
1071
+ build.onResolve({ filter: ROUTES_REGISTRY_FILTER }, ({ path }) => ({
1022
1072
  namespace: "file",
1023
- path: registryVirtualPath,
1073
+ path:
1074
+ path === ROUTES_REGISTRY_SPECIFIER ? registryVirtualPath : composableRegistryVirtualPath,
1024
1075
  }));
1025
- build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async () => {
1026
- const contents = await serverRegistrySource(options.instances, routeFilesBySpecifier);
1076
+ build.onLoad({ filter: ROUTES_REGISTRY_FILE_FILTER, namespace: "file" }, async ({ path }) => {
1077
+ const contents = await serverRegistrySource(
1078
+ options.instances,
1079
+ routeFilesBySpecifier,
1080
+ false,
1081
+ path === registryVirtualPath
1082
+ );
1027
1083
  await validateRouteModules(routeFilesBySpecifier.values());
1028
1084
  return { contents, loader: "ts" };
1029
1085
  });
@@ -1050,9 +1106,9 @@ export function createRoutesPlugin(options: CreateRoutesPluginOptions): Bun.BunP
1050
1106
  };
1051
1107
  }
1052
1108
  );
1053
- for (const { instance, namespace } of instancesBySpecifier.values()) {
1109
+ for (const { instance, namespace, includeRootCatchAll } of instancesBySpecifier.values()) {
1054
1110
  build.onLoad({ filter: VIRTUAL_ROUTES_FILTER, namespace }, () => ({
1055
- contents: serverProxySource(instance),
1111
+ contents: serverProxySource(instance, includeRootCatchAll),
1056
1112
  loader: "ts",
1057
1113
  }));
1058
1114
  }
package/src/rsc/codec.ts CHANGED
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
+ import { isProductionBuild } from "../shared/production-build.ts";
5
6
  import { drainFlight, type FlightRenderSession } from "./flight-drain.ts";
6
7
  import type { RscRenderOperation } from "./render-error.ts";
7
8
 
@@ -9,7 +10,7 @@ interface ServerCodec {
9
10
  renderFlight: (model: unknown, signal: AbortSignal | undefined) => FlightRenderSession;
10
11
  }
11
12
 
12
- let serverCodecPromise: Promise<ServerCodec> | undefined;
13
+ const serverCodecPromises = new Map<"development" | "production", Promise<ServerCodec>>();
13
14
 
14
15
  export function resolveConfiguredCodecPath(configuredPath: string | undefined): string | undefined {
15
16
  if (configuredPath === undefined || configuredPath.trim() === "") {
@@ -31,11 +32,13 @@ export function resolveBuiltCodecPath(
31
32
  }
32
33
 
33
34
  function loadServerCodec(): Promise<ServerCodec> {
34
- if (serverCodecPromise !== undefined) {
35
- return serverCodecPromise;
35
+ const mode = isProductionBuild() ? "production" : "development";
36
+ const existing = serverCodecPromises.get(mode);
37
+ if (existing !== undefined) {
38
+ return existing;
36
39
  }
37
40
 
38
- serverCodecPromise = (async () => {
41
+ const codecPromise = (async () => {
39
42
  const configuredCodecPath = resolveConfiguredCodecPath(process.env.FURIN_RSC_CODEC_PATH);
40
43
  if (configuredCodecPath !== undefined) {
41
44
  return import(pathToFileURL(configuredCodecPath).href) as Promise<ServerCodec>;
@@ -44,7 +47,7 @@ function loadServerCodec(): Promise<ServerCodec> {
44
47
  if (builtCodecPath !== undefined) {
45
48
  return import(pathToFileURL(builtCodecPath).href) as Promise<ServerCodec>;
46
49
  }
47
- const outdir = join(tmpdir(), `furin-rsc-${process.pid}-${Bun.hash(import.meta.url)}`);
50
+ const outdir = join(tmpdir(), `furin-rsc-${process.pid}-${Bun.hash(import.meta.url)}-${mode}`);
48
51
  mkdirSync(outdir, { recursive: true });
49
52
  const sourcePath = join(import.meta.dir, "server-codec.ts");
50
53
  if (!existsSync(sourcePath)) {
@@ -54,6 +57,7 @@ function loadServerCodec(): Promise<ServerCodec> {
54
57
  }
55
58
  const result = await Bun.build({
56
59
  conditions: ["react-server"],
60
+ define: { "process.env.NODE_ENV": JSON.stringify(mode) },
57
61
  entrypoints: [sourcePath],
58
62
  format: "esm",
59
63
  minify: false,
@@ -72,7 +76,8 @@ function loadServerCodec(): Promise<ServerCodec> {
72
76
  return import(pathToFileURL(output.path).href) as Promise<ServerCodec>;
73
77
  })();
74
78
 
75
- return serverCodecPromise;
79
+ serverCodecPromises.set(mode, codecPromise);
80
+ return codecPromise;
76
81
  }
77
82
 
78
83
  export async function encodeFlight(
@@ -1,3 +1,5 @@
1
+ import { isProductionBuild } from "../shared/production-build.ts";
2
+
1
3
  export type RscRenderOperation = "createCompositeComponent" | "renderServerComponent";
2
4
 
3
5
  interface FurinRscRenderErrorOptions {
@@ -53,7 +55,7 @@ function detectComponent(error: unknown, hook: string | undefined): string | und
53
55
  }
54
56
 
55
57
  function renderErrorMessage(options: FurinRscRenderErrorOptions): string {
56
- if (typeof process !== "undefined" && process.env.NODE_ENV === "production") {
58
+ if (isProductionBuild()) {
57
59
  return `[furin/rsc] Server Component rendering failed inside ${options.operation}().`;
58
60
  }
59
61
  if (options.hook !== undefined && options.component !== undefined) {
@@ -0,0 +1,99 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { staticPlugin } from "@elysia/static";
4
+ import { type AnyElysia, Elysia, file } from "elysia";
5
+ import type { CompileContext, EmbeddedAppData } from "../internal.ts";
6
+
7
+ function resolveEmbeddedAssetPath(directory: string, requestPath: string): string | null {
8
+ const assetPath = resolve(directory, requestPath);
9
+ const pathFromDirectory = relative(directory, assetPath);
10
+ if (
11
+ pathFromDirectory === "" ||
12
+ pathFromDirectory === ".." ||
13
+ pathFromDirectory.startsWith(`..${sep}`) ||
14
+ isAbsolute(pathFromDirectory)
15
+ ) {
16
+ return null;
17
+ }
18
+ return assetPath;
19
+ }
20
+
21
+ async function loadEmbeddedAsset(
22
+ directory: string,
23
+ requestPath: string
24
+ ): Promise<ReturnType<typeof Bun.file> | null> {
25
+ const assetPath = resolveEmbeddedAssetPath(directory, requestPath);
26
+ if (assetPath === null) {
27
+ return null;
28
+ }
29
+ const asset = Bun.file(assetPath);
30
+ return (await asset.exists()) ? asset : null;
31
+ }
32
+
33
+ function createEmbeddedAssetsPlugin(embedded: EmbeddedAppData): AnyElysia {
34
+ const { clientDir, publicDir } = embedded;
35
+ if (!publicDir) {
36
+ return new Elysia().get("/_client/*", async ({ params, set, status }) => {
37
+ const asset = await loadEmbeddedAsset(clientDir, params["*"]);
38
+ if (asset === null) {
39
+ return status("Not Found");
40
+ }
41
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
42
+ return asset;
43
+ });
44
+ }
45
+
46
+ return new Elysia()
47
+ .get("/favicon.ico", async ({ status }) => {
48
+ const asset = await loadEmbeddedAsset(publicDir, "favicon.ico");
49
+ return asset ?? status("Not Found");
50
+ })
51
+ .get("/public/*", async ({ params, set, status }) => {
52
+ const asset = await loadEmbeddedAsset(publicDir, params["*"]);
53
+ if (asset === null) {
54
+ return status("Not Found");
55
+ }
56
+ set.headers["cache-control"] = "public, max-age=86400";
57
+ return asset;
58
+ })
59
+ .get("/_client/*", async ({ params, set, status }) => {
60
+ const asset = await loadEmbeddedAsset(clientDir, params["*"]);
61
+ if (asset === null) {
62
+ return status("Not Found");
63
+ }
64
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
65
+ return asset;
66
+ });
67
+ }
68
+
69
+ export async function createProductionAssetsPlugin(
70
+ ctx: CompileContext,
71
+ embedded: EmbeddedAppData | undefined,
72
+ clientDir: string
73
+ ): Promise<AnyElysia> {
74
+ if (ctx.serveAssets === false) {
75
+ return new Elysia();
76
+ }
77
+ if (embedded) {
78
+ // @elysia/static scans with Bun.Glob, which cannot open BunFS directories
79
+ // in Bun 1.4.0. Direct file lookup also avoids enumerating assets at startup.
80
+ return createEmbeddedAssetsPlugin(embedded);
81
+ }
82
+
83
+ const publicDir = join(dirname(clientDir), "public");
84
+ const publicAssets = existsSync(publicDir)
85
+ ? new Elysia()
86
+ .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
87
+ .use(await staticPlugin({ assets: publicDir, prefix: "/public" }))
88
+ : new Elysia();
89
+
90
+ return publicAssets.use(
91
+ await staticPlugin({
92
+ assets: clientDir,
93
+ headers: {
94
+ "Cache-Control": "public, max-age=31536000, immutable",
95
+ },
96
+ prefix: "/_client",
97
+ })
98
+ );
99
+ }
@@ -1,4 +1,4 @@
1
- import { type AfterHandler, Elysia } from "elysia";
1
+ import { Elysia } from "elysia";
2
2
  import {
3
3
  appendPendingInvalidationHeader,
4
4
  isSuccessfulMutationResponse,
@@ -6,17 +6,17 @@ import {
6
6
  } from "./runtime.ts";
7
7
  import type { InvalidationInput } from "./types.ts";
8
8
 
9
- type AnyAfterHandleContext = Parameters<AfterHandler>[0];
9
+ type AnyAfterHandleContext = Parameters<typeof isSuccessfulMutationResponse>[0];
10
10
 
11
11
  export function furinInvalidate() {
12
12
  return new Elysia({ name: "furin-invalidate" }).macro({
13
13
  invalidate(rules: InvalidationInput) {
14
14
  return {
15
- afterHandle(ctx: AnyAfterHandleContext) {
15
+ async afterHandle(ctx: AnyAfterHandleContext) {
16
16
  if (!isSuccessfulMutationResponse(ctx)) {
17
17
  return;
18
18
  }
19
- runInvalidationRules(rules);
19
+ await runInvalidationRules(rules);
20
20
  appendPendingInvalidationHeader(ctx.set);
21
21
  },
22
22
  };
@@ -6,6 +6,7 @@ import {
6
6
  revalidatePath,
7
7
  revalidatePathForInstance,
8
8
  } from "../cache/invalidation.ts";
9
+ import { getPageCacheAdapter } from "../cache/page-cache-state.ts";
9
10
  import { callCacheTagPurger } from "../cache/purger.ts";
10
11
  import { pathWithoutSearch } from "../cache/route-cache.ts";
11
12
  import {
@@ -124,48 +125,78 @@ export function appendPendingInvalidationHeader(set: Context["set"]): string[] {
124
125
  return pending;
125
126
  }
126
127
 
127
- export function revalidateTag(tags: string | readonly string[]): boolean {
128
+ async function invalidateTagsForInstance(
129
+ instance: ReturnType<typeof allInstances>[number],
130
+ tagList: readonly string[]
131
+ ): Promise<{ deleted: boolean; purgedPaths: string[] }> {
132
+ let deleted = false;
133
+ const purgedPaths = new Set<string>();
134
+ const logicalPurgedPaths = new Set<string>();
135
+ const pageCache = getPageCacheAdapter(instance);
136
+ const sharedResult =
137
+ pageCache === undefined
138
+ ? undefined
139
+ : await pageCache.invalidate({
140
+ kind: "tags",
141
+ scope: instance.prefix,
142
+ tags: tagList,
143
+ });
144
+ if (sharedResult !== undefined) {
145
+ deleted = sharedResult.invalidated;
146
+ }
147
+ const taggedPaths = new Set([
148
+ ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
149
+ ...(sharedResult?.paths ?? []),
150
+ ]);
151
+ // Registry paths are LOGICAL (unprefixed); the CDN caches the PHYSICAL
152
+ // request URL, so prefix each with the instance's mount prefix before
153
+ // queueing it for purge — otherwise a mounted app's `/admin/x` stays stale.
154
+ for (const path of taggedPaths) {
155
+ const logicalPath = pathWithoutSearch(path);
156
+ const result = revalidatePathForInstance(instance, logicalPath, "page", false);
157
+ deleted = result.deleted || deleted;
158
+ purgedPaths.add(physicalPath(instance.prefix, logicalPath));
159
+ logicalPurgedPaths.add(logicalPath);
160
+ for (const purged of result.purgedPaths) {
161
+ purgedPaths.add(physicalPath(instance.prefix, purged));
162
+ logicalPurgedPaths.add(purged);
163
+ }
164
+ }
165
+ if (IS_DEV) {
166
+ withInstance(instance, () => {
167
+ const request = currentInstrumentationRequest();
168
+ const operationId = request === undefined ? null : request.operationId;
169
+ const requestId = request === undefined ? null : request.requestId;
170
+ emitCacheInvalidated({
171
+ deleted,
172
+ operationId,
173
+ purgedPaths: logicalPurgedPaths.size,
174
+ reason: "tag",
175
+ requestId,
176
+ target: tagList.join(","),
177
+ });
178
+ });
179
+ }
180
+ return { deleted, purgedPaths: [...purgedPaths] };
181
+ }
182
+
183
+ export async function revalidateTag(tags: string | readonly string[]): Promise<boolean> {
128
184
  const tagList = typeof tags === "string" ? [tags] : [...tags];
129
185
  // Tags are cross-app by design: with several mounted furin instances a
130
186
  // shared mutation must be able to invalidate pages rendered by any of them.
131
187
  // But each instance's tag-registered paths are evicted from THAT instance's
132
188
  // caches only — the cross-app fan-out of `revalidatePath` would also evict
133
189
  // a sibling app's unrelated page that merely shares the pathname.
134
- let deleted = false;
135
- const purgedPaths = new Set<string>();
136
190
  callCacheTagPurger(tagList);
137
- for (const instance of allInstances()) {
138
- let instanceDeleted = false;
139
- const instancePurgedPaths = new Set<string>();
140
- // Registry paths are LOGICAL (unprefixed); the CDN caches the PHYSICAL
141
- // request URL, so prefix each with the instance's mount prefix before
142
- // queueing it for purge — otherwise a mounted app's `/admin/x` stays stale.
143
- for (const path of getAutoInvalidateRegistry(instance).pathsForTags(tagList)) {
144
- const logicalPath = pathWithoutSearch(path);
145
- const result = revalidatePathForInstance(instance, logicalPath, "page", false);
146
- deleted = result.deleted || deleted;
147
- instanceDeleted = result.deleted || instanceDeleted;
148
- purgedPaths.add(physicalPath(instance.prefix, logicalPath));
149
- instancePurgedPaths.add(logicalPath);
150
- for (const purged of result.purgedPaths) {
151
- purgedPaths.add(physicalPath(instance.prefix, purged));
152
- instancePurgedPaths.add(purged);
153
- }
154
- }
155
- if (IS_DEV) {
156
- withInstance(instance, () => {
157
- const request = currentInstrumentationRequest();
158
- const operationId = request === undefined ? null : request.operationId;
159
- const requestId = request === undefined ? null : request.requestId;
160
- emitCacheInvalidated({
161
- deleted: instanceDeleted,
162
- operationId,
163
- purgedPaths: instancePurgedPaths.size,
164
- reason: "tag",
165
- requestId,
166
- target: tagList.join(","),
167
- });
168
- });
191
+ const results = await Promise.all(
192
+ allInstances().map((instance) => invalidateTagsForInstance(instance, tagList))
193
+ );
194
+ const purgedPaths = new Set<string>();
195
+ let deleted = false;
196
+ for (const result of results) {
197
+ deleted = result.deleted || deleted;
198
+ for (const path of result.purgedPaths) {
199
+ purgedPaths.add(path);
169
200
  }
170
201
  }
171
202
  // One batched CDN purge — the CDN sits in front of every mounted app, so
@@ -174,15 +205,16 @@ export function revalidateTag(tags: string | readonly string[]): boolean {
174
205
  return deleted;
175
206
  }
176
207
 
177
- export function runInvalidationRules(input: InvalidationInput): boolean {
178
- let deleted = false;
179
- for (const rule of toRules(input)) {
208
+ export async function runInvalidationRules(input: InvalidationInput): Promise<boolean> {
209
+ const operations = toRules(input).flatMap((rule) => {
210
+ const pending: Promise<boolean>[] = [];
180
211
  if ("path" in rule && rule.path) {
181
- deleted = revalidatePath(rule.path, rule.type) || deleted;
212
+ pending.push(revalidatePath(rule.path, rule.type));
182
213
  }
183
214
  if (rule.tags && rule.tags.length > 0) {
184
- deleted = revalidateTag(rule.tags) || deleted;
215
+ pending.push(revalidateTag(rule.tags));
185
216
  }
186
- }
187
- return deleted;
217
+ return pending;
218
+ });
219
+ return (await Promise.all(operations)).some(Boolean);
188
220
  }
@@ -1,4 +1,5 @@
1
1
  import { type AnyElysia, Elysia } from "elysia";
2
+ import { websocket } from "elysia/websocket";
2
3
  import { browserEventsClientSource } from "../../client/browser-events-runtime.ts";
3
4
  import {
4
5
  BROWSER_EVENT_PROTOCOL_VERSION,
@@ -8,6 +9,7 @@ import { forbiddenDevelopmentRequest } from "../dev/request-security.ts";
8
9
  import { IS_DEV } from "../runtime-env.ts";
9
10
  import type { FurinSyncOptions } from "../sync/config.ts";
10
11
  import { subscribeSyncCursor } from "../sync/stream.ts";
12
+ import { registerBrowserEventConnection, unregisterBrowserEventConnection } from "./shutdown.ts";
11
13
  import type { BrowserEventSource, BrowserEventSubscription } from "./types.ts";
12
14
 
13
15
  const CLIENT_PATH = "/_furin/events/client.js";
@@ -22,8 +24,10 @@ interface BrowserEventsPluginOptions {
22
24
  }
23
25
 
24
26
  interface ConnectionState {
27
+ close: () => void;
25
28
  closed: boolean;
26
29
  heartbeat: ReturnType<typeof setInterval>;
30
+ server: Bun.Server<unknown>;
27
31
  subscriptions: BrowserEventSubscription[];
28
32
  }
29
33
 
@@ -32,6 +36,7 @@ function releaseConnection(state: ConnectionState): void {
32
36
  return;
33
37
  }
34
38
  state.closed = true;
39
+ unregisterBrowserEventConnection(state.server, state.close);
35
40
  clearInterval(state.heartbeat);
36
41
  for (const subscription of state.subscriptions) {
37
42
  subscription.unsubscribe();
@@ -60,6 +65,7 @@ export function createBrowserEventsPlugin(options: BrowserEventsPluginOptions):
60
65
  const connections = new Map<string, ConnectionState>();
61
66
  const { sources = [], sync } = options;
62
67
  return new Elysia({ name: "furin-browser-events" })
68
+ .use(websocket())
63
69
  .get(CLIENT_PATH, ({ request, server }) => {
64
70
  const forbidden = forbiddenBrowserRequest(request, server);
65
71
  if (forbidden) {
@@ -105,12 +111,18 @@ export function createBrowserEventsPlugin(options: BrowserEventsPluginOptions):
105
111
  }
106
112
  };
107
113
  const state: ConnectionState = {
114
+ close: () => ws.close(1001, "Server shutting down"),
108
115
  closed: false,
109
- heartbeat: setInterval(() => ws.ping(), HEARTBEAT_INTERVAL_MS),
116
+ heartbeat: setInterval(
117
+ () => (ws as unknown as { ping: () => number }).ping(),
118
+ HEARTBEAT_INTERVAL_MS
119
+ ),
120
+ server: ws.server as Bun.Server<unknown>,
110
121
  subscriptions: [],
111
122
  };
112
123
  state.heartbeat.unref?.();
113
124
  connections.set(ws.id, state);
125
+ registerBrowserEventConnection(state.server, state.close);
114
126
  const keep = (subscription: BrowserEventSubscription): void => {
115
127
  if (state.closed) {
116
128
  subscription.unsubscribe();
@@ -0,0 +1,32 @@
1
+ const closeConnections = new WeakMap<Bun.Server<unknown>, Set<() => void>>();
2
+
3
+ export function registerBrowserEventConnection(
4
+ server: Bun.Server<unknown>,
5
+ close: () => void
6
+ ): void {
7
+ let connections = closeConnections.get(server);
8
+ if (!connections) {
9
+ connections = new Set();
10
+ closeConnections.set(server, connections);
11
+ }
12
+ connections.add(close);
13
+ }
14
+
15
+ export function unregisterBrowserEventConnection(
16
+ server: Bun.Server<unknown>,
17
+ close: () => void
18
+ ): void {
19
+ closeConnections.get(server)?.delete(close);
20
+ }
21
+
22
+ export function closeBrowserEventConnections(server: Bun.Server<unknown>): void {
23
+ const connections = closeConnections.get(server);
24
+ if (!connections) {
25
+ return;
26
+ }
27
+ closeConnections.delete(server);
28
+ for (const close of connections) {
29
+ close();
30
+ }
31
+ connections.clear();
32
+ }