@teyik0/furin 0.6.0-alpha.1 → 0.7.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 (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
@@ -0,0 +1,51 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { aotFactory } from "elysia/plugin/aot/unplugin";
3
+ import { isomorphicTransformPlugin } from "../plugin/transform-isomorphic.ts";
4
+
5
+ export type AotWorkerOperation =
6
+ | { method: "start" | "end" }
7
+ | { code: string; method: "transform"; path: string };
8
+
9
+ export type AotWorkerRequest = AotWorkerOperation & { id: number };
10
+
11
+ export interface AotWorkerResult {
12
+ code?: string;
13
+ virtualType?: string;
14
+ }
15
+
16
+ export type AotWorkerResponse =
17
+ | (AotWorkerResult & { id: number; ok: true })
18
+ | { error: Error; id: number; ok: false };
19
+
20
+ const port = parentPort;
21
+ if (!port) {
22
+ throw new Error("[furin] Elysia AOT worker requires a parent port.");
23
+ }
24
+ const { entry } = workerData as { entry: string };
25
+ const hooks = aotFactory({ entry, strip: false, target: "bun" });
26
+ Bun.plugin(isomorphicTransformPlugin("server"));
27
+
28
+ port.on("message", async (request: AotWorkerRequest) => {
29
+ try {
30
+ let code: string | undefined;
31
+ let virtualType: string | undefined;
32
+ if (request.method === "start") {
33
+ await hooks.buildStart?.();
34
+ code = hooks.load?.("\0elysia/compiled");
35
+ virtualType = hooks.load?.("\0elysia/type");
36
+ } else if (request.method === "transform") {
37
+ if (hooks.transformInclude?.(request.path) !== false) {
38
+ code = hooks.transform?.(request.code, request.path);
39
+ }
40
+ } else {
41
+ hooks.buildEnd?.();
42
+ }
43
+ port.postMessage({ code, id: request.id, ok: true, virtualType } satisfies AotWorkerResponse);
44
+ } catch (error) {
45
+ port.postMessage({
46
+ error: error instanceof Error ? error : new Error(String(error)),
47
+ id: request.id,
48
+ ok: false,
49
+ } satisfies AotWorkerResponse);
50
+ }
51
+ });
@@ -1,9 +1,25 @@
1
- import { dirname, resolve } from "node:path";
2
- import { aotFactory } from "elysia/plugin/aot/unplugin";
1
+ import { dirname, join, resolve } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { Worker } from "node:worker_threads";
4
+ import type {
5
+ AotWorkerOperation,
6
+ AotWorkerRequest,
7
+ AotWorkerResponse,
8
+ AotWorkerResult,
9
+ } from "./elysia-aot-worker.ts";
3
10
 
4
11
  const AOT_NAMESPACE = "furin-elysia-aot";
5
12
  const ELYSIA_RESOLVE_DIR = dirname(Bun.resolveSync("elysia", import.meta.dir));
13
+ // The published package ships src/ too; resolving from the package entry also
14
+ // works when this adapter is bundled into dist/build/index.js or dist/cli/index.js.
15
+ const AOT_WORKER_PATH = join(
16
+ dirname(dirname(fileURLToPath(import.meta.resolve("@teyik0/furin")))),
17
+ "src/build/elysia-aot-worker.ts"
18
+ );
6
19
  const SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
20
+ const ELYSIA_IMPORT_FILTER = /^elysia(?:\/(?!compiled$|type$).*)?$/;
21
+ const ELYSIA_VIRTUAL_IMPORT_FILTER = /^elysia\/(?:compiled|type)$/;
22
+ const ANY_MODULE_FILTER = /.*/;
7
23
  const WEBSOCKET_STUB_MARKER =
8
24
  "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
9
25
 
@@ -39,16 +55,57 @@ export function handleWSResponse(){return e()}
39
55
  `;
40
56
  }
41
57
 
42
- /** Elysia AOT plugin with the no-WebSocket stub compatibility fix. */
58
+ /** Elysia AOT evaluation has its own module cache, independent of prerender loaders. */
43
59
  export function elysiaAot(entry: string): Bun.BunPlugin {
44
60
  const entryPath = resolve(entry);
45
- const hooks = aotFactory({ entry, strip: false, target: "bun" });
46
61
  return {
47
62
  name: "elysia-aot",
48
63
  async setup(build) {
64
+ const worker = new Worker(AOT_WORKER_PATH, { workerData: { entry: entryPath } });
65
+ const pending = new Map<
66
+ number,
67
+ {
68
+ reject: (error: Error) => void;
69
+ resolve: (response: AotWorkerResult) => void;
70
+ }
71
+ >();
72
+ let nextId = 0;
73
+ let workerFailure: Error | undefined;
74
+ const fail = (error: Error): void => {
75
+ workerFailure = error;
76
+ for (const request of pending.values()) {
77
+ request.reject(error);
78
+ }
79
+ pending.clear();
80
+ };
81
+ worker.on("message", (response: AotWorkerResponse) => {
82
+ const request = pending.get(response.id);
83
+ pending.delete(response.id);
84
+ if (response.ok) {
85
+ request?.resolve(response);
86
+ } else {
87
+ request?.reject(response.error);
88
+ }
89
+ });
90
+ worker.on("error", fail);
91
+ worker.on("exit", (code) => fail(new Error(`[furin] Elysia AOT worker exited (${code}).`)));
92
+ const request = (payload: AotWorkerOperation) =>
93
+ new Promise<AotWorkerResult>((resolveResponse, reject) => {
94
+ if (workerFailure) {
95
+ reject(workerFailure);
96
+ return;
97
+ }
98
+ const id = nextId;
99
+ nextId += 1;
100
+ pending.set(id, { reject, resolve: resolveResponse });
101
+ worker.postMessage({ ...payload, id } satisfies AotWorkerRequest);
102
+ });
103
+ let compiled: string | undefined;
104
+ let virtualType: string | undefined;
49
105
  try {
50
- await hooks.buildStart?.();
106
+ ({ code: compiled, virtualType } = await request({ method: "start" }));
51
107
  } catch (error) {
108
+ await worker.terminate();
52
109
  if (
53
110
  error instanceof Error &&
54
111
  error.message.startsWith("[elysia-aot]") &&
@@ -59,20 +116,33 @@ export function elysiaAot(entry: string): Bun.BunPlugin {
59
116
  }
60
117
  throw error;
61
118
  }
119
+ build.onEnd(async () => {
120
+ try {
121
+ await request({ method: "end" });
122
+ } finally {
123
+ await worker.terminate();
124
+ }
125
+ });
62
126
  const entrySource = await Bun.file(entryPath).text();
63
- const transformedEntry = await hooks.transform?.(entrySource, entryPath);
127
+ const { code: transformedEntry } = await request({
128
+ code: entrySource,
129
+ method: "transform",
130
+ path: entryPath,
131
+ });
64
132
  if (transformedEntry !== undefined) {
65
133
  await Bun.write(entryPath, transformedEntry);
66
134
  }
67
- build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
135
+ build.onResolve({ filter: ELYSIA_IMPORT_FILTER }, ({ path }) => ({
68
136
  path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR),
69
137
  }));
70
- build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
71
- const resolved = hooks.resolveId?.(path);
72
- return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
138
+ build.onResolve({ filter: ELYSIA_VIRTUAL_IMPORT_FILTER }, ({ path }) => {
139
+ if (path === "elysia/type" && virtualType === undefined) {
140
+ return;
141
+ }
142
+ return { namespace: AOT_NAMESPACE, path };
73
143
  });
74
- build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
75
- const contents = hooks.load?.(path);
144
+ build.onLoad({ filter: ANY_MODULE_FILTER, namespace: AOT_NAMESPACE }, ({ path }) => {
145
+ const contents = path === "elysia/compiled" ? compiled : virtualType;
76
146
  return contents === undefined
77
147
  ? undefined
78
148
  : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
@@ -81,11 +151,8 @@ export function elysiaAot(entry: string): Bun.BunPlugin {
81
151
  if (resolve(path) === entryPath) {
82
152
  return;
83
153
  }
84
- if (hooks.transformInclude?.(path) === false) {
85
- return;
86
- }
87
154
  const original = await Bun.file(path).text();
88
- const transformed = await hooks.transform?.(original, path);
155
+ const { code: transformed } = await request({ code: original, method: "transform", path });
89
156
  if (transformed === undefined) {
90
157
  return;
91
158
  }
@@ -94,9 +161,6 @@ export function elysiaAot(entry: string): Bun.BunPlugin {
94
161
  loader: loaderFor(path),
95
162
  };
96
163
  });
97
- build.onEnd(() => {
98
- hooks.buildEnd?.();
99
- });
100
164
  },
101
165
  };
102
166
  }
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import type { SsgCacheEntry } from "../server/cache/index.ts";
5
+ import type { ClientPreloadManifest } from "./preload-manifest.ts";
5
6
 
6
7
  // import.meta.resolve() runs at runtime (not inlined at bundle time), resolves
7
8
  // through package exports, and is the Web-standard API. The main entry is
@@ -32,6 +33,8 @@ export interface EntryAppContext {
32
33
  nativeRoutes?: string;
33
34
  /** Mount prefix baked into the context for runtime lookup (`""` = root). */
34
35
  prefix?: string;
36
+ /** Chunk URLs to modulepreload, produced by the client build. */
37
+ preloadManifest?: ClientPreloadManifest;
35
38
  rootConventions?: { errorPath?: string; notFoundPath?: string };
36
39
  rootPath: string;
37
40
  routeMetadata?: Record<
@@ -165,6 +168,9 @@ function buildAppContextBlock(
165
168
  const serveAssetsLine =
166
169
  app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
167
170
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
171
+ const preloadManifestLine = app.preloadManifest
172
+ ? ` preloadManifest: ${JSON.stringify(app.preloadManifest)},`
173
+ : "";
168
174
  const templateHtmlLine =
169
175
  app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
170
176
 
@@ -186,6 +192,7 @@ function buildAppContextBlock(
186
192
  routeMetadataLine,
187
193
  serveAssetsLine,
188
194
  ssgCacheLine,
195
+ preloadManifestLine,
189
196
  templateHtmlLine,
190
197
  ...(app.extraContext ?? []),
191
198
  "});",
@@ -31,6 +31,7 @@ export function generateHydrateEntry(
31
31
  basePath: string,
32
32
  clientLogging: boolean
33
33
  ): string {
34
+ const rootDirectory = rootLayout.replaceAll("\\", "/").split("/").slice(0, -1).join("/");
34
35
  const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
35
36
  if (!filePath) {
36
37
  return;
@@ -85,6 +86,9 @@ export function generateHydrateEntry(
85
86
  if (notFoundIdent) {
86
87
  parts.push(`notFound: ${notFoundIdent}.default`);
87
88
  }
89
+ if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
90
+ parts.push("isRoot: false");
91
+ }
88
92
  boundaryLiterals.push(`{ ${parts.join(", ")} }`);
89
93
  }
90
94
 
@@ -106,7 +110,7 @@ export function generateHydrateEntry(
106
110
  ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]`
107
111
  : "";
108
112
  const pageComponentKey = JSON.stringify(`page:${resolvedPage}`);
109
- const loadBody = `Promise.all([${lazyImports.join(", ")}]).then(([${importIdents.join(", ")}]) => { const __furin_page_route = __furin_page.route; let __furin_parent = root; ${layoutAssignments} return { default: { __type: "FURIN_PAGE", _route: { __type: "FURIN_ROUTE", parent: __furin_parent }, component: hotComponent(${pageComponentKey}, __furin_page_route.component) }${boundaryResult} }; })`;
113
+ const loadBody = `Promise.all([${lazyImports.join(", ")}]).then(([${importIdents.join(", ")}]) => { const __furin_page_route = __furin_page.route; let __furin_parent = root; ${layoutAssignments} return { default: { __type: "FURIN_PAGE", _route: { __type: "FURIN_ROUTE", parent: __furin_parent, remountDeps: __furin_page_route.remountDeps }, component: hotComponent(${pageComponentKey}, __furin_page_route.component) }${boundaryResult} }; })`;
110
114
 
111
115
  const searchDefaultsEntry = searchDefaults
112
116
  ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
@@ -361,6 +365,12 @@ if (__deferred && __deferred._chunks) {
361
365
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
362
366
  } as any);
363
367
  } else {
368
+ // A removed active route has no match in the new development manifest.
369
+ // Reload its document so the server can render the current 404 response.
370
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
371
+ window.location.reload();
372
+ return;
373
+ }
364
374
  // No match and no 404 signal — either the client bundle is out of sync
365
375
  // with the server (stale deploy) or the server returned something we
366
376
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -447,13 +457,21 @@ if (__deferred && __deferred._chunks) {
447
457
  export function writeDevFiles(
448
458
  routes: ResolvedRoute[],
449
459
  { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }: BuildClientOptions,
450
- projectRoot: string
460
+ projectRoot: string,
461
+ serverSourceVersion?: string
451
462
  ): void {
452
463
  if (!existsSync(outDir)) {
453
464
  mkdirSync(outDir, { recursive: true });
454
465
  }
455
466
 
456
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
467
+ // Server-only helpers are absent from Bun's client graph. A live version
468
+ // makes their edits use the same transactional HMR path as client edits.
469
+ const serverVersion =
470
+ serverSourceVersion === undefined
471
+ ? ""
472
+ : `\nif (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};\n`;
473
+ const hydrateCode =
474
+ generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
457
475
  const hydratePath = join(outDir, "_hydrate.tsx");
458
476
  const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
459
477
  let changed = false;
@@ -0,0 +1,100 @@
1
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { basename, resolve } from "node:path";
3
+ import { clientModuleKey } from "../plugin/transform-client-module.ts";
4
+ import type { ResolvedRoute } from "../server/router/types.ts";
5
+
6
+ const CLIENT_MODULE_KEY_RE = /(["'`])(__FURIN_CLIENT_MODULE_[a-z0-9]+__)\1/g;
7
+
8
+ /** Chunk URLs to `<link rel="modulepreload">`, derived from the client build graph. */
9
+ export interface ClientPreloadManifest {
10
+ /** `clientModule()` key → the module's chunk and its transitive static imports. */
11
+ modules: Record<string, string[]>;
12
+ /** Route pattern → page, layout and boundary chunks plus their transitive static imports. */
13
+ routes: Record<string, string[]>;
14
+ }
15
+
16
+ /** Client modules a route's hydration loads (mirrors the generated hydrate entry). */
17
+ function routeModulePaths(route: ResolvedRoute): string[] {
18
+ const layouts = (route.routeChain ?? [])
19
+ .slice(1)
20
+ .filter((entry) => entry.layout && entry.sourcePath)
21
+ .map((entry) => entry.sourcePath as string);
22
+ const boundaries = (route.segmentBoundaries ?? []).flatMap((segment) =>
23
+ [segment.errorPath, segment.notFoundPath].filter((path) => path !== undefined)
24
+ );
25
+ return [route.path, ...layouts, ...boundaries];
26
+ }
27
+
28
+ function realPath(path: string): string | null {
29
+ return existsSync(path) ? realpathSync(path) : null;
30
+ }
31
+
32
+ /**
33
+ * Builds the preload manifest from Bun's metafile and swaps every
34
+ * `clientModule()` key left in the emitted JS for its chunk URLs.
35
+ *
36
+ * Chunks the entry already loads statically are excluded. Rewriting a chunk
37
+ * after hashing is safe: its hash covers the hashes of every chunk it imports,
38
+ * so the URLs it now embeds can only change when its own name changes.
39
+ */
40
+ export function writeClientPreloadManifest(
41
+ metafile: Bun.BuildMetafile,
42
+ outputPaths: string[],
43
+ entryChunkPath: string,
44
+ routes: ResolvedRoute[],
45
+ publicPrefix: string
46
+ ): ClientPreloadManifest {
47
+ const outputs = new Map(
48
+ Object.entries(metafile.outputs).map(([path, output]) => [basename(path), output])
49
+ );
50
+ const closure = (file: string, seen: Set<string>): Set<string> => {
51
+ if (!seen.has(file)) {
52
+ seen.add(file);
53
+ for (const imported of outputs.get(file)?.imports ?? []) {
54
+ if (imported.kind === "import-statement") {
55
+ closure(basename(imported.path), seen);
56
+ }
57
+ }
58
+ }
59
+ return seen;
60
+ };
61
+ const entryFiles = closure(basename(entryChunkPath), new Set());
62
+ const hrefsOf = (file: string) =>
63
+ [...closure(file, new Set())]
64
+ .filter((chunk) => !entryFiles.has(chunk))
65
+ .map((chunk) => `${publicPrefix}${chunk}`);
66
+
67
+ const chunkByModule = new Map<string, string>();
68
+ for (const [file, output] of outputs) {
69
+ const modulePath = output.entryPoint ? realPath(resolve(output.entryPoint)) : null;
70
+ if (modulePath !== null) {
71
+ chunkByModule.set(modulePath, file);
72
+ }
73
+ }
74
+
75
+ const routeManifest: ClientPreloadManifest["routes"] = {};
76
+ for (const route of routes) {
77
+ const files = routeModulePaths(route)
78
+ .map((path) => chunkByModule.get(realPath(path) ?? path))
79
+ .filter((file) => file !== undefined);
80
+ routeManifest[route.pattern] = [...new Set(files.flatMap(hrefsOf))];
81
+ }
82
+
83
+ const moduleHrefs = new Map(
84
+ [...chunkByModule].map(([modulePath, file]) => [clientModuleKey(modulePath), file])
85
+ );
86
+ const modules: ClientPreloadManifest["modules"] = {};
87
+ for (const path of outputPaths.filter((output) => output.endsWith(".js"))) {
88
+ const code = readFileSync(path, "utf8");
89
+ const rewritten = code.replace(CLIENT_MODULE_KEY_RE, (_match, _quote, key: string) => {
90
+ const file = moduleHrefs.get(key);
91
+ modules[key] = file === undefined ? [] : hrefsOf(file);
92
+ return JSON.stringify(modules[key]);
93
+ });
94
+ if (rewritten !== code) {
95
+ writeFileSync(path, rewritten);
96
+ }
97
+ }
98
+
99
+ return { modules, routes: routeManifest };
100
+ }
@@ -5,10 +5,10 @@ const DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.j
5
5
  const DEV_RUNTIME_IMPORT =
6
6
  /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
7
7
  const DEV_BUILD_IMPORT =
8
- /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
8
+ /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\](?:route-config-autofix|transform-client))(?:\.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|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
11
+ /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix|transform-client)(?:\.ts|\.js)?$/;
12
12
  const PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
13
13
  const FURIN_RUNTIME_ROOT = resolve(import.meta.dir, "..");
14
14
 
@@ -21,7 +21,10 @@ function isFurinRuntimePath(path: string): boolean {
21
21
  );
22
22
  }
23
23
 
24
- function devBuildExport(path: string): "fixRouteConfigLayout" | "writeDevFiles" {
24
+ function devBuildExport(path: string): "fixRouteConfigLayout" | "getHmrDataSignature" | "writeDevFiles" {
25
+ if (path.includes("transform-client")) {
26
+ return "getHmrDataSignature";
27
+ }
25
28
  return path.includes("route-config-autofix") ? "fixRouteConfigLayout" : "writeDevFiles";
26
29
  }
27
30
 
@@ -26,6 +26,8 @@ export interface BuildClientOptions {
26
26
  outDir: string;
27
27
  pagesDir?: string;
28
28
  plugins?: Bun.BunPlugin[];
29
+ /** Record route chunks in the preload manifest. Defaults to true. */
30
+ preloadRouteChunks?: boolean;
29
31
  /** Enable Bun's native Rust React Compiler. Defaults to true. */
30
32
  reactCompiler?: boolean;
31
33
  /**
@@ -112,6 +114,8 @@ export interface BuildAppOptions {
112
114
  optimizeImports?: string[];
113
115
  pagesDir?: string;
114
116
  plugins?: Bun.BunPlugin[];
117
+ /** Module preloading (furin.config.ts `preload`). */
118
+ preload?: { routeChunks?: boolean };
115
119
  /** Enable Bun's native Rust React Compiler for client bundles. Defaults to true. */
116
120
  reactCompiler?: boolean;
117
121
  rootDir?: string;
package/src/cli/index.ts CHANGED
@@ -181,6 +181,7 @@ if (command === "preview") {
181
181
  optimizeImports: config.optimizeImports,
182
182
  pagesDir: undefined,
183
183
  plugins: config.plugins,
184
+ preload: config.preload,
184
185
  reactCompiler: config.reactCompiler,
185
186
  rootDir: config.rootDir,
186
187
  serverEntry: resolvedServerEntry,
@@ -150,6 +150,8 @@ export function installBrowserEventsRuntime(
150
150
  reconnectAttempt = 0;
151
151
  updateStatus("connected");
152
152
  });
153
+ // This listener belongs to our same-origin EventSource, not window.postMessage.
154
+ // react-doctor-disable-next-line react-doctor/postmessage-origin-risk
153
155
  connection.addEventListener("message", (message) => onMessageData(message.data));
154
156
  connection.addEventListener("error", () => {
155
157
  if (eventSource !== connection || suspended) {
@@ -185,6 +187,8 @@ export function installBrowserEventsRuntime(
185
187
  reconnectAttempt = 0;
186
188
  updateStatus("connected");
187
189
  });
190
+ // This listener belongs to our same-host WebSocket, not window.postMessage.
191
+ // react-doctor-disable-next-line react-doctor/postmessage-origin-risk
188
192
  connection.addEventListener("message", (message) => onMessageData(message.data));
189
193
  connection.addEventListener("close", () => {
190
194
  if (socket !== connection) {
@@ -0,0 +1,57 @@
1
+ import { preloadModule } from "react-dom";
2
+
3
+ /** A browser-only module whose chunks can be preloaded during SSR. */
4
+ export interface ClientModule<T> {
5
+ /** Chunk URLs of the module and its static imports. Empty in dev mode. */
6
+ readonly hrefs: readonly string[];
7
+ /** Imports the module. Only call it in the browser (e.g. in an effect). */
8
+ load: () => Promise<T>;
9
+ }
10
+
11
+ let resolveModuleHrefs: (key: string) => readonly string[] = () => [];
12
+ let resolveNonce: () => string | undefined = () => undefined;
13
+
14
+ /** @internal Reads the nonce from the active server render, without bundling server state. */
15
+ export function setClientModuleNonceResolver(resolver: () => string | undefined): void {
16
+ resolveNonce = resolver;
17
+ }
18
+
19
+ /** @internal The server resolves build keys against the client preload manifest. */
20
+ export function setClientModuleHrefResolver(resolver: (key: string) => readonly string[]): void {
21
+ resolveModuleHrefs = resolver;
22
+ }
23
+
24
+ /**
25
+ * Declares a module that only runs in the browser, e.g. a WebGL scene.
26
+ *
27
+ * Pass an inline `() => import("./module")`. Furin's build keeps the import in
28
+ * the client bundle, strips it from the server bundle, and records the chunk
29
+ * URLs so `preloadClientModule()` can emit `<link rel="modulepreload">` tags.
30
+ *
31
+ * @param build Injected by Furin's build — never pass it yourself.
32
+ */
33
+ export function clientModule<T>(
34
+ load: () => Promise<T>,
35
+ build?: string | readonly string[]
36
+ ): ClientModule<T> {
37
+ return {
38
+ get hrefs() {
39
+ if (build === undefined) {
40
+ return [];
41
+ }
42
+ return typeof build === "string" ? resolveModuleHrefs(build) : build;
43
+ },
44
+ load,
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Preloads a client module's chunks. Call it while rendering: during SSR React
50
+ * hoists one `<link rel="modulepreload">` per chunk into `<head>`.
51
+ */
52
+ export function preloadClientModule<T>(mod: ClientModule<T>): void {
53
+ const nonce = resolveNonce();
54
+ for (const href of mod.hrefs) {
55
+ preloadModule(href, { as: "script", nonce });
56
+ }
57
+ }
@@ -1,3 +1,5 @@
1
+ import type { RemountDeps } from "../shared/page-key.ts";
2
+
1
3
  type ClientComponent = (props: never) => React.ReactNode;
2
4
 
3
5
  interface ClientRuntimeProps {
@@ -10,8 +12,11 @@ interface ClientRuntimeProps {
10
12
 
11
13
  type ClientRuntimeComponent = (props: ClientRuntimeProps) => React.ReactNode;
12
14
 
13
- export function defineRoute() {
15
+ function createRouteBuilder(remountDeps: RemountDeps<never, never> | undefined) {
14
16
  return {
17
+ config(options: { remountDeps?: RemountDeps<never, never> }) {
18
+ return createRouteBuilder(options.remountDeps);
19
+ },
15
20
  layout<Component extends ClientComponent>(component: Component) {
16
21
  const runtimeComponent = component as unknown as ClientRuntimeComponent;
17
22
  return {
@@ -26,11 +31,16 @@ export function defineRoute() {
26
31
  __type: "FURIN_ROUTE" as const,
27
32
  component: runtimeComponent,
28
33
  page: runtimeComponent,
34
+ remountDeps,
29
35
  };
30
36
  },
31
37
  };
32
38
  }
33
39
 
40
+ export function defineRoute() {
41
+ return createRouteBuilder(undefined);
42
+ }
43
+
34
44
  /** Client stub for the root-layout builder — identical surface. */
35
45
  export function defineRootRoute() {
36
46
  return defineRoute();
@@ -1,4 +1,5 @@
1
1
  import { createContext, createElement, type ReactNode, useContext } from "react";
2
+ import { preloadModule } from "react-dom";
2
3
  import type { HeadOptions, MetaDescriptor } from "../client.ts";
3
4
 
4
5
  export interface DocumentAssets {
@@ -7,6 +8,8 @@ export interface DocumentAssets {
7
8
  extensionErrorFilterScript?: string;
8
9
  faviconHref: string | undefined;
9
10
  frameworkModules: readonly string[];
11
+ /** Route chunks to `<link rel="modulepreload">` (production server renders only). */
12
+ modulePreloads?: readonly string[];
10
13
  staticMode: boolean;
11
14
  stylesheets: readonly string[];
12
15
  }
@@ -44,25 +47,25 @@ export function useDocumentState(): DocumentState | null {
44
47
  return useContext(DocumentContext);
45
48
  }
46
49
 
47
- function renderMeta(meta: MetaDescriptor, index: number): ReactNode {
50
+ function renderMeta(meta: MetaDescriptor, key: string): ReactNode {
48
51
  if ("title" in meta) {
49
- return <title key={`title:${index}`}>{meta.title}</title>;
52
+ return <title key={key}>{meta.title}</title>;
50
53
  }
51
54
  if ("script:ld+json" in meta) {
52
55
  return (
53
56
  <script
54
57
  // biome-ignore lint/security/noDangerouslySetInnerHtml: JSON-LD is an explicit raw-head API and is escaped by the route author contract.
55
58
  dangerouslySetInnerHTML={{ __html: serializeJson(meta["script:ld+json"]) }}
56
- key={`json-ld:${index}`}
59
+ key={key}
57
60
  type="application/ld+json"
58
61
  />
59
62
  );
60
63
  }
61
64
  if ("tagName" in meta) {
62
65
  const { tagName, ...attributes } = meta;
63
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
66
+ return createElement(tagName, { ...attributes, key });
64
67
  }
65
- return createElement("meta", { ...meta, key: `meta:${index}` });
68
+ return createElement("meta", { ...meta, key });
66
69
  }
67
70
 
68
71
  export function HeadContent(): ReactNode {
@@ -70,6 +73,16 @@ export function HeadContent(): ReactNode {
70
73
  if (state === null) {
71
74
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
72
75
  }
76
+ for (const href of state.assets.modulePreloads ?? []) {
77
+ preloadModule(href, { as: "script", nonce: state.nonce });
78
+ }
79
+ const occurrences = new Map<string, number>();
80
+ const descriptorKey = (descriptor: object): string => {
81
+ const identity = JSON.stringify(descriptor);
82
+ const occurrence = occurrences.get(identity) ?? 0;
83
+ occurrences.set(identity, occurrence + 1);
84
+ return `${identity}:${occurrence}`;
85
+ };
73
86
 
74
87
  return (
75
88
  <>
@@ -89,27 +102,24 @@ export function HeadContent(): ReactNode {
89
102
  {state.assets.stylesheets.map((href) => (
90
103
  <link crossOrigin="" href={href} key={href} rel="stylesheet" />
91
104
  ))}
92
- {state.head?.meta?.map(renderMeta)}
93
- {state.head?.links?.map((link, index) => (
94
- // biome-ignore lint/suspicious/noArrayIndexKey: duplicate link descriptors are valid and their declared order is significant.
95
- <link key={`${link.rel}:${link.href}:${index}`} {...link} />
105
+ {state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta)))}
106
+ {state.head?.links?.map((link) => (
107
+ <link key={descriptorKey(link)} {...link} />
96
108
  ))}
97
- {state.head?.scripts?.map(({ children, ...attributes }, index) => (
109
+ {state.head?.scripts?.map(({ children, ...attributes }) => (
98
110
  <script
99
- // biome-ignore lint/suspicious/noArrayIndexKey: duplicate inline scripts are valid and their declared order is significant.
100
- key={`script:${index}`}
111
+ key={descriptorKey({ children, ...attributes })}
101
112
  {...attributes}
102
- // biome-ignore lint/security/noDangerouslySetInnerHtml: HeadOptions scripts are an explicit raw HTML API.
103
- dangerouslySetInnerHTML={children === undefined ? undefined : { __html: children }}
104
113
  nonce={state.nonce ?? attributes.nonce}
105
- />
114
+ >
115
+ {children}
116
+ </script>
106
117
  ))}
107
- {state.head?.styles?.map(({ children, type }, index) => (
118
+ {state.head?.styles?.map(({ children, type }) => (
108
119
  <style
109
120
  // biome-ignore lint/security/noDangerouslySetInnerHtml: HeadOptions styles are an explicit raw HTML API.
110
121
  dangerouslySetInnerHTML={{ __html: children }}
111
- // biome-ignore lint/suspicious/noArrayIndexKey: duplicate inline styles are valid and their declared order is significant.
112
- key={`style:${index}`}
122
+ key={descriptorKey({ children, type })}
113
123
  nonce={state.nonce}
114
124
  type={type}
115
125
  />