@spooky-sync/core 0.0.1-canary.23 → 0.0.1-canary.231

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 (165) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2650 -58
  3. package/dist/index.js +12800 -2419
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +141 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +138 -25
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +235 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1861 -152
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +165 -86
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  65. package/src/modules/sync/queue/queue-down.ts +108 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  77. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  78. package/src/modules/sync/sync.subquery.test.ts +82 -0
  79. package/src/modules/sync/sync.tabs.test.ts +249 -0
  80. package/src/modules/sync/sync.ts +1868 -98
  81. package/src/modules/sync/utils.test.ts +269 -2
  82. package/src/modules/sync/utils.ts +201 -16
  83. package/src/otel/index.ts +13 -10
  84. package/src/services/blobs/blob-cache.test.ts +359 -0
  85. package/src/services/blobs/blob-cache.ts +603 -0
  86. package/src/services/blobs/blob-manifest.ts +227 -0
  87. package/src/services/blobs/blob-store.test.ts +77 -0
  88. package/src/services/blobs/blob-store.ts +359 -0
  89. package/src/services/blobs/blob.fixture.ts +90 -0
  90. package/src/services/blobs/index.ts +70 -0
  91. package/src/services/database/cache-engine.ts +193 -0
  92. package/src/services/database/connection-supervisor.test.ts +289 -0
  93. package/src/services/database/connection-supervisor.ts +415 -0
  94. package/src/services/database/database.query-timeout.test.ts +83 -0
  95. package/src/services/database/database.ts +41 -12
  96. package/src/services/database/engine-factory.ts +33 -0
  97. package/src/services/database/errors.ts +34 -0
  98. package/src/services/database/events/index.ts +2 -1
  99. package/src/services/database/index.ts +7 -0
  100. package/src/services/database/local-migrator.ts +30 -27
  101. package/src/services/database/local.test.ts +64 -0
  102. package/src/services/database/local.ts +484 -67
  103. package/src/services/database/plan-render.test.ts +159 -0
  104. package/src/services/database/plan-render.ts +108 -0
  105. package/src/services/database/relation-resolver.test.ts +413 -0
  106. package/src/services/database/relation-resolver.ts +0 -0
  107. package/src/services/database/remote.ts +192 -15
  108. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  109. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  110. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  111. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  112. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  113. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  114. package/src/services/database/sqlite-lock-verify.ts +45 -0
  115. package/src/services/database/sqlite-open.test.ts +150 -0
  116. package/src/services/database/sqlite-open.ts +164 -0
  117. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  118. package/src/services/database/sqlite-plan-sql.ts +138 -0
  119. package/src/services/database/sqlite-projection.test.ts +99 -0
  120. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  121. package/src/services/database/sqlite-select.test.ts +246 -0
  122. package/src/services/database/sqlite-select.ts +131 -0
  123. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  124. package/src/services/database/sqlite-transport.ts +224 -0
  125. package/src/services/database/sqlite-worker.ts +437 -0
  126. package/src/services/database/surql-translate.ts +416 -0
  127. package/src/services/database/surreal-cache-engine.ts +161 -0
  128. package/src/services/logger/index.ts +3 -2
  129. package/src/services/persistence/localstorage.ts +2 -2
  130. package/src/services/persistence/resilient.ts +11 -4
  131. package/src/services/persistence/surrealdb.ts +10 -10
  132. package/src/services/stream-processor/index.ts +796 -84
  133. package/src/services/stream-processor/permissions.test.ts +47 -0
  134. package/src/services/stream-processor/permissions.ts +53 -0
  135. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  136. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  137. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  138. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  139. package/src/services/stream-processor/wasm-types.ts +59 -3
  140. package/src/services/tabs/broker-client.ts +283 -0
  141. package/src/services/tabs/broker.test.ts +327 -0
  142. package/src/services/tabs/coordinator.test.ts +365 -0
  143. package/src/services/tabs/coordinator.ts +633 -0
  144. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  145. package/src/services/tabs/leader-locks.ts +75 -0
  146. package/src/services/tabs/protocol.ts +258 -0
  147. package/src/services/tabs/support.ts +36 -0
  148. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  149. package/src/sp00ky.auth-order.test.ts +112 -0
  150. package/src/sp00ky.init-query.test.ts +183 -0
  151. package/src/sp00ky.local-first.test.ts +60 -0
  152. package/src/sp00ky.ts +1772 -0
  153. package/src/types.ts +528 -13
  154. package/src/utils/blurhash.ts +90 -0
  155. package/src/utils/error-classification.test.ts +44 -0
  156. package/src/utils/error-classification.ts +7 -0
  157. package/src/utils/index.ts +79 -13
  158. package/src/utils/parser.test.ts +49 -120
  159. package/src/utils/parser.ts +32 -2
  160. package/src/utils/semver.test.ts +32 -0
  161. package/src/utils/semver.ts +30 -0
  162. package/src/utils/surql.ts +30 -18
  163. package/src/utils/withRetry.test.ts +1 -1
  164. package/tsdown.config.ts +86 -1
  165. package/src/spooky.ts +0 -395
package/dist/index.d.ts CHANGED
@@ -1,81 +1,290 @@
1
- import { C as Logger$1, S as UpdateOptions, T as EventSystem, _ as RunOptions, a as MutationEvent, b as SpookyQueryResultPromise, c as PinoTransmit, d as QueryHash, f as QueryState, g as RecordVersionDiff, h as RecordVersionArray, i as MutationCallback, l as QueryConfig, m as QueryUpdateCallback, n as EventSubscriptionOptions, o as MutationEventType, p as QueryTimeToLive, r as Level, s as PersistenceClient, t as DebounceOptions, u as QueryConfigRecord, v as SpookyConfig, w as EventDefinition, x as StoreType, y as SpookyQueryResult } from "./types.js";
1
+ import { A as Sp00kyQueryResultPromise, B as LocalStore, C as ReconnectConfig, D as RunOptions, E as RegistrationTimings, F as SyncHealthConfig, G as SyncEventSystem, H as DatabaseEventSystem, I as SyncHealthStatus, K as EventDefinition, L as TimingPhase, M as StorageHealthStatus, N as StoreType, O as Sp00kyConfig, P as SyncHealth, R as UpdateOptions, S as QueryUpdateCallback, T as RecordVersionDiff, U as DatabaseEventTypes, V as SealedQuery, W as Logger$1, _ as QueryState, a as MATERIALIZATION_SAMPLE_WINDOW, b as QueryTimeToLive, c as MutationEventType, d as PinoTransmit, f as PreloadOptions, g as QueryHash, h as QueryConfigRecord, i as Level, j as StorageHealth, k as Sp00kyQueryResult, l as PersistenceClient, m as QueryConfig, n as DebounceOptions, o as MutationCallback, p as PreloadRefresh, q as EventSystem, r as EventSubscriptionOptions, s as MutationEvent, t as ConnectionState, u as PhaseStat, v as QueryStatus, w as RecordVersionArray, x as QueryTimings, y as QueryStatusCallback, z as UpEvent } from "./types.js";
2
2
  import * as surrealdb0 from "surrealdb";
3
- import { Duration, RecordId, Surreal, SurrealTransaction } from "surrealdb";
4
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
3
+ import { Duration, RecordId, Surreal as Surreal$1, SurrealEvents, SurrealTransaction } from "surrealdb";
4
+ import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
5
5
  import { Logger } from "pino";
6
+ import { decode, encode, isBlurhashValid } from "blurhash";
7
+ import { LoroDoc } from "loro-crdt";
6
8
 
7
- //#region src/services/database/events/index.d.ts
8
- declare const DatabaseEventTypes: {
9
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
10
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
11
- };
12
- interface DatabaseQueryEventPayload {
13
- query: string;
14
- vars?: Record<string, unknown>;
15
- duration: number;
16
- success: boolean;
17
- error?: string;
18
- timestamp: number;
19
- }
20
- type DatabaseEventTypeMap = {
21
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
22
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
23
- };
24
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
25
- //#endregion
26
- //#region src/utils/surql.d.ts
27
- interface SealedQuery<T = void> {
28
- readonly sql: string;
29
- readonly extract: (results: unknown[]) => T;
30
- }
31
- //#endregion
32
9
  //#region src/services/database/database.d.ts
33
10
  declare abstract class AbstractDatabaseService {
34
- protected client: Surreal;
11
+ protected client: Surreal$1;
35
12
  protected logger: Logger$1;
36
13
  protected events: DatabaseEventSystem;
14
+ /**
15
+ * Per-query deadline in ms; `0` disables. The remote service sets it from
16
+ * `queryTimeoutMs` (see `RemoteDatabaseService`), the local one from
17
+ * `localOpTimeoutMs` (see `LocalDatabaseService`): a local query can be
18
+ * legitimately slow, but it must never be endless - every query waits on the
19
+ * previous link of {@link query}'s chain, and one that never settled wedged
20
+ * every later local op behind it.
21
+ */
22
+ protected queryTimeoutMs: number;
23
+ /** The error a deadline expiry rejects with; the local service substitutes
24
+ * its typed `LocalOpTimeoutError`. "timed out" in the message is
25
+ * load-bearing either way: `classifySyncError` keys off it. */
26
+ protected timeoutError(_query: string): Error;
37
27
  protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
38
- constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
28
+ constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
39
29
  abstract connect(): Promise<void>;
40
- getClient(): Surreal;
30
+ getClient(): Surreal$1;
41
31
  getEvents(): DatabaseEventSystem;
42
32
  tx(): Promise<SurrealTransaction>;
43
33
  private queryQueue;
44
34
  /**
45
35
  * Execute a query with serialized execution to prevent WASM transaction issues.
36
+ *
37
+ * Serialization means every query waits on the previous one, so a call that
38
+ * never settles blocks the whole chain forever. {@link queryTimeoutMs} bounds
39
+ * each link: on expiry this promise rejects and the chain moves on, even
40
+ * though the underlying RPC is still parked in the SDK's pending map.
46
41
  */
47
42
  query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
48
43
  execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
49
44
  close(): Promise<void>;
50
45
  }
51
46
  //#endregion
52
- //#region src/services/database/local.d.ts
53
- declare class LocalDatabaseService extends AbstractDatabaseService {
54
- private config;
55
- protected eventType: "DATABASE_LOCAL_QUERY";
56
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
57
- getConfig(): SpookyConfig<any>['database'];
58
- connect(): Promise<void>;
59
- }
60
- //#endregion
61
47
  //#region src/services/database/remote.d.ts
48
+ /** Transport events the SDK publishes, mapped 1:1 to {@link ConnectionState}. */
49
+ type RemoteConnectionEvent = ConnectionState | 'error';
62
50
  declare class RemoteDatabaseService extends AbstractDatabaseService {
63
51
  private config;
64
52
  protected eventType: "DATABASE_REMOTE_QUERY";
65
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
66
- getConfig(): SpookyConfig<any>['database'];
53
+ private readonly reconnectConfig;
54
+ /**
55
+ * In-flight `connect()`, so concurrent callers (boot + supervisor revive +
56
+ * an `online` event landing at the same moment) share one attempt instead of
57
+ * racing two sockets. Cleared on settle, so a later call always reconnects.
58
+ */
59
+ private connecting;
60
+ /**
61
+ * The token to re-authenticate a freshly opened socket with, kept current by
62
+ * {@link setAuthToken}.
63
+ *
64
+ * `config.token` is fixed at construction and most apps never set it: they
65
+ * sign in later, which authenticates the socket that happens to be open at
66
+ * the time. That is enough for the SDK's OWN reconnects (it replays
67
+ * `version`/`use`/`authenticate` itself), but not for the supervisor's revive
68
+ * loop, which builds a socket from scratch. Without this the revived socket
69
+ * came back UNAUTHENTICATED and stayed that way for the life of the page,
70
+ * while the client's `currentUserId` — restored from local storage — kept
71
+ * reporting the user as signed in.
72
+ *
73
+ * The visible damage is silent and total: `fn::query::register` sends
74
+ * `<string>($auth.id OR '')`, so every view registered afterwards is stamped
75
+ * with an empty identity, and every `$auth.id` predicate in it resolves
76
+ * false. Public tables keep returning rows while everything owned by the user
77
+ * returns nothing, on a page that still looks signed in.
78
+ */
79
+ private authToken;
80
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
81
+ getConfig(): Sp00kyConfig<any>['database'];
82
+ /**
83
+ * Send one SurrealQL statement so that it survives the page going away.
84
+ *
85
+ * A WebSocket `send()` during `pagehide` is not guaranteed to flush — the
86
+ * browser may tear the socket down first, and the frame is simply lost.
87
+ * Measured: an unload-time release over the live socket reached the server
88
+ * zero times out of one. `fetch` with `keepalive` is the primitive the
89
+ * platform actually guarantees here, so this goes over SurrealDB's HTTP
90
+ * `/sql` endpoint instead of the RPC socket.
91
+ *
92
+ * Best-effort by design: no await, no retry, errors swallowed. Every caller
93
+ * must have a server-side fallback that makes a lost beacon a non-event.
94
+ */
95
+ beaconSql(sql: string): void;
96
+ /**
97
+ * Record the token every future connect should authenticate with, or `null`
98
+ * on sign-out. See {@link authToken}.
99
+ *
100
+ * Does not touch the CURRENT socket: callers authenticate that themselves
101
+ * (sign-in and session restore both already do). This only makes the next
102
+ * from-scratch connect reproduce that state.
103
+ */
104
+ setAuthToken(token: string | null): void;
105
+ /** Resolved reconnect tunables; the supervisor reads its own knobs here. */
106
+ getReconnectConfig(): Required<ReconnectConfig>;
107
+ /** Current transport state as reported by the SDK. */
108
+ getStatus(): ConnectionState;
109
+ /**
110
+ * Observe transport events. Thin passthrough so callers (the supervisor,
111
+ * sync, CRDT) don't have to reach through `getClient()`.
112
+ */
113
+ subscribeConnection<K extends RemoteConnectionEvent>(event: K, cb: (...payload: SurrealEvents[K]) => void): () => void;
114
+ /**
115
+ * Tear the socket down on purpose. Used by the heartbeat watchdog when a
116
+ * socket stops answering but never closes: `close()` makes the SDK publish
117
+ * `disconnected`, which is what drives the supervisor's revive loop.
118
+ */
119
+ forceClose(): Promise<void>;
120
+ /**
121
+ * Open (or re-open) the remote connection.
122
+ *
123
+ * Safe to call repeatedly: concurrent calls share the in-flight attempt, and
124
+ * a call after a `disconnected` builds a fresh socket. `use()` and
125
+ * `authenticate()` are re-applied here for the cold path; the SDK also
126
+ * replays them itself on its own internal reconnects.
127
+ */
67
128
  connect(): Promise<void>;
129
+ private doConnect;
68
130
  signin(params: any): Promise<any>;
69
131
  signup(params: any): Promise<any>;
70
132
  authenticate(token: string): Promise<any>;
71
133
  invalidate(): Promise<void>;
72
134
  }
73
135
  //#endregion
136
+ //#region src/services/database/connection-supervisor.d.ts
137
+ /**
138
+ * Keeps the remote WebSocket alive for the whole life of the page.
139
+ *
140
+ * The SurrealDB SDK reconnects on its own after a socket `close`, but that
141
+ * covers only one of three ways the connection dies:
142
+ *
143
+ * 1. **Socket closes, SDK recovers.** Handled entirely by the SDK. This
144
+ * supervisor only observes it (to report `reconnecting` upward).
145
+ * 2. **Socket closes, SDK gives up.** With `attempts: -1` this shouldn't happen
146
+ * from exhaustion — but the SDK also terminates the engine permanently when
147
+ * its post-reconnect handshake throws (it re-runs `version()`, `use()`,
148
+ * `authenticate()` on every reconnect and closes the engine on any error).
149
+ * One transient hiccup there would otherwise kill the page's connection for
150
+ * good. The revive loop re-opens from scratch.
151
+ * 3. **Socket never closes at all.** A half-open connection: the peer is gone
152
+ * (NAT timeout, wifi switch, laptop sleep) but no FIN ever arrives, so
153
+ * `readyState` stays OPEN and the SDK's own 30s ping — fire-and-forget, no
154
+ * response deadline — never notices. Nothing ever fires a `close` event, so
155
+ * nothing ever triggers a reconnect. The heartbeat detects this and forces
156
+ * the teardown that case 2's loop then repairs.
157
+ *
158
+ * Plus wake triggers: coming back `online` or un-hiding the tab probes
159
+ * immediately rather than waiting out a backoff that was scheduled while the
160
+ * network was known-down.
161
+ */
162
+ declare class ConnectionSupervisor {
163
+ private readonly remote;
164
+ private readonly logger;
165
+ private readonly config;
166
+ private state;
167
+ private subscribers;
168
+ private started;
169
+ private disposed;
170
+ private heartbeatTimer;
171
+ private heartbeatInFlight;
172
+ /** Consecutive failed probes. See {@link FAILURES_BEFORE_TEARDOWN}. */
173
+ private heartbeatFailures;
174
+ private reviveTimer;
175
+ private reviveAttempts;
176
+ /** Timestamp of the last wake-triggered probe, for rate limiting. */
177
+ private lastWakeProbeAt;
178
+ private reviving;
179
+ /**
180
+ * Set while the browser reports itself offline. Retrying a socket against a
181
+ * down interface only burns backoff, so the loop parks until `online` fires.
182
+ */
183
+ private suspended;
184
+ private teardown;
185
+ private static readonly REVIVE_BASE_MS;
186
+ /**
187
+ * How many consecutive heartbeat failures it takes to tear the socket down.
188
+ *
189
+ * The probe rides the same serialized queue as every other RPC (deliberately
190
+ * — see {@link beat}), which means it cannot distinguish a WEDGED queue from
191
+ * a merely BUSY one. A single slow window (a large sync burst, one heavy
192
+ * app query) used to be enough to force-close a perfectly healthy socket,
193
+ * and the resulting reconnect re-registered every active query about a
194
+ * second later. That self-inflicted teardown manufactured the very reconnect
195
+ * storms this class exists to survive. A genuinely dead socket still fails
196
+ * every probe, so it is torn down one interval later than before.
197
+ */
198
+ private static readonly FAILURES_BEFORE_TEARDOWN;
199
+ /** Retry delay after an inconclusive (first) heartbeat failure. */
200
+ private static readonly HEARTBEAT_RETRY_MS;
201
+ /** Floor between probes triggered by wake events (tab focus, pageshow). */
202
+ private static readonly WAKE_PROBE_MIN_INTERVAL_MS;
203
+ constructor(remote: RemoteDatabaseService, logger: Logger$1, config?: Required<ReconnectConfig>);
204
+ /** Latest observed transport state. */
205
+ get connection(): ConnectionState;
206
+ /**
207
+ * Observe transport state. Fires immediately with the current value and again
208
+ * on every change. Returns an unsubscribe.
209
+ */
210
+ subscribe(cb: (state: ConnectionState) => void): () => void;
211
+ /**
212
+ * Begin supervising. Call once, after the initial {@link
213
+ * RemoteDatabaseService.connect}. Idempotent.
214
+ */
215
+ start(): void;
216
+ /** Stop all timers and listeners. Safe to call more than once. */
217
+ dispose(): void;
218
+ private setState;
219
+ private clearReviveTimer;
220
+ /**
221
+ * Queue the next `connect()` attempt on exponential backoff, capped at
222
+ * `superviseRetryDelayMaxMs`. Never gives up — the page is expected to
223
+ * outlive any outage.
224
+ */
225
+ private scheduleRevive;
226
+ private revive;
227
+ private stopHeartbeat;
228
+ private startHeartbeat;
229
+ /**
230
+ * Probe the server end-to-end. Deliberately goes through
231
+ * `remote.query` — the same serialized queue every other remote call uses —
232
+ * so a queue wedged behind a stuck RPC also fails the heartbeat instead of
233
+ * being invisible to it.
234
+ */
235
+ private beat;
236
+ /**
237
+ * A restored network or an un-hidden tab is the strongest available hint that
238
+ * a reconnect will now succeed, so probe immediately instead of waiting out a
239
+ * backoff scheduled under worse conditions.
240
+ */
241
+ private installWakeTriggers;
242
+ /**
243
+ * Reset the backoff and act on whichever problem is present: reconnect if the
244
+ * socket is gone, otherwise probe it (it may be half-open — which is exactly
245
+ * what a sleep/wake cycle produces).
246
+ */
247
+ private wake;
248
+ }
249
+ //#endregion
250
+ //#region src/modules/sync/queue/queue-down.d.ts
251
+ type RegisterEvent = {
252
+ type: 'register';
253
+ payload: {
254
+ hash: string;
255
+ };
256
+ };
257
+ type SyncEvent = {
258
+ type: 'sync';
259
+ payload: {
260
+ hash: string;
261
+ };
262
+ };
263
+ type HeartbeatEvent = {
264
+ type: 'heartbeat';
265
+ payload: {
266
+ hash: string;
267
+ };
268
+ };
269
+ type CleanupEvent = {
270
+ type: 'cleanup';
271
+ payload: {
272
+ hash: string;
273
+ };
274
+ };
275
+ type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
276
+ //#endregion
74
277
  //#region src/services/stream-processor/wasm-types.d.ts
75
278
  interface WasmStreamUpdate {
76
279
  query_id: string;
77
280
  result_hash: string;
78
281
  result_data: RecordVersionArray;
282
+ timing_store_apply_ms?: number;
283
+ timing_circuit_step_ms?: number;
284
+ timing_transform_ms?: number;
285
+ timing_parse_ms?: number;
286
+ timing_plan_ms?: number;
287
+ timing_snapshot_ms?: number;
79
288
  }
80
289
  //#endregion
81
290
  //#region src/services/stream-processor/index.d.ts
@@ -96,6 +305,33 @@ interface StreamUpdate {
96
305
  queryHash: string;
97
306
  localArray: RecordVersionArray;
98
307
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
308
+ /**
309
+ * Client-internal: not from the circuit. A membership-only change that
310
+ * needed no fetch is re-materialized through this same path so it cannot
311
+ * race a real update (DataModule.scheduleRematerialize). Carries the last
312
+ * known `localArray`; consumers that describe an INGEST (persist, metrics,
313
+ * devtools events) skip it.
314
+ */
315
+ synthetic?: boolean;
316
+ /**
317
+ * End-to-end ingest latency for the WASM call that produced this update,
318
+ * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
319
+ * for the initial register_view snapshot.
320
+ */
321
+ materializationTimeMs?: number;
322
+ /** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
323
+ storeApplyMs?: number;
324
+ circuitStepMs?: number;
325
+ transformMs?: number;
326
+ /**
327
+ * One-shot registration timings (ms). Only set on the StreamUpdate returned
328
+ * by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
329
+ */
330
+ registration?: {
331
+ parseMs: number;
332
+ planMs: number;
333
+ snapshotMs: number;
334
+ };
99
335
  }
100
336
  type StreamProcessorEvents = {
101
337
  stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
@@ -107,34 +343,204 @@ type StreamProcessorEvents = {
107
343
  interface StreamUpdateReceiver {
108
344
  onStreamUpdate(update: StreamUpdate): void;
109
345
  }
346
+ /** One row change in the shape `ingestMany` consumes. */
347
+ interface IngestRecord {
348
+ table: string;
349
+ /** `MERGE` overlays the given fields on the stored row (projection widening). */
350
+ op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
351
+ id: string;
352
+ record: any;
353
+ }
354
+ /**
355
+ * What the boot-time prime needs from the client: which tables to walk, how
356
+ * to recognise a snapshot written under a different schema, and which rows'
357
+ * local `_00_rv` must not be reported as the server's.
358
+ */
359
+ interface CircuitPrimeContext {
360
+ tables: string[];
361
+ schemaHash: string;
362
+ /** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
363
+ * locally and may exceed the server's next version). */
364
+ pendingIds: Set<string>;
365
+ /** Receives every `(id, rv)` the prime put into the circuit, per table, so
366
+ * the sync layer can skip re-downloading bodies it already has. */
367
+ onVersions?: (table: string, entries: [string, number][]) => void;
368
+ }
369
+ /** Storage key of the circuit snapshot inside the local store. */
370
+
110
371
  declare class StreamProcessorService {
111
372
  events: EventSystem<StreamProcessorEvents>;
112
373
  private db;
113
- private persistenceClient;
114
374
  private logger;
115
375
  private processor;
116
376
  private isInitialized;
117
377
  private receivers;
118
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
378
+ private batching;
379
+ private batchBuffer;
380
+ private sessionAuth;
381
+ private stateGeneration;
382
+ private persistState;
383
+ private persistCircuit;
384
+ private checkpointMs;
385
+ private checkpointTimer;
386
+ private snapshotDirty;
387
+ private dirtyRows;
388
+ private hideHandler;
389
+ private checkpointInFlight;
390
+ private projection;
391
+ private primed;
392
+ private schemaHash;
393
+ private widenQueue;
394
+ private widenPending;
395
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, logger: Logger);
119
396
  /**
120
397
  * Add a receiver for stream updates.
121
398
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
122
399
  */
123
400
  addReceiver(receiver: StreamUpdateReceiver): void;
124
401
  private notifyUpdates;
402
+ private dispatchUpdates;
403
+ /**
404
+ * Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
405
+ * affected query once every record has been ingested. Use this whenever
406
+ * multiple records land at once (sync fetching N rows, the boot prime).
407
+ *
408
+ * The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
409
+ * circuit step per chunk (a step walks every registered view, so per-record
410
+ * ingest paid that fixed cost N times), but never the whole batch at once,
411
+ * because the wasm side has to hold every parsed row of a call at the same
412
+ * time and wasm32 dlmalloc never returns that peak.
413
+ *
414
+ * Returns the records that were ingested. A chunk that fails is reported
415
+ * and skipped, not retried (a retry would double-apply whatever the failed
416
+ * step already committed), and the remaining chunks still run.
417
+ */
418
+ ingestMany(records: IngestRecord[]): IngestRecord[];
419
+ /**
420
+ * Open a coalescing window. While open, the per-record stream updates
421
+ * emitted by `ingest` are buffered (one entry per queryHash) instead of
422
+ * dispatched. Always paired with `flushCoalescing()` in a try/finally by
423
+ * `ingestMany` so the window always closes — otherwise the processor stays
424
+ * stuck buffering forever.
425
+ *
426
+ * No-op if a window is already open (nested batches aren't expected here).
427
+ */
428
+ private beginCoalescing;
429
+ /**
430
+ * Close the coalescing window and flush: dispatch one coalesced
431
+ * `StreamUpdate` per buffered queryHash, then persist processor state once
432
+ * for the whole batch (instead of once per ingest).
433
+ */
434
+ private flushCoalescing;
125
435
  /**
126
436
  * Initialize the WASM module and processor.
127
437
  * This must be called before using other methods.
128
438
  */
129
439
  init(): Promise<void>;
130
- loadState(): Promise<void>;
131
- saveState(): Promise<void>;
440
+ /**
441
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
442
+ * local-bucket switches: the old circuit holds the previous user's rows AND
443
+ * views registered with the previous `$auth` context, so neither may survive.
444
+ * Deliberately loads nothing: the snapshot in the store being swapped away
445
+ * from belongs to the previous bucket; the caller primes the new bucket's
446
+ * circuit (`primeFromLocal`) once its store is open, and the DataModule
447
+ * rebind re-registers every live view against this fresh processor. Caller
448
+ * must re-seed `setPermissions` afterwards (a fresh circuit default-denies
449
+ * every table).
450
+ */
451
+ reset(): Promise<void>;
452
+ /**
453
+ * Release the wasm circuit and stop checkpointing. Call when the client is
454
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
455
+ * one full circuit per instance.
456
+ */
457
+ dispose(): void;
458
+ /**
459
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
460
+ * not expose `free`, and a double free must not take the app down.
461
+ */
462
+ private freeProcessor;
463
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
464
+ setPersistenceEnabled(enabled: boolean): void;
465
+ /**
466
+ * Snapshot persistence (`persistCircuit`). When on, the circuit's store is
467
+ * written to the local store on a checkpoint interval and when the page
468
+ * goes hidden, and restored by {@link primeFromLocal} on the next boot.
469
+ */
470
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
471
+ /**
472
+ * Field projection (`circuitProjection`, default on). Takes effect on the
473
+ * next processor (`init`/`reset`) and on rows written after that.
474
+ */
475
+ configureProjection(enabled: boolean): void;
476
+ private applyProjection;
477
+ /** Resolves once the boot-time prime has finished (or was skipped). */
478
+ whenPrimed(): Promise<void>;
479
+ /**
480
+ * Fill the circuit from the LOCAL store, in the background.
481
+ *
482
+ * With a usable snapshot: install it under whatever views have registered
483
+ * meanwhile (`load_store_state` re-primes them), then `reconcile` each table
484
+ * against the store's `(id, rv)` list so rows deleted since the checkpoint
485
+ * are stepped out and only rows added or changed since are read back and
486
+ * ingested. Without one: read every row and ingest it, chunked.
487
+ *
488
+ * Either way the circuit ends up equal to the local store without touching
489
+ * the network, so the first sync diff is a real delta rather than "fetch
490
+ * everything". The returned promise never rejects; `whenPrimed` gates on it.
491
+ */
492
+ primeFromLocal(ctx: CircuitPrimeContext): Promise<void>;
493
+ private runPrime;
494
+ /** Publish wasm updates produced outside an ingest (restore, reconcile). */
495
+ private dispatchWasmUpdates;
496
+ /**
497
+ * Record that the circuit changed by `rows` rows. Cheap; the snapshot is
498
+ * deferred to the checkpoint timer and skipped entirely when `persistCircuit`
499
+ * is off.
500
+ */
501
+ private markSnapshotDirty;
502
+ private startCheckpoints;
503
+ /** Stop checkpointing and drop the visibility listeners. */
504
+ stopCheckpoints(): void;
505
+ /**
506
+ * Write the circuit's store to the local store as a snapshot. Compacts the
507
+ * row arena first when dead bytes outweigh live ones. Serialised: a second
508
+ * call while one is in flight joins it. No-op unless persistence is on, this
509
+ * tab owns the store, and the engine can hold a snapshot.
510
+ */
511
+ checkpoint(reason?: string): Promise<void>;
512
+ private runCheckpoint;
513
+ /**
514
+ * Projection widening: a newly registered view evaluates fields that rows
515
+ * already in the circuit were stored without. Merge just those fields in,
516
+ * table by table, from the local store. The view registered against what
517
+ * was present and converges as the merges step through.
518
+ */
519
+ private scheduleWiden;
520
+ private runWiden;
521
+ /**
522
+ * Seed per-table `select` permission predicates ({ [table]: whereText }).
523
+ * Must run after the processor exists and before any `register_view`, else
524
+ * non-`_00_` tables are default-denied and registration fails.
525
+ */
526
+ setPermissions(permissions: Record<string, string>): void;
527
+ /**
528
+ * Set the current session's auth identity for permission injection,
529
+ * mirroring the server's `fn::query::register`
530
+ * (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
531
+ * Stored as strings (empty when logged out) and applied to every
532
+ * `register_view` in {@link registerQueryPlan}. Must be set before a
533
+ * `$auth`-gated query registers (and re-set on auth state changes), or the
534
+ * in-browser SSP's `permission_inject` rejects it with
535
+ * "requires $auth but registration params lack it".
536
+ */
537
+ setSessionAuth(authId: string | null, access: string | null): void;
132
538
  /**
133
539
  * Ingest a record change into the processor.
134
540
  * Emits 'stream_update' event if materialized views are affected.
135
541
  * @param isOptimistic true = local mutation (increment versions), false = remote sync (keep versions)
136
542
  */
137
- ingest(table: string, op: 'CREATE' | 'UPDATE' | 'DELETE', id: string, record: any): WasmStreamUpdate[];
543
+ ingest(table: string, op: IngestRecord['op'], id: string, record: any): WasmStreamUpdate[];
138
544
  /**
139
545
  * Register a new query plan.
140
546
  * Emits 'stream_update' with the initial result.
@@ -147,6 +553,1222 @@ declare class StreamProcessorService {
147
553
  private normalizeValue;
148
554
  }
149
555
  //#endregion
556
+ //#region src/modules/cache/types.d.ts
557
+ type RecordWithId = Record<string, any> & {
558
+ id: RecordId<string>;
559
+ };
560
+ interface QueryConfig$1 {
561
+ queryHash: string;
562
+ surql: string;
563
+ params: Record<string, any>;
564
+ ttl: QueryTimeToLive | Duration;
565
+ lastActiveAt: Date;
566
+ }
567
+ interface CacheRecord {
568
+ table: string;
569
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
570
+ record: RecordWithId;
571
+ version: number;
572
+ }
573
+ //#endregion
574
+ //#region src/modules/cache/index.d.ts
575
+ /**
576
+ * CacheModule - Centralized storage and DBSP ingestion
577
+ *
578
+ * Single responsibility: Handle all local storage operations and DBSP ingestion.
579
+ * This module acts as the bridge between data operations and persistence.
580
+ */
581
+ /** One ingested change, in exactly the shape `ingestMany` consumes. Shared
582
+ * with the tabs protocol so a leader can relay its ingests to followers. */
583
+ interface CacheIngestTuple {
584
+ table: string;
585
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
586
+ id: string;
587
+ record: Record<string, unknown>;
588
+ }
589
+ declare class CacheModule implements StreamUpdateReceiver {
590
+ private local;
591
+ private streamProcessor;
592
+ private logger;
593
+ private streamUpdateCallback;
594
+ private versionLookups;
595
+ /** Shared-tabs leader: fan every committed ingest out to follower circuits.
596
+ * Fired AFTER the local tx (the rows are already in the shared store, so a
597
+ * follower only needs the circuit feed). A follower relays its own
598
+ * mutations to the leader the same way, see {@link setIngestRelay}. */
599
+ private ingestRelay;
600
+ /** See {@link setIngestRelay}. */
601
+ private relayLocalWritesOnly;
602
+ constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
603
+ /**
604
+ * Implements StreamUpdateReceiver interface
605
+ * Called directly by StreamProcessor when views change
606
+ */
607
+ onStreamUpdate(update: StreamUpdate): void;
608
+ /**
609
+ * Fan every committed ingest out to the other tabs. The leader relays
610
+ * everything (its sync fetches are the only copy the followers get). A
611
+ * follower relays with `localWritesOnly`: just the mutation path, which is
612
+ * the only thing it knows that the leader does not. Its sync-fetched
613
+ * batches are the leader's data coming back and must not be re-broadcast,
614
+ * or every follower registration would fan its whole working set to
615
+ * every tab.
616
+ */
617
+ setIngestRelay(cb: ((tuples: CacheIngestTuple[]) => void) | null, opts?: {
618
+ localWritesOnly?: boolean;
619
+ }): void;
620
+ /**
621
+ * Shared-tabs follower: feed relayed tuples into THIS tab's circuit only.
622
+ * The rows are already in the shared store (the leader wrote them), so no
623
+ * local write happens here; the normal chain then runs: SSP -> stream update
624
+ * -> DataModule debounce -> materializeRecords (re-reads via the port
625
+ * transport) -> this tab's subscriptions fire with this tab's hashes.
626
+ */
627
+ applyRelayedIngest(tuples: CacheIngestTuple[]): void;
628
+ lookup(recordId: string): number;
629
+ /**
630
+ * Seed the version memo from rows the circuit was primed with out of the
631
+ * local store, so the first post-reload sync diff does not re-download
632
+ * bodies the browser already has. Only rows the prime actually put into the
633
+ * circuit belong here: a memo entry with no circuit row would make the diff
634
+ * flag the id forever while nothing ever fetches it.
635
+ */
636
+ primeVersions(entries: [string, number][]): void;
637
+ /** Drop the version cache on a bucket switch — a stale version would make
638
+ * the sync diff skip fetching a body the new bucket legitimately needs. */
639
+ clearVersionLookups(): void;
640
+ /**
641
+ * Save a single record to local DB and ingest into DBSP
642
+ * Used by mutations (create/update)
643
+ */
644
+ save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
645
+ /**
646
+ * Save multiple records in a batch
647
+ * More efficient than calling save() multiple times
648
+ * Used by sync operations
649
+ */
650
+ saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
651
+ /**
652
+ * Delete a record from local DB and ingest deletion into DBSP
653
+ */
654
+ delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
655
+ /**
656
+ * Register a query with DBSP to create a materialized view
657
+ * Returns the initial result array
658
+ */
659
+ registerQuery(config: QueryConfig$1): {
660
+ localArray: RecordVersionArray;
661
+ registrationTimings?: {
662
+ parseMs: number;
663
+ planMs: number;
664
+ snapshotMs: number;
665
+ };
666
+ };
667
+ /**
668
+ * Unregister a query from DBSP
669
+ */
670
+ unregisterQuery(queryHash: string): void;
671
+ }
672
+ //#endregion
673
+ //#region src/modules/data/index.d.ts
674
+ /**
675
+ * DataModule - Unified query and mutation management
676
+ *
677
+ * Merges the functionality of QueryManager and MutationManager.
678
+ * Uses CacheModule for all storage operations.
679
+ */
680
+ /** A `_00_window` row as read back: the id-set and whether the server vouched
681
+ * for it (which is what allows an empty set to count as known membership). */
682
+ interface DurableMembership {
683
+ ids: RecordVersionArray;
684
+ confirmed: boolean;
685
+ }
686
+ declare class DataModule<S extends SchemaStructure> {
687
+ private cache;
688
+ private local;
689
+ private schema;
690
+ private streamDebounceTime;
691
+ /** Tab identity baked into mutation ids (shared-tabs rollback routing);
692
+ * undefined in solo mode, where mutation-id falls back to a session id. */
693
+ private tabId;
694
+ private activeQueries;
695
+ private pendingQueries;
696
+ private subscriptions;
697
+ private statusSubscriptions;
698
+ private mutationCallbacks;
699
+ private debounceTimers;
700
+ private pendingStreamUpdates;
701
+ private fetchDepth;
702
+ private logger;
703
+ /**
704
+ * Optional observer notified whenever a query's fetch status changes.
705
+ * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
706
+ * settable field (rather than a constructor arg) because DevTools is
707
+ * constructed after DataModule.
708
+ */
709
+ onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
710
+ /**
711
+ * Optional observer invoked when a still-subscribed query's TTL heartbeat
712
+ * fires (~90% of the TTL). Wired by Sp00kyClient to
713
+ * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
714
+ * row's `lastActiveAt` so an actively-watched query never expires. Settable
715
+ * field (not a constructor arg) because the sync engine is wired after
716
+ * DataModule is constructed — mirrors `onQueryStatusChange`.
717
+ */
718
+ onHeartbeat?: (hash: QueryHash) => void;
719
+ /**
720
+ * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
721
+ * viewport-windowed list cancelling an off-screen window) loses its last
722
+ * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
723
+ * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
724
+ * instead of leaving it for the TTL sweep. The local view + state are freed in
725
+ * {@link finalizeDeregister} only after that remote delete, so a fast
726
+ * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
727
+ */
728
+ onDeregister?: (hash: QueryHash) => void;
729
+ private sessionId;
730
+ private currentUserId;
731
+ constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
732
+ init(sessionId: string): Promise<void>;
733
+ /**
734
+ * Update the session salt used in query-id hashing. Call this when the
735
+ * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
736
+ * registered queries will get fresh, session-scoped IDs.
737
+ */
738
+ setSessionId(sessionId: string): void;
739
+ /** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
740
+ * a follower's mutation routes back to the tab that made it. */
741
+ setTabId(tabId: string): void;
742
+ /**
743
+ * Update the authenticated user record id. Pass `null` on sign-out.
744
+ * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
745
+ * the poll route to the same per-user `_00_list_ref_user_<id>` the
746
+ * SSP writes to.
747
+ */
748
+ setCurrentUserId(userId: string | null): void;
749
+ /** Read-only view of the authenticated user id used for per-user
750
+ * `_00_list_ref` routing. Other modules consult this so they pick the
751
+ * same table name DataModule does. */
752
+ getCurrentUserId(): string | null;
753
+ /**
754
+ * Register a query and return its hash for subscriptions
755
+ */
756
+ query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
757
+ /**
758
+ * Subscribe to query updates
759
+ */
760
+ subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
761
+ immediate?: boolean;
762
+ }): () => void;
763
+ /**
764
+ * Subscribe to a query's fetch-status changes (idle/fetching).
765
+ * With `{ immediate: true }` the callback fires synchronously with the
766
+ * current status (defaults to `idle` if the query isn't registered yet).
767
+ */
768
+ subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
769
+ immediate?: boolean;
770
+ }): () => void;
771
+ /**
772
+ * Set a query's fetch status and notify status observers (DevTools +
773
+ * `subscribeStatus` listeners). No-op when the status is unchanged or the
774
+ * query is unknown.
775
+ */
776
+ setQueryStatus(queryHash: string, status: QueryStatus): void;
777
+ /**
778
+ * Enter a fetch cycle for a query. Refcounted: registration and concurrent
779
+ * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
780
+ * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
781
+ * emits `idle`. Always pair with `endFetching` in a `finally`.
782
+ */
783
+ beginFetching(queryHash: string): void;
784
+ /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
785
+ endFetching(queryHash: string): void;
786
+ /**
787
+ * Subscribe to mutations (for sync)
788
+ */
789
+ onMutation(callback: MutationCallback): () => void;
790
+ /**
791
+ * Handle stream updates from DBSP (via CacheModule)
792
+ */
793
+ onStreamUpdate(update: StreamUpdate): Promise<void>;
794
+ /** Coalesce `update` onto the query's trailing timer (see onStreamUpdate). */
795
+ private queueStreamUpdate;
796
+ /**
797
+ * Re-materialize + notify a query whose MEMBERSHIP changed without any row
798
+ * needing to be fetched, i.e. without the SSP stream update that normally
799
+ * carries the notify. That is every row this client wrote itself: the local
800
+ * CREATE memoized it at `_00_rv = 1`, the server publishes it at 1, so the
801
+ * sync engine rightly fetches nothing - and then nobody told the subscribers
802
+ * that `remoteArray` now holds the id. The row appeared on reload only.
803
+ *
804
+ * Routed through the same per-query debounce as a real stream update, so it
805
+ * cannot race one: a pending real update already materializes against the
806
+ * current `remoteArray` and wins. The synthetic update re-uses the circuit's
807
+ * last `localArray` and skips the persist/metrics that describe an ingest.
808
+ */
809
+ scheduleRematerialize(queryHash: string): void;
810
+ /**
811
+ * Process a query's pending (debounced) stream update NOW instead of on the
812
+ * trailing edge. Called by the sync engine before it flips a query back to
813
+ * `idle`, so the status change never races ahead of the rows it fetched.
814
+ * No-op when nothing is pending. The pending entry is removed before the
815
+ * await so a concurrently-firing timer can't process it twice.
816
+ */
817
+ flushPendingStreamUpdate(queryHash: string): Promise<boolean>;
818
+ /**
819
+ * Materialize a query's result rows from the local store.
820
+ *
821
+ * A query's rows are its MEMBERSHIP — the id-set the server put in
822
+ * `_00_list_ref` (`remoteArray`) — not "every local body that matches the
823
+ * WHERE". Those two disagree, and the disagreement was the bug: when a row
824
+ * leaves a query's window but still exists upstream, `handleRemovedRecords`
825
+ * keeps its local body and never re-fetches it, so a predicate re-scan finds
826
+ * that stale body still matching and keeps rendering the row. Selecting the
827
+ * id-set directly is also the only correct thing for a windowed query, where
828
+ * re-applying `START m` against the shared local store skips the window's own
829
+ * rows entirely (sparse windowing) and returns nothing.
830
+ *
831
+ * The rendered set is:
832
+ *
833
+ * (membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes
834
+ *
835
+ * The middle term keeps optimistic writes visible without re-admitting stale
836
+ * rows. Every local write is fed to the SSP (`cache.saveBatch` →
837
+ * `ingestMany`), so `localArray` answers "does this row match the predicate
838
+ * per LOCAL truth". A pending write that moves a row into the window is in
839
+ * `localArray` and shows; one that moves a row out is absent and does not; a
840
+ * stale body the server dropped has no pending write at all, so it stays out.
841
+ * `pendingDeletes` covers the reverse lag — the server still lists a row whose
842
+ * DELETE is sitting in our outbox.
843
+ *
844
+ * Falls back to the predicate scan only when membership has never been
845
+ * established (a query first run on this device), so an offline first paint
846
+ * still shows something.
847
+ */
848
+ private materializeRecords;
849
+ /**
850
+ * The materialization itself, without the DevTools timing wrapper. Split out so
851
+ * cold-start seeding can use it before a `QueryState` exists.
852
+ */
853
+ private materializeFromConfig;
854
+ /**
855
+ * The authoritative membership list to render from, or `null` when membership
856
+ * has never been established and the caller must fall back to a scan.
857
+ *
858
+ * A windowed query has no usable fallback — re-running its `START m` locally
859
+ * returns the wrong rows — so it renders from whatever id-set is on hand
860
+ * (SSP's included) rather than degrading to a scan. That is the pre-existing
861
+ * behavior for windows and is preserved.
862
+ */
863
+ private resolveMembership;
864
+ private readonly settledWrites;
865
+ private readonly settledDeletes;
866
+ private pendingIds;
867
+ private pendingIdsAt;
868
+ private pendingIdsInflight;
869
+ private static readonly PENDING_IDS_TTL_MS;
870
+ private pendingIdsGen;
871
+ private static readonly PENDING_IDS_MAX_REREADS;
872
+ /** Drop the cached outbox ids. Cheap; call it on anything that could change
873
+ * `_00_pending_mutations`. */
874
+ private invalidatePendingIds;
875
+ /**
876
+ * Grace period for a settled write. Long enough to cover an SSP round trip
877
+ * that is running slowly (seconds, not milliseconds, when the edge path is
878
+ * backed up), short enough that a write the server silently dropped cannot
879
+ * linger misleadingly.
880
+ *
881
+ * The rejection case does NOT rely on this expiring: an application error
882
+ * rolls the mutation back and never reports it settled, so it vanishes at
883
+ * once. This deadline only bounds the case where the write succeeded and its
884
+ * membership never arrived at all.
885
+ *
886
+ * 30 s, up from 10 s. At 10 s every server hiccup longer than a scheduler
887
+ * drain plus one slow database commit showed up as the user's own chat
888
+ * message vanishing and coming back a minute later. 30 s covers a drain and
889
+ * a stalled commit end to end; a membership that takes longer than that is
890
+ * a server fault the admin heartbeat reports, not something to paper over.
891
+ */
892
+ private static readonly SETTLED_WRITE_GRACE_MS;
893
+ /**
894
+ * Whether any settled write or delete is still waiting for membership to
895
+ * catch up. The sync poll keeps its fast cadence while this is true, so a
896
+ * missed LIVE notification for the edge is picked up on the next poll tick
897
+ * rather than after the idle backoff.
898
+ */
899
+ hasSettledWritesPending(): boolean;
900
+ /**
901
+ * Report that a mutation was accepted by the server and its outbox row
902
+ * removed. Called only on the SUCCESS path — a rolled-back mutation must
903
+ * disappear immediately, which is what makes this safe.
904
+ */
905
+ noteWriteSettled(recordId: string, mutationType: string): void;
906
+ /** Drop entries past their deadline. */
907
+ private pruneSettled;
908
+ /** Apply the pending-write union and pending-delete subtraction, and map to
909
+ * RecordIds for the engines' id-set path. */
910
+ private buildRenderIds;
911
+ private processStreamUpdate;
912
+ /**
913
+ * Compute p55/p90/p99 from a rolling window of materialization samples.
914
+ * Returns nulls for any percentile that has no samples yet so SurrealDB
915
+ * `option<float>` columns stay NONE rather than 0 before the first ingest.
916
+ */
917
+ private computeMaterializationPercentiles;
918
+ /** Record a per-phase timing sample (ms) on a query's rolling window. */
919
+ private recordPhase;
920
+ /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
921
+ recordRemoteFetch(hash: string, ms: number): void;
922
+ /**
923
+ * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
924
+ * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
925
+ */
926
+ recordFrontendTiming(hash: string, ms: number): void;
927
+ /**
928
+ * Build the per-query processing-time breakdown surfaced to the DevTools panel
929
+ * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
930
+ * the rest come from the per-phase rolling windows + one-shot registration timings.
931
+ */
932
+ phaseTimings(q: QueryState): QueryTimings;
933
+ /**
934
+ * Get query state (for sync and devtools)
935
+ */
936
+ getQueryByHash(hash: string): QueryState | undefined;
937
+ /**
938
+ * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
939
+ * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
940
+ * We gate on `remoteArray`, not local `records`: a windowed query is often
941
+ * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
942
+ * but it still hasn't loaded its own full window from the server — so it should
943
+ * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
944
+ */
945
+ isCold(hash: string): boolean;
946
+ /**
947
+ * Walk a hydrated record's fields and append any EMBEDDED child records to
948
+ * `batch` (recursing for nested related fields). An embedded child is a
949
+ * value that is itself a record — a non-null object whose `id` is a
950
+ * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
951
+ * bare `RecordId` (a foreign-key reference) or any other value is skipped,
952
+ * so this never mistakes a FK column for an embedded body. Children are
953
+ * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
954
+ * to their table's real columns (which strips the alias/related fields).
955
+ * `seen` dedupes within the batch.
956
+ */
957
+ private collectEmbeddedChildren;
958
+ /**
959
+ * Prepare a subquery-bearing row (preload / hydration) for the schemafull
960
+ * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
961
+ * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
962
+ * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
963
+ * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
964
+ * with relations already RecordIds — passes through unchanged.
965
+ */
966
+ private flattenRelationsForStorage;
967
+ /**
968
+ * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
969
+ * surql run directly) so the query DISPLAYS immediately, while the full realtime
970
+ * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
971
+ * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
972
+ * `remoteArray` so windowed queries materialize the correct window (no sparse
973
+ * local-circuit issue). Runs at most once per query (the `hydrated` flag).
974
+ */
975
+ applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
976
+ /**
977
+ * Build the cache batch for a set of one-shot rows and persist it to the
978
+ * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
979
+ * and extracts EMBEDDED related children (any nesting depth) as their own
980
+ * records — a `.related()` query returns its children embedded, and a later
981
+ * correlated re-materialization needs them present as standalone rows.
982
+ * Shared by `applyHydration` (live registration) and `persistSnapshot`
983
+ * (preload).
984
+ */
985
+ private buildAndSaveCacheBatch;
986
+ /**
987
+ * Preload/prewarm: persist one-shot rows (and their embedded related children)
988
+ * into the local cache WITHOUT registering a query — no `activeQueries` entry,
989
+ * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
990
+ * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
991
+ * first paint from them instantly, then registers a live view to freshen.
992
+ */
993
+ persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
994
+ /**
995
+ * Read the durable preload freshness marker for a query hash, or null if this
996
+ * query was never preloaded in the current bucket. Co-located with the cached
997
+ * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
998
+ * data also clears the marker — a stale marker can't claim "warm" when the
999
+ * rows are gone. Any read error is treated as cold.
1000
+ */
1001
+ getPreloadMarker(hash: string): Promise<{
1002
+ fetchedAt: number;
1003
+ rowCount: number;
1004
+ } | null>;
1005
+ /** Stamp the preload freshness marker after a successful snapshot fetch. */
1006
+ writePreloadMarker(hash: string, rowCount: number): Promise<void>;
1007
+ /**
1008
+ * Read the durable membership row, or `null` if this query has never had
1009
+ * authoritative membership on this device. Any read error is treated as
1010
+ * "unknown" so a broken row degrades to the predicate scan rather than
1011
+ * rendering an empty list.
1012
+ *
1013
+ * `confirmed` is true only for rows written after the server itself vouched
1014
+ * for the set (a non-empty id-set, or an empty one it reported a row count of
1015
+ * zero for, or an empty one that followed a non-empty one in the same
1016
+ * session). Rows written before the marker existed, including the `[]` rows a
1017
+ * pre-`ea56f50e` client mirrored from an unflushed read, read as unconfirmed.
1018
+ */
1019
+ getWindowMembership(key: string): Promise<DurableMembership | null>;
1020
+ /**
1021
+ * Persist the durable membership row. Best-effort: callers must not fail a
1022
+ * sync round because the mirror write failed.
1023
+ *
1024
+ * `confirmed` says whether a cold start may trust this row even when it is
1025
+ * empty. A confirmed empty is a real answer ("the server says this query has
1026
+ * no rows") and stays empty across a reload; an unconfirmed empty is the
1027
+ * retry budget's guess and falls back to the predicate scan on the next boot,
1028
+ * exactly as every empty row did before the marker existed.
1029
+ */
1030
+ writeWindowMembership(key: string, ids: RecordVersionArray, confirmed: boolean): Promise<void>;
1031
+ /**
1032
+ * Record ids with a mutation still in the outbox, split by direction.
1033
+ *
1034
+ * Both halves feed {@link materializeRecords}: `writes` keeps optimistic
1035
+ * creates/updates visible before the server has acknowledged them, and
1036
+ * `deletes` suppresses rows the server still lists because our DELETE hasn't
1037
+ * been processed yet. Reading `_00_pending_mutations` (rather than tracking
1038
+ * ids in memory) is what makes both survive a reload.
1039
+ *
1040
+ * On failure returns empty sets: membership alone then decides, which can
1041
+ * briefly hide an optimistic write but never resurrects a deleted row.
1042
+ */
1043
+ getPendingRecordIds(): Promise<{
1044
+ writes: Set<string>;
1045
+ deletes: Set<string>;
1046
+ }>;
1047
+ /** The uncached read. Also the reload path after an invalidation, so the ids
1048
+ * still survive a reload exactly as before. `gen` is the generation the read
1049
+ * was issued under; the result is cached only if it is still current. */
1050
+ private readPendingRecordIds;
1051
+ /** True while ≥1 live subscriber is watching this query (refcount guard). */
1052
+ hasSubscribers(hash: string): boolean;
1053
+ /**
1054
+ * Opt-in eager teardown for a query whose LAST subscriber just left — used by
1055
+ * viewport-windowed lists to cancel off-screen windows instead of leaving
1056
+ * their remote views to expire on the TTL sweep. No-op while any subscriber
1057
+ * remains (refcount). Only enqueues the remote cleanup here; the local WASM
1058
+ * view + in-memory state are freed in {@link finalizeDeregister} after the
1059
+ * remote delete completes, so a re-subscribe in between aborts/heals it.
1060
+ *
1061
+ * NOTE: most queries should NOT use this — the default keep-alive on
1062
+ * unsubscribe avoids re-registration churn on navigation.
1063
+ */
1064
+ deregisterQuery(hash: string): void;
1065
+ /**
1066
+ * Final local teardown after the remote `_00_query` row was deleted: free the
1067
+ * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
1068
+ * (`cleanupQuery`) guarantees no subscriber remains.
1069
+ */
1070
+ finalizeDeregister(hash: string): void;
1071
+ /**
1072
+ * Get query state by id (for sync and devtools)
1073
+ */
1074
+ getQueryById(id: RecordId<string>): QueryState | undefined;
1075
+ /**
1076
+ * Get all active queries (for devtools)
1077
+ */
1078
+ getActiveQueries(): QueryState[];
1079
+ getActiveQueryHashes(): QueryHash[];
1080
+ updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
1081
+ updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray, opts?: {
1082
+ /** `_00_query.rowCount` read in the same round trip; `null` = unknown. */
1083
+ serverRowCount?: number | null;
1084
+ }): Promise<void>;
1085
+ /**
1086
+ * Cancel every armed timer ahead of a local-bucket switch: stream-update
1087
+ * debounce timers (their pending updates carry the OLD bucket's id-sets) and
1088
+ * per-query TTL heartbeats (they'd refresh the previous user's remote
1089
+ * `_00_query` rows under the new session). The rebind re-arms heartbeats.
1090
+ */
1091
+ quiesce(): void;
1092
+ /**
1093
+ * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
1094
+ * `useQuery` subscriptions are keyed by hash and don't re-register on auth
1095
+ * changes, so the hooks must stay attached. Per query:
1096
+ * 1. reset the sync arrays + hydration flag and drop the previous user's
1097
+ * records, notifying subscribers with the new-bucket materialization
1098
+ * (usually empty) so their rows leave the UI immediately;
1099
+ * 2. recreate the `_00_query` row in the new bucket;
1100
+ * 3. re-register the SSP view on the (fresh, post-reset) processor — this
1101
+ * also rebinds the view to the NEW `$auth` context;
1102
+ * 4. restart the TTL heartbeat.
1103
+ * Returns the hashes so the caller can enqueue remote re-registration, which
1104
+ * refills records from the server via the normal register→sync→notify path.
1105
+ */
1106
+ rebindAfterBucketSwitch(): Promise<QueryHash[]>;
1107
+ /**
1108
+ * Called after a query's initial sync completes.
1109
+ * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
1110
+ */
1111
+ notifyQuerySynced(queryHash: string): Promise<void>;
1112
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
1113
+ /**
1114
+ * Build the outbox job record + resolve its table for a backend route.
1115
+ *
1116
+ * Every job is a single execution. Recurring work is declared server-side
1117
+ * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
1118
+ * so nothing here needs to know about schedules.
1119
+ */
1120
+ private buildJobRecord;
1121
+ /**
1122
+ * Create a new record
1123
+ */
1124
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
1125
+ /**
1126
+ * Update an existing record
1127
+ */
1128
+ update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
1129
+ /**
1130
+ * Delete a record
1131
+ */
1132
+ delete(table: string, id: string): Promise<void>;
1133
+ /**
1134
+ * Rollback a failed optimistic create by deleting the record locally
1135
+ */
1136
+ rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
1137
+ /**
1138
+ * Rollback a failed optimistic update by restoring the previous record state
1139
+ */
1140
+ rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
1141
+ /**
1142
+ * Force a re-materialize + notify of every active query on `tableName`.
1143
+ * Used after a DELETE landed in the local store (this tab's own, or one
1144
+ * relayed from another tab): the SSP may not emit a view update for a
1145
+ * DELETE ingest, and the re-materialize reads the store, which already
1146
+ * excludes the row. Each query is isolated so one failing re-materialize
1147
+ * can't stop the others.
1148
+ */
1149
+ notifyTableQueries(tableName: string): Promise<void>;
1150
+ /**
1151
+ * Remove a record from all active query states and notify subscribers
1152
+ */
1153
+ private removeRecordFromQueries;
1154
+ private createAndRegisterQuery;
1155
+ private createNewQuery;
1156
+ private calculateHash;
1157
+ /**
1158
+ * Session-independent counterpart of {@link calculateHash}: the key for a
1159
+ * query's durable `_00_window` membership row.
1160
+ *
1161
+ * Deliberately the SAME inputs minus the `session::id()` salt, so the two keys
1162
+ * can never drift apart. The salt is right for `_00_query` (two tabs must not
1163
+ * fight over one row) and wrong for membership, which has to be recognizable
1164
+ * after a reload — a reload mints a new session id, and offline the salt is
1165
+ * `''`, so a salted key can never match what the previous session wrote.
1166
+ */
1167
+ private calculateMembershipKey;
1168
+ private sha256;
1169
+ private startTTLHeartbeat;
1170
+ private replaceRecordInQueries;
1171
+ }
1172
+ /**
1173
+ * Parse update options to generate push event options
1174
+ */
1175
+ //#endregion
1176
+ //#region src/services/tabs/protocol.d.ts
1177
+ type TabId = string;
1178
+ type TabRole = 'solo' | 'leader' | 'follower';
1179
+ /** Broker pings every tab at this cadence. */
1180
+
1181
+ /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
1182
+ * consumes, so relayed batches feed follower circuits without reshaping. */
1183
+ interface IngestTuple {
1184
+ table: string;
1185
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
1186
+ id: string;
1187
+ record: Record<string, unknown>;
1188
+ }
1189
+ type FollowerToLeaderMessage = {
1190
+ type: 'sync-hello';
1191
+ tabId: TabId;
1192
+ }
1193
+ /** The follower committed an outbox row (through the shared store) and the
1194
+ * leader should drain it. Idempotent; a new leader's loadFromDatabase is
1195
+ * the backstop for a notify lost in a failover window. */ | {
1196
+ type: 'mutation-enqueued';
1197
+ mutationId: string;
1198
+ } | {
1199
+ type: 'request-poll';
1200
+ }
1201
+ /** An optimistic write this follower committed to the SHARED store and
1202
+ * ingested into its own circuit. The leader ingests it (no DB write, the
1203
+ * row is already there) and fans it out to every OTHER follower as
1204
+ * `ingest-relay`, so a follower's write lands in every tab in one hop
1205
+ * instead of after the server round-trip. */ | {
1206
+ type: 'ingest';
1207
+ tuples: IngestTuple[];
1208
+ };
1209
+ type LeaderToFollowerMessage = {
1210
+ type: 'db-ready';
1211
+ leadershipId: number;
1212
+ bucketId: string;
1213
+ storageHealth: StorageHealth;
1214
+ }
1215
+ /** Every ingest the leader's CacheModule committed, so follower circuits
1216
+ * stay live without their own fetch. seq detects gaps. */ | {
1217
+ type: 'ingest-relay';
1218
+ tuples: IngestTuple[];
1219
+ leadershipId: number;
1220
+ seq: number;
1221
+ }
1222
+ /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
1223
+ * queryId against its own DataModule and ignores foreign queries. */ | {
1224
+ type: 'list-ref-change';
1225
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
1226
+ queryId: string;
1227
+ recordId: string;
1228
+ version: number;
1229
+ parent: boolean;
1230
+ }
1231
+ /** The leader's drain rolled back a mutation owned by this tab. */ | {
1232
+ type: 'mutation-rolled-back';
1233
+ mutationId: string;
1234
+ recordId: string;
1235
+ eventType: 'create' | 'update' | 'delete';
1236
+ error: string;
1237
+ }
1238
+ /** The leader's drain pushed a mutation and deleted its outbox row from the
1239
+ * SHARED store. Every follower starts its settled-write grace so a row it
1240
+ * was rendering as a pending write does not blink out before its
1241
+ * `_00_list_ref` membership arrives. */ | {
1242
+ type: 'mutation-settled';
1243
+ mutationId: string;
1244
+ recordId: string;
1245
+ eventType: 'create' | 'update' | 'delete';
1246
+ };
1247
+ //#endregion
1248
+ //#region src/services/tabs/coordinator.d.ts
1249
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
1250
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
1251
+ declare class LeaderSyncHub {
1252
+ readonly leadershipId: number;
1253
+ private logger;
1254
+ private followers;
1255
+ private seq;
1256
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1257
+ onFollowerDetached: ((tabId: TabId) => void) | null;
1258
+ constructor(leadershipId: number, logger: Logger$1);
1259
+ attach(tabId: TabId, port: MessagePort): void;
1260
+ detach(tabId: TabId): void;
1261
+ detachAll(): void;
1262
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1263
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1264
+ /** Stamped ingest relay; seq lets followers detect gaps. */
1265
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1266
+ get followerCount(): number;
1267
+ get relayedBatches(): number;
1268
+ }
1269
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
1270
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
1271
+ * backstopped by the new leader reloading the shared outbox from the store. */
1272
+ declare class SyncForwarder {
1273
+ private tabId;
1274
+ private port;
1275
+ private queued;
1276
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1277
+ constructor(tabId: TabId);
1278
+ rebind(port: MessagePort): void;
1279
+ unbind(): void;
1280
+ private post;
1281
+ mutationEnqueued(mutationId: string): void;
1282
+ /** An optimistic write this tab just ingested. Deliberately NOT queued while
1283
+ * detached: a new leader primes its circuit from the shared store, which
1284
+ * already holds the row, and replaying a stale tuple at it later would put
1285
+ * an older `_00_rv` in its version memo. */
1286
+ ingest(tuples: IngestTuple[]): void;
1287
+ requestPoll(): void;
1288
+ }
1289
+ //#endregion
1290
+ //#region src/modules/sync/sync.d.ts
1291
+ /**
1292
+ * Tunables for `Sp00kySync` construction.
1293
+ */
1294
+ interface Sp00kySyncOptions {
1295
+ /**
1296
+ * Cadence (ms) for the `_00_list_ref` poll fallback that catches
1297
+ * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
1298
+ * values fall back to the default; see
1299
+ * {@link resolveListRefPollInterval}.
1300
+ */
1301
+ refSyncIntervalMs?: number;
1302
+ /**
1303
+ * Enable realtime sync for unauthenticated clients against the shared
1304
+ * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
1305
+ * Defaults to `false`.
1306
+ */
1307
+ anonymousLiveQueries?: boolean;
1308
+ /**
1309
+ * Consecutive failed sync rounds before sync health flips to `degraded`.
1310
+ * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
1311
+ * Defaults to `3`.
1312
+ */
1313
+ degradeAfterConsecutiveFailures?: number;
1314
+ /**
1315
+ * Max time a single mutation push may take before it is treated as a network
1316
+ * failure and retried. Guards against an RPC that never settles wedging the
1317
+ * up-queue for the session. Defaults to 30000; `0` disables the timeout.
1318
+ */
1319
+ pushTimeoutMs?: number;
1320
+ /**
1321
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1322
+ * it is treated as a network failure and retried. The mirror of
1323
+ * {@link pushTimeoutMs} for the read side, which had no such guard: a
1324
+ * `fn::query::register` that never settled held its slot in the down drain,
1325
+ * and every later registration behind it, for the rest of the session.
1326
+ * Defaults to 30000; `0` disables the timeout.
1327
+ */
1328
+ downTimeoutMs?: number;
1329
+ /**
1330
+ * Transport supervisor. Sync reads its state to report `connection` in
1331
+ * {@link SyncHealth} so a UI can show "reconnecting…" the instant the socket
1332
+ * drops, without waiting for the degrade threshold. Optional: omitted in
1333
+ * tests, where `connection` then reports `connected`.
1334
+ */
1335
+ connectionSupervisor?: ConnectionSupervisor;
1336
+ }
1337
+ /**
1338
+ * The main synchronization engine for Sp00ky.
1339
+ * Handles the bidirectional synchronization between the local database and the remote backend.
1340
+ * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
1341
+ * @template S The schema structure type.
1342
+ */
1343
+ declare class Sp00kySync<S extends SchemaStructure> {
1344
+ private local;
1345
+ private remote;
1346
+ private cache;
1347
+ private dataModule;
1348
+ private schema;
1349
+ private upQueue;
1350
+ private downQueue;
1351
+ private isInit;
1352
+ private logger;
1353
+ private syncEngine;
1354
+ /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
1355
+ * from `this.events`, which carries Sp00kySync-level events like
1356
+ * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
1357
+ get engineEvents(): SyncEventSystem;
1358
+ private scheduler;
1359
+ /**
1360
+ * Set by any event that means the socket we registered on is gone, so the
1361
+ * next `connected` knows it must re-subscribe rather than treat itself as the
1362
+ * initial connect. See {@link subscribeToReconnect}.
1363
+ */
1364
+ private needsResubscribe;
1365
+ /** When the last reconnect-driven full refetch ran, for burst coalescing. */
1366
+ private lastReconnectRefetchAt;
1367
+ /**
1368
+ * Minimum gap between reconnect-driven full refetches. Long enough to absorb
1369
+ * a flapping socket (the SDK reconnect ladder starts at 1s), short enough
1370
+ * that a genuine drop minutes later still refetches.
1371
+ */
1372
+ private static readonly RECONNECT_REFETCH_COOLDOWN_MS;
1373
+ /** Poll interval while waiting for a reconnected session to re-authenticate. */
1374
+ private static readonly AUTH_READY_RETRY_MS;
1375
+ /** Attempts before giving up on re-auth and skipping the refetch entirely. */
1376
+ private static readonly AUTH_READY_MAX_ATTEMPTS;
1377
+ events: SyncEventSystem;
1378
+ private currentUserId;
1379
+ private tabRole;
1380
+ private tabId;
1381
+ private hub;
1382
+ private forwarder;
1383
+ private refMode;
1384
+ private readonly anonLiveEnabled;
1385
+ private currentLiveQueryUuid;
1386
+ private liveQueryUnsubscribe;
1387
+ private listRefPollTimer;
1388
+ private listRefPollRunning;
1389
+ private listRefPollInFlight;
1390
+ readonly refSyncIntervalMs: number;
1391
+ private listRefIdleStreak;
1392
+ private stillRemoteStreaks;
1393
+ private lastLiveEventAt;
1394
+ private _liveRetryCount;
1395
+ get liveRetryCount(): number;
1396
+ get isSyncing(): boolean;
1397
+ get pendingMutationCount(): number;
1398
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
1399
+ private readonly degradeAfterFailures;
1400
+ /** Per-push RPC deadline; see {@link withPushTimeout}. */
1401
+ private readonly pushTimeoutMs;
1402
+ private readonly downTimeoutMs;
1403
+ private consecutiveSyncFailures;
1404
+ private syncHealthStatus;
1405
+ private lastSyncErrorKind;
1406
+ private lastSyncErrorMessage;
1407
+ private hasSyncedOnce;
1408
+ private selfHealTimer;
1409
+ private selfHealAttempts;
1410
+ private static readonly SELF_HEAL_BASE_MS;
1411
+ private static readonly SELF_HEAL_MAX_MS;
1412
+ /**
1413
+ * Transport supervisor, when one was supplied. Sync only reads state from it;
1414
+ * it never drives reconnects itself.
1415
+ */
1416
+ private readonly connectionSupervisor?;
1417
+ /**
1418
+ * Mirror of the supervisor's state. Defaults to `connected` so a client
1419
+ * constructed without a supervisor (tests, embedders) reports the same health
1420
+ * shape it always has rather than a permanent false "disconnected".
1421
+ */
1422
+ private connectionState;
1423
+ /** Current sync-health snapshot. */
1424
+ get syncHealth(): SyncHealth;
1425
+ /**
1426
+ * Observe sync health. The callback fires immediately with the current
1427
+ * status and again on every healthy↔degraded transition. Returns an
1428
+ * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
1429
+ */
1430
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1431
+ private emitSyncHealth;
1432
+ /**
1433
+ * Mirror the supervisor's transport state into {@link SyncHealth} and emit on
1434
+ * every change, so a UI can react to a dropped socket immediately instead of
1435
+ * waiting for `degradeAfterFailures` failed rounds. `status` is untouched:
1436
+ * a brief reconnect is not a degradation.
1437
+ *
1438
+ * No explicit unsubscribe: the supervisor is owned by the same client and
1439
+ * drops all subscribers in its own `dispose()`, which `Sp00kyClient.close()`
1440
+ * calls first.
1441
+ */
1442
+ private subscribeToConnectionState;
1443
+ /**
1444
+ * Fed by the scheduler once per drained sync round. Individual failures are
1445
+ * absorbed by the queue's retry; only a run of `degradeAfterFailures`
1446
+ * consecutive failures flips the status to `degraded`, and the next clean
1447
+ * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
1448
+ * is 0).
1449
+ */
1450
+ private recordSyncOutcome;
1451
+ /**
1452
+ * Begin self-heal retries (no-op if already running). Started on the
1453
+ * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
1454
+ */
1455
+ private startSelfHeal;
1456
+ private scheduleSelfHeal;
1457
+ private stopSelfHeal;
1458
+ /**
1459
+ * Release a deregistered query's remote view immediately instead of leaving
1460
+ * it to the TTL sweep. Off by default; see the reasoning in
1461
+ * {@link cleanupQuery}. Kept as a field rather than deleted so the eager path
1462
+ * can be re-enabled in a test once the subquery-body repair path exists.
1463
+ */
1464
+ private readonly releaseQueriesEagerly;
1465
+ constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
1466
+ /**
1467
+ * Initializes the synchronization system.
1468
+ * Starts the scheduler and initiates the initial sync cycles.
1469
+ * @throws Error if already initialized.
1470
+ */
1471
+ init(): Promise<void>;
1472
+ /** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
1473
+ * never starts LIVE; its own registration/poll paths stay untouched). */
1474
+ setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void;
1475
+ /** In-flight {@link resumeLeaderDuties}, so a second call joins the first
1476
+ * instead of double-draining the outbox. */
1477
+ private leaderDutiesInFlight;
1478
+ /** Resolves once the in-browser circuit has been primed from the local
1479
+ * store. Every sync diff waits on it: diffing against an empty circuit
1480
+ * classifies the whole working set as missing and re-downloads it. */
1481
+ private primeGate;
1482
+ /** The prime we last waited on. `whenPrimed` hands out one promise per
1483
+ * prime, so a new identity means a new prime (boot, bucket switch) ran. */
1484
+ private settledPrime;
1485
+ setPrimeGate(gate: () => Promise<void>): void;
1486
+ /**
1487
+ * Leader WIRING only, and deliberately synchronous.
1488
+ *
1489
+ * The coordinator publishes the leader role and tells the broker
1490
+ * `leader-ready` the moment the store is adopted, and the broker can mint a
1491
+ * follower's ports on the very next tick. So the follower-message handler
1492
+ * has to be live before this returns, or a mutation forwarded in that window
1493
+ * is dropped. Everything that can block (outbox reload, LIVE restart) moved
1494
+ * to {@link resumeLeaderDuties}: a promotion that waits on the network holds
1495
+ * `leader-ready` back, and a broker whose leader never reports ready serves
1496
+ * no follower ports and re-elects no one, which wedges the whole namespace.
1497
+ */
1498
+ promoteToLeader(hub: LeaderSyncHub): void;
1499
+ /** Leader duties: drain the shared outbox, own the single list_ref LIVE,
1500
+ * relay LIVE events and rollbacks to followers. Idempotent for a boot-time
1501
+ * leader; a runtime promotion (failover) reloads the outbox, which now
1502
+ * holds EVERY tab's rows, and restarts LIVE under this session. Runs in the
1503
+ * background off the promotion path, so however long it takes (or if it
1504
+ * never finishes) the tab is already a working leader. */
1505
+ resumeLeaderDuties(): Promise<void>;
1506
+ /** Follower duties: no outbox drain, no LIVE. Mutations forward to the
1507
+ * leader; everything else (registration, per-query sync, poll) runs
1508
+ * against this tab's own remote session as usual. */
1509
+ demoteToFollower(forwarder: SyncForwarder): void;
1510
+ /**
1511
+ * A pending mutation was discarded because it can never be sent.
1512
+ *
1513
+ * This is a lost write, so it must not stay invisible. Every failure in this
1514
+ * chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
1515
+ * shows, which is how an outbox could sit undrained for hours with the UI
1516
+ * reporting nothing. Surfaces as a rollback event (the mutation will never
1517
+ * apply, which is what a subscriber needs to know) and degrades sync health.
1518
+ */
1519
+ private onMutationDropped;
1520
+ /** A forwarded outbox row from a follower: load + drain it. Idempotent. */
1521
+ enqueueForwardedMutation(mutationId: string): Promise<void>;
1522
+ /**
1523
+ * Tuples another tab already committed to the shared store: feed them to
1524
+ * THIS tab's circuit (no local write). A DELETE additionally forces a
1525
+ * re-materialize of the table's queries, exactly as the writing tab does
1526
+ * for itself, because the SSP may not emit a view update for it.
1527
+ */
1528
+ private applyRelayedIngest;
1529
+ /** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
1530
+ * and run the exact same handling the LIVE subscription would have. */
1531
+ private applyRelayedListRefChange;
1532
+ /** One immediate poll cycle (failover convergence). */
1533
+ forcePollRound(): Promise<void>;
1534
+ /**
1535
+ * Quiesce all sync activity ahead of a local-bucket switch. After this
1536
+ * resolves, nothing in the sync module writes to the local store: the poll
1537
+ * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
1538
+ * timers are cancelled (their outbox rows are already persisted), and the
1539
+ * scheduler has drained its in-flight queue item — including that item's
1540
+ * outbox-row delete, which must land in the OLD bucket. Queued down-events
1541
+ * are dropped (they reference old-bucket query rows; the post-switch rebind
1542
+ * re-enqueues registrations). The old user's un-pushed outbox is deliberately
1543
+ * NOT drained: the remote session already belongs to the next user.
1544
+ */
1545
+ prepareBucketSwitch(): Promise<void>;
1546
+ /**
1547
+ * Resume syncing against the freshly-opened bucket: reload the mutation
1548
+ * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
1549
+ * offline work) and restart the scheduler. LIVE + the list_ref poll restart
1550
+ * via the `setCurrentUserId` call that follows in the auth listener.
1551
+ */
1552
+ completeBucketSwitch(): Promise<void>;
1553
+ /**
1554
+ * Push the authenticated user's record id from the parent client's
1555
+ * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
1556
+ * any) and re-registers it under the new user's dedicated table so
1557
+ * SurrealDB binds the permission rule under the post-flip auth
1558
+ * context. Pass `null` on sign-out.
1559
+ *
1560
+ * The dedicated `_00_list_ref_user_<id>` table is created lazily by
1561
+ * the SSP when the first query registration arrives, which may be
1562
+ * concurrent with this call. We retry the LIVE registration with a
1563
+ * short backoff so a "table not found" race resolves without
1564
+ * surfacing as a permanent auth-loading hang.
1565
+ */
1566
+ setCurrentUserId(userId: string | null): Promise<void>;
1567
+ private startListRefPoll;
1568
+ private stopListRefPoll;
1569
+ /**
1570
+ * One poll cycle: refetch `_00_list_ref` for every active query. Returns
1571
+ * whether ANY query's remoteArray actually changed — the scheduler uses this
1572
+ * to drive the adaptive idle backoff.
1573
+ *
1574
+ * Also the ONLY health signal that runs while the page is idle. Sync health is
1575
+ * otherwise activity-driven (mutations/registrations via the scheduler,
1576
+ * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
1577
+ * would linger until the next mutation and a genuine idle drop would be
1578
+ * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
1579
+ * so idle health self-recovers (and self-degrades) with no user action. A clean
1580
+ * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
1581
+ * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
1582
+ */
1583
+ private pollListRefForActiveQueries;
1584
+ /**
1585
+ * Pull the upstream list_ref entries for `queryHash`, diff them
1586
+ * against the local `remoteArray` cache, sync any added/updated rows
1587
+ * through the SyncEngine, then persist the new remoteArray. This is
1588
+ * the same shape `createRemoteQuery` does for its initial fetch and
1589
+ * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
1590
+ * it on a timer as a fallback for missed LIVE notifications.
1591
+ */
1592
+ private refetchListRefForQuery;
1593
+ /**
1594
+ * Resolve the current `_00_list_ref` table name for the active auth
1595
+ * context. Public so the `createRemoteQuery` initial-fetch path can
1596
+ * read from the right per-user table.
1597
+ *
1598
+ * Reads the user id from `DataModule` rather than the local mirror,
1599
+ * because `DataModule.setCurrentUserId` runs synchronously from the
1600
+ * auth callback (before any `await`), whereas `sync.setCurrentUserId`
1601
+ * is async — the userQuery's initial fetch can fire between those
1602
+ * two points and we need the correct table name immediately.
1603
+ */
1604
+ listRefTable(): string;
1605
+ private killRefLiveQuery;
1606
+ private restartRefLiveQuery;
1607
+ /**
1608
+ * Drop local LIVE bookkeeping without issuing a `KILL`.
1609
+ *
1610
+ * Called when the socket dies. The server-side subscription is scoped to that
1611
+ * WebSocket session and died with it, so there is nothing left to kill — and
1612
+ * by the time the reconnect handler runs, the client reports `connected`
1613
+ * again, which would otherwise send a `KILL` for a stale uuid on the *new*
1614
+ * session and hold up the restart queued behind it.
1615
+ */
1616
+ private invalidateRefLiveQuery;
1617
+ private subscribeToReconnect;
1618
+ /**
1619
+ * Whether the REMOTE SESSION currently carries `$auth.id`.
1620
+ *
1621
+ * Not the same question as `currentUserId`, and that gap is the whole point:
1622
+ * `currentUserId` is this client's own record of who signed in and survives a
1623
+ * socket drop untouched, while `$auth` lives on the WebSocket session and has
1624
+ * to be re-applied after every reconnect. Registering in the window between
1625
+ * the two is silently destructive, because `fn::query::register` sends
1626
+ * `<string>($auth.id OR '')` and the SSP stores that value write-once: the
1627
+ * view's edges then route to the global `_00_list_ref` stamped `auth_id = ''`,
1628
+ * which that table's own permission rule (`auth_id = $auth.id`) makes
1629
+ * unreadable to the very user who registered it.
1630
+ *
1631
+ * Signed-out clients answer `true`: `''` is the honest identity there, not a
1632
+ * race.
1633
+ */
1634
+ private remoteAuthEstablished;
1635
+ /**
1636
+ * Wait for the reconnected session to carry an identity again, then
1637
+ * re-register every active query and re-bind LIVE.
1638
+ *
1639
+ * Giving up without registering is deliberately better than registering
1640
+ * anyway: a registration made with no `$auth.id` produces a view its own
1641
+ * owner cannot read, and it is write-once, so it stays that way. Skipping
1642
+ * leaves the query unregistered and visibly loading, which the next
1643
+ * reconnect or heartbeat retries.
1644
+ */
1645
+ private refetchAfterReconnect;
1646
+ private startRefLiveQueries;
1647
+ private handleRemoteListRefChange;
1648
+ /**
1649
+ * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
1650
+ * `parent` set) for a `.related()` query. Unlike primary rows, child rows
1651
+ * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
1652
+ * keep the child BODY fresh in the local cache so the in-browser SSP's
1653
+ * subquery-table dependency re-materializes the parent view.
1654
+ *
1655
+ * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
1656
+ * no-op: a child leaving this query's set must not delete a body another
1657
+ * query may still show (see `syncSubqueryChildren` deletion-safety note);
1658
+ * a genuine record delete propagates via the normal delete path.
1659
+ */
1660
+ private handleRemoteSubqueryChange;
1661
+ /**
1662
+ * Enqueues a 'down' event (from remote to local) for processing.
1663
+ * @param event The DownEvent to enqueue.
1664
+ */
1665
+ enqueueDownEvent(event: DownEvent): void;
1666
+ /**
1667
+ * Bound a mutation push so it always settles.
1668
+ *
1669
+ * `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
1670
+ * flag only clears in the `finally` of the drain loop. A push whose RPC never
1671
+ * settles (socket dropped mid-flight, response lost) therefore wedges the
1672
+ * up-queue for the rest of the session: no retry, no error, no further
1673
+ * mutation ever sent. A timeout turns that into an ordinary network failure,
1674
+ * which `UpQueue.next` re-queues for the next trigger. The message deliberately
1675
+ * contains "timed out" so `classifySyncError` treats it as `network` and
1676
+ * retries rather than rolling the mutation back.
1677
+ */
1678
+ private withPushTimeout;
1679
+ private processUpEvent;
1680
+ /**
1681
+ * A mutation the server accepted, reported once its outbox row is gone.
1682
+ *
1683
+ * Keeps the written row in the render set until its membership arrives.
1684
+ * Without this the row is briefly in neither term of
1685
+ * `(membership ∪ pendingWrites) − pendingDeletes` — the outbox delete is
1686
+ * tied to the push, while membership waits on the SSP ingesting the row,
1687
+ * materializing the view, writing the `_00_list_ref` edge and this client
1688
+ * reading it back. The writer therefore watched its own comment appear,
1689
+ * vanish, and return, while every other client showed it throughout.
1690
+ */
1691
+ private handleMutationSettled;
1692
+ private handleRollback;
1693
+ private processDownEvent;
1694
+ private withDownTimeout;
1695
+ private runDownEvent;
1696
+ /**
1697
+ * Synchronizes a specific query by hash.
1698
+ * Compares local and remote version arrays and fetches differences.
1699
+ * @param hash The hash of the query to sync.
1700
+ */
1701
+ syncQuery(hash: string): Promise<void>;
1702
+ /**
1703
+ * Run a sync for a single query while reflecting its fetch status. Marks the
1704
+ * query `fetching` for the duration when the diff actually pulls records
1705
+ * (added/updated), then resets to `idle` in a `finally` so a failed sync
1706
+ * never leaves a query stuck `fetching`. Part A's notification coalescing
1707
+ * means the single resulting UI update lands after this completes.
1708
+ */
1709
+ private runSyncForQuery;
1710
+ /**
1711
+ * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1712
+ * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1713
+ * server's `_00_list_ref` still lists them until it's processed, and the diff
1714
+ * would otherwise resurrect a just-deleted record.
1715
+ */
1716
+ private getPendingDeleteIds;
1717
+ /**
1718
+ * Enqueues a list of mutations (up events) to be sent to the remote.
1719
+ * @param mutations Array of UpEvents (create/update/delete) to enqueue.
1720
+ */
1721
+ enqueueMutation(mutations: UpEvent[]): Promise<void>;
1722
+ /**
1723
+ * Best-effort release of THIS tab's views as the page goes away.
1724
+ *
1725
+ * Without it a closed tab's views stay materialized on the SSP for a full
1726
+ * TTL (10 minutes by default), because nothing else tears them down:
1727
+ * `releaseQueriesEagerly` is off, so the TTL sweep is the only reclaim path.
1728
+ * On a busy tenant that is a generation of live views per reload, each still
1729
+ * being stepped by every ingest, for ten minutes after the last human left.
1730
+ *
1731
+ * This is NOT `releaseQueriesEagerly` re-enabled. That released views
1732
+ * mid-session on a viewport change and tore the window out from under a live
1733
+ * page (see `cleanupQuery`); this runs only when the page itself is going
1734
+ * away and nothing is left to render.
1735
+ *
1736
+ * Safe against other tabs by construction: `fn::query::unsubscribe` drops
1737
+ * only this session from `subscribers` and deletes the row solely when it
1738
+ * was the last one, so a second tab of the same user keeps its view.
1739
+ *
1740
+ * One statement, not one per id: an unload handler gets a few milliseconds,
1741
+ * and N round trips would not survive it. Fire-and-forget — if the frame
1742
+ * does not make it out, the TTL sweep still reclaims exactly as before, so
1743
+ * the worst case is today's behaviour.
1744
+ */
1745
+ releaseViewsOnUnload(): void;
1746
+ private registerQuery;
1747
+ private createRemoteQuery;
1748
+ /**
1749
+ * Sync the BODIES of a `.related()` query's subquery child rows into the
1750
+ * local cache, separately from the primary window array. The SSP writes
1751
+ * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
1752
+ * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
1753
+ * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
1754
+ * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
1755
+ * them into the local DB AND the in-browser SSP, whose subquery-table
1756
+ * dependency then re-materializes the parent view (no explicit notify).
1757
+ *
1758
+ * Deletion safety: we pass `removed: []` deliberately. A child body can be
1759
+ * shared by other queries; letting `handleRemovedRecords` delete one that
1760
+ * merely left THIS query's child set would clobber data another query still
1761
+ * shows. Genuine record deletes flow through the normal delete path; a
1762
+ * lingering orphan body is invisible (the correlated WHERE stops matching).
1763
+ *
1764
+ * Kept off `runSyncForQuery` on purpose so child fetches never flip the
1765
+ * query to `fetching` or skew its DevTools timings.
1766
+ */
1767
+ private syncSubqueryChildren;
1768
+ heartbeatQuery(queryHash: string): Promise<void>;
1769
+ private cleanupQuery;
1770
+ }
1771
+ //#endregion
150
1772
  //#region src/modules/auth/events/index.d.ts
151
1773
  declare const AuthEventTypes: {
152
1774
  readonly AuthStateChanged: "AUTH_STATE_CHANGED";
@@ -169,6 +1791,13 @@ declare class AuthService<S extends SchemaStructure> {
169
1791
  token: string | null;
170
1792
  currentUser: any | null;
171
1793
  isAuthenticated: boolean;
1794
+ /**
1795
+ * The record-access method name for the current session (e.g. `"account"`),
1796
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
1797
+ * permission injection so `$access`-gated table predicates resolve locally,
1798
+ * mirroring the server's `$access`. Null when logged out.
1799
+ */
1800
+ access: string | null;
172
1801
  isLoading: boolean;
173
1802
  private events;
174
1803
  get eventSystem(): AuthEventSystem;
@@ -181,6 +1810,24 @@ declare class AuthService<S extends SchemaStructure> {
181
1810
  */
182
1811
  subscribe(cb: (userId: string | null) => void): () => void;
183
1812
  private notifyListeners;
1813
+ /**
1814
+ * Restore a session from the locally cached JWT, with NO network.
1815
+ *
1816
+ * This is what makes a warm boot paint instantly and what makes an offline
1817
+ * boot possible at all: the token is in local storage, and it already carries
1818
+ * both the access method and the `$auth.id` record id. Everything the client
1819
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
1820
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
1821
+ * available before a socket exists.
1822
+ *
1823
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
1824
+ * afterwards in the background and downgrades to a real sign-out if the
1825
+ * server rejects it. Nothing is trusted that the server has not also seen -
1826
+ * the local store only ever holds rows the server previously sent.
1827
+ *
1828
+ * Returns the restored user id, or null when there is no usable token.
1829
+ */
1830
+ restoreSessionFromToken(): Promise<string | null>;
184
1831
  /**
185
1832
  * Check for existing session and validate
186
1833
  */
@@ -190,17 +1837,672 @@ declare class AuthService<S extends SchemaStructure> {
190
1837
  */
191
1838
  signOut(): Promise<void>;
192
1839
  private setSession;
1840
+ /** Fallback when the token carries no `AC` claim: if the schema defines
1841
+ * exactly one record-access method, assume the session used it. */
1842
+ private defaultAccessName;
193
1843
  signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
194
1844
  signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
195
1845
  }
196
1846
  //#endregion
197
- //#region src/spooky.d.ts
1847
+ //#region src/modules/crdt/crdt-field.d.ts
1848
+ declare const CURSOR_COLORS: string[];
1849
+ declare function cursorColorFromName(name: string): string;
1850
+ declare class CrdtField {
1851
+ private fieldName;
1852
+ private doc;
1853
+ private pushTimer;
1854
+ private local;
1855
+ private remote;
1856
+ private recordId;
1857
+ private sessionId;
1858
+ private unsubscribe;
1859
+ private lastPushTime;
1860
+ private lastCursorPushTime;
1861
+ private loadedFromCrdt;
1862
+ private pushRetryCount;
1863
+ private logger;
1864
+ private cursorsEnabled;
1865
+ /** Remote-push debounce. Local writes happen immediately on every Loro
1866
+ * update; the remote UPSERT is coalesced over this window. Configured
1867
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
1868
+ private remoteDebounceMs;
1869
+ private _onCursorUpdate;
1870
+ private pendingCursorUpdate;
1871
+ /** Callback set by the editor to receive remote cursor updates.
1872
+ * Any cursor data that arrived before this callback was set will be replayed. */
1873
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
1874
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
1875
+ /**
1876
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
1877
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
1878
+ * import graph so it only ships to apps that use CRDT fields.
1879
+ */
1880
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
1881
+ getDoc(): LoroDoc;
1882
+ /** Whether the LoroDoc was loaded from saved CRDT state */
1883
+ hasContent(): boolean;
1884
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
1885
+ /**
1886
+ * Stop syncing this field. Flushes one final remote push by default so the
1887
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
1888
+ * the remote session already belongs to the NEXT user, and pushing this
1889
+ * (previous user's) snapshot under it would clobber the record remotely.
1890
+ */
1891
+ stopSync(options?: {
1892
+ flush?: boolean;
1893
+ }): void;
1894
+ importRemote(state: Uint8Array): void;
1895
+ exportSnapshot(): Uint8Array;
1896
+ /** Push this session's cursor blob into the parent row at
1897
+ * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
1898
+ * field — the editor still calls this method optimistically, but
1899
+ * without `@cursor` on the schema there's nowhere to store the blob.
1900
+ * The UPDATE itself fires the parent table's LIVE feed, so other
1901
+ * browsers receive the cursor change without a separate `_00_rv` bump. */
1902
+ pushCursorState(encoded: Uint8Array): Promise<void>;
1903
+ /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
1904
+ importRemoteCursor(base64State: string): void;
1905
+ private scheduleRemotePush;
1906
+ /** SET path inside a parent row for the current snapshot. `@crdt`-only
1907
+ * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
1908
+ * fields hold a `{ state, cursors }` object so the snapshot lives at
1909
+ * `<field>.state` next to per-session cursor blobs. */
1910
+ private statePath;
1911
+ /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
1912
+ * every local update and every remote import so reloads (online or
1913
+ * offline) see the freshest content immediately. Failures are
1914
+ * swallowed — a stale local write must never block user input. */
1915
+ private persistLocal;
1916
+ private pushToRemote;
1917
+ }
1918
+ //#endregion
1919
+ //#region src/modules/crdt/index.d.ts
1920
+ /**
1921
+ * CrdtManager manages active CrdtField instances and their sync channels.
1922
+ *
1923
+ * Collaborative state lives in two dedicated tables (defined in
1924
+ * `apps/cli/src/meta_tables_remote.surql`):
1925
+ * - `_00_crdt` { record_id, field, state } — one row per (record, field)
1926
+ * - `_00_cursor` { record_id, session_id, field, state } — one row per
1927
+ * (record, session, field)
1928
+ *
1929
+ * Splitting them off the parent row is what makes offline edits mergeable:
1930
+ * each (record, field) gets its own row, so concurrent offline writes don't
1931
+ * collide on the parent's last-write-wins semantics.
1932
+ *
1933
+ * Cross-browser delivery still rides the parent table's existing LIVE feed
1934
+ * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
1935
+ * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
1936
+ * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
1937
+ * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
1938
+ * via subquery. Permission inheritance happens server-side via
1939
+ * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
1940
+ */
1941
+ declare class CrdtManager {
1942
+ private schema;
1943
+ private local;
1944
+ private remote;
1945
+ private debounceMs;
1946
+ private fields;
1947
+ private liveByTable;
1948
+ private pendingLive;
1949
+ private staleTables;
1950
+ private connectionGeneration;
1951
+ private connectionUnsubscribes;
1952
+ private logger;
1953
+ private sessionId;
1954
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
1955
+ /**
1956
+ * Re-establish table LIVEs after a socket drop.
1957
+ *
1958
+ * A LIVE subscription lives and dies with its WebSocket session, and
1959
+ * `ensureTableSubscription` is memoized on `liveByTable` — so without this,
1960
+ * the first reconnect leaves CRDT realtime permanently dead: the map still
1961
+ * holds a uuid for a subscription the server has forgotten, so every later
1962
+ * `open()` short-circuits and no LIVE is ever re-issued.
1963
+ *
1964
+ * Both drop events matter: the SDK publishes `reconnecting` (not
1965
+ * `disconnected`) when it intends to recover on its own, and `disconnected`
1966
+ * only once it has given up.
1967
+ */
1968
+ private subscribeToReconnect;
1969
+ /** Stop observing transport events. Separate from {@link closeAll}, which also
1970
+ * runs on a bucket switch where the manager keeps being used. */
1971
+ dispose(): void;
1972
+ private hasOpenFieldFor;
1973
+ /** Set the session id that scopes this client's cursor entries. Must be
1974
+ * called before `open()` for cursors to be pushed under a stable key.
1975
+ * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
1976
+ * for the data-module salt). */
1977
+ setSessionId(sessionId: string): void;
1978
+ /**
1979
+ * Open a CRDT field for collaborative editing.
1980
+ *
1981
+ * @param table - Table name
1982
+ * @param recordId - Full record ID (e.g., "thread:abc")
1983
+ * @param field - Field name (e.g., "title", "content")
1984
+ * @param fallbackText - Current plain text from the record, used to seed the
1985
+ * LoroDoc if no CRDT state exists yet (migration path)
1986
+ */
1987
+ open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
1988
+ close(table: string, recordId: string, field: string): void;
1989
+ /**
1990
+ * Close every open field + table LIVE. Fields flush a final remote push by
1991
+ * default; pass `{ flush: false }` on a bucket switch, where that flush
1992
+ * would push the previous user's snapshot under the next user's session.
1993
+ */
1994
+ closeAll(options?: {
1995
+ flush?: boolean;
1996
+ }): void;
1997
+ /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
1998
+ * every open CrdtField on `table`. */
1999
+ private ensureTableSubscription;
2000
+ /** Apply a parent-row payload from a non-LIVE source (e.g. the
2001
+ * list_ref-driven sync engine, when the cross-user LIVE on the
2002
+ * parent table is filtered out by the SurrealDB cross-session
2003
+ * permission gap). Same semantics as the internal `dispatchRow`. */
2004
+ applyRow(table: string, row: Record<string, unknown>): void;
2005
+ /** Dispatch a parent-row LIVE event to every open CrdtField on that
2006
+ * record. Each open field reads its slice of the row directly — the
2007
+ * CRDT snapshot is a column on the parent now, so there is no
2008
+ * follow-up subquery. */
2009
+ private dispatchRow;
2010
+ /** One-shot remote fetch for a row whose CRDT field hasn't synced
2011
+ * locally yet (fresh device, memory-backed local DB after reload, …).
2012
+ * Used by `open()` when the local read came up empty. Subsequent
2013
+ * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
2014
+ private fetchAndDispatchRow;
2015
+ /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
2016
+ * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
2017
+ private fieldHasCursor;
2018
+ /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
2019
+ * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
2020
+ * `{ state, cursors }` where `state` carries the snapshot bytes. */
2021
+ private extractSnapshot;
2022
+ private killTableSubscription;
2023
+ private makeKey;
2024
+ /**
2025
+ * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
2026
+ * typos, removed annotations, and stale schema codegen at the call site instead
2027
+ * of silently producing a non-CRDT writer.
2028
+ */
2029
+ private assertCrdtField;
2030
+ }
2031
+ //#endregion
2032
+ //#region src/modules/feature-flag/index.d.ts
2033
+ interface FeatureFlagSnapshot {
2034
+ variant: string | undefined;
2035
+ payload: unknown | undefined;
2036
+ }
2037
+ interface FeatureFlagOptions {
2038
+ fallback?: string;
2039
+ ttl?: QueryTimeToLive;
2040
+ }
2041
+ /**
2042
+ * A locally forced variant. Applies to THIS browser only and is never sent to
2043
+ * the server — the assignment in `_00_user_feature` is untouched, so clearing
2044
+ * the override restores whatever the server says.
2045
+ */
2046
+ interface FeatureFlagOverride {
2047
+ variant: string;
2048
+ payload?: unknown;
2049
+ }
2050
+ declare class FeatureFlagHandle {
2051
+ readonly key: string;
2052
+ readonly fallback: string | undefined;
2053
+ private latest;
2054
+ private listeners;
2055
+ private unsubscribeFn;
2056
+ private onCloseFn;
2057
+ private closed;
2058
+ constructor(key: string, fallback: string | undefined);
2059
+ attach(unsubscribe: () => void): void;
2060
+ detach(): void;
2061
+ set(snapshot: FeatureFlagSnapshot): void;
2062
+ variant(): string | undefined;
2063
+ payload<T = unknown>(): T | undefined;
2064
+ enabled(): boolean;
2065
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
2066
+ onClose(cb: () => void): void;
2067
+ close(): void;
2068
+ }
2069
+ interface FeatureFlagModuleDeps<S extends SchemaStructure> {
2070
+ dataModule: DataModule<S>;
2071
+ sync: Sp00kySync<S>;
2072
+ auth: AuthService<S>;
2073
+ logger: Logger$1;
2074
+ }
2075
+ declare class FeatureFlagModule<S extends SchemaStructure> {
2076
+ private deps;
2077
+ private logger;
2078
+ private handles;
2079
+ private authUnsubscribe;
2080
+ private lastUserId;
2081
+ private querySubscription;
2082
+ private starting;
2083
+ private ttl;
2084
+ private snapshots;
2085
+ private loaded;
2086
+ private overrides;
2087
+ constructor(deps: FeatureFlagModuleDeps<S>);
2088
+ init(): void;
2089
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2090
+ closeAll(): Promise<void>;
2091
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
2092
+ private refresh;
2093
+ private teardownQuery;
2094
+ /** Start the single shared live query (idempotent; no-op with no handles). */
2095
+ private ensureStarted;
2096
+ /** Live query result → per-key snapshots → push to every active handle. */
2097
+ private applyRecords;
2098
+ /**
2099
+ * Force `key` to `variant` in THIS browser. Pass `null` to clear.
2100
+ *
2101
+ * Nothing is written to the server: the `_00_user_feature` assignment is
2102
+ * untouched, so clearing restores whatever the server says. Persisted to
2103
+ * localStorage on the page origin, so it survives a reload.
2104
+ */
2105
+ setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
2106
+ clearLocalOverrides(): void;
2107
+ getLocalOverrides(): Record<string, FeatureFlagOverride>;
2108
+ /** The assignment for `key`, with any local override taking precedence. */
2109
+ private resolve;
2110
+ private pushAll;
2111
+ private loadOverrides;
2112
+ private persistOverrides;
2113
+ }
2114
+ //#endregion
2115
+ //#region src/modules/app-release/index.d.ts
2116
+ interface AppReleaseSnapshot {
2117
+ /** Latest announced version for the app, or undefined when no row exists. */
2118
+ version: string | undefined;
2119
+ /** Clients should clear SW/caches when reloading onto this version. */
2120
+ cacheBust: boolean;
2121
+ /** Clients should reload/update immediately instead of asking. */
2122
+ mandatory: boolean;
2123
+ releasedAt: string | undefined;
2124
+ }
2125
+ interface AppReleaseOptions {
2126
+ ttl?: QueryTimeToLive;
2127
+ }
2128
+ declare class AppReleaseHandle {
2129
+ readonly app: string;
2130
+ private latest;
2131
+ private listeners;
2132
+ private onCloseFn;
2133
+ private closed;
2134
+ constructor(app: string);
2135
+ set(snapshot: AppReleaseSnapshot): void;
2136
+ snapshot(): AppReleaseSnapshot;
2137
+ version(): string | undefined;
2138
+ /** True when the announced version is semver-newer than `currentVersion`. */
2139
+ updateAvailable(currentVersion: string): boolean;
2140
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
2141
+ onClose(cb: () => void): void;
2142
+ close(): void;
2143
+ }
2144
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
2145
+ dataModule: DataModule<S>;
2146
+ sync: Sp00kySync<S>;
2147
+ auth: AuthService<S>;
2148
+ logger: Logger$1;
2149
+ }
2150
+ declare class AppReleaseModule<S extends SchemaStructure> {
2151
+ private deps;
2152
+ private logger;
2153
+ private handles;
2154
+ private authUnsubscribe;
2155
+ private lastUserId;
2156
+ private querySubscription;
2157
+ private starting;
2158
+ private ttl;
2159
+ private snapshots;
2160
+ private loaded;
2161
+ constructor(deps: AppReleaseModuleDeps<S>);
2162
+ init(): void;
2163
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2164
+ closeAll(): Promise<void>;
2165
+ private refresh;
2166
+ private teardownQuery;
2167
+ private ensureStarted;
2168
+ private applyRecords;
2169
+ }
2170
+ //#endregion
2171
+ //#region src/services/blobs/blob-store.d.ts
2172
+ /**
2173
+ * Byte storage for cached bucket files.
2174
+ *
2175
+ * The default implementation is OPFS. Bucket files never arrive over HTTP in
2176
+ * this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
2177
+ * neither the browser's HTTP cache nor the Cache API can hold them. We persist
2178
+ * the bytes ourselves, and OPFS is the cheapest place to put them: a read is
2179
+ * `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
2180
+ * without ever moving the bytes through the JS heap.
2181
+ *
2182
+ * Layout is real nested directories rather than one hashed filename:
2183
+ *
2184
+ * sp00ky-blobs/<namespace>/<bucket>/<...path segments>
2185
+ *
2186
+ * That costs a `getDirectoryHandle` per segment on write, and buys the property
2187
+ * the whole orphan story rests on: the full `(bucket, path)` key is recoverable
2188
+ * from a directory walk alone. The `_00_blob` manifest can therefore be wiped
2189
+ * (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
2190
+ * rebuilt from disk instead of taking the cached bytes down with it.
2191
+ */
2192
+ /** Identifies one cached file: the bucket it lives in and its path within. */
2193
+ interface BlobKey {
2194
+ bucket: string;
2195
+ path: string;
2196
+ }
2197
+ /** What a directory walk can tell us about a stored file, with no manifest. */
2198
+ interface BlobStat {
2199
+ key: BlobKey;
2200
+ size: number;
2201
+ /** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
2202
+ mtime: number;
2203
+ }
2204
+ interface BlobStore {
2205
+ /** False for {@link MemoryBlobStore} and for OPFS-less environments: the
2206
+ * cache still dedupes and serves within a tab, but nothing survives reload. */
2207
+ readonly persistent: boolean;
2208
+ /** Namespace (the local bucketId) all keys are resolved under. */
2209
+ readonly namespace: string;
2210
+ read(key: BlobKey): Promise<Blob | null>;
2211
+ /** Returns the number of bytes written. Throws on quota exhaustion. */
2212
+ write(key: BlobKey, bytes: Blob): Promise<number>;
2213
+ remove(key: BlobKey): Promise<void>;
2214
+ /** Every committed file under the current namespace. Sweeps torn writes. */
2215
+ list(): Promise<BlobStat[]>;
2216
+ /** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
2217
+ clear(): Promise<void>;
2218
+ /** Point at another namespace. Does not touch the bytes of the old one. */
2219
+ setNamespace(namespace: string): void;
2220
+ }
2221
+ //#endregion
2222
+ //#region src/services/blobs/blob-manifest.d.ts
2223
+ interface BlobEntry {
2224
+ /** `${bucket}/${path}` — also the `_00_blob` row id. */
2225
+ id: string;
2226
+ bucket: string;
2227
+ path: string;
2228
+ size: number;
2229
+ contentType: string;
2230
+ createdAt: number;
2231
+ lastAccess: number;
2232
+ hits: number;
2233
+ /** Exempt from pressure eviction. Never expires on its own. */
2234
+ pinned: boolean;
2235
+ }
2236
+ declare class BlobManifest {
2237
+ private local;
2238
+ private entries;
2239
+ /** Ids whose in-memory state has not been written back yet. */
2240
+ private dirty;
2241
+ private removed;
2242
+ private flushing;
2243
+ constructor(local: LocalStore);
2244
+ /**
2245
+ * Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
2246
+ * this never needs a full-table scan (and therefore never needs a QueryPlan).
2247
+ * Any read failure yields an empty manifest: reconcile then rebuilds every
2248
+ * row from disk, which is exactly the desired degradation.
2249
+ */
2250
+ load(ids: string[]): Promise<void>;
2251
+ get(key: BlobKey): BlobEntry | undefined;
2252
+ getById(id: string): BlobEntry | undefined;
2253
+ all(): BlobEntry[];
2254
+ totalBytes(): number;
2255
+ pinnedBytes(): number;
2256
+ put(entry: BlobEntry): void;
2257
+ touch(id: string, now: number): void;
2258
+ setPinned(id: string, pinned: boolean): boolean;
2259
+ remove(id: string): void;
2260
+ /** Forget everything without scheduling deletes — for a bucket switch, where
2261
+ * the rows belong to the store we are leaving and must stay put. */
2262
+ reset(): void;
2263
+ hasPendingWrites(): boolean;
2264
+ /**
2265
+ * Write back pending changes. Serialized: a second concurrent flush awaits
2266
+ * the first rather than racing it into the same rows. Failures are swallowed
2267
+ * on purpose — a lost metadata write costs an LRU timestamp, and the entry is
2268
+ * rebuilt from disk on the next reconcile.
2269
+ */
2270
+ flush(): Promise<void>;
2271
+ private doFlush;
2272
+ }
2273
+ //#endregion
2274
+ //#region src/services/blobs/blob-cache.d.ts
2275
+ interface BlobUrlLease {
2276
+ url: string;
2277
+ release(): void;
2278
+ }
2279
+ interface BlobReadOptions {
2280
+ /** Write through to L1 on a miss. Default true. */
2281
+ persist?: boolean;
2282
+ /** Mark the entry exempt from pressure eviction. */
2283
+ pin?: boolean;
2284
+ /**
2285
+ * Default `'never'`: a bucket path is treated as immutable, which is how the
2286
+ * client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
2287
+ * `head()` to compare sizes before trusting L1.
2288
+ */
2289
+ revalidate?: 'never' | 'head';
2290
+ /** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
2291
+ reload?: boolean;
2292
+ }
2293
+ interface BlobCacheStats {
2294
+ entries: number;
2295
+ totalBytes: number;
2296
+ budgetBytes: number;
2297
+ pinnedBytes: number;
2298
+ evictedEntries: number;
2299
+ evictedBytes: number;
2300
+ reconciledEntries: number;
2301
+ hits: number;
2302
+ misses: number;
2303
+ persistent: boolean;
2304
+ /** True when pinned bytes alone exceed the budget: new entries stop being
2305
+ * written rather than pinned ones being thrown away. */
2306
+ persistPaused: boolean;
2307
+ }
2308
+ interface BlobCacheOptions {
2309
+ store: BlobStore;
2310
+ manifest: BlobManifest;
2311
+ /** L2 read. Resolves to null when the file does not exist remotely. */
2312
+ fetchRemote(key: BlobKey): Promise<Blob | null>;
2313
+ /** L2 metadata, for `revalidate: 'head'`. */
2314
+ headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
2315
+ logger: Logger$1;
2316
+ maxBytes: number;
2317
+ now?: () => number;
2318
+ /** Injected so the URL layer is exercisable off a DOM (node tests). */
2319
+ urls?: {
2320
+ create(blob: Blob): string;
2321
+ revoke(url: string): void;
2322
+ };
2323
+ }
2324
+ declare class BlobCache {
2325
+ private readonly store;
2326
+ private readonly manifest;
2327
+ private readonly fetchRemote;
2328
+ private readonly headRemote?;
2329
+ private readonly logger;
2330
+ private readonly now;
2331
+ private readonly urlFactory;
2332
+ private maxBytes;
2333
+ private persistPaused;
2334
+ /** Set after a quota failure survives one forced eviction. */
2335
+ private persistDisabled;
2336
+ private readonly urls;
2337
+ /** Ids at zero references, oldest first — the hot-URL window. */
2338
+ private idleUrls;
2339
+ private readonly inflight;
2340
+ private flushTimer;
2341
+ private readonly onPageHide;
2342
+ /**
2343
+ * Resolves once the manifest has been reconciled against disk. Reads await
2344
+ * it, so `start()` does NOT have to be awaited on the boot path — blocking
2345
+ * boot on an OPFS directory walk delayed the WebSocket connect (and with it
2346
+ * the connection supervisor) for no benefit.
2347
+ */
2348
+ private ready;
2349
+ private hits;
2350
+ private misses;
2351
+ private evictedEntries;
2352
+ private evictedBytes;
2353
+ private reconciledEntries;
2354
+ constructor(opts: BlobCacheOptions);
2355
+ /** Coalesce manifest write-back. Metadata only, so losing the tail costs an
2356
+ * LRU timestamp that reconcile reseeds from the file mtime. */
2357
+ private scheduleFlush;
2358
+ /**
2359
+ * Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
2360
+ * Returns null when the file does not exist remotely and is not cached.
2361
+ */
2362
+ read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
2363
+ /**
2364
+ * An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
2365
+ * revoked once the last holder lets go and it falls out of the hot window.
2366
+ */
2367
+ acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
2368
+ private lease;
2369
+ private releaseUrl;
2370
+ private revokeUrl;
2371
+ /** L1 lookup with the size check that catches torn and cross-tab writes. */
2372
+ private readLocal;
2373
+ /** True when the remote agrees with the cached size, or cannot be reached. */
2374
+ private headMatches;
2375
+ private fetchDeduped;
2376
+ private persist;
2377
+ private writeThrough;
2378
+ /** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
2379
+ invalidate(key: BlobKey): Promise<void>;
2380
+ private dropLocal;
2381
+ setPinned(key: BlobKey, pinned: boolean): void;
2382
+ /**
2383
+ * Bring total bytes under budget by dropping the least recently used
2384
+ * entries. Pinned entries and anything with a live object URL are skipped —
2385
+ * evicting bytes that a mounted `<img>` is displaying would blank it.
2386
+ */
2387
+ private enforceBudget;
2388
+ /** Evict LRU-first until at or below `target`. Returns the resulting total. */
2389
+ private evictTo;
2390
+ /**
2391
+ * Rebuild the manifest from what is actually on disk. OPFS wins on existence
2392
+ * in both directions: files with no row get a row (seeded from mtime), rows
2393
+ * are only loaded for files that exist, and torn `.part-` writes are swept by
2394
+ * the walk itself.
2395
+ *
2396
+ * Rows whose file vanished outside our control (a browser origin eviction)
2397
+ * are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
2398
+ * found on disk — and are overwritten if that path is cached again.
2399
+ */
2400
+ reconcile(): Promise<void>;
2401
+ /** Warm the cache for offline use. Skips anything already cached. */
2402
+ prefetch(keys: BlobKey[]): Promise<void>;
2403
+ /** Bind to the boot bucket and hydrate the manifest from disk. Separate from
2404
+ * {@link setNamespace} because boot must reconcile even when the namespace
2405
+ * it lands on is the one the store was constructed with. */
2406
+ start(namespace: string): Promise<void>;
2407
+ /** Repoint at another local bucket. The bytes of the old one stay on disk so
2408
+ * switching back (or signing back in) is still warm. */
2409
+ setNamespace(namespace: string): Promise<void>;
2410
+ setMaxBytes(maxBytes: number): void;
2411
+ /** Delete every cached byte in the current namespace. */
2412
+ clear(): Promise<void>;
2413
+ flush(): Promise<void>;
2414
+ /** Flush metadata and drop every object URL. Must run before the local store
2415
+ * closes — the flush writes through it. */
2416
+ close(): Promise<void>;
2417
+ stats(): BlobCacheStats;
2418
+ }
2419
+ //#endregion
2420
+ //#region src/utils/blurhash.d.ts
2421
+ /**
2422
+ * Blurhash generation settings. `true` enables with the defaults below, `false`
2423
+ * disables. Resolution order for a put: per-call option > client config >
2424
+ * default ON. See {@link Sp00kyConfig.blurhash}.
2425
+ */
2426
+ type BlurhashSetting = boolean | BlurhashEncodeOptions;
2427
+ interface BlurhashEncodeOptions {
2428
+ /** Horizontal detail components, 1-9. Defaults to 4. */
2429
+ componentX?: number;
2430
+ /** Vertical detail components, 1-9. Defaults to 3. */
2431
+ componentY?: number;
2432
+ }
2433
+ /**
2434
+ * Where an image's blurhash lives: a tiny sidecar object in the same bucket.
2435
+ * Buckets have no per-object metadata channel (`put` is just `.put($content)`),
2436
+ * so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
2437
+ */
2438
+ declare function blurhashSidecarPath(path: string): string;
2439
+ /** Extensions `bucket.put` treats as images worth hashing. */
2440
+ declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
2441
+ declare function isImagePath(path: string): boolean;
2442
+ /**
2443
+ * Decode `content` as an image and compute its blurhash. Browser-only: returns
2444
+ * null (never throws) when image decoding is unavailable (node, workers without
2445
+ * canvas), when the bytes are not a decodable image, or on any other failure —
2446
+ * a missing hash must never break the upload that triggered it.
2447
+ */
2448
+ declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
2449
+ //#endregion
2450
+ //#region src/sp00ky.d.ts
2451
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
2452
+ declare function bucketContentToBlob(content: unknown): Blob | null;
2453
+ interface BucketPutOptions {
2454
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
2455
+ blurhash?: BlurhashSetting;
2456
+ }
2457
+ interface BucketPutResult {
2458
+ /** The computed blurhash when the content was a hashable image; else null. */
2459
+ blurhash: string | null;
2460
+ }
2461
+ interface BucketHandleSettings {
2462
+ blurhash?: BlurhashSetting;
2463
+ logger?: {
2464
+ warn: (obj: unknown, msg?: string) => void;
2465
+ };
2466
+ }
198
2467
  declare class BucketHandle {
199
2468
  private bucketName;
200
2469
  private remote;
201
- constructor(bucketName: string, remote: RemoteDatabaseService);
202
- put(path: string, content: string | Uint8Array | Blob): Promise<void>;
2470
+ /** Absent on the raw handle the cache itself reads through. */
2471
+ private blobs?;
2472
+ private settings?;
2473
+ constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
2474
+ blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined);
2475
+ /** Effective blurhash setting: per-call option > client config > default ON. */
2476
+ private resolveBlurhash;
2477
+ put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
2478
+ /**
2479
+ * The blurhash stored alongside an uploaded image (see
2480
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
2481
+ * blob cache, so a warm client answers from OPFS without a network hop, and
2482
+ * misses are remembered per tab so a hashless image costs at most one
2483
+ * serialized remote read per session.
2484
+ */
2485
+ blurhash(path: string): Promise<string | null>;
203
2486
  get(path: string): Promise<unknown>;
2487
+ /**
2488
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
2489
+ * {@link get} this survives a reload and works offline. Returns null when the
2490
+ * file exists in neither place.
2491
+ */
2492
+ read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
2493
+ /**
2494
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
2495
+ * MUST call `release()` when the URL goes off screen. Returns null when the
2496
+ * file does not exist, or when object URLs are unavailable (non-browser).
2497
+ */
2498
+ url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
2499
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
2500
+ pin(path: string): void;
2501
+ unpin(path: string): void;
2502
+ /** Drop `path` from the local cache without touching the remote file. */
2503
+ evict(path: string): Promise<void>;
2504
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
2505
+ prefetch(paths: string[]): Promise<void>;
204
2506
  delete(path: string): Promise<void>;
205
2507
  exists(path: string): Promise<boolean>;
206
2508
  head(path: string): Promise<Record<string, unknown>>;
@@ -208,55 +2510,345 @@ declare class BucketHandle {
208
2510
  rename(sourcePath: string, targetPath: string): Promise<void>;
209
2511
  list(prefix?: string): Promise<string[]>;
210
2512
  }
211
- declare class SpookyClient<S extends SchemaStructure> {
2513
+ declare class Sp00kyClient<S extends SchemaStructure> {
212
2514
  private config;
213
2515
  private local;
214
2516
  private remote;
2517
+ private blobs;
2518
+ private connectionSupervisor;
215
2519
  private persistenceClient;
216
2520
  private migrator;
217
2521
  private cache;
218
2522
  private dataModule;
219
2523
  private sync;
220
2524
  private devTools;
2525
+ private crdtManager;
2526
+ /**
2527
+ * True once the LOCAL half of boot is done and the client can serve reads
2528
+ * from the local store. Distinct from being connected: `syncHealth` covers
2529
+ * reaching the server and `storageHealth` covers whether the local store is
2530
+ * durable, but neither says "usable". Consumers gate their first paint on
2531
+ * this, which is what makes a warm boot instant and an offline boot possible.
2532
+ */
2533
+ private localReady;
2534
+ private saltUserId;
2535
+ private featureFlags;
2536
+ private appReleases;
2537
+ private preloadedHashes;
2538
+ private pendingQueryInits;
221
2539
  private logger;
222
2540
  auth: AuthService<S>;
223
2541
  streamProcessor: StreamProcessorService;
224
- get remoteClient(): Surreal;
225
- get localClient(): Surreal;
2542
+ private tabsCoordinator;
2543
+ private sharedActive;
2544
+ /** Current shared-tabs role, or null when the feature is off/fell back. */
2545
+ get tabRole(): TabRole | null;
2546
+ get remoteClient(): surrealdb0.Surreal;
2547
+ get localClient(): unknown;
226
2548
  get pendingMutationCount(): number;
2549
+ /** Number of times the initial list_ref LIVE subscription retried on
2550
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
2551
+ * pre-emptive user-table creation got there first; >0 when LIVE
2552
+ * registration hit a "table not found" race. Exposed so the e2e
2553
+ * suite can guard the pre-emptive path against regression. */
2554
+ get liveRetryCount(): number;
227
2555
  subscribeToPendingMutations(cb: (count: number) => void): () => void;
228
- constructor(config: SpookyConfig<S>);
2556
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
2557
+ get syncHealth(): SyncHealth;
2558
+ /**
2559
+ * Observe sync health. Fires immediately with the current status and again
2560
+ * on every healthy↔degraded transition. Returns an unsubscribe.
2561
+ */
2562
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2563
+ /** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
2564
+ * engines that don't report it. */
2565
+ get storageHealth(): StorageHealth;
2566
+ /**
2567
+ * Observe local-store durability. Fires immediately with the current snapshot
2568
+ * and again on every change (at most once per bucket open in practice).
2569
+ * Returns an unsubscribe.
2570
+ */
2571
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2572
+ constructor(config: Sp00kyConfig<S>);
2573
+ /** The shared-tabs role machinery, wired to this client's modules. */
2574
+ private buildTabsCoordinator;
229
2575
  /**
230
2576
  * Setup direct callbacks instead of event subscriptions
231
2577
  */
232
2578
  private setupCallbacks;
233
2579
  init(): Promise<void>;
2580
+ /**
2581
+ * The network half of boot: connect, verify the restored session, and let the
2582
+ * sync engine catch up. Runs in the background after `init()` has already
2583
+ * resolved, so nothing here is on the paint path.
2584
+ *
2585
+ * Every step is best-effort. A failure leaves the client in exactly the state
2586
+ * a warm offline boot is in - local reads working, writes queued in the
2587
+ * outbox - and the connection supervisor keeps retrying underneath.
2588
+ */
2589
+ private initRemote;
2590
+ /**
2591
+ * Write the signed-in user's own row, as the SERVER just returned it, into
2592
+ * the local store.
2593
+ *
2594
+ * `AuthService.check()` (boot verification, sign-in, an app-driven refresh)
2595
+ * runs `SELECT * FROM ONLY $auth.id` and keeps the answer on
2596
+ * `auth.currentUser`; nothing consumed it beyond the id. Meanwhile the app's
2597
+ * own `user` query paints local-first from whatever body the store holds,
2598
+ * and that body is only refreshed when the server's row version reaches
2599
+ * this client through membership (`_00_list_ref`). While the SSP is down or
2600
+ * bootstrapping that never happens, so a device that registered before the
2601
+ * account was verified kept rendering a row without `email_verified` and
2602
+ * the app parked the user on "Verify your email" over a server that said
2603
+ * "already verified". The authoritative row was already in hand.
2604
+ *
2605
+ * MERGE semantics (`CacheModule.saveBatch`) keep local-only fields, and
2606
+ * re-using the memoized version keeps the sync dedup honest: this is a
2607
+ * field refresh, not a version claim. `notifyTableQueries` re-materializes
2608
+ * the `user` queries so the gate flips without waiting for a stream update.
2609
+ * Best-effort: a failure here leaves things exactly as they were.
2610
+ */
2611
+ private persistVerifiedUser;
2612
+ private bucketSwitchChain;
2613
+ private pendingBucketTarget;
2614
+ /**
2615
+ * Ensure the local store is this user's bucket, switching if needed. Called
2616
+ * from the auth listener on every auth flip; concurrent calls are chained
2617
+ * and superseded intermediates are skipped (latest target wins).
2618
+ */
2619
+ private ensureLocalBucket;
2620
+ /**
2621
+ * The bucket-switch choreography: drain → swap → rebind.
2622
+ *
2623
+ * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
2624
+ * outbox delete lands in the OLD bucket, debounce timers cancelled),
2625
+ * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
2626
+ * (the remote session already belongs to the next user).
2627
+ *
2628
+ * Swap: gate closes so any local query issued mid-switch (sibling auth
2629
+ * subscribers, FeatureFlagModule) waits and then runs against the NEW
2630
+ * bucket; store swaps open-new-before-close-old; schema provisions
2631
+ * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
2632
+ * sessionId-salted hashes with stale arrays — record bodies stay warm);
2633
+ * SSP resets to a fresh circuit with re-seeded permissions.
2634
+ *
2635
+ * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
2636
+ * into the OLD bucket's `_00_kv` before this listener ran), active queries
2637
+ * re-homed keeping their hashes, sync resumed on the new bucket's own
2638
+ * outbox, and every query re-registered remotely to refill from the server.
2639
+ */
2640
+ private doSwitchBucket;
2641
+ /** Removes the `pagehide` listener installed in `init`; see `close`. */
2642
+ private detachUnloadRelease;
234
2643
  close(): Promise<void>;
2644
+ /**
2645
+ * Subscribe to a feature flag for the current user. Returns a
2646
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
2647
+ * accessors reflect the latest assignment from `_00_user_feature`,
2648
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
2649
+ *
2650
+ * Permissions are enforced by SurrealDB: a client can only ever see
2651
+ * its own row, and cannot create or modify assignments.
2652
+ */
2653
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2654
+ /**
2655
+ * Force a feature flag to `variant` in THIS browser only; `null` clears it.
2656
+ *
2657
+ * Nothing is sent to the server — the `_00_user_feature` assignment is
2658
+ * untouched, so clearing restores whatever the server says. Persisted to
2659
+ * localStorage, survives reloads, and applies while signed out. Backs the
2660
+ * DevTools Access tab, and is a convenient hook for tests.
2661
+ *
2662
+ * To change a flag for OTHER users you need admin rights (`spky admin add`)
2663
+ * and the DevTools Access tab, or `spky flag`.
2664
+ */
2665
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2666
+ /** Drop every local feature flag override set via `setFeatureOverride`. */
2667
+ clearFeatureOverrides(): void;
2668
+ /** The local feature flag overrides currently in effect, keyed by flag. */
2669
+ getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2670
+ /**
2671
+ * Observe the announced release of an app (`_00_app_release:<app>`, written
2672
+ * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
2673
+ * announced version plus the cache-bust/mandatory flags, and
2674
+ * `updateAvailable(currentVersion)` compares it semver-wise against the
2675
+ * running build. World-readable; writes are root-only.
2676
+ */
2677
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
235
2678
  authenticate(token: string): Promise<surrealdb0.Tokens>;
2679
+ /**
2680
+ * Open a CRDT field for collaborative editing.
2681
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
2682
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
2683
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
2684
+ */
2685
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2686
+ /**
2687
+ * Close a CRDT field when editing is done.
2688
+ */
2689
+ closeCrdtField(table: string, recordId: string, field: string): void;
236
2690
  deauthenticate(): Promise<void>;
237
- query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, SpookyQueryResultPromise>;
2691
+ query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
238
2692
  private initQuery;
2693
+ /**
2694
+ * Background tail of {@link initQuery}: instant-hydrate (opt-in via
2695
+ * `config.instantHydrate`, and only when the query is cold) followed by
2696
+ * enqueuing the `register` down-event. Never rejects — both halves catch and
2697
+ * log, so `void`-ing the returned promise can't produce an unhandled
2698
+ * rejection. By default (hydrate off) the register lifecycle is the single
2699
+ * freshness path; the one-shot fetch is an optimization apps enable
2700
+ * explicitly, and it runs regardless of preload state — cache-first delivery
2701
+ * never depends on WHY rows are cached.
2702
+ */
2703
+ private finishQueryInit;
2704
+ /**
2705
+ * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
2706
+ * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
2707
+ *
2708
+ * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
2709
+ * - COLD (never preloaded in this bucket): fetch the query one-shot from the
2710
+ * remote, persist the rows (+ embedded `.related()` children), stamp the
2711
+ * marker — and AWAIT it. This is the "smart waiting" first load: callers can
2712
+ * `await db.preload(...)` to hold the UI until the data is ready.
2713
+ * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
2714
+ * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
2715
+ * Default `onUse` does nothing; the data freshens when the real `useQuery`
2716
+ * mounts and registers its live view.
2717
+ *
2718
+ * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
2719
+ * written, so it's retried next load). Deduped per session by query hash.
2720
+ */
2721
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
2722
+ /**
2723
+ * One-shot remote fetch + local persist for a preload query. Returns the row
2724
+ * count on success, or -1 on failure (best-effort: logged, never thrown) so
2725
+ * the caller skips stamping the freshness marker and retries next load.
2726
+ */
2727
+ private fetchAndPersist;
239
2728
  queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
240
2729
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
241
2730
  immediate?: boolean;
242
2731
  }): Promise<() => void>;
2732
+ /**
2733
+ * Opt-in eager teardown for a query whose last subscriber has gone away
2734
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
2735
+ * while any subscriber remains. Tears down the remote `_00_query` view +
2736
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
2737
+ * (no call here) keeps the view resident for cheap re-subscription.
2738
+ */
2739
+ deregisterQuery(queryHash: string): void;
2740
+ /**
2741
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
2742
+ * `{ immediate: true }` the callback fires synchronously with the current
2743
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
2744
+ */
2745
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
2746
+ immediate?: boolean;
2747
+ }): () => void;
2748
+ /**
2749
+ * Report the frontend processing time (ms) a client framework spent applying
2750
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
2751
+ * surface the "frontend" phase of the per-query timing breakdown.
2752
+ */
2753
+ reportFrontendTiming(queryHash: string, ms: number): void;
243
2754
  run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
244
2755
  bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2756
+ /** Cache-free handle. The blob cache reads the remote through this, so a
2757
+ * cache miss can't loop back into the cache. */
2758
+ private rawBucket;
2759
+ /** Blob cache counters for DevTools. */
2760
+ getBlobCacheStats(): BlobCacheStats;
245
2761
  create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
246
2762
  update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
247
2763
  [x: string]: /*elided*/any;
248
2764
  }>;
249
2765
  delete(table: string, id: string): Promise<void>;
2766
+ /**
2767
+ * Whether the local store is initialized and reads can be served. See the
2768
+ * `localReady` field: this is deliberately independent of connectivity.
2769
+ */
2770
+ isLocalReady(): boolean;
250
2771
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
251
- private persistClientId;
252
- private loadOrGenerateClientId;
2772
+ /**
2773
+ * Mint the salt used for query-id hashing, so two sessions registering the
2774
+ * same logical query get distinct `_00_query` rows.
2775
+ *
2776
+ * Generated LOCALLY, deliberately. This used to be `RETURN <string>session::id()`,
2777
+ * which cost a serial round trip on the critical boot path and resolved to
2778
+ * `''` offline. The value never needed to come from the server: the server
2779
+ * derives its own `clientId` inside `fn::query::register` and *ignores*
2780
+ * whatever the caller passed, and the permission rules that matter gate on
2781
+ * `auth_id = $auth.id` rather than the session (`_00_list_ref`). Session
2782
+ * scoping via `clientId = session::id()` was in fact removed upstream because
2783
+ * it broke a user with two tabs open. All this value has to be is unique per
2784
+ * browser session, which `randomUUID` gives us for free and offline.
2785
+ */
2786
+ /**
2787
+ * The current principal as the `"table:id"` string the in-browser SSP wants
2788
+ * for `$auth.id`, or null when signed out.
2789
+ *
2790
+ * Tolerates BOTH shapes `currentUser.id` can take, which is the point:
2791
+ * a session restored from the cached token carries a plain string (the JWT's
2792
+ * `ID` claim), while one verified by the server carries a RecordId. Passing
2793
+ * the former to `encodeRecordId` reads `.table` off a string and throws
2794
+ * during boot.
2795
+ */
2796
+ /**
2797
+ * Prime the in-browser circuit from the local store. Builds the context the
2798
+ * stream processor needs: every synced table (the app schema plus the
2799
+ * server-written meta tables that sync down), a schema hash so a snapshot
2800
+ * projected under another schema is not trusted, and the ids whose local
2801
+ * `_00_rv` was bumped by an unsettled mutation.
2802
+ */
2803
+ private primeCircuit;
2804
+ private sessionAuthId;
2805
+ private mintSessionSalt;
253
2806
  }
254
2807
  //#endregion
2808
+ //#region src/utils/semver.d.ts
2809
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
2810
+ declare function semverGt(a: unknown, b: unknown): boolean;
2811
+ //#endregion
2812
+ //#region src/services/database/errors.d.ts
2813
+ /**
2814
+ * A local-store operation that did not answer within its deadline.
2815
+ *
2816
+ * The local write path (`db.create` / `db.update` / `db.delete`, every local
2817
+ * query behind them) used to have no deadline anywhere: the SQLite worker
2818
+ * transport parks a call until the worker replies, the surrealdb engine's
2819
+ * query chain waits on the previous link, and `withRetry` retries without a
2820
+ * clock. One op that never settled (a worker starved behind a long select, a
2821
+ * lock verification awaiting `navigator.locks.query()` forever) left the
2822
+ * caller's promise pending for the tab's lifetime - a chat composer that never
2823
+ * re-enabled, a call that never got past "Connecting".
2824
+ *
2825
+ * The message says "timed out" on purpose: `classifySyncError` keys off it and
2826
+ * treats the failure as transient (re-queue), never as an application error
2827
+ * that rolls the mutation back. `retryable: false` keeps `withRetry` from
2828
+ * spinning on it: the op is still running in the engine, retrying queues a
2829
+ * second copy behind it.
2830
+ */
2831
+ declare class LocalOpTimeoutError extends Error {
2832
+ readonly name = "LocalOpTimeoutError";
2833
+ readonly retryable = false;
2834
+ readonly op: string;
2835
+ readonly timeoutMs: number;
2836
+ constructor(op: string, timeoutMs: number);
2837
+ }
2838
+ /** Default deadline for one local-store operation. Generous: a cold 4k-row
2839
+ * select on a throttled tab is seconds, not tens of seconds. */
2840
+ declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
2841
+ //#endregion
255
2842
  //#region src/utils/index.d.ts
256
2843
  declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
2844
+ /**
2845
+ * Convert plain text to simple HTML paragraphs.
2846
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
2847
+ */
2848
+ declare function textToHtml(text: string): string;
257
2849
  /**
258
2850
  * Helper for retrying DB operations with exponential backoff
259
2851
  */
260
2852
 
261
2853
  //#endregion
262
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions, SpookyClient, SpookyConfig, SpookyQueryResult, SpookyQueryResultPromise, StoreType, UpdateOptions, createAuthEventSystem, fileToUint8Array };
2854
+ export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, isBlurhashValid, isImagePath, semverGt, textToHtml };