@teyik0/furin 0.4.0-alpha.1 → 0.4.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 (193) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +4 -3
  7. package/dist/build/compile-entry.ts +24 -69
  8. package/dist/build/entry-template.d.ts +4 -2
  9. package/dist/build/entry-template.ts +31 -8
  10. package/dist/build/index.d.ts +1 -1
  11. package/dist/build/index.js +8596 -6375
  12. package/dist/build/ssg-cache.d.ts +13 -0
  13. package/dist/build/types.d.ts +25 -2
  14. package/dist/build/virtual-entry.d.ts +8 -0
  15. package/dist/cache.d.ts +5 -0
  16. package/dist/cache.js +97 -0
  17. package/dist/cli/index.js +9099 -6771
  18. package/dist/cli/preview.d.ts +7 -0
  19. package/dist/client/boundaries.d.ts +1 -0
  20. package/dist/client/browser-events-runtime.d.ts +2 -0
  21. package/dist/client/browser-events.d.ts +2 -0
  22. package/dist/client/define-route.d.ts +9 -8
  23. package/dist/client/dev-error-overlay.d.ts +1 -0
  24. package/dist/client/dev-error-overlay.ts +201 -0
  25. package/dist/client/document.d.ts +1 -0
  26. package/dist/client/hmr.d.ts +4 -2
  27. package/dist/client/link.js +251 -82
  28. package/dist/client/router/provider.d.ts +1 -1
  29. package/dist/client/router/sync-catch-up.d.ts +1 -1
  30. package/dist/client/router/types.d.ts +8 -10
  31. package/dist/client.js +37 -23
  32. package/dist/config.d.ts +17 -0
  33. package/dist/config.js +9 -1
  34. package/dist/define-route.d.ts +11 -8
  35. package/dist/devtools/protocol.d.ts +2 -2
  36. package/dist/furin.d.ts +1 -1
  37. package/dist/furin.js +12991 -9491
  38. package/dist/plugin/index.js +476 -7
  39. package/dist/plugin/routes.d.ts +4 -3
  40. package/dist/rsc/build/index.d.ts +5 -1
  41. package/dist/server/browser-events/plugin.d.ts +11 -0
  42. package/dist/server/browser-events/types.d.ts +9 -0
  43. package/dist/server/cache/invalidation.d.ts +1 -2
  44. package/dist/server/cache/isr.d.ts +1 -0
  45. package/dist/server/cache/purger.d.ts +7 -0
  46. package/dist/server/cache/runtime-cache.d.ts +21 -0
  47. package/dist/server/dev/browser-events.d.ts +4 -0
  48. package/dist/server/dev/diagnostics.d.ts +39 -0
  49. package/dist/server/dev/error.d.ts +17 -0
  50. package/dist/server/dev/graph.d.ts +86 -0
  51. package/dist/server/dev/plugin.d.ts +9 -0
  52. package/dist/server/dev/request-security.d.ts +1 -0
  53. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  54. package/dist/server/dev/runtime.production.d.ts +5 -0
  55. package/dist/server/dev/symbolicate.d.ts +11 -0
  56. package/dist/server/dev/transform-failure.d.ts +4 -0
  57. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  58. package/dist/server/devtools/hub.d.ts +3 -2
  59. package/dist/server/devtools/instrumentation.d.ts +1 -1
  60. package/dist/server/devtools/instrumentation.production.d.ts +1 -1
  61. package/dist/server/devtools/plugin.d.ts +1 -1
  62. package/dist/server/external-prerender.d.ts +2 -0
  63. package/dist/server/instance.d.ts +2 -2
  64. package/dist/server/internal.d.ts +14 -2
  65. package/dist/server/internal.js +436 -1
  66. package/dist/server/render/element.d.ts +1 -0
  67. package/dist/server/render/index.d.ts +1 -1
  68. package/dist/server/render/index.ts +1 -1
  69. package/dist/server/render/ppr-document.d.ts +21 -0
  70. package/dist/server/render/ppr-request.d.ts +26 -0
  71. package/dist/server/render/ppr-route.d.ts +3 -1
  72. package/dist/server/render/shell.ts +0 -12
  73. package/dist/server/render/ssg.d.ts +2 -0
  74. package/dist/server/render/ssr.d.ts +17 -6
  75. package/dist/server/router/hmr.production.d.ts +2 -0
  76. package/dist/server/router/patterns.d.ts +1 -0
  77. package/dist/server/router/plugin.d.ts +3 -1
  78. package/dist/server/sync/adapter.d.ts +13 -0
  79. package/dist/server/sync/config.d.ts +5 -5
  80. package/dist/server/sync/index.d.ts +6 -6
  81. package/dist/server/sync/index.js +491 -516
  82. package/dist/server/sync/notifier.d.ts +1 -0
  83. package/dist/server/sync/postgres/index.d.ts +12 -1
  84. package/dist/server/sync/postgres/index.js +101 -6
  85. package/dist/server/sync/stream.d.ts +4 -13
  86. package/dist/shared/await.d.ts +3 -3
  87. package/dist/shared/browser-events.d.ts +22 -0
  88. package/dist/shared/compact-json.d.ts +8 -0
  89. package/dist/shared/deferred-ndjson.d.ts +6 -5
  90. package/dist/shared/dev-diagnostics.d.ts +36 -0
  91. package/dist/shared/prefix.d.ts +2 -0
  92. package/package.json +16 -7
  93. package/src/adapter/README.md +45 -0
  94. package/src/adapter/bun.ts +45 -268
  95. package/src/adapter/package.ts +15 -9
  96. package/src/adapter/runtime-build.ts +375 -0
  97. package/src/adapter/static.ts +79 -2
  98. package/src/adapter/vercel.ts +857 -0
  99. package/src/build/client.ts +38 -13
  100. package/src/build/compile-entry.ts +24 -69
  101. package/src/build/entry-template.ts +31 -8
  102. package/src/build/hydrate.ts +60 -20
  103. package/src/build/index.ts +19 -5
  104. package/src/build/production-instrumentation.ts +56 -4
  105. package/src/build/shared.ts +2 -1
  106. package/src/build/ssg-cache.ts +97 -11
  107. package/src/build/types.ts +31 -2
  108. package/src/build/virtual-entry.ts +27 -0
  109. package/src/cache.ts +14 -0
  110. package/src/cli/index.ts +55 -3
  111. package/src/cli/preview.ts +90 -0
  112. package/src/client/boundaries.tsx +10 -1
  113. package/src/client/browser-events-runtime.ts +204 -0
  114. package/src/client/browser-events.ts +22 -0
  115. package/src/client/define-route.ts +7 -17
  116. package/src/client/dev-error-overlay.ts +201 -0
  117. package/src/client/document.tsx +4 -7
  118. package/src/client/hmr.ts +26 -3
  119. package/src/client/router/boundary-tree.tsx +4 -4
  120. package/src/client/router/provider.tsx +165 -63
  121. package/src/client/router/sync-catch-up.ts +3 -4
  122. package/src/client/router/types.ts +6 -6
  123. package/src/config.ts +25 -0
  124. package/src/define-route.ts +20 -7
  125. package/src/devtools/devtools-element.js +56 -77
  126. package/src/devtools/protocol.ts +2 -2
  127. package/src/furin.ts +157 -77
  128. package/src/plugin/routes.ts +206 -36
  129. package/src/plugin/transform-client.ts +685 -3
  130. package/src/react-dom-edge.d.ts +6 -0
  131. package/src/rsc/build/index.ts +15 -3
  132. package/src/server/auto-invalidate/runtime.ts +5 -2
  133. package/src/server/browser-events/plugin.ts +168 -0
  134. package/src/server/browser-events/types.ts +11 -0
  135. package/src/server/cache/dev-loader.ts +30 -29
  136. package/src/server/cache/invalidation.ts +13 -22
  137. package/src/server/cache/isr.ts +9 -0
  138. package/src/server/cache/purger.ts +41 -0
  139. package/src/server/cache/runtime-cache.ts +137 -0
  140. package/src/server/dev/browser-events.ts +54 -0
  141. package/src/server/dev/diagnostics.ts +297 -0
  142. package/src/server/dev/error.ts +148 -0
  143. package/src/server/dev/graph.ts +438 -0
  144. package/src/server/dev/plugin.ts +130 -0
  145. package/src/server/dev/request-security.ts +38 -0
  146. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  147. package/src/server/dev/runtime.production.ts +24 -0
  148. package/src/server/dev/symbolicate.ts +135 -0
  149. package/src/server/dev/transform-failure.ts +8 -0
  150. package/src/server/dev-page-plugin.production.ts +3 -0
  151. package/src/server/dev-page-plugin.ts +92 -53
  152. package/src/server/devtools/hub.ts +6 -5
  153. package/src/server/devtools/instrumentation.production.ts +1 -1
  154. package/src/server/devtools/instrumentation.ts +12 -6
  155. package/src/server/devtools/plugin.ts +7 -150
  156. package/src/server/external-prerender.ts +10 -0
  157. package/src/server/instance.ts +3 -3
  158. package/src/server/internal.ts +39 -2
  159. package/src/server/render/assemble.ts +4 -4
  160. package/src/server/render/document.tsx +13 -4
  161. package/src/server/render/element.tsx +18 -14
  162. package/src/server/render/index.ts +1 -1
  163. package/src/server/render/isr.ts +44 -19
  164. package/src/server/render/loaders.ts +13 -3
  165. package/src/server/render/not-found.ts +28 -4
  166. package/src/server/render/ppr-document.ts +239 -0
  167. package/src/server/render/ppr-request.ts +104 -0
  168. package/src/server/render/ppr-route.ts +152 -31
  169. package/src/server/render/shell.ts +0 -12
  170. package/src/server/render/ssg.ts +38 -20
  171. package/src/server/render/ssr.ts +211 -83
  172. package/src/server/render/template.ts +47 -11
  173. package/src/server/router/defined-route.ts +7 -39
  174. package/src/server/router/hmr.production.ts +7 -0
  175. package/src/server/router/hmr.ts +106 -67
  176. package/src/server/router/patterns.ts +5 -1
  177. package/src/server/router/plugin.ts +124 -35
  178. package/src/server/router/source-version.ts +3 -10
  179. package/src/server/sync/adapter.ts +13 -0
  180. package/src/server/sync/config.ts +12 -12
  181. package/src/server/sync/index.ts +8 -8
  182. package/src/server/sync/notifier.ts +1 -0
  183. package/src/server/sync/plugin.ts +4 -1
  184. package/src/server/sync/postgres/index.ts +111 -5
  185. package/src/server/sync/runtime.ts +12 -0
  186. package/src/server/sync/stream.ts +78 -113
  187. package/src/shared/await.tsx +3 -3
  188. package/src/shared/browser-events.ts +28 -0
  189. package/src/shared/compact-json.ts +77 -0
  190. package/src/shared/deferred-ndjson.ts +20 -6
  191. package/src/shared/dev-diagnostics.ts +44 -0
  192. package/src/shared/prefix.ts +8 -0
  193. package/src/shared/route-map.ts +10 -1
@@ -1,17 +1,15 @@
1
1
  const ELEMENT_NAME = "furin-devtools";
2
- const PROTOCOL_VERSION = 1;
3
- const DEVTOOLS_EVENT = "furin.devtools";
2
+ const PROTOCOL_VERSION = 2;
4
3
  const MAX_BROWSER_EVENTS = 200;
5
4
  const RUNTIME_KEY = Symbol.for("furin.devtools.runtime");
5
+ const BROWSER_EVENTS_RUNTIME_KEY = Symbol.for("furin.browser-events.runtime");
6
6
  const runtime =
7
7
  window[RUNTIME_KEY] ??
8
8
  (window[RUNTIME_KEY] = {
9
9
  cleanup: null,
10
- eventSource: window.EventSource,
11
10
  fetch: window.fetch,
12
11
  });
13
12
  const nativeFetch = runtime.fetch;
14
- const NativeEventSource = runtime.eventSource;
15
13
  const browserState =
16
14
  runtime.browserState ??
17
15
  (runtime.browserState = {
@@ -107,7 +105,7 @@ function isSnapshot(snapshot) {
107
105
  typeof snapshot.instance.prefix === "string" &&
108
106
  isObject(snapshot.sync) &&
109
107
  typeof snapshot.sync.enabled === "boolean" &&
110
- (snapshot.sync.streamPath === null || typeof snapshot.sync.streamPath === "string") &&
108
+ (snapshot.sync.changesPath === null || typeof snapshot.sync.changesPath === "string") &&
111
109
  Array.isArray(snapshot.events) &&
112
110
  snapshot.events.every(isServerEvent) &&
113
111
  Array.isArray(snapshot.routes) &&
@@ -226,68 +224,43 @@ function installFetchObserver() {
226
224
  };
227
225
  }
228
226
 
229
- function installSyncObserver(sync) {
230
- if (!(sync.enabled && sync.streamPath && typeof NativeEventSource === "function")) {
227
+ function installSyncObserver(sync, browserEvents) {
228
+ if (!(sync.enabled && sync.changesPath)) {
231
229
  return () => undefined;
232
230
  }
233
- const syncUrl = new URL(assetUrl(sync.streamPath), window.location.href);
234
- class ObservedEventSource extends NativeEventSource {
235
- constructor(url, options) {
236
- super(url, options);
237
- const absolute = new URL(String(url), window.location.href);
238
- if (absolute.origin !== syncUrl.origin || absolute.pathname !== syncUrl.pathname) {
239
- return;
240
- }
241
- browserState.syncStatus = "connecting";
231
+ const path = assetUrl("/_furin/events");
232
+ const cleanups = [];
233
+ cleanups.push(
234
+ browserEvents.subscribeStatus((status) => {
235
+ browserState.syncStatus = status;
242
236
  pushBounded(browserState.syncEvents, {
243
237
  cursor: null,
244
238
  timestamp: Date.now(),
245
- type: "connecting",
246
- url: absolute.pathname,
247
- });
248
- this.addEventListener("open", () => {
249
- browserState.syncStatus = "connected";
250
- pushBounded(browserState.syncEvents, {
251
- cursor: null,
252
- timestamp: Date.now(),
253
- type: "connected",
254
- url: absolute.pathname,
255
- });
256
- notifyBrowserState();
239
+ type: status,
240
+ url: path,
257
241
  });
258
- this.addEventListener("error", () => {
259
- browserState.syncStatus = "reconnecting";
260
- pushBounded(browserState.syncEvents, {
261
- cursor: null,
262
- timestamp: Date.now(),
263
- type: "reconnecting",
264
- url: absolute.pathname,
265
- });
266
- notifyBrowserState();
267
- });
268
- this.addEventListener("furin.sync", (event) => {
269
- let cursor = null;
270
- try {
271
- const payload = JSON.parse(event.data);
272
- cursor = typeof payload.cursor === "string" ? payload.cursor : null;
273
- } catch {
274
- cursor = null;
275
- }
276
- pushBounded(browserState.syncEvents, {
277
- cursor,
278
- timestamp: Date.now(),
279
- type: "cursor",
280
- url: absolute.pathname,
281
- });
282
- notifyBrowserState();
242
+ notifyBrowserState();
243
+ })
244
+ );
245
+ cleanups.push(
246
+ browserEvents.subscribe("sync", (event) => {
247
+ const cursor =
248
+ isObject(event?.data) && typeof event.data.cursor === "string" ? event.data.cursor : null;
249
+ if (cursor === null) {
250
+ return;
251
+ }
252
+ pushBounded(browserState.syncEvents, {
253
+ cursor,
254
+ timestamp: Date.now(),
255
+ type: "cursor",
256
+ url: path,
283
257
  });
284
258
  notifyBrowserState();
285
- }
286
- }
287
- window.EventSource = ObservedEventSource;
259
+ })
260
+ );
288
261
  return () => {
289
- if (window.EventSource === ObservedEventSource) {
290
- window.EventSource = NativeEventSource;
262
+ for (const cleanup of cleanups) {
263
+ cleanup();
291
264
  }
292
265
  };
293
266
  }
@@ -717,15 +690,15 @@ class FurinDevtoolsElement extends HTMLElement {
717
690
  (event) =>
718
691
  `<tr><td>${statusDot(syncEventStatus(event.type))}${escapeHtml(event.type)}</td><td><code>${escapeHtml(event.cursor ?? "—")}</code></td><td>${escapeHtml(event.url)}</td><td><time>${formatTime(event.timestamp)}</time></td></tr>`
719
692
  );
720
- return `<div class="page-head"><div><h1>Sync stream</h1><p>The application’s native EventSource connection and cursors.</p></div><span class="connection">${statusDot(
693
+ return `<div class="page-head"><div><h1>Sync events</h1><p>The shared browser event connection and durable cursors.</p></div><span class="connection">${statusDot(
721
694
  enabled ? browserState.syncStatus : "disabled"
722
695
  )}${escapeHtml(enabled ? browserState.syncStatus : "disabled")}</span></div>
723
696
  <section class="block sync-summary"><dl><div><dt>Configured</dt><dd>${
724
697
  enabled ? "yes" : "no"
725
- }</dd></div><div><dt>Stream</dt><dd><code>${escapeHtml(
726
- this.#snapshot.sync.streamPath ?? "—"
698
+ }</dd></div><div><dt>Changes</dt><dd><code>${escapeHtml(
699
+ this.#snapshot.sync.changesPath ?? "—"
727
700
  )}</code></dd></div><div><dt>Events</dt><dd>${events.length}</dd></div></dl></section>
728
- ${table(["State", "Cursor", "Stream", "Time"], rows)}`;
701
+ ${table(["State", "Cursor", "Socket", "Time"], rows)}`;
729
702
  }
730
703
 
731
704
  renderBundle() {
@@ -848,9 +821,14 @@ async function start() {
848
821
  runtime.cleanup = null;
849
822
  };
850
823
  try {
851
- cleanups.push(installFetchObserver());
852
- cleanups.push(installSyncObserver(snapshot.sync));
853
- cleanups.push(installResourceObserver());
824
+ const browserEvents = window[BROWSER_EVENTS_RUNTIME_KEY];
825
+ if (
826
+ !browserEvents ||
827
+ typeof browserEvents.subscribe !== "function" ||
828
+ typeof browserEvents.subscribeStatus !== "function"
829
+ ) {
830
+ throw new Error("Furin browser event transport is unavailable");
831
+ }
854
832
  if (!customElements.get(ELEMENT_NAME)) {
855
833
  customElements.define(ELEMENT_NAME, FurinDevtoolsElement);
856
834
  }
@@ -860,21 +838,22 @@ async function start() {
860
838
  cleanups.push(() => element.remove());
861
839
  }
862
840
  element.setSnapshot(snapshot);
841
+ cleanups.push(installFetchObserver());
842
+ cleanups.push(installSyncObserver(snapshot.sync, browserEvents));
843
+ cleanups.push(installResourceObserver());
863
844
  cleanups.push(installKeyboardShortcut());
864
- const source = new NativeEventSource(
865
- `${assetUrl("/_furin/devtools/events")}?after=${snapshot.lastEventId}`
866
- );
867
- cleanups.push(() => source.close());
868
- source.addEventListener(DEVTOOLS_EVENT, (event) => {
869
- try {
870
- const payload = JSON.parse(event.data);
871
- if (isServerEvent(payload) && payload.instanceId === snapshot.instance.id) {
845
+ cleanups.push(
846
+ browserEvents.subscribe("devtools", (event) => {
847
+ const payload = event?.data;
848
+ if (
849
+ isServerEvent(payload) &&
850
+ payload.id > snapshot.lastEventId &&
851
+ payload.instanceId === snapshot.instance.id
852
+ ) {
872
853
  element.appendEvent(payload);
873
854
  }
874
- } catch {
875
- // A malformed development event must never affect the application.
876
- }
877
- });
855
+ })
856
+ );
878
857
  runtime.cleanup = cleanup;
879
858
  } catch (error) {
880
859
  cleanup();
@@ -1,4 +1,4 @@
1
- export const DEVTOOLS_PROTOCOL_VERSION = 1 as const;
1
+ export const DEVTOOLS_PROTOCOL_VERSION = 2 as const;
2
2
 
3
3
  export type DevtoolsRouteMode = "isr" | "ssg" | "ssr";
4
4
 
@@ -28,8 +28,8 @@ export interface DevtoolsInstance {
28
28
  }
29
29
 
30
30
  export interface DevtoolsSyncSnapshot {
31
+ changesPath: string | null;
31
32
  enabled: boolean;
32
- streamPath: string | null;
33
33
  }
34
34
 
35
35
  export type DevtoolsServerEvent =
package/src/furin.ts CHANGED
@@ -6,8 +6,10 @@ import { type AnyElysia, Elysia, file } from "elysia";
6
6
  import type { DrainContext, LoggerConfig } from "evlog";
7
7
  import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
8
  import { FURIN_RENDER_DECORATOR, type FurinRouteDispatcher } from "./define-route.ts";
9
+ import { createBrowserEventsPlugin } from "./server/browser-events/plugin.ts";
9
10
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
10
11
  import { setSSGCache } from "./server/cache/ssg.ts";
12
+ import type { DevelopmentRouteSnapshot, DevGraph } from "./server/dev/graph.ts";
11
13
  import {
12
14
  createInstrumentationPlugin,
13
15
  instrumentationLoggerExclusions,
@@ -47,14 +49,42 @@ import {
47
49
  } from "./server/router/schemas.ts";
48
50
  import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
49
51
  import { IS_DEV } from "./server/runtime-env.ts";
50
- import { type FurinSyncOption, resolveSyncStreamPath } from "./server/sync/config.ts";
51
- import { createSyncStreamPlugin } from "./server/sync/stream.ts";
52
+ import { type FurinSyncOption, resolveSyncPath } from "./server/sync/config.ts";
53
+ import { createSyncChangesPlugin } from "./server/sync/stream.ts";
52
54
 
53
55
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
54
56
  export interface FurinCacheTags {}
55
57
 
56
58
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
57
59
 
60
+ function createProductionBrowserEventsPlugin(sync: FurinSyncOption | undefined): AnyElysia {
61
+ return sync ? createBrowserEventsPlugin({ sync }) : new Elysia();
62
+ }
63
+
64
+ function repairedDevelopmentRoutes(
65
+ snapshot: DevelopmentRouteSnapshot,
66
+ changedSources: readonly string[],
67
+ graph: DevGraph<DevelopmentRouteSnapshot | null>
68
+ ): { patterns: ReadonlySet<string>; root: boolean } {
69
+ const patterns = new Set<string>();
70
+ for (const route of snapshot.routes) {
71
+ if (
72
+ changedSources.some(
73
+ (sourcePath) => route.path === sourcePath || graph.dependsOn(route.path, sourcePath)
74
+ )
75
+ ) {
76
+ patterns.add(route.pattern);
77
+ }
78
+ }
79
+ return {
80
+ patterns,
81
+ root: changedSources.some(
82
+ (sourcePath) =>
83
+ snapshot.root.path === sourcePath || graph.dependsOn(snapshot.root.path, sourcePath)
84
+ ),
85
+ };
86
+ }
87
+
58
88
  import { clientDirNameForPrefix } from "./shared/prefix.ts";
59
89
 
60
90
  // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
@@ -77,8 +107,6 @@ export { clientDirNameForPrefix } from "./shared/prefix.ts";
77
107
 
78
108
  const MAX_BROWSER_INGEST_BYTES = 64 * 1024;
79
109
  const MAX_BROWSER_INGEST_EVENTS = 100;
80
- const DEV_ROUTE_TOPOLOGY_POLL_INTERVAL_MS = 100;
81
-
82
110
  function resolveClientDirFromArgv(prefix: string): string {
83
111
  const dirName = clientDirNameForPrefix(prefix);
84
112
  return (
@@ -185,10 +213,11 @@ async function setupProdTemplate(
185
213
  instance: FurinInstance
186
214
  ): Promise<void> {
187
215
  if (embedded) {
188
- if (!embedded.template) {
216
+ const templatePath = join(embedded.clientDir, "index.html");
217
+ if (!existsSync(templatePath)) {
189
218
  throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
190
219
  }
191
- const html = await Bun.file(embedded.template).text();
220
+ const html = await Bun.file(templatePath).text();
192
221
  setProductionTemplateContent(html, instance);
193
222
  return;
194
223
  }
@@ -200,6 +229,19 @@ async function setupProdTemplate(
200
229
  setProductionTemplatePath(templatePath, instance);
201
230
  }
202
231
 
232
+ async function setupCompiledTemplate(
233
+ ctx: CompileContext,
234
+ embedded: EmbeddedAppData | undefined,
235
+ clientDir: string,
236
+ instance: FurinInstance
237
+ ): Promise<void> {
238
+ if (ctx.templateHtml === undefined) {
239
+ await setupProdTemplate(embedded, clientDir, instance);
240
+ return;
241
+ }
242
+ setProductionTemplateContent(ctx.templateHtml, instance);
243
+ }
244
+
203
245
  /**
204
246
  * Shape of one browser-submitted log event. The named keys are the dangerous
205
247
  * ones stripped before `log.set` (prototype-pollution vectors, plus the
@@ -267,7 +309,7 @@ async function readBrowserIngest(request: Request): Promise<BrowserIngestRead> {
267
309
  /** Evlog wide-event plugin + browser log ingest endpoint for one instance. */
268
310
  function createLoggerPlugin(
269
311
  prefix: string,
270
- syncStreamPath: string | undefined,
312
+ syncPath: string | undefined,
271
313
  logger: EvlogElysiaOptions | undefined,
272
314
  clientLogging: boolean
273
315
  ): Elysia {
@@ -282,7 +324,7 @@ function createLoggerPlugin(
282
324
  `${prefix}/favicon.ico`,
283
325
  `${prefix}/_bun_hmr_entry/**`,
284
326
  ...instrumentationLoggerExclusions(prefix),
285
- ...(syncStreamPath ? [`${prefix}${syncStreamPath}`] : []),
327
+ ...(syncPath ? [`${prefix}${syncPath}/**`] : []),
286
328
  // Note: /_furin/data is logged with the *logical* path rewritten by
287
329
  // createDataEndpoint via useLogger().set({ path }), so SPA navigations
288
330
  // appear as "GET /board/123 200" — same shape as a normal SSR nav.
@@ -454,12 +496,6 @@ function createNativeRouteRenderer(
454
496
  };
455
497
  }
456
498
 
457
- interface DevelopmentRouteSnapshot {
458
- render: FurinRouteDispatcher;
459
- root: RootLayout;
460
- routes: ResolvedRoute[];
461
- }
462
-
463
499
  function createDevelopmentRouteSnapshot(
464
500
  prefix: string,
465
501
  root: RootLayout,
@@ -522,7 +558,7 @@ export interface FurinOptions {
522
558
  prefix?: string;
523
559
  /**
524
560
  * Configures Furin's sync event stream with the required adapter. The
525
- * optional `streamPath` defaults to `/_furin/sync`. Omit this option or pass
561
+ * optional `path` defaults to `/_furin/sync`. Omit this option or pass
526
562
  * `false` to disable sync.
527
563
  */
528
564
  sync?: FurinSyncOption;
@@ -553,7 +589,7 @@ export async function furin({
553
589
  sync,
554
590
  }: FurinOptions = {}) {
555
591
  const prefix = normalizePrefix(rawPrefix);
556
- const syncStreamPath = resolveSyncStreamPath(sync);
592
+ const syncPath = resolveSyncPath(sync);
557
593
  const elysiaLoggerOptions = initializeLogger(logger);
558
594
 
559
595
  const cwd = process.cwd();
@@ -564,7 +600,7 @@ export async function furin({
564
600
  const ctx = getCompileContext(paramPagesDir, prefix);
565
601
  const loggerPlugin = createLoggerPlugin(
566
602
  prefix,
567
- syncStreamPath,
603
+ syncPath,
568
604
  elysiaLoggerOptions,
569
605
  clientLogging === true || ctx?.clientLogging === true
570
606
  );
@@ -581,7 +617,7 @@ export async function furin({
581
617
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
582
618
  assertPrefixAvailable(prefix, normalizedPagesDir);
583
619
  const instance = createInstance(prefix, normalizedPagesDir);
584
- instance.syncStreamPath = syncStreamPath;
620
+ instance.syncPath = syncPath;
585
621
 
586
622
  // ── Dev: Bun native HMR ────────────────────────────────────────────────
587
623
  if (IS_DEV) {
@@ -590,6 +626,12 @@ export async function furin({
590
626
  const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
591
627
  const furinDir = resolve(cwd, ".furin", instanceSlug);
592
628
  // Lazy import — build pipeline has native deps not available in compiled binaries
629
+ const { devDiagnosticStore, publishDevDiagnostic } = await import(
630
+ "./server/dev/diagnostics.ts"
631
+ );
632
+ const { devGraph } = await import("./server/dev/graph.ts");
633
+ const { createDevDiagnosticPlugin } = await import("./server/dev/plugin.ts");
634
+ const { createDevelopmentBrowserEventSources } = await import("./server/dev/browser-events.ts");
593
635
  const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
594
636
  registerDevPagePlugin();
595
637
  const {
@@ -632,12 +674,17 @@ export async function furin({
632
674
  };
633
675
  applyRouteConfigAutofix();
634
676
 
635
- const { furinShell: nativeRoutesApp } = (await import(routeModuleSpecifier(routeInstance))) as {
636
- furinShell: AnyElysia;
637
- };
638
- const { root, routes } = await loadDevelopmentRoutes(resolvedPagesDir);
639
- let currentSnapshot = createDevelopmentRouteSnapshot(prefix, root, routes);
640
- nativeRouteRenderers.set(instance, (context) => currentSnapshot.render(context));
677
+ const graph = devGraph(instance);
678
+ const { nativeRoutesApp, root, routes } = await withInstance(instance, async () => {
679
+ const { furinShell } = (await import(routeModuleSpecifier(routeInstance))) as {
680
+ furinShell: AnyElysia;
681
+ };
682
+ const loaded = await loadDevelopmentRoutes(resolvedPagesDir);
683
+ return { nativeRoutesApp: furinShell, ...loaded };
684
+ });
685
+ const initialSnapshot = createDevelopmentRouteSnapshot(prefix, root, routes);
686
+ const currentSnapshot = (): DevelopmentRouteSnapshot => graph.snapshot ?? initialSnapshot;
687
+ nativeRouteRenderers.set(instance, (context) => currentSnapshot().render(context));
641
688
 
642
689
  const { writeDevFiles } = await import("./build/hydrate.ts");
643
690
  const writeCurrentDevFiles = (snapshot: DevelopmentRouteSnapshot): void => {
@@ -656,14 +703,36 @@ export async function furin({
656
703
  cwd
657
704
  );
658
705
  };
659
- writeCurrentDevFiles(currentSnapshot);
660
- const refreshDevelopmentRoutes = async (): Promise<void> => {
661
- invalidateStampedRouteModules();
662
- const next = await loadDevelopmentRoutes(resolvedPagesDir);
663
- const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
664
- writeCurrentDevFiles(nextSnapshot);
665
- currentSnapshot = nextSnapshot;
666
- };
706
+ writeCurrentDevFiles(initialSnapshot);
707
+ graph.commit(initialSnapshot);
708
+ const refreshDevelopmentRoutes = (changedSources: readonly string[]): Promise<void> =>
709
+ withInstance(instance, async () => {
710
+ invalidateStampedRouteModules();
711
+ try {
712
+ const previousSnapshot = currentSnapshot();
713
+ const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
714
+ const next = await loadDevelopmentRoutes(resolvedPagesDir);
715
+ const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
716
+ writeCurrentDevFiles(nextSnapshot);
717
+ graph.commit(nextSnapshot);
718
+ const diagnostics = devDiagnosticStore(instance);
719
+ if (repaired.root) {
720
+ diagnostics.markReady("*");
721
+ }
722
+ for (const pattern of repaired.patterns) {
723
+ if (diagnostics.markReady(pattern)) {
724
+ break;
725
+ }
726
+ }
727
+ } catch (error) {
728
+ publishDevDiagnostic(error, {
729
+ entryPath: join(resolvedPagesDir, "root.tsx"),
730
+ phase: "import",
731
+ route: "*",
732
+ });
733
+ throw error;
734
+ }
735
+ });
667
736
  const devHtmlBundle = (await import(join(furinDir, "index.html"))).default;
668
737
  const publicDir = resolve(cwd, "public");
669
738
  const publicExists = existsSync(publicDir);
@@ -681,20 +750,31 @@ export async function furin({
681
750
  .onStart(() => {
682
751
  routeTopologyWatcher = registerDevRouteTopologyWatcher({
683
752
  instance: routeInstance,
684
- onRouteFilesTouched: async () => {
753
+ onRouteFilesTouched: async (sourcePaths) => {
685
754
  applyRouteConfigAutofix();
686
- await refreshDevelopmentRoutes();
755
+ await refreshDevelopmentRoutes(sourcePaths);
687
756
  },
688
- onTopologyChange: async () => {
757
+ onSourceError: (error, sourcePath) => {
758
+ const route = currentSnapshot().routes.find((candidate) =>
759
+ graph.dependsOn(candidate.path, sourcePath)
760
+ );
761
+ withInstance(instance, () =>
762
+ publishDevDiagnostic(error, {
763
+ entryPath: route?.path ?? sourcePath,
764
+ phase: "transform",
765
+ route: route?.pattern ?? "*",
766
+ })
767
+ );
768
+ },
769
+ onTopologyChange: async (sourcePaths) => {
689
770
  // Bun --hot cannot be triggered from generated artifacts (its
690
771
  // watch graph is the entry's static imports), so topology changes
691
772
  // are served by swapping the dispatcher's route matcher. Hot-added
692
773
  // routes then resolve through the NOT_FOUND fallback below;
693
774
  // removed routes 404 through the renderer's miss path.
694
775
  applyRouteConfigAutofix();
695
- await refreshDevelopmentRoutes();
776
+ await refreshDevelopmentRoutes(sourcePaths);
696
777
  },
697
- pollIntervalMs: DEV_ROUTE_TOPOLOGY_POLL_INTERVAL_MS,
698
778
  });
699
779
  })
700
780
  .onStop(() => {
@@ -709,7 +789,7 @@ export async function furin({
709
789
  // instances mounted on the same parent app.
710
790
  .onError(async ({ code, request, server }) => {
711
791
  if (code === "NOT_FOUND") {
712
- return await renderRootNotFound(currentSnapshot.root, request, server?.url.origin);
792
+ return await renderRootNotFound(currentSnapshot().root, request, server?.url.origin);
713
793
  }
714
794
  })
715
795
  .onAfterHandle(({ set }) => {
@@ -728,9 +808,27 @@ export async function furin({
728
808
  ? file(join(publicDir, "favicon.ico"))
729
809
  : () => new Response(null, { status: 404 })
730
810
  )
731
- .use(createInstrumentationPlugin(() => currentSnapshot.routes, syncStreamPath))
732
- .use(sync ? createSyncStreamPlugin(sync) : new Elysia())
733
- .use(createDataEndpoint(() => currentSnapshot.routes))
811
+ .use(
812
+ createBrowserEventsPlugin({
813
+ sources: createDevelopmentBrowserEventSources(instance, devDiagnosticStore(instance)),
814
+ sync: sync || undefined,
815
+ })
816
+ )
817
+ .use(
818
+ createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
819
+ await routeTopologyWatcher?.refresh();
820
+ })
821
+ )
822
+ .use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
823
+ .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
824
+ .use(
825
+ createDataEndpoint(async (request) => {
826
+ if (request.headers.get("x-furin-hmr-refresh") === "1") {
827
+ await routeTopologyWatcher?.refresh();
828
+ }
829
+ return currentSnapshot().routes;
830
+ })
831
+ )
734
832
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
735
833
  .use(nativeRoutesApp)
736
834
  .use(
@@ -785,10 +883,9 @@ export async function furin({
785
883
  });
786
884
 
787
885
  const embedded = ctx?.embedded;
788
- const clientDir = embedded ? "" : (explicitClientDir ?? resolveClientDirFromArgv(prefix));
789
- await setupProdTemplate(embedded, clientDir, instance);
886
+ const clientDir = embedded?.clientDir ?? explicitClientDir ?? resolveClientDirFromArgv(prefix);
887
+ await setupCompiledTemplate(ctx, embedded, clientDir, instance);
790
888
 
791
- const clientAssetPrefix = `${prefix}/_client/`;
792
889
  const prodApp = new Elysia({
793
890
  name: instanceName,
794
891
  prefix: prefix || undefined,
@@ -802,12 +899,7 @@ export async function furin({
802
899
  return await renderRootNotFound(root, request, server?.url.origin);
803
900
  }
804
901
  })
805
- .onAfterHandle(({ path, set }) => {
806
- // Content-hashed client assets are permanently cacheable — browsers never need to
807
- // revalidate them because any change produces a new filename.
808
- if (path.startsWith(clientAssetPrefix)) {
809
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
810
- }
902
+ .onAfterHandle(({ set }) => {
811
903
  // Forward pending revalidation paths so the client can bust its prefetch cache
812
904
  const pending = consumePendingInvalidations();
813
905
  if (pending.length > 0) {
@@ -829,43 +921,31 @@ export async function furin({
829
921
  })
830
922
  .use(
831
923
  await (async () => {
832
- if (embedded) {
833
- return new Elysia()
834
- .get("/favicon.ico", ({ status }) => {
835
- const asset = embedded.assets["/public/favicon.ico"];
836
- if (!asset) {
837
- return status("Not Found");
838
- }
839
- return Bun.file(asset);
840
- })
841
- .get("/_client/*", ({ params, status }) => {
842
- const asset = embedded.assets[`/_client/${params["*"]}`];
843
- if (!asset) {
844
- return status("Not Found");
845
- }
846
- return Bun.file(asset);
847
- })
848
- .get("/public/*", ({ params, status }) => {
849
- const asset = embedded.assets[`/public/${params["*"]}`];
850
- if (!asset) {
851
- return status("Not Found");
852
- }
853
- return Bun.file(asset);
854
- });
924
+ if (ctx.serveAssets === false) {
925
+ return new Elysia();
855
926
  }
856
- const publicDir = join(dirname(clientDir), "public");
927
+ const publicDir = embedded?.publicDir ?? join(dirname(clientDir), "public");
857
928
  const app = new Elysia();
858
929
  if (existsSync(publicDir)) {
859
930
  app
860
931
  .get("/favicon.ico", file(join(publicDir, "favicon.ico")))
861
932
  .use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
862
933
  }
863
- app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
934
+ app.use(
935
+ await staticPlugin({
936
+ assets: clientDir,
937
+ headers: {
938
+ "Cache-Control": "public, max-age=31536000, immutable",
939
+ },
940
+ prefix: "/_client",
941
+ })
942
+ );
864
943
  return app;
865
944
  })()
866
945
  )
867
- .use(sync ? createSyncStreamPlugin(sync) : new Elysia())
868
- .use(createDataEndpoint(routes))
946
+ .use(createProductionBrowserEventsPlugin(sync))
947
+ .use(sync ? createSyncChangesPlugin(sync) : new Elysia())
948
+ .use(createDataEndpoint(routes, root))
869
949
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
870
950
  .use(ctx.nativeRoutes)
871
951
  .use(createNotFoundHandling(prefix, routes, root));