@spooky-sync/core 0.0.1-canary.34 → 0.0.1-canary.341

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 (269) hide show
  1. package/AGENTS.md +90 -0
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2117 -142
  4. package/dist/index.js +16436 -2575
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/otel/index.js +3 -3
  9. package/dist/pure.d.ts +389 -0
  10. package/dist/pure.js +24 -0
  11. package/dist/sqlite-open.js +392 -0
  12. package/dist/sqlite-worker.d.ts +1 -0
  13. package/dist/sqlite-worker.js +439 -0
  14. package/dist/sw.d.ts +207 -0
  15. package/dist/sw.js +393 -0
  16. package/dist/tabs-broker-worker.d.ts +8 -0
  17. package/dist/tabs-broker-worker.js +477 -0
  18. package/dist/types.d.ts +1917 -38
  19. package/dist/worker-edges.js +480 -0
  20. package/dist/worker-impersonation.js +60 -0
  21. package/dist/worker-ref-tables.d.ts +48 -0
  22. package/dist/worker-types.d.ts +112 -0
  23. package/dist/worker-types.js +73 -0
  24. package/package.json +28 -7
  25. package/scripts/check-broker-bundle.mjs +33 -0
  26. package/scripts/check-worker-entries.mjs +173 -0
  27. package/skills/sp00ky-core/SKILL.md +37 -7
  28. package/skills/sp00ky-core/references/config.md +7 -1
  29. package/src/boot/auth-flip.saga.test.ts +135 -0
  30. package/src/boot/auth-flip.saga.ts +77 -0
  31. package/src/boot/boot.saga.test.ts +203 -0
  32. package/src/boot/boot.saga.ts +146 -0
  33. package/src/boot/bucket-switch.saga.test.ts +189 -0
  34. package/src/boot/bucket-switch.saga.ts +136 -0
  35. package/src/boot/preload.saga.test.ts +96 -0
  36. package/src/boot/preload.saga.ts +45 -0
  37. package/src/bucket-blurhash.test.ts +148 -0
  38. package/src/build-globals.d.ts +12 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +352 -0
  41. package/src/client/router.test.ts +58 -0
  42. package/src/client/router.ts +100 -0
  43. package/src/client/runtime.test.ts +235 -0
  44. package/src/client/runtime.ts +296 -0
  45. package/src/client/services.test.ts +74 -0
  46. package/src/client/services.ts +436 -0
  47. package/src/client/sp00ky-client.test.ts +341 -0
  48. package/src/client/sp00ky-client.ts +625 -0
  49. package/src/events/events.test.ts +2 -1
  50. package/src/events/index.ts +3 -0
  51. package/src/index.ts +69 -1
  52. package/src/kernel/constants.test.ts +19 -0
  53. package/src/kernel/constants.ts +80 -0
  54. package/src/kernel/effects.test.ts +40 -0
  55. package/src/kernel/effects.ts +169 -0
  56. package/src/kernel/events.ts +57 -0
  57. package/src/kernel/interpreter.test.ts +116 -0
  58. package/src/kernel/interpreter.ts +148 -0
  59. package/src/kernel/saga.test.ts +89 -0
  60. package/src/kernel/saga.ts +73 -0
  61. package/src/live/index.test.ts +512 -0
  62. package/src/live/index.ts +1059 -0
  63. package/src/modules/app-release/index.test.ts +125 -0
  64. package/src/modules/app-release/index.ts +209 -0
  65. package/src/modules/auth/auth.local-first.test.ts +228 -0
  66. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  67. package/src/modules/auth/events/index.ts +9 -2
  68. package/src/modules/auth/impersonation-banner.ts +443 -0
  69. package/src/modules/auth/impersonation.integration.test.ts +205 -0
  70. package/src/modules/auth/impersonation.test.ts +377 -0
  71. package/src/modules/auth/impersonation.ts +179 -0
  72. package/src/modules/auth/index.ts +543 -22
  73. package/src/modules/crdt/acceptance.ts +75 -0
  74. package/src/modules/crdt/bytes.ts +50 -0
  75. package/src/modules/crdt/crdt-field.ts +125 -0
  76. package/src/modules/crdt/crdt.test.ts +515 -0
  77. package/src/modules/crdt/hash.ts +103 -0
  78. package/src/modules/crdt/index.ts +793 -0
  79. package/src/modules/crdt/loro-loader.ts +25 -0
  80. package/src/modules/crdt/mirror.ts +37 -0
  81. package/src/modules/devtools/flags.ts +349 -0
  82. package/src/modules/devtools/index.ts +748 -95
  83. package/src/modules/devtools/mutations.test.ts +92 -0
  84. package/src/modules/devtools/mutations.ts +160 -0
  85. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  86. package/src/modules/devtools/state-shape.test.ts +263 -0
  87. package/src/modules/devtools/storage-info.test.ts +79 -0
  88. package/src/modules/devtools/storage-info.ts +168 -0
  89. package/src/modules/devtools/versions.test.ts +74 -0
  90. package/src/modules/devtools/versions.ts +110 -0
  91. package/src/modules/feature-flag/index.test.ts +298 -0
  92. package/src/modules/feature-flag/index.ts +316 -0
  93. package/src/modules/ref-tables.test.ts +93 -0
  94. package/src/modules/ref-tables.ts +91 -0
  95. package/src/modules/web-push/index.test.ts +824 -0
  96. package/src/modules/web-push/index.ts +1027 -0
  97. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  98. package/src/mutation/jobs.test.ts +25 -0
  99. package/src/mutation/jobs.ts +41 -0
  100. package/src/mutation/mutation-id.test.ts +37 -0
  101. package/src/mutation/mutation-id.ts +35 -0
  102. package/src/mutation/pending-writes.integration.test.ts +175 -0
  103. package/src/mutation/push.saga.test.ts +361 -0
  104. package/src/mutation/push.saga.ts +245 -0
  105. package/src/mutation/rows.test.ts +278 -0
  106. package/src/mutation/rows.ts +499 -0
  107. package/src/mutation/tray.saga.test.ts +63 -0
  108. package/src/mutation/tray.saga.ts +48 -0
  109. package/src/mutation/write.saga.test.ts +316 -0
  110. package/src/mutation/write.saga.ts +268 -0
  111. package/src/otel/index.ts +10 -7
  112. package/src/pure.ts +66 -0
  113. package/src/push/types.ts +174 -0
  114. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  115. package/src/query/env.test.ts +23 -0
  116. package/src/query/env.ts +65 -0
  117. package/src/query/fetch.saga.test.ts +199 -0
  118. package/src/query/fetch.saga.ts +120 -0
  119. package/src/query/hash.test.ts +14 -0
  120. package/src/query/hash.ts +18 -0
  121. package/src/query/id-set-plan.test.ts +132 -0
  122. package/src/query/lifecycle.saga.test.ts +274 -0
  123. package/src/query/lifecycle.saga.ts +186 -0
  124. package/src/query/list-ref-live.integration.test.ts +203 -0
  125. package/src/query/materialize.saga.test.ts +188 -0
  126. package/src/query/materialize.saga.ts +96 -0
  127. package/src/query/materialize.test.ts +58 -0
  128. package/src/query/materialize.ts +57 -0
  129. package/src/query/membership.saga.test.ts +482 -0
  130. package/src/query/membership.saga.ts +315 -0
  131. package/src/query/membership.test.ts +151 -0
  132. package/src/query/membership.ts +234 -0
  133. package/src/query/register.saga.test.ts +312 -0
  134. package/src/query/register.saga.ts +235 -0
  135. package/src/query/render-set.test.ts +47 -0
  136. package/src/query/render-set.ts +71 -0
  137. package/src/query/session-guard.integration.test.ts +304 -0
  138. package/src/query/sql.test.ts +118 -0
  139. package/src/query/sql.ts +157 -0
  140. package/src/query/window-query.test.ts +70 -0
  141. package/src/query/window-query.ts +208 -0
  142. package/src/services/blobs/blob-cache.test.ts +359 -0
  143. package/src/services/blobs/blob-cache.ts +603 -0
  144. package/src/services/blobs/blob-manifest.ts +227 -0
  145. package/src/services/blobs/blob-store.test.ts +77 -0
  146. package/src/services/blobs/blob-store.ts +359 -0
  147. package/src/services/blobs/blob.fixture.ts +90 -0
  148. package/src/services/blobs/index.ts +70 -0
  149. package/src/services/database/cache-engine.ts +209 -0
  150. package/src/services/database/connection-supervisor.test.ts +318 -0
  151. package/src/services/database/connection-supervisor.ts +422 -0
  152. package/src/services/database/database.query-timeout.test.ts +140 -0
  153. package/src/services/database/database.responses.test.ts +43 -0
  154. package/src/services/database/database.ts +156 -61
  155. package/src/services/database/engine-factory.ts +33 -0
  156. package/src/services/database/errors.ts +34 -0
  157. package/src/services/database/events/index.ts +2 -1
  158. package/src/services/database/index.ts +7 -0
  159. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  160. package/src/services/database/local-migrator.integration.test.ts +110 -0
  161. package/src/services/database/local-migrator.ts +61 -16
  162. package/src/services/database/local.test.ts +150 -0
  163. package/src/services/database/local.ts +508 -63
  164. package/src/services/database/plan-render.test.ts +159 -0
  165. package/src/services/database/plan-render.ts +108 -0
  166. package/src/services/database/relation-resolver.test.ts +484 -0
  167. package/src/services/database/relation-resolver.ts +0 -0
  168. package/src/services/database/remote.ts +285 -6
  169. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  170. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  171. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  172. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  173. package/src/services/database/sqlite-column-reset.ts +91 -0
  174. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  175. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  176. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  177. package/src/services/database/sqlite-lock-verify.ts +45 -0
  178. package/src/services/database/sqlite-open.test.ts +150 -0
  179. package/src/services/database/sqlite-open.ts +164 -0
  180. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  181. package/src/services/database/sqlite-plan-sql.ts +196 -0
  182. package/src/services/database/sqlite-projection.test.ts +121 -0
  183. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  184. package/src/services/database/sqlite-select.test.ts +261 -0
  185. package/src/services/database/sqlite-select.ts +131 -0
  186. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  187. package/src/services/database/sqlite-transport.ts +224 -0
  188. package/src/services/database/sqlite-worker.ts +437 -0
  189. package/src/services/database/surql-translate.ts +417 -0
  190. package/src/services/database/surreal-cache-engine.ts +163 -0
  191. package/src/services/logger/index.test.ts +132 -0
  192. package/src/services/logger/index.ts +189 -7
  193. package/src/services/persistence/localstorage.ts +2 -2
  194. package/src/services/persistence/resilient.ts +10 -3
  195. package/src/services/persistence/surrealdb.ts +4 -4
  196. package/src/services/stream-processor/index.ts +806 -67
  197. package/src/services/stream-processor/permissions.test.ts +47 -0
  198. package/src/services/stream-processor/permissions.ts +53 -0
  199. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  200. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  201. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  202. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  203. package/src/services/stream-processor/wasm-types.ts +58 -2
  204. package/src/services/tabs/broker-client.ts +284 -0
  205. package/src/services/tabs/broker.test.ts +381 -0
  206. package/src/services/tabs/coordinator.test.ts +386 -0
  207. package/src/services/tabs/coordinator.ts +646 -0
  208. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  209. package/src/services/tabs/leader-locks.ts +75 -0
  210. package/src/services/tabs/protocol.ts +262 -0
  211. package/src/services/tabs/support.ts +36 -0
  212. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  213. package/src/sp00ky.ts +5 -395
  214. package/src/state/client-state.ts +216 -0
  215. package/src/state/lifecycle.test.ts +184 -0
  216. package/src/state/lifecycle.ts +127 -0
  217. package/src/state/reducers.test.ts +319 -0
  218. package/src/state/reducers.ts +550 -0
  219. package/src/state/selectors.test.ts +188 -0
  220. package/src/state/selectors.ts +259 -0
  221. package/src/sw/index.test.ts +582 -0
  222. package/src/sw/index.ts +607 -0
  223. package/src/sw/store.ts +96 -0
  224. package/src/sync/connection.saga.test.ts +97 -0
  225. package/src/sync/connection.saga.ts +89 -0
  226. package/src/sync/live.saga.test.ts +229 -0
  227. package/src/sync/live.saga.ts +116 -0
  228. package/src/sync/policy.health.test.ts +56 -0
  229. package/src/sync/policy.test.ts +663 -0
  230. package/src/sync/policy.ts +515 -0
  231. package/src/sync/poll.saga.test.ts +51 -0
  232. package/src/sync/poll.saga.ts +36 -0
  233. package/src/sync/tabs.saga.test.ts +78 -0
  234. package/src/sync/tabs.saga.ts +96 -0
  235. package/src/testing/adapters.ts +137 -0
  236. package/src/testing/build.ts +63 -0
  237. package/src/testing/fake-services.ts +63 -0
  238. package/src/testing/run-pure.test.ts +92 -0
  239. package/src/testing/run-pure.ts +128 -0
  240. package/src/testing/services.ts +17 -0
  241. package/src/types.ts +661 -10
  242. package/src/utils/blurhash.ts +90 -0
  243. package/src/utils/edges.ts +57 -0
  244. package/src/utils/error-classification.test.ts +105 -0
  245. package/src/utils/error-classification.ts +64 -0
  246. package/src/utils/index.ts +89 -12
  247. package/src/utils/parser.test.ts +67 -102
  248. package/src/utils/parser.ts +64 -2
  249. package/src/utils/semver.test.ts +32 -0
  250. package/src/utils/semver.ts +30 -0
  251. package/src/utils/sha256.ts +15 -0
  252. package/src/utils/surql.ts +29 -18
  253. package/src/utils/utils.test.ts +3 -2
  254. package/tsdown.config.ts +117 -3
  255. package/vitest.config.ts +48 -0
  256. package/src/modules/cache/index.ts +0 -241
  257. package/src/modules/cache/types.ts +0 -19
  258. package/src/modules/data/data.test.ts +0 -58
  259. package/src/modules/data/index.ts +0 -879
  260. package/src/modules/sync/engine.ts +0 -173
  261. package/src/modules/sync/events/index.ts +0 -77
  262. package/src/modules/sync/index.ts +0 -3
  263. package/src/modules/sync/queue/index.ts +0 -2
  264. package/src/modules/sync/queue/queue-down.ts +0 -89
  265. package/src/modules/sync/queue/queue-up.ts +0 -223
  266. package/src/modules/sync/scheduler.ts +0 -84
  267. package/src/modules/sync/sync.ts +0 -421
  268. package/src/modules/sync/utils.test.ts +0 -311
  269. package/src/modules/sync/utils.ts +0 -167
package/src/types.ts CHANGED
@@ -1,9 +1,11 @@
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 { ImpersonationBannerConfig } from './modules/auth/impersonation-banner';
2
+ import type { RecordId, SchemaStructure, QueryPlan } from '@spooky-sync/query-builder';
3
+ import type { Level, LoggerOptions } from 'pino';
4
+ import type { PushEventOptions } from './events/index';
5
+ import type { LocalEngineChoice } from './services/database/cache-engine';
6
+ import type { WebPushConfig } from './modules/web-push/index';
5
7
 
6
- export type { Level } from 'pino';
8
+ export type { Level };
7
9
 
8
10
  /**
9
11
  * A pino browser transmit object for forwarding logs to an external sink (e.g. OpenTelemetry).
@@ -67,6 +69,26 @@ export type QueryTimeToLive =
67
69
  | '12h'
68
70
  | '1d';
69
71
 
72
+ /**
73
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
74
+ * The FIRST load (cold) always fetches + blocks regardless.
75
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
76
+ * real `useQuery` mounts and registers its live view. No network on load.
77
+ * - `background`: return instantly, but kick a one-time silent refetch.
78
+ * - `stale`: like `background`, but only if the cached copy is older than
79
+ * `staleTime`.
80
+ */
81
+ export type PreloadRefresh = 'onUse' | 'background' | 'stale';
82
+
83
+ export interface PreloadOptions {
84
+ /** Abort a cold preload that is still waiting for the server. */
85
+ signal?: AbortSignal;
86
+ /** @deprecated Preload is a registered query now; a warm preload never refetches by itself. Ignored. */
87
+ refresh?: PreloadRefresh;
88
+ /** @deprecated Ignored. */
89
+ staleTime?: QueryTimeToLive;
90
+ }
91
+
70
92
  /**
71
93
  * Result object returned when a query is registered or executed.
72
94
  */
@@ -98,9 +120,40 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
98
120
  store?: StoreType;
99
121
  /** Authentication token. */
100
122
  token?: string;
123
+ /**
124
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
125
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
126
+ * table/relation level. Defaults to true; set false to force the legacy
127
+ * multi-hop path (escape hatch while the worker-side path beds in).
128
+ */
129
+ workerSelect?: boolean;
130
+ /**
131
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
132
+ * keep the connection alive indefinitely without configuration. See
133
+ * {@link ReconnectConfig}.
134
+ */
135
+ reconnect?: ReconnectConfig;
136
+ /**
137
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
138
+ * a single promise chain, so one call that never settles (half-open socket:
139
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
140
+ * otherwise wedge ALL later remote traffic behind it — including the sync
141
+ * poll's own health probe, leaving health pinned at `healthy` with no
142
+ * banner and no self-heal. The deadline turns that into an ordinary network
143
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
144
+ */
145
+ queryTimeoutMs?: number;
146
+ /**
147
+ * Deadline (ms) for every LOCAL store operation (a SQLite worker round trip,
148
+ * or a query on the in-process surrealdb engine). Local ops are serialized
149
+ * too, and one that never answered - a worker starved behind a long select,
150
+ * a lock verification with no clock - left every `db.create`/`db.update`
151
+ * promise pending for the tab's lifetime. On expiry the call rejects with
152
+ * `LocalOpTimeoutError` (the op itself keeps running in the engine and is
153
+ * not retried). `0` disables. Defaults to `30_000`.
154
+ */
155
+ localOpTimeoutMs?: number;
101
156
  };
102
- /** Unique client identifier. If not provided, one will be generated. */
103
- clientId?: string;
104
157
  /** The schema definition. */
105
158
  schema: S;
106
159
  /** The compiled SURQL schema string. */
@@ -112,17 +165,402 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
112
165
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
113
166
  */
114
167
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
168
+ /**
169
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
170
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
171
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
172
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
173
+ * this engine. See `services/database/cache-engine.ts`.
174
+ */
175
+ localEngine?: LocalEngineChoice;
176
+ /**
177
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
178
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
179
+ * how bucket reads behaved before it existed.
180
+ *
181
+ * Nothing in this cache expires on a timer — an image whose row is still in
182
+ * the local store has to stay available offline. Bytes are only dropped when
183
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
184
+ * reconcile finds no file behind a row, or when the cache is over budget, in
185
+ * which case the least-recently-used unpinned entries go first. See
186
+ * `services/blobs/blob-cache.ts`.
187
+ */
188
+ blobCache?: {
189
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
190
+ enabled?: boolean;
191
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
192
+ * `navigator.storage.estimate()`. */
193
+ maxBytes?: number;
194
+ /**
195
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
196
+ * `false`, matching the local store: cached files are namespaced per local
197
+ * bucket, so signing back in is warm and no user can read another's cache.
198
+ * Turn on for shared devices.
199
+ */
200
+ clearOnSignOut?: boolean;
201
+ };
202
+ /**
203
+ * Share ONE durable local store across all tabs of this origin (default
204
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
205
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
206
+ * worker and the sync loop, and follower tabs read/write the same store over
207
+ * MessagePorts, so every tab is durable instead of only the first one.
208
+ *
209
+ * Falls back to solo mode (exactly the flag-off behavior, including the
210
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
211
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
212
+ * not sqlite, or the broker rejects the tab (mixed app versions).
213
+ *
214
+ * Failover: when the leader tab closes or freezes, a follower is promoted
215
+ * within seconds; queries briefly refetch and mutations are never lost once
216
+ * their local write resolved (the shared outbox survives in the store).
217
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
218
+ */
219
+ sharedTabs?: boolean;
220
+ /**
221
+ * Persist the in-browser SSP circuit's store as a snapshot in the local
222
+ * store, so a reload restores it and only steps in what changed since.
223
+ * Defaults to `true` under `localEngine: 'sqlite'` (the OPFS-backed store
224
+ * can hold the bytes) and `false` otherwise.
225
+ *
226
+ * Without a snapshot the circuit is primed by reading every cached row back
227
+ * out of the local store; either way a reload never re-downloads the working
228
+ * set, which is what an empty circuit used to force: every id in the
229
+ * server's list_ref classified as missing.
230
+ *
231
+ * Snapshots are store-only (views are re-registered per session) and written
232
+ * on a checkpoint interval ({@link circuitCheckpointMs}) and when the page
233
+ * goes hidden, never per ingest or per query registration.
234
+ */
235
+ persistCircuit?: boolean;
236
+ /**
237
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
238
+ * 30000. Ignored when `persistCircuit` is off.
239
+ */
240
+ circuitCheckpointMs?: number;
241
+ /**
242
+ * Keep only the fields registered queries evaluate (filter predicates, join
243
+ * keys, sort keys, plus `id`/`_00_rv`) per row in the in-browser circuit.
244
+ * Default `true`. The circuit only ever reads those fields; bodies are
245
+ * rendered from the local store. Measured on 7700 rows with 20 KB bodies:
246
+ * the wasm heap peak went from ~500 MB to ~24 MB and the snapshot from
247
+ * 156 MB to 1.2 MB. A query that evaluates a field earlier rows were kept
248
+ * without has that field merged in from the local store on registration.
249
+ */
250
+ circuitProjection?: boolean;
115
251
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
116
252
  otelTransmit?: PinoTransmit;
117
253
  /**
118
- * Debounce time in milliseconds for stream updates.
119
- * Defaults to 100ms.
254
+ * Debounce time in milliseconds for stream updates (the client-side SSP
255
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
256
+ * per-record updates per query before notifying readers).
257
+ * Defaults to 50ms.
120
258
  */
121
259
  streamDebounceTime?: number;
260
+ /**
261
+ * How long in milliseconds the first edit to a collaborative (CRDT) field
262
+ * after a quiet spell waits before it goes out, so a burst of keystrokes
263
+ * travels as one edit-log row. Local state is kept on every change (so
264
+ * reload and offline work). Defaults to 50ms.
265
+ */
266
+ crdtDebounceMs?: number;
267
+ /**
268
+ * The shortest gap in milliseconds between two edit-log rows of one CRDT
269
+ * field: while someone keeps typing, their edits go out on this cadence
270
+ * instead of waiting for a pause. Lower = other collaborators see the text
271
+ * sooner and more rows are written; higher = fewer rows and more lag.
272
+ * Defaults to 200ms.
273
+ */
274
+ crdtSendIntervalMs?: number;
275
+ /**
276
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
277
+ * preloaded at client startup (fetched as a separate chunk on page load) so
278
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
279
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
280
+ * out of apps that don't use collaboration. Defaults to `false`.
281
+ */
282
+ crdt?: boolean;
283
+ /**
284
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
285
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
286
+ * convergence + more query load; higher = the inverse. Non-positive
287
+ * values fall back to the default (500ms).
288
+ */
289
+ refSyncIntervalMs?: number;
290
+ /**
291
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
292
+ * registered with no server result yet, its surql also runs directly on the
293
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
294
+ * before the full register lifecycle completes. Hydrated rows carry their
295
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
296
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
297
+ * paints from the local cache immediately — however the rows got there
298
+ * (preload, prior sync). Default `false`: the register lifecycle
299
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
300
+ * freshness path and no duplicate one-shot fetches are made.
301
+ */
302
+ instantHydrate?: boolean;
303
+ /**
304
+ * Carry the changed row's body on the LIVE notification instead of going
305
+ * back for it.
306
+ *
307
+ * The client holds exactly one live subscription, on its `_00_list_ref`
308
+ * table. Without this, the notification names the row and the client then
309
+ * pulls it with `SELECT * FROM $ids`. The edge
310
+ * is a real graph edge, so `FETCH out` makes SurrealDB resolve the row into
311
+ * the notification and the body fetch disappears.
312
+ *
313
+ * The push stays advisory: the body is landed exactly the way a fetched body
314
+ * is (store write, circuit ingest, version recorded), so a notification the
315
+ * server drops costs nothing but the old round trip. A row joining a live
316
+ * view is committed to membership from the notification either way (no
317
+ * re-read); with this on, the body fetch is saved as well.
318
+ *
319
+ * Default `false`. The cost is wire bytes: one edit bumps the edge in every
320
+ * view holding the row, and under `FETCH` each of those notifications
321
+ * carries its own full copy of the body.
322
+ */
323
+ liveInlineBodies?: boolean;
324
+ /**
325
+ * Enable realtime sync while signed out. When `true`, the client starts its
326
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
327
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
328
+ * page gets live `useQuery` updates over world-readable tables. Requires the
329
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
330
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
331
+ * one-shot but never sync live, and a `preload` made while signed out returns
332
+ * at once rather than wait for membership that never comes.
333
+ */
334
+ enableAnonymousLiveQueries?: boolean;
335
+ /**
336
+ * Opt in to the raw remote escape hatches (`useRemote`, `remoteQuery`,
337
+ * `queryRaw`) when the generated schema's `policy.queryAllowlist` is `warn`
338
+ * or `enforce`. With the allowlist on, the server only accepts query shapes
339
+ * that `spky generate` collected from the query builder, so a hand-written
340
+ * SurrealQL string cannot be allowlisted and these methods throw unless this
341
+ * flag is `true`. Defaults to `false`.
342
+ */
343
+ allowRawRemote?: boolean;
344
+ /**
345
+ * How the "you are impersonating" warning is shown while an admin acts as
346
+ * another user. The built-in one (hazard stripes at the top, the page
347
+ * shifted down onto them) needs no configuration; this is for restyling it,
348
+ * or replacing it with the app's own.
349
+ *
350
+ * See `ImpersonationBannerConfig`. Replacing it does not mean "no warning":
351
+ * if the app has not acknowledged its own banner shortly after impersonation
352
+ * starts, the built-in one appears anyway.
353
+ */
354
+ impersonationBanner?: ImpersonationBannerConfig;
355
+ /**
356
+ * Surface sustained sync failures as a "degraded" health status that the app
357
+ * can observe via `subscribeToSyncHealth` (or the client-solid
358
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
359
+ *
360
+ * Individual failures — a transient remote 500 on query registration, a
361
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
362
+ * throw at the app. This only controls when a *run* of consecutive failures
363
+ * is reported. Status flips back to `healthy` on the next successful sync
364
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
365
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
366
+ */
367
+ syncHealth?: SyncHealthConfig | false;
368
+ /**
369
+ * Automatic blurhash placeholders for bucket image uploads. On every
370
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
371
+ * the client computes a blurhash and stores it as a tiny sidecar object
372
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
373
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
374
+ * helpers) to paint a placeholder until the image is decoded.
375
+ *
376
+ * `true` (the default) enables with 4x3 components; pass
377
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
378
+ * A per-call `put(path, content, { blurhash })` option overrides this.
379
+ */
380
+ blurhash?: boolean | { componentX?: number; componentY?: number };
381
+ /**
382
+ * Buckets declared `BACKEND "r2"` keep their files with the SSP (R2 on
383
+ * Cloudflare, a directory under `spky dev`) instead of in SurrealDB, which
384
+ * on Surreal Cloud can only hold memory buckets. `endpoint` is the SSP's
385
+ * URL: `spky dev` and `spky deploy` hand it to Vite as
386
+ * `VITE_SPKY_FILES_ENDPOINT`.
387
+ */
388
+ files?: { endpoint?: string };
389
+ /**
390
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
391
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
392
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
393
+ * settles stops every later mutation for the session, with no retry and no
394
+ * error. On expiry the push is treated as a network failure and re-queued.
395
+ * `0` disables. Defaults to `30_000`.
396
+ */
397
+ pushTimeoutMs?: number;
398
+ /**
399
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
400
+ * it is retried. Mirror of {@link pushTimeoutMs} for the read side.
401
+ * Defaults to 30000; `0` disables the timeout.
402
+ */
403
+ downTimeoutMs?: number;
404
+ /**
405
+ * Web Push on this page (`client.webPush`, `db.webPush`). Everything is
406
+ * optional and the defaults need no service worker configuration here:
407
+ * `autoSync` (repair this browser's subscription after sign-in),
408
+ * `unsubscribeOnSignOut` (drop this device's subscription on `signOut()`),
409
+ * `bridge` (post the session to the service worker for live rendering) are
410
+ * on; `serviceWorkerUrl` registers a worker when the app does not.
411
+ * See the `push-notifications` docs page.
412
+ */
413
+ webPush?: WebPushConfig;
414
+ }
415
+
416
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
417
+ export interface SyncHealthConfig {
418
+ /**
419
+ * Number of consecutive failed sync rounds (up or down) before the status
420
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
421
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
422
+ * disables degraded reporting entirely.
423
+ */
424
+ degradeAfterConsecutiveFailures?: number;
425
+ }
426
+
427
+ /**
428
+ * Tunables for WebSocket reconnect and liveness detection. See
429
+ * {@link Sp00kyConfig.database.reconnect}.
430
+ *
431
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
432
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
433
+ * supervisor above it re-opens the connection from scratch whenever the SDK
434
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
435
+ * engine permanently in that case, so a supervisor is required, not optional.
436
+ * The heartbeat covers the third case: a socket that never closes at all.
437
+ */
438
+ export interface ReconnectConfig {
439
+ /**
440
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
441
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
442
+ * ~62s outage and then gives up for the life of the page).
443
+ */
444
+ attempts?: number;
445
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
446
+ retryDelayMax?: number;
447
+ /**
448
+ * Cadence of the application-level liveness probe (`RETURN true`) that
449
+ * detects a half-open socket the transport never reports as closed.
450
+ * `0` disables the heartbeat. Defaults to `20_000`.
451
+ */
452
+ heartbeatIntervalMs?: number;
453
+ /**
454
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
455
+ * regardless of what its `readyState` claims, so the connection is torn down
456
+ * and rebuilt. Defaults to `10_000`.
457
+ */
458
+ heartbeatTimeoutMs?: number;
459
+ /**
460
+ * Cap on the supervisor's own backoff between `connect()` retries once the
461
+ * SDK has given up. Defaults to `15_000`.
462
+ */
463
+ superviseRetryDelayMaxMs?: number;
464
+ }
465
+
466
+ /**
467
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
468
+ *
469
+ * These answer different questions: `connection` is about the socket,
470
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
471
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
472
+ * usually still `healthy` for the first few seconds.
473
+ */
474
+ export type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
475
+
476
+ export type SyncHealthStatus = 'healthy' | 'degraded';
477
+
478
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
479
+ export interface SyncHealth {
480
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
481
+ status: SyncHealthStatus;
482
+ /** Consecutive failed sync rounds at the moment of this report. */
483
+ consecutiveFailures: number;
484
+ /** Classification of the most recent failure (only set while `degraded`). */
485
+ kind?: 'network' | 'application';
486
+ /** Message of the most recent failure (only set while `degraded`). */
487
+ error?: string;
488
+ /**
489
+ * `true` once at least one sync round has succeeded this session. Lets a UI
490
+ * distinguish a first-time "connecting" phase (never reached the server yet,
491
+ * so a cold-start failure run is expected) from a real lost connection after
492
+ * a working session. Never resets back to `false` once set.
493
+ */
494
+ everConnected: boolean;
495
+ /**
496
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
497
+ * one flips the instant the socket drops, whereas `status` only degrades
498
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
499
+ * immediately without waiting for the degrade threshold.
500
+ */
501
+ connection: ConnectionState;
502
+ }
503
+
504
+ export type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
505
+
506
+ /**
507
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
508
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
509
+ * server, this one is about whether the local store survives a reload.
510
+ *
511
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
512
+ * which only one client per bucket can hold open. When it can't be opened (a
513
+ * second tab of the app already has it, an insecure context, a full pool) the
514
+ * engine keeps working against an in-memory DB, which holds the whole dataset
515
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
516
+ * so a UI can warn about it.
517
+ */
518
+ export interface StorageHealth {
519
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
520
+ status: StorageHealthStatus;
521
+ /**
522
+ * `true` only when durable storage was REQUESTED and could not be opened.
523
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
524
+ * is a choice rather than a failure, so a UI can key off this alone.
525
+ */
526
+ fallback: boolean;
527
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
528
+ error?: string;
529
+ /**
530
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
531
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
532
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
533
+ * single-tab behavior. Absent entirely when the feature is off.
534
+ */
535
+ role?: 'leader' | 'follower' | 'solo';
122
536
  }
123
537
 
124
538
  export type QueryHash = string;
125
539
 
540
+ /**
541
+ * One changed row delivered inline on a LIVE notification, when the
542
+ * subscription was opened with the body joined on (see
543
+ * {@link Sp00kyConfig.liveInlineBodies}). `version` is the edge's `version`,
544
+ * i.e. the same number the membership read would have reported for this row.
545
+ */
546
+ export interface InlineRow {
547
+ id: string;
548
+ version: number;
549
+ record: Record<string, unknown>;
550
+ }
551
+
552
+ /**
553
+ * A row that joined a query's view, or moved to a newer version, as one LIVE
554
+ * notification on `_00_list_ref` reports it: the edge's `out` and `version`.
555
+ * The client commits it to the query's membership straight away instead of
556
+ * re-reading the edges (see `sync/live.saga.ts`).
557
+ */
558
+ export interface EdgeDelta {
559
+ hash: QueryHash;
560
+ id: string;
561
+ version: number;
562
+ }
563
+
126
564
  // Flat array format: [[record-id, version], [record-id, version], ...]
127
565
  export type RecordVersionArray = Array<[string, number]>;
128
566
 
@@ -148,12 +586,50 @@ export interface QueryConfig {
148
586
  id: RecordId<string>;
149
587
  /** The SURQL query string. */
150
588
  surql: string;
589
+ /**
590
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
591
+ * `_00_query`). Present when the query came from the query-builder. Non-
592
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
593
+ * instead of re-running `surql`, which they cannot parse.
594
+ */
595
+ plan?: QueryPlan;
151
596
  /** Parameters used in the query. */
152
597
  params: Record<string, any>;
153
598
  /** The version array representing the local state of results. */
154
599
  localArray: RecordVersionArray;
155
600
  /** The version array representing the remote (server) state of results. */
156
601
  remoteArray: RecordVersionArray;
602
+ /**
603
+ * In-memory only (never persisted to `_00_query`): version array of the
604
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
605
+ * child-body sync is idempotent across polls. Kept separate from
606
+ * `remoteArray` so related child rows never enter the primary window /
607
+ * `rowCount` / `localArray`.
608
+ */
609
+ subqueryRemoteArray?: RecordVersionArray;
610
+ /**
611
+ * Whether authoritative membership (`remoteArray`) has ever been established
612
+ * for this query — either fetched from `_00_list_ref` this session, or read
613
+ * back from the durable `_00_view` row on a cold start.
614
+ *
615
+ * Tri-state matters: "known and empty" must render an empty list, while
616
+ * "never established" has to fall back to a predicate scan of the local store
617
+ * so a query first run on this device still paints offline. A
618
+ * `remoteArray.length === 0` check cannot tell those apart.
619
+ *
620
+ * On a cold start it is seeded from the durable `_00_view` row when that
621
+ * row is non-empty, or empty but `confirmed` (the server reported zero rows
622
+ * for the query). An unconfirmed empty row is ignored, so a device poisoned
623
+ * by an old client that mirrored unflushed reads still self-heals.
624
+ */
625
+ membershipKnown?: boolean;
626
+ /**
627
+ * Key of this query's durable `_00_view` membership row: a hash of
628
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
629
+ * survives a reload (which mints a new session id) and a bucket switch.
630
+ * In-memory only.
631
+ */
632
+ membershipKey?: string;
157
633
  /** Time-To-Live for this query. */
158
634
  ttl: QueryTimeToLive;
159
635
  /** Timestamp when the query was last accessed/active. */
@@ -164,6 +640,42 @@ export interface QueryConfig {
164
640
 
165
641
  export type QueryConfigRecord = QueryConfig & { id: string };
166
642
 
643
+ /**
644
+ * Runtime fetch status of a live query.
645
+ * - `idle`: registered, initial sync completed, and not currently fetching
646
+ * missing records — the materialized rows are authoritative (a windowed
647
+ * query's short result really is the end of the list).
648
+ * - `fetching`: the query is registering (a query is born `fetching` until its
649
+ * initial remote sync completes) or the sync engine is fetching/ingesting
650
+ * missing records for it. Any pending debounced result is flushed BEFORE the
651
+ * flip back to `idle`, so idle status never races ahead of the rows.
652
+ */
653
+ export type QueryStatus = 'idle' | 'fetching';
654
+
655
+ /**
656
+ * What the server's `_00_query` row says about a view, read alongside its
657
+ * `_00_list_ref` edges (registration, the poll, a targeted re-read).
658
+ *
659
+ * - `present: false`: the row is not there (or not readable). The SSP no
660
+ * longer has this view: a TTL sweep, an SSP reset, a scheduler wipe. An
661
+ * empty edge set read at the same time is NOT "no rows", it is "no view".
662
+ * - `state: 'materializing'`: the SSP has (re)computed the set and its edges
663
+ * are in flight; an empty read is "not landed yet".
664
+ * - `state: 'ready'`: the edges are committed (flipped in the same
665
+ * transaction), so `rowCount === 0` with no edges is a real empty result.
666
+ * - `state: null`: a server that predates the marker; only `rowCount` can be
667
+ * used, with its `> 0` = flush window / `0` = empty ambiguity.
668
+ */
669
+ export interface ServerViewMeta {
670
+ present: boolean;
671
+ /** `_00_query.rowCount`; `null` when unreadable. */
672
+ rowCount: number | null;
673
+ state: 'materializing' | 'ready' | null;
674
+ }
675
+
676
+ /** Outcome of handing a server id-set to `DataModule.updateQueryRemoteArray`. */
677
+ export type MembershipOutcome = 'applied' | 'ignored' | 'view-lost';
678
+
167
679
  /**
168
680
  * Internal state of a live query.
169
681
  */
@@ -172,17 +684,135 @@ export interface QueryState {
172
684
  config: QueryConfig;
173
685
  /** The current cached records for this query. */
174
686
  records: Record<string, any>[];
687
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
688
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
689
+ hydrated?: boolean;
690
+ /** Set once a server-side membership set has been accepted this session
691
+ * (`updateQueryRemoteArray`). The `register` down-event is enqueued before
692
+ * the instant-hydrate, so a hydrate that finishes later must not prime
693
+ * membership over the authoritative set. Ephemeral. */
694
+ serverMembership?: boolean;
695
+ /**
696
+ * Set when the server's `_00_query` row for this query went missing while
697
+ * we held membership (TTL sweep, SSP reset, scheduler wipe). The view is
698
+ * being re-registered; until a readable row comes back, empty reads are
699
+ * NOT the server's answer and nothing is dropped. Ephemeral.
700
+ */
701
+ viewLost?: boolean;
702
+ /** Last `_00_query.state` read from the server, for DevTools. Ephemeral. */
703
+ serverState?: 'materializing' | 'ready' | null;
704
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
705
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
706
+ * always emits at least once even when its records are unchanged — otherwise
707
+ * an empty re-registered window would never notify and stay "loading". */
708
+ syncNotified?: boolean;
709
+ /**
710
+ * Subscribers hold the rows of a known membership (see `QueryLifecycle`'s
711
+ * `answered`): what the authority channel and the bindings'
712
+ * `isAuthoritative()` report. Ephemeral.
713
+ */
714
+ answered?: boolean;
175
715
  /** Timer for TTL expiration. */
176
716
  ttlTimer: NodeJS.Timeout | null;
177
717
  /** TTL duration in milliseconds. */
178
718
  ttlDurationMs: number;
719
+ /** When the last TTL heartbeat for this query was sent (ms epoch); `undefined` before the first. */
720
+ lastHeartbeatAt?: number;
179
721
  /** Number of times the query has been updated. */
180
722
  updateCount: number;
723
+ /** Timestamp (ms) of the last user-visible update, or null before the first
724
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
725
+ lastUpdatedAt: number | null;
726
+ /**
727
+ * Rolling window of the most recent materialization-step latencies (ms).
728
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
729
+ * before each persist to `_00_query`. Samples themselves are not persisted.
730
+ */
731
+ materializationSamples: number[];
732
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
733
+ lastIngestLatencyMs: number | null;
734
+ /** Cumulative count of ingest/materialization errors observed for this query. */
735
+ errorCount: number;
736
+ /**
737
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
738
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
739
+ * pulling missing records for this query, otherwise `idle`.
740
+ */
741
+ status: QueryStatus;
742
+ /**
743
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
744
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
745
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
746
+ */
747
+ phaseSamples: Record<string, number[]>;
748
+ /** Most recent sample (ms) per phase, or null. */
749
+ phaseLast: Record<string, number | null>;
750
+ /** One-shot SSP registration timings (ms). */
751
+ registrationTimings: RegistrationTimings;
752
+ }
753
+
754
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
755
+ export const MATERIALIZATION_SAMPLE_WINDOW = 100;
756
+
757
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
758
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
759
+ export type TimingPhase =
760
+ | 'ssp'
761
+ | 'sspStoreApply'
762
+ | 'sspCircuitStep'
763
+ | 'sspTransform'
764
+ | 'localFetch'
765
+ | 'remoteFetch'
766
+ | 'frontend';
767
+
768
+ /** One-shot registration timings (ms), captured once when a query registers. */
769
+ export interface RegistrationTimings {
770
+ /** SSP surql→plan parse + permission injection. */
771
+ parseMs: number | null;
772
+ /** SSP operator-DAG build. */
773
+ planMs: number | null;
774
+ /** SSP initial snapshot evaluation. */
775
+ snapshotMs: number | null;
776
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
777
+ wallMs: number | null;
778
+ }
779
+
780
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
781
+ export interface PhaseStat {
782
+ lastMs: number | null;
783
+ p50: number | null;
784
+ p90: number | null;
785
+ p99: number | null;
786
+ count: number;
787
+ }
788
+
789
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
790
+ export interface QueryTimings {
791
+ ssp: PhaseStat;
792
+ sspStoreApply: PhaseStat;
793
+ sspCircuitStep: PhaseStat;
794
+ sspTransform: PhaseStat;
795
+ localFetch: PhaseStat;
796
+ remoteFetch: PhaseStat;
797
+ frontend: PhaseStat;
798
+ registration: RegistrationTimings;
799
+ updateCount: number;
800
+ errorCount: number;
181
801
  }
182
802
 
183
803
  // Callback types
184
804
  export type QueryUpdateCallback = (records: Record<string, any>[]) => void;
185
- export type MutationCallback = (mutations: UpEvent[]) => void;
805
+ export type QueryStatusCallback = (status: QueryStatus) => void;
806
+ /**
807
+ * Observer for a query's authority flips: `true` once subscribers hold the
808
+ * rendered rows of a known membership (a server answer whose bodies are
809
+ * local, or the durable membership of an earlier session), delivered after
810
+ * the rows that vouch for it; `false` when it is reset (bucket switch). Knowing the set is
811
+ * not enough: a `cached` re-seed or a just-applied server set has no rows
812
+ * painted yet. What the bindings' `isAuthoritative()` mirrors.
813
+ */
814
+ export type QueryAuthorityCallback = (known: boolean) => void;
815
+ export type MutationCallback = (mutations: MutationEvent[]) => void;
186
816
 
187
817
  export type MutationEventType = 'create' | 'update' | 'delete';
188
818
 
@@ -214,6 +844,13 @@ export interface RunOptions {
214
844
  assignedTo?: string;
215
845
  max_retries?: number;
216
846
  retry_strategy?: 'linear' | 'exponential';
847
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
848
+ timeout?: number;
849
+ /**
850
+ * Minimum delay in milliseconds before the job is eligible to run. While
851
+ * delayed the job stays pending (enqueued) and can still be killed.
852
+ */
853
+ delay?: number;
217
854
  }
218
855
 
219
856
  /**
@@ -239,4 +876,18 @@ export interface DebounceOptions {
239
876
  key?: 'recordId' | 'recordId_x_fields';
240
877
  /** The debounce delay in milliseconds. */
241
878
  delay?: number;
879
+ /**
880
+ * Keep the pending patch across a reload or a closed tab. Default `true`.
881
+ *
882
+ * Every call also writes the merged patch to `_00_pending_writes`, in the
883
+ * same local transaction as the row itself. When the page is hidden (tab
884
+ * switch, reload, close, app sent to the background) every pending patch is
885
+ * moved into the outbox and pushed at once instead of waiting out `delay`.
886
+ * A page that dies before that finishes leaves the patch in the store, and
887
+ * the next boot moves it into the outbox.
888
+ *
889
+ * `false` keeps the patch in memory only, so whatever is still inside its
890
+ * delay is lost on reload. Meant for throwaway state like a cursor position.
891
+ */
892
+ flushOnHide?: boolean;
242
893
  }