@spooky-sync/core 0.0.1-canary.27 → 0.0.1-canary.270

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