@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) 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/entry-template.d.ts +3 -0
  4. package/dist/build/entry-template.ts +7 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +1671 -276
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/types.d.ts +6 -0
  9. package/dist/cli/index.js +1672 -286
  10. package/dist/client/client-module.d.ts +26 -0
  11. package/dist/client/define-route.d.ts +9 -0
  12. package/dist/client/document.d.ts +2 -0
  13. package/dist/client/internal/runtime-types.d.ts +2 -0
  14. package/dist/client/link.js +932 -118
  15. package/dist/client/mutation.d.ts +38 -0
  16. package/dist/client/query-store.d.ts +85 -0
  17. package/dist/client/query.d.ts +14 -0
  18. package/dist/client/route-api.d.ts +11 -0
  19. package/dist/client/router/context.d.ts +3 -2
  20. package/dist/client/router/index.d.ts +1 -1
  21. package/dist/client/router/link-utils.d.ts +8 -1
  22. package/dist/client/router/navigation.d.ts +2 -9
  23. package/dist/client/router/optimistic.d.ts +41 -0
  24. package/dist/client/router/search/index.d.ts +3 -3
  25. package/dist/client/router/search-store.d.ts +1 -0
  26. package/dist/client/router/sync-catch-up.d.ts +3 -0
  27. package/dist/client/router/types.d.ts +49 -7
  28. package/dist/client/sync.d.ts +39 -22
  29. package/dist/client.d.ts +11 -33
  30. package/dist/client.js +1219 -59
  31. package/dist/config.d.ts +7 -0
  32. package/dist/config.js +1 -0
  33. package/dist/define-route.d.ts +78 -32
  34. package/dist/env.d.ts +2 -2
  35. package/dist/furin.d.ts +1 -2
  36. package/dist/furin.js +2448 -710
  37. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  38. package/dist/plugin/index.js +349 -18
  39. package/dist/plugin/transform-client-module.d.ts +16 -0
  40. package/dist/plugin/transform-client.d.ts +2 -0
  41. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  42. package/dist/routes.d.ts +6 -0
  43. package/dist/rsc-client.js +87 -16
  44. package/dist/rsc.js +87 -16
  45. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  46. package/dist/server/auto-invalidate/types.d.ts +2 -0
  47. package/dist/server/cache/isr.d.ts +2 -4
  48. package/dist/server/cache/route-cache.d.ts +5 -0
  49. package/dist/server/dev/graph.d.ts +1 -0
  50. package/dist/server/dev-page-plugin.d.ts +5 -19
  51. package/dist/server/internal.d.ts +3 -0
  52. package/dist/server/internal.js +55 -35
  53. package/dist/server/production-server.js +54 -34
  54. package/dist/server/render/loaders.d.ts +4 -2
  55. package/dist/server/render/react-stream.d.ts +3 -0
  56. package/dist/server/render/ssr.d.ts +2 -1
  57. package/dist/server/render/template.d.ts +4 -0
  58. package/dist/server/router/defined-route.d.ts +2 -0
  59. package/dist/server/router/hmr.d.ts +1 -1
  60. package/dist/server/sync/adapter.d.ts +25 -4
  61. package/dist/server/sync/atomic.d.ts +25 -0
  62. package/dist/server/sync/drizzle/index.d.ts +45 -0
  63. package/dist/server/sync/drizzle/index.js +540 -0
  64. package/dist/server/sync/execution-error.d.ts +2 -0
  65. package/dist/server/sync/index.d.ts +2 -1
  66. package/dist/server/sync/index.js +533 -105
  67. package/dist/server/sync/mutation-handler.d.ts +4 -0
  68. package/dist/server/sync/plugin.d.ts +34 -11
  69. package/dist/server/sync/postgres/execute.d.ts +3 -0
  70. package/dist/server/sync/postgres/index.d.ts +12 -1
  71. package/dist/server/sync/postgres/index.js +34 -13
  72. package/dist/server/sync/postgres/sql.d.ts +8 -0
  73. package/dist/server/sync/prisma/index.d.ts +24 -0
  74. package/dist/server/sync/prisma/index.js +340 -0
  75. package/dist/server/sync/queries.d.ts +21 -0
  76. package/dist/server/sync/query-context.d.ts +5 -0
  77. package/dist/server/sync/redis/index.js +3 -3
  78. package/dist/server/sync/redis/scripts.d.ts +1 -1
  79. package/dist/server/sync/response.d.ts +1 -0
  80. package/dist/server/sync/sqlite/index.d.ts +3 -0
  81. package/dist/server/sync/sqlite/index.js +10 -4
  82. package/dist/server/sync/stream.d.ts +2 -5
  83. package/dist/server/sync/validation.d.ts +4 -0
  84. package/dist/shared/defer.d.ts +31 -0
  85. package/dist/shared/error.d.ts +2 -2
  86. package/dist/shared/page-key.d.ts +7 -0
  87. package/dist/shared/query-bindings.d.ts +12 -0
  88. package/dist/shared/route-frame.d.ts +1 -0
  89. package/dist/shared/sync-query.d.ts +40 -0
  90. package/package.json +29 -6
  91. package/src/adapter/package.ts +12 -2
  92. package/src/adapter/runtime-build.ts +63 -12
  93. package/src/adapter/static.ts +7 -2
  94. package/src/adapter/vercel.ts +15 -13
  95. package/src/build/client.ts +23 -5
  96. package/src/build/entry-template.ts +7 -0
  97. package/src/build/hydrate.ts +17 -3
  98. package/src/build/preload-manifest.ts +100 -0
  99. package/src/build/production-instrumentation.ts +6 -3
  100. package/src/build/types.ts +4 -0
  101. package/src/cli/index.ts +1 -0
  102. package/src/client/browser-events-runtime.ts +4 -0
  103. package/src/client/client-module.ts +57 -0
  104. package/src/client/define-route.ts +11 -1
  105. package/src/client/document.tsx +28 -18
  106. package/src/client/hmr.ts +2 -1
  107. package/src/client/internal/runtime-types.ts +2 -0
  108. package/src/client/link.tsx +8 -8
  109. package/src/client/mutation.ts +136 -0
  110. package/src/client/query-store.ts +418 -0
  111. package/src/client/query.tsx +67 -0
  112. package/src/client/route-api.tsx +75 -0
  113. package/src/client/router/boundary-tree.tsx +7 -2
  114. package/src/client/router/context.ts +57 -4
  115. package/src/client/router/index.ts +3 -0
  116. package/src/client/router/link-utils.ts +29 -1
  117. package/src/client/router/navigation.ts +3 -50
  118. package/src/client/router/optimistic.ts +233 -0
  119. package/src/client/router/provider.tsx +304 -44
  120. package/src/client/router/search/index.ts +37 -17
  121. package/src/client/router/search-store.ts +4 -0
  122. package/src/client/router/sync-catch-up.ts +7 -0
  123. package/src/client/router/types.ts +71 -9
  124. package/src/client/sync.ts +438 -65
  125. package/src/client.ts +20 -60
  126. package/src/config.ts +5 -0
  127. package/src/define-route.ts +113 -55
  128. package/src/env.d.ts +2 -2
  129. package/src/furin.ts +75 -13
  130. package/src/plugin/hmr-dependencies.ts +58 -0
  131. package/src/plugin/index.ts +38 -2
  132. package/src/plugin/routes.ts +3 -3
  133. package/src/plugin/transform-client-module.ts +123 -0
  134. package/src/plugin/transform-client.ts +293 -13
  135. package/src/plugin/transform-isomorphic.ts +11 -5
  136. package/src/routes.ts +8 -0
  137. package/src/rsc/shared.tsx +104 -18
  138. package/src/server/auto-invalidate/registry.ts +4 -0
  139. package/src/server/auto-invalidate/runtime.ts +17 -0
  140. package/src/server/auto-invalidate/types.ts +6 -0
  141. package/src/server/cache/isr.ts +6 -34
  142. package/src/server/cache/route-cache.ts +40 -4
  143. package/src/server/dev/graph.ts +16 -2
  144. package/src/server/dev-page-plugin.ts +93 -59
  145. package/src/server/internal.ts +3 -0
  146. package/src/server/render/document.tsx +10 -1
  147. package/src/server/render/element.tsx +7 -2
  148. package/src/server/render/isr.ts +61 -29
  149. package/src/server/render/loaders.ts +118 -47
  150. package/src/server/render/mixed-cache.ts +33 -4
  151. package/src/server/render/not-found.ts +4 -7
  152. package/src/server/render/ppr-document.ts +2 -1
  153. package/src/server/render/ppr-route.ts +30 -10
  154. package/src/server/render/react-stream.ts +17 -0
  155. package/src/server/render/route-frame-transport.ts +3 -0
  156. package/src/server/render/ssg.ts +51 -18
  157. package/src/server/render/ssr.ts +53 -8
  158. package/src/server/render/template.ts +23 -0
  159. package/src/server/router/defined-route.ts +3 -0
  160. package/src/server/router/hmr.ts +3 -2
  161. package/src/server/router/plugin.ts +27 -12
  162. package/src/server/sync/adapter.ts +41 -4
  163. package/src/server/sync/atomic.ts +303 -0
  164. package/src/server/sync/drizzle/index.ts +145 -0
  165. package/src/server/sync/execution-error.ts +1 -0
  166. package/src/server/sync/fingerprint.ts +2 -6
  167. package/src/server/sync/index.ts +6 -0
  168. package/src/server/sync/mutation-handler.ts +69 -0
  169. package/src/server/sync/plugin.ts +177 -60
  170. package/src/server/sync/postgres/execute.ts +20 -0
  171. package/src/server/sync/postgres/index.ts +52 -16
  172. package/src/server/sync/postgres/sql.ts +20 -0
  173. package/src/server/sync/prisma/index.ts +70 -0
  174. package/src/server/sync/queries.ts +75 -0
  175. package/src/server/sync/query-context.ts +85 -0
  176. package/src/server/sync/redis/index.ts +7 -3
  177. package/src/server/sync/redis/scripts.ts +1 -1
  178. package/src/server/sync/response.ts +21 -0
  179. package/src/server/sync/sqlite/index.ts +19 -8
  180. package/src/server/sync/stream.ts +14 -22
  181. package/src/server/sync/validation.ts +34 -0
  182. package/src/shared/defer.ts +48 -0
  183. package/src/shared/error.ts +2 -2
  184. package/src/shared/page-key.ts +36 -0
  185. package/src/shared/query-bindings.ts +138 -0
  186. package/src/shared/route-frame.ts +13 -1
  187. package/src/shared/route-map.ts +12 -2
  188. package/src/shared/sync-query.ts +138 -0
@@ -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
  "});",
@@ -106,7 +106,7 @@ export function generateHydrateEntry(
106
106
  ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]`
107
107
  : "";
108
108
  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} }; })`;
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, remountDeps: __furin_page_route.remountDeps }, component: hotComponent(${pageComponentKey}, __furin_page_route.component) }${boundaryResult} }; })`;
110
110
 
111
111
  const searchDefaultsEntry = searchDefaults
112
112
  ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
@@ -361,6 +361,12 @@ if (__deferred && __deferred._chunks) {
361
361
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
362
362
  } as any);
363
363
  } else {
364
+ // A removed active route has no match in the new development manifest.
365
+ // Reload its document so the server can render the current 404 response.
366
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
367
+ window.location.reload();
368
+ return;
369
+ }
364
370
  // No match and no 404 signal — either the client bundle is out of sync
365
371
  // with the server (stale deploy) or the server returned something we
366
372
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -447,13 +453,21 @@ if (__deferred && __deferred._chunks) {
447
453
  export function writeDevFiles(
448
454
  routes: ResolvedRoute[],
449
455
  { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }: BuildClientOptions,
450
- projectRoot: string
456
+ projectRoot: string,
457
+ serverSourceVersion?: string
451
458
  ): void {
452
459
  if (!existsSync(outDir)) {
453
460
  mkdirSync(outDir, { recursive: true });
454
461
  }
455
462
 
456
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
463
+ // Server-only helpers are absent from Bun's client graph. A live version
464
+ // makes their edits use the same transactional HMR path as client edits.
465
+ const serverVersion =
466
+ serverSourceVersion === undefined
467
+ ? ""
468
+ : `\nif (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};\n`;
469
+ const hydrateCode =
470
+ generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
457
471
  const hydratePath = join(outDir, "_hydrate.tsx");
458
472
  const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
459
473
  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
  />
package/src/client/hmr.ts CHANGED
@@ -57,7 +57,8 @@ export function updateHotComponent<Props>(
57
57
  boundary: (props) => slot.current(props),
58
58
  current: component as ClientComponent<never>,
59
59
  signature: readHookSignature(component),
60
- stable: (props) => jsx(slot.boundary as (props: unknown) => ReactNode, props) as ReactNode,
60
+ stable: (props: object) =>
61
+ jsx(slot.boundary as (props: unknown) => ReactNode, { ...props }) as ReactNode,
61
62
  };
62
63
  registry.set(key, slot);
63
64
  return slot.stable as ClientComponent<Props>;
@@ -1,6 +1,7 @@
1
1
  import type React from "react";
2
2
  import type { HeadOptions, RenderingMode } from "../../client.ts";
3
3
  import type { RequestLoaderContext } from "../../define-route.ts";
4
+ import type { RemountDeps } from "../../shared/page-key.ts";
4
5
 
5
6
  export type RuntimeData = Record<string, unknown>;
6
7
 
@@ -22,6 +23,7 @@ export interface RuntimeRoute {
22
23
  params?: unknown;
23
24
  parent?: RuntimeRoute;
24
25
  query?: unknown;
26
+ remountDeps?: RemountDeps<object, object>;
25
27
  requestLoader?: (ctx: RequestLoaderContext) => Awaitable<object>;
26
28
  revalidate?: number;
27
29
  sourcePath?: string;
@@ -4,14 +4,14 @@ import {
4
4
  findSearchDefaultsForRouteTarget,
5
5
  type SearchParamsInput,
6
6
  } from "../shared/search-params.ts";
7
- import { CLIENT_FALLBACK_ROUTER, RouterContext, useRouter } from "./router/context.ts";
7
+ import { CLIENT_FALLBACK_ROUTER, RouterContext, useRouterContext } from "./router/context.ts";
8
8
  import {
9
9
  applyLinkParams,
10
10
  buildHref,
11
11
  navigationHrefPolicy,
12
12
  normalizeHref,
13
13
  } from "./router/link-utils.ts";
14
- import type { LinkProps, RouterContextValue, RouteTo } from "./router/types.ts";
14
+ import type { LinkBaseProps, LinkProps, RouterContextValue, RouteTo } from "./router/types.ts";
15
15
 
16
16
  // biome-ignore lint/performance/noBarrelFile: re-exporting router symbols preserves backward compatibility for @teyik0/furin/link consumers
17
17
  export * from "./router/index.ts";
@@ -40,7 +40,7 @@ function computeLinkView<To extends RouteTo>(
40
40
  activeProps,
41
41
  inactiveProps,
42
42
  }: Pick<
43
- LinkProps<To>,
43
+ LinkBaseProps<To>,
44
44
  "to" | "params" | "search" | "hash" | "children" | "activeProps" | "inactiveProps"
45
45
  >,
46
46
  router: RouterContextValue
@@ -108,8 +108,8 @@ function LinkInteractive<To extends RouteTo>({
108
108
  // @ts-expect-error: defensive strip of accidental href prop passed via spread
109
109
  href: _href,
110
110
  ...anchorProps
111
- }: LinkProps<To>): React.ReactElement {
112
- const router = useRouter();
111
+ }: LinkBaseProps<To>): React.ReactElement {
112
+ const router = useRouterContext();
113
113
  const anchorRef = useRef<HTMLAnchorElement>(null);
114
114
  const intentTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
115
115
 
@@ -278,7 +278,7 @@ export const SSR_FALLBACK_ROUTER: RouterContextValue = {
278
278
  * returning the final `<a>` element.
279
279
  */
280
280
  function renderLinkElement<To extends RouteTo>(
281
- props: LinkProps<To>,
281
+ props: LinkBaseProps<To>,
282
282
  router: RouterContextValue
283
283
  ): React.ReactElement {
284
284
  const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
@@ -347,8 +347,8 @@ export function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactEleme
347
347
 
348
348
  // ── Client rendering ──────────────────────────────────────────────────────
349
349
  return createElement(
350
- LinkInteractive as React.ComponentType<LinkProps<RouteTo>>,
351
- props as LinkProps<RouteTo>
350
+ LinkInteractive as React.ComponentType<LinkBaseProps<RouteTo>>,
351
+ props as LinkBaseProps<RouteTo>
352
352
  );
353
353
  }
354
354
 
@@ -0,0 +1,136 @@
1
+ import { EdenFetchError } from "@elysia/eden";
2
+ import { useCallback, useRef, useState } from "react";
3
+
4
+ interface MutationResponse {
5
+ data: unknown;
6
+ error: unknown;
7
+ }
8
+
9
+ type MutationMethod = (...args: never[]) => Promise<MutationResponse>;
10
+ type MutationData<Method extends MutationMethod> = Awaited<ReturnType<Method>>["data"];
11
+ type ErrorValue<Value> = Value extends { detail: string }
12
+ ? Value
13
+ : Value extends readonly unknown[]
14
+ ? { detail: string }
15
+ : Value extends object
16
+ ? Omit<Value, "detail"> & { detail: string }
17
+ : { detail: string };
18
+ type ApiError<Failure> = Failure extends { status: infer Status extends number; value: infer Value }
19
+ ? Value extends { detail: string }
20
+ ? Failure
21
+ : EdenFetchError<Status, ErrorValue<Value>>
22
+ : never;
23
+ type MutationError<Method extends MutationMethod> =
24
+ | ApiError<NonNullable<Awaited<ReturnType<Method>>["error"]>>
25
+ | EdenFetchError<0, { detail: string }>;
26
+
27
+ function isApiError(value: unknown): value is { status: number; value: unknown } {
28
+ return (
29
+ typeof value === "object" &&
30
+ value !== null &&
31
+ "status" in value &&
32
+ typeof value.status === "number" &&
33
+ "value" in value
34
+ );
35
+ }
36
+
37
+ function normalizeMutationError<Method extends MutationMethod>(
38
+ cause: unknown
39
+ ): MutationError<Method> {
40
+ const exception =
41
+ isApiError(cause) && cause.status === 0 && cause.value instanceof Error ? cause.value : cause;
42
+ if (isApiError(exception)) {
43
+ const { value } = exception;
44
+ if (
45
+ typeof value === "object" &&
46
+ value !== null &&
47
+ "detail" in value &&
48
+ typeof value.detail === "string"
49
+ ) {
50
+ return exception as MutationError<Method>;
51
+ }
52
+ const error = new EdenFetchError(exception.status, {
53
+ ...(typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}),
54
+ detail: typeof value === "string" && value ? value : "Mutation failed",
55
+ });
56
+ error.cause = exception;
57
+ return error as MutationError<Method>;
58
+ }
59
+ const error = new EdenFetchError(0, {
60
+ detail: exception instanceof Error ? exception.message : "Mutation failed",
61
+ });
62
+ error.cause = exception;
63
+ return error;
64
+ }
65
+
66
+ interface MutationOptions<Method extends MutationMethod> {
67
+ onError?: (error: MutationError<Method>) => void | Promise<void>;
68
+ onSuccess?: (data: MutationData<Method>) => void | Promise<void>;
69
+ }
70
+
71
+ export function useMutation<Method extends MutationMethod>(
72
+ method: Method,
73
+ options?: MutationOptions<Method>
74
+ ) {
75
+ const [state, setState] = useState<{
76
+ data: MutationData<Method> | undefined;
77
+ error: MutationError<Method> | null;
78
+ isPending: boolean;
79
+ }>({ data: undefined, error: null, isPending: false });
80
+ const latest = useRef<number>(0);
81
+ const pending = useRef<number>(0);
82
+
83
+ const mutateAsync = useCallback(
84
+ async (...args: Parameters<Method>): Promise<MutationData<Method>> => {
85
+ latest.current += 1;
86
+ const invocation = latest.current;
87
+ pending.current += 1;
88
+ setState({ data: undefined, error: null, isPending: true });
89
+ try {
90
+ const result = (await Reflect.apply(method, undefined, args)) as Awaited<
91
+ ReturnType<Method>
92
+ >;
93
+ if (result.error !== null) {
94
+ if (
95
+ "response" in result &&
96
+ result.response === undefined &&
97
+ result.error instanceof EdenFetchError &&
98
+ result.error.status === 503 &&
99
+ (result.error.value instanceof Error || typeof result.error.value === "string")
100
+ ) {
101
+ throw result.error.value;
102
+ }
103
+ throw result.error;
104
+ }
105
+ await options?.onSuccess?.(result.data);
106
+ if (latest.current === invocation) {
107
+ setState((previous) => ({ ...previous, data: result.data, error: null }));
108
+ }
109
+ return result.data;
110
+ } catch (cause) {
111
+ const failure = normalizeMutationError<Method>(cause);
112
+ if (latest.current === invocation) {
113
+ setState((previous) => ({ ...previous, data: undefined, error: failure }));
114
+ }
115
+ await options?.onError?.(failure);
116
+ throw failure;
117
+ } finally {
118
+ pending.current -= 1;
119
+ setState((previous) => ({ ...previous, isPending: pending.current > 0 }));
120
+ }
121
+ },
122
+ [method, options]
123
+ );
124
+ const mutate = useCallback(
125
+ (...args: Parameters<Method>): void => {
126
+ mutateAsync(...args).catch(() => undefined);
127
+ },
128
+ [mutateAsync]
129
+ );
130
+ const reset = useCallback(() => {
131
+ latest.current += 1;
132
+ setState((previous) => ({ ...previous, data: undefined, error: null }));
133
+ }, []);
134
+
135
+ return { ...state, mutate, mutateAsync, reset };
136
+ }