@spooky-sync/core 0.0.1-canary.21 → 0.0.1-canary.210

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 (163) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2514 -58
  3. package/dist/index.js +12561 -2449
  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 +101 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +127 -24
  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 +206 -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 +1815 -151
  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 +164 -82
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +180 -0
  65. package/src/modules/sync/queue/queue-down.ts +80 -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.subquery.test.ts +82 -0
  77. package/src/modules/sync/sync.tabs.test.ts +249 -0
  78. package/src/modules/sync/sync.ts +1726 -99
  79. package/src/modules/sync/utils.test.ts +269 -2
  80. package/src/modules/sync/utils.ts +201 -17
  81. package/src/otel/index.ts +13 -10
  82. package/src/services/blobs/blob-cache.test.ts +359 -0
  83. package/src/services/blobs/blob-cache.ts +603 -0
  84. package/src/services/blobs/blob-manifest.ts +227 -0
  85. package/src/services/blobs/blob-store.test.ts +77 -0
  86. package/src/services/blobs/blob-store.ts +359 -0
  87. package/src/services/blobs/blob.fixture.ts +90 -0
  88. package/src/services/blobs/index.ts +70 -0
  89. package/src/services/database/cache-engine.ts +193 -0
  90. package/src/services/database/connection-supervisor.test.ts +289 -0
  91. package/src/services/database/connection-supervisor.ts +415 -0
  92. package/src/services/database/database.query-timeout.test.ts +83 -0
  93. package/src/services/database/database.ts +41 -12
  94. package/src/services/database/engine-factory.ts +33 -0
  95. package/src/services/database/errors.ts +34 -0
  96. package/src/services/database/events/index.ts +2 -1
  97. package/src/services/database/index.ts +7 -0
  98. package/src/services/database/local-migrator.ts +30 -27
  99. package/src/services/database/local.test.ts +64 -0
  100. package/src/services/database/local.ts +484 -67
  101. package/src/services/database/plan-render.test.ts +159 -0
  102. package/src/services/database/plan-render.ts +108 -0
  103. package/src/services/database/relation-resolver.test.ts +413 -0
  104. package/src/services/database/relation-resolver.ts +0 -0
  105. package/src/services/database/remote.ts +110 -14
  106. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  107. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  108. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  109. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  110. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  111. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  112. package/src/services/database/sqlite-lock-verify.ts +45 -0
  113. package/src/services/database/sqlite-open.test.ts +150 -0
  114. package/src/services/database/sqlite-open.ts +164 -0
  115. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  116. package/src/services/database/sqlite-plan-sql.ts +138 -0
  117. package/src/services/database/sqlite-projection.test.ts +99 -0
  118. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  119. package/src/services/database/sqlite-select.test.ts +246 -0
  120. package/src/services/database/sqlite-select.ts +131 -0
  121. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  122. package/src/services/database/sqlite-transport.ts +224 -0
  123. package/src/services/database/sqlite-worker.ts +437 -0
  124. package/src/services/database/surql-translate.ts +416 -0
  125. package/src/services/database/surreal-cache-engine.ts +161 -0
  126. package/src/services/logger/index.ts +3 -2
  127. package/src/services/persistence/localstorage.ts +2 -2
  128. package/src/services/persistence/resilient.ts +11 -4
  129. package/src/services/persistence/surrealdb.ts +10 -10
  130. package/src/services/stream-processor/index.ts +796 -84
  131. package/src/services/stream-processor/permissions.test.ts +47 -0
  132. package/src/services/stream-processor/permissions.ts +53 -0
  133. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  134. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  135. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  136. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  137. package/src/services/stream-processor/wasm-types.ts +59 -3
  138. package/src/services/tabs/broker-client.ts +283 -0
  139. package/src/services/tabs/broker.test.ts +327 -0
  140. package/src/services/tabs/coordinator.test.ts +365 -0
  141. package/src/services/tabs/coordinator.ts +633 -0
  142. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  143. package/src/services/tabs/leader-locks.ts +75 -0
  144. package/src/services/tabs/protocol.ts +258 -0
  145. package/src/services/tabs/support.ts +36 -0
  146. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  147. package/src/sp00ky.auth-order.test.ts +92 -0
  148. package/src/sp00ky.init-query.test.ts +183 -0
  149. package/src/sp00ky.local-first.test.ts +60 -0
  150. package/src/sp00ky.ts +1693 -0
  151. package/src/types.ts +528 -13
  152. package/src/utils/blurhash.ts +90 -0
  153. package/src/utils/error-classification.test.ts +44 -0
  154. package/src/utils/error-classification.ts +7 -0
  155. package/src/utils/index.ts +79 -13
  156. package/src/utils/parser.test.ts +49 -120
  157. package/src/utils/parser.ts +32 -2
  158. package/src/utils/semver.test.ts +32 -0
  159. package/src/utils/semver.ts +30 -0
  160. package/src/utils/surql.ts +30 -18
  161. package/src/utils/withRetry.test.ts +1 -1
  162. package/tsdown.config.ts +86 -1
  163. package/src/spooky.ts +0 -395
package/src/types.ts CHANGED
@@ -1,9 +1,10 @@
1
- import { RecordId, SchemaStructure } from '@spooky-sync/query-builder';
2
- import { Level, type LoggerOptions } from 'pino';
3
- import { PushEventOptions } from './events/index';
4
- import { UpEvent } from './modules/sync/index';
1
+ import type { RecordId, SchemaStructure, QueryPlan } from '@spooky-sync/query-builder';
2
+ import type { Level, LoggerOptions } from 'pino';
3
+ import type { PushEventOptions } from './events/index';
4
+ import type { UpEvent } from './modules/sync/index';
5
+ import type { LocalEngineChoice } from './services/database/cache-engine';
5
6
 
6
- export type { Level } from 'pino';
7
+ export type { Level };
7
8
 
8
9
  /**
9
10
  * A pino browser transmit object for forwarding logs to an external sink (e.g. OpenTelemetry).
@@ -67,25 +68,43 @@ export type QueryTimeToLive =
67
68
  | '12h'
68
69
  | '1d';
69
70
 
71
+ /**
72
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
73
+ * The FIRST load (cold) always fetches + blocks regardless.
74
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
75
+ * real `useQuery` mounts and registers its live view. No network on load.
76
+ * - `background`: return instantly, but kick a one-time silent refetch.
77
+ * - `stale`: like `background`, but only if the cached copy is older than
78
+ * `staleTime`.
79
+ */
80
+ export type PreloadRefresh = 'onUse' | 'background' | 'stale';
81
+
82
+ export interface PreloadOptions {
83
+ /** How to refresh when the query is already cached locally. Default `onUse`. */
84
+ refresh?: PreloadRefresh;
85
+ /** For `refresh: 'stale'` — max age before a warm copy is refetched. Default `1h`. */
86
+ staleTime?: QueryTimeToLive;
87
+ }
88
+
70
89
  /**
71
90
  * Result object returned when a query is registered or executed.
72
91
  */
73
- export interface SpookyQueryResult {
92
+ export interface Sp00kyQueryResult {
74
93
  /** The unique hash identifier for the query. */
75
94
  hash: string;
76
95
  }
77
96
 
78
- export type SpookyQueryResultPromise = Promise<SpookyQueryResult>;
97
+ export type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
79
98
 
80
99
  export interface EventSubscriptionOptions {
81
100
  priority?: number;
82
101
  }
83
102
 
84
103
  /**
85
- * Configuration options for the Spooky client.
104
+ * Configuration options for the Sp00ky client.
86
105
  * @template S The schema structure type.
87
106
  */
88
- export interface SpookyConfig<S extends SchemaStructure> {
107
+ export interface Sp00kyConfig<S extends SchemaStructure> {
89
108
  /** Database connection configuration. */
90
109
  database: {
91
110
  /** The SurrealDB endpoint URL. */
@@ -98,9 +117,40 @@ export interface SpookyConfig<S extends SchemaStructure> {
98
117
  store?: StoreType;
99
118
  /** Authentication token. */
100
119
  token?: string;
120
+ /**
121
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
122
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
123
+ * table/relation level. Defaults to true; set false to force the legacy
124
+ * multi-hop path (escape hatch while the worker-side path beds in).
125
+ */
126
+ workerSelect?: boolean;
127
+ /**
128
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
129
+ * keep the connection alive indefinitely without configuration. See
130
+ * {@link ReconnectConfig}.
131
+ */
132
+ reconnect?: ReconnectConfig;
133
+ /**
134
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
135
+ * a single promise chain, so one call that never settles (half-open socket:
136
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
137
+ * otherwise wedge ALL later remote traffic behind it — including the sync
138
+ * poll's own health probe, leaving health pinned at `healthy` with no
139
+ * banner and no self-heal. The deadline turns that into an ordinary network
140
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
141
+ */
142
+ queryTimeoutMs?: number;
143
+ /**
144
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
145
+ * or a query on the in-process surrealdb engine). Local ops are serialized
146
+ * too, and one that never answered - a worker starved behind a long select,
147
+ * a lock verification with no clock - left every `db.create`/`db.update`
148
+ * promise pending for the tab's lifetime. On expiry the call rejects with
149
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
150
+ * not retried). `0` disables. Defaults to `30_000`.
151
+ */
152
+ localOpTimeoutMs?: number;
101
153
  };
102
- /** Unique client identifier. If not provided, one will be generated. */
103
- clientId?: string;
104
154
  /** The schema definition. */
105
155
  schema: S;
106
156
  /** The compiled SURQL schema string. */
@@ -112,13 +162,308 @@ export interface SpookyConfig<S extends SchemaStructure> {
112
162
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
113
163
  */
114
164
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
165
+ /**
166
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
167
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
168
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
169
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
170
+ * this engine. See `services/database/cache-engine.ts`.
171
+ */
172
+ localEngine?: LocalEngineChoice;
173
+ /**
174
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
175
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
176
+ * how bucket reads behaved before it existed.
177
+ *
178
+ * Nothing in this cache expires on a timer — an image whose row is still in
179
+ * the local store has to stay available offline. Bytes are only dropped when
180
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
181
+ * reconcile finds no file behind a row, or when the cache is over budget, in
182
+ * which case the least-recently-used unpinned entries go first. See
183
+ * `services/blobs/blob-cache.ts`.
184
+ */
185
+ blobCache?: {
186
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
187
+ enabled?: boolean;
188
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
189
+ * `navigator.storage.estimate()`. */
190
+ maxBytes?: number;
191
+ /**
192
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
193
+ * `false`, matching the local store: cached files are namespaced per local
194
+ * bucket, so signing back in is warm and no user can read another's cache.
195
+ * Turn on for shared devices.
196
+ */
197
+ clearOnSignOut?: boolean;
198
+ };
199
+ /**
200
+ * Share ONE durable local store across all tabs of this origin (default
201
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
202
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
203
+ * worker and the sync loop, and follower tabs read/write the same store over
204
+ * MessagePorts, so every tab is durable instead of only the first one.
205
+ *
206
+ * Falls back to solo mode (exactly the flag-off behavior, including the
207
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
208
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
209
+ * not sqlite, or the broker rejects the tab (mixed app versions).
210
+ *
211
+ * Failover: when the leader tab closes or freezes, a follower is promoted
212
+ * within seconds; queries briefly refetch and mutations are never lost once
213
+ * their local write resolved (the shared outbox survives in the store).
214
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
215
+ */
216
+ sharedTabs?: boolean;
217
+ /**
218
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
219
+ * store, so a reload restores it and only steps in what changed since.
220
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
221
+ * can hold the bytes) and `false` otherwise.
222
+ *
223
+ * Without a snapshot the circuit is primed by reading every cached row back
224
+ * out of the local store; either way a reload never re-downloads the working
225
+ * set, which is what an empty circuit used to force: every id in the
226
+ * server's list_ref classified as missing.
227
+ *
228
+ * Snapshots are store-only (views are re-registered per session) and written
229
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
230
+ * goes hidden, never per ingest or per query registration.
231
+ */
232
+ persistCircuit?: boolean;
233
+ /**
234
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
235
+ * 30000. Ignored when `persistCircuit` is off.
236
+ */
237
+ circuitCheckpointMs?: number;
238
+ /**
239
+ * Keep only the fields registered queries evaluate (filter predicates, join
240
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
241
+ * Default `true`. The circuit only ever reads those fields; bodies are
242
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
243
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
244
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
245
+ * without has that field merged in from the local store on registration.
246
+ */
247
+ circuitProjection?: boolean;
115
248
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
116
249
  otelTransmit?: PinoTransmit;
117
250
  /**
118
- * Debounce time in milliseconds for stream updates.
119
- * Defaults to 100ms.
251
+ * Debounce time in milliseconds for stream updates (the client-side SSP
252
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
253
+ * per-record updates per query before notifying readers).
254
+ * Defaults to 50ms.
120
255
  */
121
256
  streamDebounceTime?: number;
257
+ /**
258
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
259
+ * changes to the remote database. Local writes happen immediately on
260
+ * every keystroke (so reload/offline works), but the remote UPSERT is
261
+ * coalesced over this window. Lower = snappier remote propagation +
262
+ * more network traffic; higher = less traffic + more lag for other
263
+ * collaborators. Defaults to 500ms.
264
+ */
265
+ crdtDebounceMs?: number;
266
+ /**
267
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
268
+ * preloaded at client startup (fetched as a separate chunk on page load) so
269
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
270
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
271
+ * out of apps that don't use collaboration. Defaults to `false`.
272
+ */
273
+ crdt?: boolean;
274
+ /**
275
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
276
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
277
+ * convergence + more query load; higher = the inverse. Non-positive
278
+ * values fall back to the default (500ms).
279
+ */
280
+ refSyncIntervalMs?: number;
281
+ /**
282
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
283
+ * registered with no server result yet, its surql also runs directly on the
284
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
285
+ * before the full register lifecycle completes. Hydrated rows carry their
286
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
287
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
288
+ * paints from the local cache immediately — however the rows got there
289
+ * (preload, prior sync). Default `false`: the register lifecycle
290
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
291
+ * freshness path and no duplicate one-shot fetches are made.
292
+ */
293
+ instantHydrate?: boolean;
294
+ /**
295
+ * Enable realtime sync while signed out. When `true`, the client starts its
296
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
297
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
298
+ * page gets live `useQuery` updates over world-readable tables. Requires the
299
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
300
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
301
+ * one-shot but never sync live.
302
+ */
303
+ enableAnonymousLiveQueries?: boolean;
304
+ /**
305
+ * Surface sustained sync failures as a "degraded" health status that the app
306
+ * can observe via `subscribeToSyncHealth` (or the client-solid
307
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
308
+ *
309
+ * Individual failures — a transient remote 500 on query registration, a
310
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
311
+ * throw at the app. This only controls when a *run* of consecutive failures
312
+ * is reported. Status flips back to `healthy` on the next successful sync
313
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
314
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
315
+ */
316
+ syncHealth?: SyncHealthConfig | false;
317
+ /**
318
+ * Automatic blurhash placeholders for bucket image uploads. On every
319
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
320
+ * the client computes a blurhash and stores it as a tiny sidecar object
321
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
322
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
323
+ * helpers) to paint a placeholder until the image is decoded.
324
+ *
325
+ * `true` (the default) enables with 4x3 components; pass
326
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
327
+ * A per-call `put(path, content, { blurhash })` option overrides this.
328
+ */
329
+ blurhash?: boolean | { componentX?: number; componentY?: number };
330
+ /**
331
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
332
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
333
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
334
+ * settles stops every later mutation for the session, with no retry and no
335
+ * error. On expiry the push is treated as a network failure and re-queued.
336
+ * `0` disables. Defaults to `30_000`.
337
+ */
338
+ pushTimeoutMs?: number;
339
+ /**
340
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
341
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
342
+ * Defaults to 30000; `0` disables the timeout.
343
+ */
344
+ downTimeoutMs?: number;
345
+ }
346
+
347
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
348
+ export interface SyncHealthConfig {
349
+ /**
350
+ * Number of consecutive failed sync rounds (up or down) before the status
351
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
352
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
353
+ * disables degraded reporting entirely.
354
+ */
355
+ degradeAfterConsecutiveFailures?: number;
356
+ }
357
+
358
+ /**
359
+ * Tunables for WebSocket reconnect and liveness detection. See
360
+ * {@link Sp00kyConfig.database.reconnect}.
361
+ *
362
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
363
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
364
+ * supervisor above it re-opens the connection from scratch whenever the SDK
365
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
366
+ * engine permanently in that case, so a supervisor is required, not optional.
367
+ * The heartbeat covers the third case: a socket that never closes at all.
368
+ */
369
+ export interface ReconnectConfig {
370
+ /**
371
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
372
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
373
+ * ~62s outage and then gives up for the life of the page).
374
+ */
375
+ attempts?: number;
376
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
377
+ retryDelayMax?: number;
378
+ /**
379
+ * Cadence of the application-level liveness probe (`RETURN true`) that
380
+ * detects a half-open socket the transport never reports as closed.
381
+ * `0` disables the heartbeat. Defaults to `20_000`.
382
+ */
383
+ heartbeatIntervalMs?: number;
384
+ /**
385
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
386
+ * regardless of what its `readyState` claims, so the connection is torn down
387
+ * and rebuilt. Defaults to `10_000`.
388
+ */
389
+ heartbeatTimeoutMs?: number;
390
+ /**
391
+ * Cap on the supervisor's own backoff between `connect()` retries once the
392
+ * SDK has given up. Defaults to `15_000`.
393
+ */
394
+ superviseRetryDelayMaxMs?: number;
395
+ }
396
+
397
+ /**
398
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
399
+ *
400
+ * These answer different questions: `connection` is about the socket,
401
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
402
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
403
+ * usually still `healthy` for the first few seconds.
404
+ */
405
+ export type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
406
+
407
+ export type SyncHealthStatus = 'healthy' | 'degraded';
408
+
409
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
410
+ export interface SyncHealth {
411
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
412
+ status: SyncHealthStatus;
413
+ /** Consecutive failed sync rounds at the moment of this report. */
414
+ consecutiveFailures: number;
415
+ /** Classification of the most recent failure (only set while `degraded`). */
416
+ kind?: 'network' | 'application';
417
+ /** Message of the most recent failure (only set while `degraded`). */
418
+ error?: string;
419
+ /**
420
+ * `true` once at least one sync round has succeeded this session. Lets a UI
421
+ * distinguish a first-time "connecting" phase (never reached the server yet,
422
+ * so a cold-start failure run is expected) from a real lost connection after
423
+ * a working session. Never resets back to `false` once set.
424
+ */
425
+ everConnected: boolean;
426
+ /**
427
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
428
+ * one flips the instant the socket drops, whereas `status` only degrades
429
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
430
+ * immediately without waiting for the degrade threshold.
431
+ */
432
+ connection: ConnectionState;
433
+ }
434
+
435
+ export type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
436
+
437
+ /**
438
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
439
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
440
+ * server, this one is about whether the local store survives a reload.
441
+ *
442
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
443
+ * which only one client per bucket can hold open. When it can't be opened (a
444
+ * second tab of the app already has it, an insecure context, a full pool) the
445
+ * engine keeps working against an in-memory DB, which holds the whole dataset
446
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
447
+ * so a UI can warn about it.
448
+ */
449
+ export interface StorageHealth {
450
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
451
+ status: StorageHealthStatus;
452
+ /**
453
+ * `true` only when durable storage was REQUESTED and could not be opened.
454
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
455
+ * is a choice rather than a failure, so a UI can key off this alone.
456
+ */
457
+ fallback: boolean;
458
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
459
+ error?: string;
460
+ /**
461
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
462
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
463
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
464
+ * single-tab behavior. Absent entirely when the feature is off.
465
+ */
466
+ role?: 'leader' | 'follower' | 'solo';
122
467
  }
123
468
 
124
469
  export type QueryHash = string;
@@ -148,12 +493,76 @@ export interface QueryConfig {
148
493
  id: RecordId<string>;
149
494
  /** The SURQL query string. */
150
495
  surql: string;
496
+ /**
497
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
498
+ * `_00_query`). Present when the query came from the query-builder. Non-
499
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
500
+ * instead of re-running `surql`, which they cannot parse.
501
+ */
502
+ plan?: QueryPlan;
151
503
  /** Parameters used in the query. */
152
504
  params: Record<string, any>;
153
505
  /** The version array representing the local state of results. */
154
506
  localArray: RecordVersionArray;
155
507
  /** The version array representing the remote (server) state of results. */
156
508
  remoteArray: RecordVersionArray;
509
+ /**
510
+ * In-memory only (never persisted to `_00_query`): version array of the
511
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
512
+ * child-body sync is idempotent across polls. Kept separate from
513
+ * `remoteArray` so related child rows never enter the primary window /
514
+ * `rowCount` / `localArray`.
515
+ */
516
+ subqueryRemoteArray?: RecordVersionArray;
517
+ /**
518
+ * Whether authoritative membership (`remoteArray`) has ever been established
519
+ * for this query — either fetched from `_00_list_ref` this session, or read
520
+ * back from the durable `_00_window` row on a cold start.
521
+ *
522
+ * Tri-state matters: "known and empty" must render an empty list, while
523
+ * "never established" has to fall back to a predicate scan of the local store
524
+ * so a query first run on this device still paints offline. A
525
+ * `remoteArray.length === 0` check cannot tell those apart.
526
+ *
527
+ * On a cold start it is seeded from the durable `_00_window` row when that
528
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
529
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
530
+ * by an old client that mirrored unflushed reads still self-heals.
531
+ */
532
+ membershipKnown?: boolean;
533
+ /**
534
+ * Whether a NON-EMPTY id-set has arrived from the server for this query in
535
+ * this session. Gates whether an empty read may be believed.
536
+ *
537
+ * The server publishes `_00_list_ref` asynchronously — the SSP queues a
538
+ * view's initial edges to a coalescing flusher and returns from
539
+ * `fn::query::register` before they land — so an empty read right after
540
+ * registration says nothing about the query being empty. Believing it (and
541
+ * mirroring it to the durable `_00_window` row) blanked lists and kept them
542
+ * blank across reloads. Once a real set has been seen, a later empty one is a
543
+ * genuine transition and must be honoured, or removed rows resurrect.
544
+ *
545
+ * In-memory only: a fresh session must re-earn the right to believe empties.
546
+ * What does persist is the `confirmed` marker on the `_00_window` row, which
547
+ * an empty set earns when it arrives with a server row count of zero or after
548
+ * a non-empty set in the same session.
549
+ */
550
+ remoteSeen?: boolean;
551
+ /**
552
+ * Consecutive empty id-sets read from the server while `remoteSeen` is still
553
+ * false. Bounds how long an unconfirmed empty may be ignored, so a window
554
+ * that genuinely emptied while this device was away is believed on the second
555
+ * read instead of rendering stale rows forever. Reset by any non-empty set.
556
+ * In-memory only.
557
+ */
558
+ emptyReads?: number;
559
+ /**
560
+ * Key of this query's durable `_00_window` membership row: a hash of
561
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
562
+ * survives a reload (which mints a new session id) and a bucket switch.
563
+ * In-memory only.
564
+ */
565
+ membershipKey?: string;
157
566
  /** Time-To-Live for this query. */
158
567
  ttl: QueryTimeToLive;
159
568
  /** Timestamp when the query was last accessed/active. */
@@ -164,6 +573,18 @@ export interface QueryConfig {
164
573
 
165
574
  export type QueryConfigRecord = QueryConfig & { id: string };
166
575
 
576
+ /**
577
+ * Runtime fetch status of a live query.
578
+ * - `idle`: registered, initial sync completed, and not currently fetching
579
+ * missing records — the materialized rows are authoritative (a windowed
580
+ * query's short result really is the end of the list).
581
+ * - `fetching`: the query is registering (a query is born `fetching` until its
582
+ * initial remote sync completes) or the sync engine is fetching/ingesting
583
+ * missing records for it. Any pending debounced result is flushed BEFORE the
584
+ * flip back to `idle`, so idle status never races ahead of the rows.
585
+ */
586
+ export type QueryStatus = 'idle' | 'fetching';
587
+
167
588
  /**
168
589
  * Internal state of a live query.
169
590
  */
@@ -172,16 +593,103 @@ export interface QueryState {
172
593
  config: QueryConfig;
173
594
  /** The current cached records for this query. */
174
595
  records: Record<string, any>[];
596
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
597
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
598
+ hydrated?: boolean;
599
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
600
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
601
+ * always emits at least once even when its records are unchanged — otherwise
602
+ * an empty re-registered window would never notify and stay "loading". */
603
+ syncNotified?: boolean;
175
604
  /** Timer for TTL expiration. */
176
605
  ttlTimer: NodeJS.Timeout | null;
177
606
  /** TTL duration in milliseconds. */
178
607
  ttlDurationMs: number;
179
608
  /** Number of times the query has been updated. */
180
609
  updateCount: number;
610
+ /** Timestamp (ms) of the last user-visible update, or null before the first
611
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
612
+ lastUpdatedAt: number | null;
613
+ /**
614
+ * Rolling window of the most recent materialization-step latencies (ms).
615
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
616
+ * before each persist to `_00_query`. Samples themselves are not persisted.
617
+ */
618
+ materializationSamples: number[];
619
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
620
+ lastIngestLatencyMs: number | null;
621
+ /** Cumulative count of ingest/materialization errors observed for this query. */
622
+ errorCount: number;
623
+ /**
624
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
625
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
626
+ * pulling missing records for this query, otherwise `idle`.
627
+ */
628
+ status: QueryStatus;
629
+ /**
630
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
631
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
632
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
633
+ */
634
+ phaseSamples: Record<string, number[]>;
635
+ /** Most recent sample (ms) per phase, or null. */
636
+ phaseLast: Record<string, number | null>;
637
+ /** One-shot SSP registration timings (ms). */
638
+ registrationTimings: RegistrationTimings;
639
+ }
640
+
641
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
642
+ export const MATERIALIZATION_SAMPLE_WINDOW = 100;
643
+
644
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
645
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
646
+ export type TimingPhase =
647
+ | 'ssp'
648
+ | 'sspStoreApply'
649
+ | 'sspCircuitStep'
650
+ | 'sspTransform'
651
+ | 'localFetch'
652
+ | 'remoteFetch'
653
+ | 'frontend';
654
+
655
+ /** One-shot registration timings (ms), captured once when a query registers. */
656
+ export interface RegistrationTimings {
657
+ /** SSP surql→plan parse + permission injection. */
658
+ parseMs: number | null;
659
+ /** SSP operator-DAG build. */
660
+ planMs: number | null;
661
+ /** SSP initial snapshot evaluation. */
662
+ snapshotMs: number | null;
663
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
664
+ wallMs: number | null;
665
+ }
666
+
667
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
668
+ export interface PhaseStat {
669
+ lastMs: number | null;
670
+ p50: number | null;
671
+ p90: number | null;
672
+ p99: number | null;
673
+ count: number;
674
+ }
675
+
676
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
677
+ export interface QueryTimings {
678
+ ssp: PhaseStat;
679
+ sspStoreApply: PhaseStat;
680
+ sspCircuitStep: PhaseStat;
681
+ sspTransform: PhaseStat;
682
+ localFetch: PhaseStat;
683
+ remoteFetch: PhaseStat;
684
+ frontend: PhaseStat;
685
+ registration: RegistrationTimings;
686
+ updateCount: number;
687
+ errorCount: number;
181
688
  }
182
689
 
183
690
  // Callback types
184
691
  export type QueryUpdateCallback = (records: Record<string, any>[]) => void;
692
+ export type QueryStatusCallback = (status: QueryStatus) => void;
185
693
  export type MutationCallback = (mutations: UpEvent[]) => void;
186
694
 
187
695
  export type MutationEventType = 'create' | 'update' | 'delete';
@@ -214,6 +722,13 @@ export interface RunOptions {
214
722
  assignedTo?: string;
215
723
  max_retries?: number;
216
724
  retry_strategy?: 'linear' | 'exponential';
725
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
726
+ timeout?: number;
727
+ /**
728
+ * Minimum delay in milliseconds before the job is eligible to run. While
729
+ * delayed the job stays pending (enqueued) and can still be killed.
730
+ */
731
+ delay?: number;
217
732
  }
218
733
 
219
734
  /**