@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
@@ -2,39 +2,39 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { currentInstance } from "../instance.ts";
3
3
  import type { SyncRuntimeOptions } from "./adapter.ts";
4
4
 
5
- const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
5
+ const SYNC_DEFAULT_PATH = "/_furin/sync";
6
6
 
7
7
  // Explicit override scope (tests, synthetic renders). When unset, the sync
8
- // stream path comes from the current furin instance.
9
- const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
8
+ // path comes from the current furin instance.
9
+ const requestSyncPath = new AsyncLocalStorage<string | undefined>();
10
10
 
11
11
  export interface FurinSyncOptions extends SyncRuntimeOptions {
12
- streamPath?: string;
12
+ path?: string;
13
13
  }
14
14
 
15
15
  export type FurinSyncOption = FurinSyncOptions | false;
16
16
 
17
- export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
17
+ export function resolveSyncPath(sync: FurinSyncOption | undefined): string | undefined {
18
18
  if (!sync) {
19
19
  return;
20
20
  }
21
- return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
+ return sync.path ?? SYNC_DEFAULT_PATH;
22
22
  }
23
23
 
24
24
  /**
25
- * Logical (unprefixed) sync stream path for the current request — injected
25
+ * Logical (unprefixed) sync path for the current request — injected
26
26
  * into rendered HTML; the client prepends its own basePath before connecting.
27
27
  */
28
- export function getSyncStreamPath(): string | undefined {
29
- const override = requestSyncStreamPath.getStore();
28
+ export function getSyncPath(): string | undefined {
29
+ const override = requestSyncPath.getStore();
30
30
  if (override !== undefined) {
31
31
  return override;
32
32
  }
33
- return currentInstance().syncStreamPath;
33
+ return currentInstance().syncPath;
34
34
  }
35
35
 
36
- export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
37
- return requestSyncStreamPath.run(path, fn);
36
+ export function runWithSyncPath<T>(path: string | undefined, fn: () => T): T {
37
+ return requestSyncPath.run(path, fn);
38
38
  }
39
39
 
40
40
  export function syncRuntimeOptions(sync: FurinSyncOptions): SyncRuntimeOptions {
@@ -1,20 +1,20 @@
1
1
  // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
2
 
3
3
  import {
4
- getSyncStreamPath as getSyncStreamPathImplementation,
5
- resolveSyncStreamPath as resolveSyncStreamPathImplementation,
6
- runWithSyncStreamPath as runWithSyncStreamPathImplementation,
4
+ getSyncPath as getSyncPathImplementation,
5
+ resolveSyncPath as resolveSyncPathImplementation,
6
+ runWithSyncPath as runWithSyncPathImplementation,
7
7
  } from "./config.ts";
8
8
  import { PollingSyncNotifier as PollingSyncNotifierImplementation } from "./notifier.ts";
9
9
  import { furinSync as furinSyncImplementation } from "./plugin.ts";
10
- import { createSyncStreamPlugin as createSyncStreamPluginImplementation } from "./stream.ts";
10
+ import { createSyncChangesPlugin as createSyncChangesPluginImplementation } from "./stream.ts";
11
11
 
12
- export const createSyncStreamPlugin = createSyncStreamPluginImplementation;
12
+ export const createSyncChangesPlugin = createSyncChangesPluginImplementation;
13
13
  export const furinSync = furinSyncImplementation;
14
- export const getSyncStreamPath = getSyncStreamPathImplementation;
14
+ export const getSyncPath = getSyncPathImplementation;
15
15
  export const PollingSyncNotifier = PollingSyncNotifierImplementation;
16
- export const resolveSyncStreamPath = resolveSyncStreamPathImplementation;
17
- export const runWithSyncStreamPath = runWithSyncStreamPathImplementation;
16
+ export const resolveSyncPath = resolveSyncPathImplementation;
17
+ export const runWithSyncPath = runWithSyncPathImplementation;
18
18
 
19
19
  export type PollingSyncNotifier = PollingSyncNotifierImplementation;
20
20
 
@@ -5,6 +5,7 @@ interface ListenerSubscription {
5
5
  }
6
6
 
7
7
  export class PollingSyncNotifier implements SyncNotifier {
8
+ readonly recovery = "self" as const;
8
9
  private readonly adapter: SyncAdapter;
9
10
  private readonly intervalMs: number;
10
11
  private readonly listeners = new Set<ListenerSubscription>();
@@ -240,7 +240,10 @@ export function furinSync(options: SyncRuntimeOptions) {
240
240
  if (completion.kind === "lost") {
241
241
  return leaseLostResponse();
242
242
  }
243
- if (completion.cursor !== undefined) {
243
+ const notificationAlreadyPublished =
244
+ runtime.adapter.notificationChannel !== undefined &&
245
+ runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
246
+ if (completion.cursor !== undefined && !notificationAlreadyPublished) {
244
247
  runtime.notifier.publish(completion.cursor).catch(() => undefined);
245
248
  }
246
249
  if (result.kind === "unreplayable") {
@@ -11,11 +11,15 @@ import type {
11
11
  SyncAdapter,
12
12
  SyncChange,
13
13
  SyncInvalidation,
14
+ SyncNotifier,
15
+ SyncSubscription,
14
16
  } from "../adapter.ts";
15
17
 
16
18
  const CHANGE_RETENTION = 1000;
17
19
  const LEASE_MS = 30_000;
18
20
  const MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
21
+ const RECOVERY_RETRY_INITIAL_MS = 250;
22
+ const RECOVERY_RETRY_MAX_MS = 32_000;
19
23
  const UNSIGNED_INTEGER_PATTERN = /^\d+$/;
20
24
 
21
25
  export interface PostgresSyncAdapterOptions {
@@ -43,6 +47,18 @@ interface ChangeRow {
43
47
  invalidations: SyncInvalidation[];
44
48
  }
45
49
 
50
+ function notificationChannel(namespace: string): string {
51
+ const digest = new Bun.CryptoHasher("sha256").update(namespace).digest("hex");
52
+ return `furin_sync_${digest.slice(0, 52)}`;
53
+ }
54
+
55
+ async function readCurrentCursor(sql: SQL, namespace: string): Promise<string> {
56
+ const rows = await sql<Pick<CursorRow, "current_cursor">[]>`
57
+ SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${namespace}
58
+ `;
59
+ return String(rows[0]?.current_cursor ?? 0);
60
+ }
61
+
46
62
  function mutationKey(input: Pick<MutationLease, "key" | "principal">): string {
47
63
  return new Bun.CryptoHasher("sha256")
48
64
  .update(`${input.principal.length}:${input.principal}${input.key}`)
@@ -61,6 +77,7 @@ function storedResponse(row: MutationRow): StoredResponse {
61
77
  }
62
78
 
63
79
  export class PostgresSyncAdapter implements SyncAdapter {
80
+ readonly notificationChannel: string;
64
81
  readonly scope = "distributed" as const;
65
82
  private readonly namespace: string;
66
83
  private readonly sql: SQL;
@@ -69,6 +86,7 @@ export class PostgresSyncAdapter implements SyncAdapter {
69
86
  if (options.namespace.length === 0) {
70
87
  throw new Error("[furin-sync-postgres] namespace must not be empty.");
71
88
  }
89
+ this.notificationChannel = notificationChannel(options.namespace);
72
90
  this.namespace = options.namespace;
73
91
  this.sql = options.sql;
74
92
  }
@@ -221,6 +239,9 @@ export class PostgresSyncAdapter implements SyncAdapter {
221
239
  AND mutation_key = ${key}
222
240
  AND mutation_id = ${input.lease.id}
223
241
  `;
242
+ if (cursor !== undefined) {
243
+ await tx.notify(this.notificationChannel, cursor);
244
+ }
224
245
  return { cursor, kind: "committed" } as const;
225
246
  });
226
247
  }
@@ -235,11 +256,8 @@ export class PostgresSyncAdapter implements SyncAdapter {
235
256
  `;
236
257
  }
237
258
 
238
- async currentCursor(): Promise<string> {
239
- const rows = await this.sql<Pick<CursorRow, "current_cursor">[]>`
240
- SELECT current_cursor FROM furin_sync.streams WHERE namespace = ${this.namespace}
241
- `;
242
- return String(rows[0]?.current_cursor ?? 0);
259
+ currentCursor(): Promise<string> {
260
+ return readCurrentCursor(this.sql, this.namespace);
243
261
  }
244
262
 
245
263
  async readChanges(input: ReadChangesInput): Promise<ChangePage> {
@@ -299,3 +317,91 @@ export class PostgresSyncAdapter implements SyncAdapter {
299
317
  export function postgresSyncAdapter(options: PostgresSyncAdapterOptions): PostgresSyncAdapter {
300
318
  return new PostgresSyncAdapter(options);
301
319
  }
320
+
321
+ export class PostgresSyncNotifier implements SyncNotifier {
322
+ readonly notificationChannel: string;
323
+ readonly recovery = "self" as const;
324
+ private readonly namespace: string;
325
+ private readonly sql: SQL;
326
+
327
+ constructor(options: PostgresSyncAdapterOptions) {
328
+ if (options.namespace.length === 0) {
329
+ throw new Error("[furin-sync-postgres] namespace must not be empty.");
330
+ }
331
+ this.notificationChannel = notificationChannel(options.namespace);
332
+ this.namespace = options.namespace;
333
+ this.sql = options.sql;
334
+ }
335
+
336
+ publish(cursor: string): Promise<void> {
337
+ return this.sql.notify(this.notificationChannel, cursor);
338
+ }
339
+
340
+ async subscribe(listener: (cursor: string) => void): Promise<SyncSubscription> {
341
+ let active = true;
342
+ let currentCursor: bigint | undefined;
343
+ let recovery: Promise<void> | undefined;
344
+ let retry: ReturnType<typeof setTimeout> | undefined;
345
+ let retryDelayMs = RECOVERY_RETRY_INITIAL_MS;
346
+ const emit = (cursor: string) => {
347
+ if (!(active && UNSIGNED_INTEGER_PATTERN.test(cursor))) {
348
+ return;
349
+ }
350
+ const nextCursor = BigInt(cursor);
351
+ if (currentCursor !== undefined && nextCursor <= currentCursor) {
352
+ return;
353
+ }
354
+ currentCursor = nextCursor;
355
+ try {
356
+ listener(cursor);
357
+ } catch {
358
+ // Notifications are best-effort wake-ups; durable recovery reads the change log.
359
+ }
360
+ };
361
+ const scheduleRecovery = () => {
362
+ if (!active || retry) {
363
+ return;
364
+ }
365
+ const delayMs = retryDelayMs;
366
+ retryDelayMs = Math.min(retryDelayMs * 2, RECOVERY_RETRY_MAX_MS);
367
+ retry = setTimeout(() => {
368
+ retry = undefined;
369
+ recover();
370
+ }, delayMs);
371
+ retry.unref?.();
372
+ };
373
+ const recover = () => {
374
+ if (!active || recovery) {
375
+ return;
376
+ }
377
+ if (retry) {
378
+ clearTimeout(retry);
379
+ retry = undefined;
380
+ }
381
+ recovery = readCurrentCursor(this.sql, this.namespace)
382
+ .then((cursor) => {
383
+ retryDelayMs = RECOVERY_RETRY_INITIAL_MS;
384
+ emit(cursor);
385
+ })
386
+ .catch(scheduleRecovery)
387
+ .finally(() => {
388
+ recovery = undefined;
389
+ });
390
+ };
391
+ const subscription = await this.sql.listen(this.notificationChannel, emit, recover);
392
+ return {
393
+ unsubscribe: () => {
394
+ active = false;
395
+ if (retry) {
396
+ clearTimeout(retry);
397
+ retry = undefined;
398
+ }
399
+ return subscription.unlisten();
400
+ },
401
+ };
402
+ }
403
+ }
404
+
405
+ export function postgresSyncNotifier(options: PostgresSyncAdapterOptions): PostgresSyncNotifier {
406
+ return new PostgresSyncNotifier(options);
407
+ }
@@ -15,8 +15,20 @@ export function resolveSyncRuntime(options: SyncRuntimeOptions): ResolvedSyncRun
15
15
  throw new Error("[furin] Production sync cannot use a process-local SyncAdapter.");
16
16
  }
17
17
  if (options.notifier) {
18
+ if (
19
+ options.adapter.notificationChannel !== undefined &&
20
+ options.notifier.notificationChannel !== undefined &&
21
+ options.adapter.notificationChannel !== options.notifier.notificationChannel
22
+ ) {
23
+ throw new Error("[furin] SyncAdapter and SyncNotifier notification channels do not match.");
24
+ }
18
25
  return { adapter: options.adapter, notifier: options.notifier };
19
26
  }
27
+ if (!IS_DEV && options.adapter.scope === "distributed") {
28
+ throw new Error(
29
+ "[furin] Distributed production sync requires an explicit SyncNotifier. Configure the adapter notifier or pass PollingSyncNotifier as a compatibility fallback."
30
+ );
31
+ }
20
32
  const existing = pollingNotifiers.get(options.adapter);
21
33
  if (existing) {
22
34
  return { adapter: options.adapter, notifier: existing };
@@ -9,98 +9,105 @@ export type { ChangePage as SyncChangePage, SyncChange } from "./adapter.ts";
9
9
 
10
10
  const DEFAULT_CHANGE_LIMIT = 100;
11
11
  const MAX_CHANGE_LIMIT = 500;
12
- const MAX_STREAM_CLIENTS = 100;
13
12
  const MAX_CURSOR_LENGTH = 128;
14
13
  const SAFETY_POLL_INTERVAL_MS = IS_DEV ? 250 : 15_000;
15
14
  const UNSIGNED_INTEGER_PATTERN = /^\d+$/;
16
- const defaultStreamPath = "/_furin/sync";
17
- const encoder = new TextEncoder();
15
+ const defaultSyncPath = "/_furin/sync";
18
16
  const noOpSubscription: SyncSubscription = {
19
17
  unsubscribe: () => Promise.resolve(),
20
18
  };
21
19
 
22
- interface StreamState {
23
- clients: Map<
24
- ReadableStreamDefaultController<Uint8Array>,
25
- ReturnType<typeof setInterval> | undefined
26
- >;
27
- cursor: string | undefined;
28
- safetyPoll: ReturnType<typeof setInterval>;
20
+ interface SyncCursorState {
21
+ cursor: string;
22
+ listeners: Set<(cursor: string) => void>;
23
+ safetyPoll: ReturnType<typeof setInterval> | undefined;
29
24
  subscription: SyncSubscription;
30
25
  }
31
26
 
32
- const streams = new Map<SyncAdapter, Promise<StreamState>>();
33
- const resolvedStates = new Set<StreamState>();
27
+ const cursorStates = new Map<SyncAdapter, Promise<SyncCursorState>>();
28
+ const resolvedStates = new Set<SyncCursorState>();
34
29
 
35
- function encodeSseCursor(cursor: string): Uint8Array {
36
- return encoder.encode(
37
- `id: ${cursor}\nevent: furin.sync\nretry: 3000\ndata: ${JSON.stringify({ cursor })}\n\n`
38
- );
39
- }
40
-
41
- function closeClient(
42
- state: StreamState,
43
- client: ReadableStreamDefaultController<Uint8Array>
44
- ): void {
45
- const heartbeat = state.clients.get(client);
46
- state.clients.delete(client);
47
- if (heartbeat) {
48
- clearInterval(heartbeat);
49
- }
50
- try {
51
- client.close();
52
- } catch {
53
- // already closed
54
- }
55
- }
56
-
57
- function notifyState(state: StreamState, cursor: string): void {
30
+ function notifyState(state: SyncCursorState, cursor: string): void {
58
31
  if (state.cursor === cursor) {
59
32
  return;
60
33
  }
61
34
  state.cursor = cursor;
62
- const chunk = encodeSseCursor(cursor);
63
- for (const client of state.clients.keys()) {
64
- if (client.desiredSize === null || client.desiredSize <= 0) {
65
- closeClient(state, client);
66
- continue;
67
- }
35
+ for (const listener of state.listeners) {
68
36
  try {
69
- client.enqueue(chunk);
37
+ listener(cursor);
70
38
  } catch {
71
- closeClient(state, client);
39
+ // One disconnected browser must not prevent delivery to other tabs.
72
40
  }
73
41
  }
74
42
  }
75
43
 
76
- async function createStreamState(runtime: ResolvedSyncRuntime): Promise<StreamState> {
77
- const state = {} as StreamState;
78
- state.clients = new Map();
44
+ async function createCursorState(runtime: ResolvedSyncRuntime): Promise<SyncCursorState> {
45
+ const state = {} as SyncCursorState;
79
46
  state.cursor = await runtime.adapter.currentCursor();
80
- state.safetyPoll = setInterval(() => {
81
- runtime.adapter
82
- .currentCursor()
83
- .then((cursor) => notifyState(state, cursor))
84
- .catch(() => undefined);
85
- }, SAFETY_POLL_INTERVAL_MS);
86
- state.safetyPoll.unref?.();
47
+ state.listeners = new Set();
48
+ state.safetyPoll = undefined;
49
+ let subscriptionFailed = false;
87
50
  state.subscription = await runtime.notifier
88
51
  .subscribe((cursor) => notifyState(state, cursor))
89
- .catch(() => noOpSubscription);
52
+ .catch(() => {
53
+ subscriptionFailed = true;
54
+ return noOpSubscription;
55
+ });
56
+ if (runtime.notifier.recovery !== "self" || subscriptionFailed) {
57
+ state.safetyPoll = setInterval(() => {
58
+ runtime.adapter
59
+ .currentCursor()
60
+ .then((cursor) => notifyState(state, cursor))
61
+ .catch(() => undefined);
62
+ }, SAFETY_POLL_INTERVAL_MS);
63
+ state.safetyPoll.unref?.();
64
+ }
90
65
  resolvedStates.add(state);
91
66
  return state;
92
67
  }
93
68
 
94
- function getStreamState(runtime: ResolvedSyncRuntime): Promise<StreamState> {
95
- const existing = streams.get(runtime.adapter);
69
+ export async function subscribeSyncCursor(
70
+ options: FurinSyncOptions,
71
+ listener: (cursor: string) => void
72
+ ): Promise<{ unsubscribe: () => void }> {
73
+ const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
74
+ const statePromise = getCursorState(runtime);
75
+ const state = await statePromise;
76
+ state.listeners.add(listener);
77
+ listener(state.cursor);
78
+ let subscribed = true;
79
+ return {
80
+ unsubscribe: () => {
81
+ if (!subscribed) {
82
+ return;
83
+ }
84
+ subscribed = false;
85
+ state.listeners.delete(listener);
86
+ if (state.listeners.size > 0) {
87
+ return;
88
+ }
89
+ if (cursorStates.get(runtime.adapter) === statePromise) {
90
+ cursorStates.delete(runtime.adapter);
91
+ }
92
+ resolvedStates.delete(state);
93
+ if (state.safetyPoll) {
94
+ clearInterval(state.safetyPoll);
95
+ }
96
+ state.subscription.unsubscribe().catch(() => undefined);
97
+ },
98
+ };
99
+ }
100
+
101
+ function getCursorState(runtime: ResolvedSyncRuntime): Promise<SyncCursorState> {
102
+ const existing = cursorStates.get(runtime.adapter);
96
103
  if (existing) {
97
104
  return existing;
98
105
  }
99
- const state = createStreamState(runtime);
100
- streams.set(runtime.adapter, state);
106
+ const state = createCursorState(runtime);
107
+ cursorStates.set(runtime.adapter, state);
101
108
  state.catch(() => {
102
- if (streams.get(runtime.adapter) === state) {
103
- streams.delete(runtime.adapter);
109
+ if (cursorStates.get(runtime.adapter) === state) {
110
+ cursorStates.delete(runtime.adapter);
104
111
  }
105
112
  });
106
113
  return state;
@@ -139,11 +146,12 @@ function clientInvalidations(change: SyncChange): string[] {
139
146
  return [...entries];
140
147
  }
141
148
 
142
- export function createSyncStreamPlugin(options: FurinSyncOptions) {
143
- const streamPath = options.streamPath ?? defaultStreamPath;
149
+ export function createSyncChangesPlugin(options: FurinSyncOptions) {
150
+ const syncPath = options.path ?? defaultSyncPath;
144
151
  const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
145
- return new Elysia({ name: `furin-sync-stream-${streamPath}` })
146
- .get(`${streamPath}/changes`, async ({ request, set }) => {
152
+ return new Elysia({ name: `furin-sync-changes-${syncPath}` }).get(
153
+ `${syncPath}/changes`,
154
+ async ({ request, set }) => {
147
155
  set.headers["cache-control"] = "no-store";
148
156
  const query = parseChangeQuery(request);
149
157
  if ("error" in query) {
@@ -157,62 +165,19 @@ export function createSyncStreamPlugin(options: FurinSyncOptions) {
157
165
  invalidations: clientInvalidations(change),
158
166
  })),
159
167
  };
160
- })
161
- .get(streamPath, async () => {
162
- const state = await getStreamState(runtime);
163
- if (state.clients.size >= MAX_STREAM_CLIENTS) {
164
- return Response.json({ code: "FURIN_SYNC_STREAM_CAPACITY" }, { status: 503 });
165
- }
166
- let controllerRef: ReadableStreamDefaultController<Uint8Array> | undefined;
167
- let heartbeat: ReturnType<typeof setInterval> | undefined;
168
- const stream = new ReadableStream<Uint8Array>({
169
- cancel() {
170
- if (controllerRef) {
171
- closeClient(state, controllerRef);
172
- }
173
- if (heartbeat) {
174
- clearInterval(heartbeat);
175
- }
176
- },
177
- start(controller) {
178
- controllerRef = controller;
179
- controller.enqueue(encoder.encode(": connected\nretry: 3000\n\n"));
180
- state.clients.set(controller, undefined);
181
- heartbeat = setInterval(() => {
182
- if (controller.desiredSize === null || controller.desiredSize <= 0) {
183
- closeClient(state, controller);
184
- return;
185
- }
186
- try {
187
- controller.enqueue(encoder.encode(": heartbeat\n\n"));
188
- } catch {
189
- closeClient(state, controller);
190
- }
191
- }, 15_000);
192
- heartbeat.unref?.();
193
- state.clients.set(controller, heartbeat);
194
- },
195
- });
196
-
197
- return new Response(stream, {
198
- headers: {
199
- "cache-control": "no-cache, no-transform",
200
- connection: "keep-alive",
201
- "content-type": "text/event-stream; charset=utf-8",
202
- },
203
- });
204
- });
168
+ }
169
+ );
205
170
  }
206
171
 
207
172
  /** @internal — closes process-local stream state between tests. */
208
173
  export function __resetSyncState(): void {
209
174
  for (const state of resolvedStates) {
210
175
  state.subscription.unsubscribe().catch(() => undefined);
211
- clearInterval(state.safetyPoll);
212
- for (const client of state.clients.keys()) {
213
- closeClient(state, client);
176
+ if (state.safetyPoll) {
177
+ clearInterval(state.safetyPoll);
214
178
  }
179
+ state.listeners.clear();
215
180
  }
216
- streams.clear();
181
+ cursorStates.clear();
217
182
  resolvedStates.clear();
218
183
  }
@@ -148,11 +148,11 @@ export interface AwaitProps<T> {
148
148
  * ```tsx
149
149
  * export const route = defineRoute()
150
150
  * .loader(() => defer({ board: "x", stats: fetchStats() }))
151
- * .page(({ data }) => (
151
+ * .page(({ board, stats }) => (
152
152
  * <div>
153
- * <h1>{data.board}</h1>
153
+ * <h1>{board}</h1>
154
154
  * <Suspense fallback={<Spinner />}>
155
- * <Await resolve={data.stats}>
155
+ * <Await resolve={stats}>
156
156
  * {(s) => <StatsBar stats={s} />}
157
157
  * </Await>
158
158
  * </Suspense>
@@ -0,0 +1,28 @@
1
+ import type { DevtoolsServerEvent } from "../devtools/protocol.ts";
2
+ import type { DevDiagnosticEvent } from "./dev-diagnostics.ts";
3
+
4
+ export const BROWSER_EVENT_PROTOCOL_VERSION = 1 as const;
5
+
6
+ export type BrowserEventEnvelope =
7
+ | {
8
+ channel: "diagnostic";
9
+ data: DevDiagnosticEvent;
10
+ version: typeof BROWSER_EVENT_PROTOCOL_VERSION;
11
+ }
12
+ | {
13
+ channel: "devtools";
14
+ data: DevtoolsServerEvent;
15
+ version: typeof BROWSER_EVENT_PROTOCOL_VERSION;
16
+ }
17
+ | {
18
+ channel: "sync";
19
+ data: { cursor: string };
20
+ version: typeof BROWSER_EVENT_PROTOCOL_VERSION;
21
+ };
22
+
23
+ export type BrowserEventChannel = BrowserEventEnvelope["channel"];
24
+
25
+ export type BrowserEventFor<TChannel extends BrowserEventChannel> = Extract<
26
+ BrowserEventEnvelope,
27
+ { channel: TChannel }
28
+ >;
@@ -0,0 +1,77 @@
1
+ type JsonScalar = boolean | null | number | string;
2
+ type JsonValue = JsonObject | JsonScalar | JsonValue[];
3
+
4
+ interface JsonObject {
5
+ [key: string]: JsonValue;
6
+ }
7
+
8
+ const COMPACT_JSON_TAG = "__furin_json_v1__";
9
+ type CompactJsonEnvelope = [typeof COMPACT_JSON_TAG, JsonObject];
10
+
11
+ function isJsonValue(value: unknown, seen: WeakSet<object>): value is JsonValue {
12
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
13
+ return true;
14
+ }
15
+ if (typeof value === "number") {
16
+ return Number.isFinite(value) && !Object.is(value, -0);
17
+ }
18
+ if (typeof value !== "object" || seen.has(value)) {
19
+ return false;
20
+ }
21
+ seen.add(value);
22
+
23
+ if (Array.isArray(value)) {
24
+ if (Reflect.ownKeys(value).length !== value.length + 1) {
25
+ return false;
26
+ }
27
+ for (let index = 0; index < value.length; index += 1) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
29
+ if (!(descriptor && "value" in descriptor && isJsonValue(descriptor.value, seen))) {
30
+ return false;
31
+ }
32
+ }
33
+ return true;
34
+ }
35
+
36
+ const prototype = Object.getPrototypeOf(value);
37
+ if (prototype !== Object.prototype && prototype !== null) {
38
+ return false;
39
+ }
40
+ const keys = Object.keys(value);
41
+ if (Reflect.ownKeys(value).length !== keys.length) {
42
+ return false;
43
+ }
44
+ return keys.every((key) => {
45
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
46
+ return descriptor !== undefined && "value" in descriptor && isJsonValue(descriptor.value, seen);
47
+ });
48
+ }
49
+
50
+ function isJsonObject(value: unknown): value is JsonObject {
51
+ return (
52
+ value !== null &&
53
+ typeof value === "object" &&
54
+ !Array.isArray(value) &&
55
+ isJsonValue(value, new WeakSet())
56
+ );
57
+ }
58
+
59
+ export function serializeCompactJsonLine(value: unknown): string | undefined {
60
+ if (!isJsonObject(value)) {
61
+ return;
62
+ }
63
+ const envelope: CompactJsonEnvelope = [COMPACT_JSON_TAG, value];
64
+ return `${JSON.stringify(envelope)}\n`;
65
+ }
66
+
67
+ export function parseCompactJsonLine(value: unknown): JsonObject | undefined {
68
+ if (
69
+ !Array.isArray(value) ||
70
+ value.length !== 2 ||
71
+ value[0] !== COMPACT_JSON_TAG ||
72
+ !isJsonObject(value[1])
73
+ ) {
74
+ return;
75
+ }
76
+ return value[1];
77
+ }