@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201

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 (148) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2184 -54
  3. package/dist/index.js +11515 -2399
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +276 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +421 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +434 -0
  11. package/dist/types.d.ts +688 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +35 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/events/index.ts +2 -1
  25. package/src/modules/auth/index.ts +59 -20
  26. package/src/modules/cache/index.ts +112 -32
  27. package/src/modules/cache/types.ts +2 -2
  28. package/src/modules/crdt/crdt-field.ts +294 -0
  29. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  30. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  31. package/src/modules/crdt/index.ts +463 -0
  32. package/src/modules/crdt/loro-loader.ts +25 -0
  33. package/src/modules/data/data.hydration.test.ts +142 -0
  34. package/src/modules/data/data.membership.test.ts +462 -0
  35. package/src/modules/data/data.rebind.test.ts +147 -0
  36. package/src/modules/data/data.run.test.ts +113 -0
  37. package/src/modules/data/data.settled-writes.test.ts +206 -0
  38. package/src/modules/data/data.status.test.ts +249 -0
  39. package/src/modules/data/id-set-plan.test.ts +122 -0
  40. package/src/modules/data/index.ts +1580 -130
  41. package/src/modules/data/mutation-id.test.ts +25 -0
  42. package/src/modules/data/mutation-id.ts +35 -0
  43. package/src/modules/data/window-query.test.ts +52 -0
  44. package/src/modules/data/window-query.ts +194 -0
  45. package/src/modules/devtools/flags.ts +349 -0
  46. package/src/modules/devtools/index.ts +386 -37
  47. package/src/modules/devtools/notify-throttle.test.ts +149 -0
  48. package/src/modules/devtools/storage-info.test.ts +79 -0
  49. package/src/modules/devtools/storage-info.ts +168 -0
  50. package/src/modules/devtools/versions.test.ts +74 -0
  51. package/src/modules/devtools/versions.ts +110 -0
  52. package/src/modules/feature-flag/index.test.ts +251 -0
  53. package/src/modules/feature-flag/index.ts +308 -0
  54. package/src/modules/ref-tables.test.ts +91 -0
  55. package/src/modules/ref-tables.ts +88 -0
  56. package/src/modules/sync/engine.ts +101 -37
  57. package/src/modules/sync/events/index.ts +9 -2
  58. package/src/modules/sync/queue/queue-down.test.ts +107 -0
  59. package/src/modules/sync/queue/queue-down.ts +35 -6
  60. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  61. package/src/modules/sync/queue/queue-up.ts +241 -57
  62. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  63. package/src/modules/sync/scheduler.retry.test.ts +156 -0
  64. package/src/modules/sync/scheduler.ts +158 -11
  65. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  66. package/src/modules/sync/sync.health.test.ts +149 -0
  67. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  68. package/src/modules/sync/sync.live-removal.test.ts +134 -0
  69. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  70. package/src/modules/sync/sync.subquery.test.ts +82 -0
  71. package/src/modules/sync/sync.ts +1558 -99
  72. package/src/modules/sync/utils.test.ts +269 -2
  73. package/src/modules/sync/utils.ts +201 -17
  74. package/src/otel/index.ts +13 -10
  75. package/src/services/blobs/blob-cache.test.ts +359 -0
  76. package/src/services/blobs/blob-cache.ts +603 -0
  77. package/src/services/blobs/blob-manifest.ts +227 -0
  78. package/src/services/blobs/blob-store.test.ts +77 -0
  79. package/src/services/blobs/blob-store.ts +359 -0
  80. package/src/services/blobs/blob.fixture.ts +90 -0
  81. package/src/services/blobs/index.ts +70 -0
  82. package/src/services/database/cache-engine.ts +160 -0
  83. package/src/services/database/connection-supervisor.test.ts +289 -0
  84. package/src/services/database/connection-supervisor.ts +415 -0
  85. package/src/services/database/database.query-timeout.test.ts +83 -0
  86. package/src/services/database/database.ts +32 -12
  87. package/src/services/database/engine-factory.ts +33 -0
  88. package/src/services/database/events/index.ts +2 -1
  89. package/src/services/database/index.ts +7 -0
  90. package/src/services/database/local-migrator.ts +30 -27
  91. package/src/services/database/local.test.ts +64 -0
  92. package/src/services/database/local.ts +478 -67
  93. package/src/services/database/plan-render.test.ts +159 -0
  94. package/src/services/database/plan-render.ts +108 -0
  95. package/src/services/database/relation-resolver.test.ts +413 -0
  96. package/src/services/database/relation-resolver.ts +0 -0
  97. package/src/services/database/remote.ts +110 -14
  98. package/src/services/database/sqlite-cache-engine.test.ts +558 -0
  99. package/src/services/database/sqlite-cache-engine.ts +1257 -0
  100. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  101. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  102. package/src/services/database/sqlite-open.test.ts +150 -0
  103. package/src/services/database/sqlite-open.ts +164 -0
  104. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  105. package/src/services/database/sqlite-plan-sql.ts +106 -0
  106. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  107. package/src/services/database/sqlite-select.test.ts +246 -0
  108. package/src/services/database/sqlite-select.ts +121 -0
  109. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  110. package/src/services/database/sqlite-transport.ts +221 -0
  111. package/src/services/database/sqlite-worker.ts +437 -0
  112. package/src/services/database/surql-translate.ts +416 -0
  113. package/src/services/database/surreal-cache-engine.ts +141 -0
  114. package/src/services/logger/index.ts +3 -2
  115. package/src/services/persistence/localstorage.ts +2 -2
  116. package/src/services/persistence/resilient.ts +11 -4
  117. package/src/services/persistence/surrealdb.ts +10 -10
  118. package/src/services/stream-processor/index.ts +444 -52
  119. package/src/services/stream-processor/permissions.test.ts +47 -0
  120. package/src/services/stream-processor/permissions.ts +53 -0
  121. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  122. package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
  123. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  124. package/src/services/stream-processor/wasm-types.ts +23 -2
  125. package/src/services/tabs/broker-client.ts +283 -0
  126. package/src/services/tabs/broker.test.ts +278 -0
  127. package/src/services/tabs/coordinator.test.ts +244 -0
  128. package/src/services/tabs/coordinator.ts +576 -0
  129. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  130. package/src/services/tabs/leader-locks.ts +75 -0
  131. package/src/services/tabs/protocol.ts +242 -0
  132. package/src/services/tabs/support.ts +36 -0
  133. package/src/services/tabs/tabs-broker-worker.ts +586 -0
  134. package/src/sp00ky.auth-order.test.ts +92 -0
  135. package/src/sp00ky.init-query.test.ts +183 -0
  136. package/src/sp00ky.ts +1543 -0
  137. package/src/types.ts +496 -13
  138. package/src/utils/blurhash.ts +90 -0
  139. package/src/utils/error-classification.test.ts +44 -0
  140. package/src/utils/error-classification.ts +7 -0
  141. package/src/utils/index.ts +73 -13
  142. package/src/utils/parser.ts +3 -2
  143. package/src/utils/semver.test.ts +32 -0
  144. package/src/utils/semver.ts +30 -0
  145. package/src/utils/surql.ts +30 -18
  146. package/src/utils/withRetry.test.ts +1 -1
  147. package/tsdown.config.ts +86 -1
  148. package/src/spooky.ts +0 -395
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RecordId } from "surrealdb";
2
- import { RecordId as RecordId$1, SchemaStructure } from "@spooky-sync/query-builder";
2
+ import { QueryPlan, QueryPlan as QueryPlan$1, RecordId as RecordId$1, SchemaStructure, WhereNode } from "@spooky-sync/query-builder";
3
3
  import { Level, Level as Level$1, Logger, LoggerOptions } from "pino";
4
4
 
5
5
  //#region src/events/index.d.ts
@@ -123,9 +123,223 @@ declare class EventSystem<E extends EventTypeMap> {
123
123
  private broadcastEvent;
124
124
  }
125
125
  //#endregion
126
+ //#region src/modules/sync/events/index.d.ts
127
+ declare const SyncEventTypes: {
128
+ readonly QueryUpdated: "SYNC_QUERY_UPDATED";
129
+ readonly RemoteDataIngested: "SYNC_REMOTE_DATA_INGESTED";
130
+ readonly MutationRolledBack: "SYNC_MUTATION_ROLLED_BACK";
131
+ readonly SyncHealthChanged: "SYNC_HEALTH_CHANGED";
132
+ };
133
+ type SyncEventTypeMap = {
134
+ [SyncEventTypes.QueryUpdated]: EventDefinition<typeof SyncEventTypes.QueryUpdated, {
135
+ queryId: any;
136
+ localHash?: string;
137
+ localArray?: RecordVersionArray;
138
+ remoteHash?: string;
139
+ remoteArray?: RecordVersionArray;
140
+ records: Record<string, any>[];
141
+ }>;
142
+ [SyncEventTypes.RemoteDataIngested]: EventDefinition<typeof SyncEventTypes.RemoteDataIngested, {
143
+ records: Record<string, any>[];
144
+ }>;
145
+ [SyncEventTypes.MutationRolledBack]: EventDefinition<typeof SyncEventTypes.MutationRolledBack, {
146
+ eventType: string;
147
+ recordId: string;
148
+ error: string;
149
+ }>;
150
+ [SyncEventTypes.SyncHealthChanged]: EventDefinition<typeof SyncEventTypes.SyncHealthChanged, SyncHealth>;
151
+ };
152
+ type SyncEventSystem = EventSystem<SyncEventTypeMap>;
153
+ //#endregion
126
154
  //#region src/services/logger/index.d.ts
127
155
  type Logger$1 = Logger;
128
156
  //#endregion
157
+ //#region src/services/database/events/index.d.ts
158
+ declare const DatabaseEventTypes: {
159
+ readonly LocalQuery: "DATABASE_LOCAL_QUERY";
160
+ readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
161
+ };
162
+ interface DatabaseQueryEventPayload {
163
+ query: string;
164
+ vars?: Record<string, unknown>;
165
+ duration: number;
166
+ success: boolean;
167
+ error?: string;
168
+ timestamp: number;
169
+ }
170
+ type DatabaseEventTypeMap = {
171
+ [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
172
+ [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
173
+ };
174
+ type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
175
+ //#endregion
176
+ //#region src/utils/surql.d.ts
177
+ interface SealedQuery<T = void> {
178
+ readonly sql: string;
179
+ readonly extract: (results: unknown[]) => T;
180
+ }
181
+ //#endregion
182
+ //#region src/modules/devtools/storage-info.d.ts
183
+ /** Engine-side numbers only the engine can produce (worker round-trips). */
184
+ interface EngineStorageDiagnostics {
185
+ engine: 'sqlite';
186
+ bucketId: string;
187
+ useOpfs: boolean;
188
+ workerSelectConfigured: boolean;
189
+ /** `false` while configured `true` means the runtime downgraded to the
190
+ * legacy multi-hop select (stale cached worker bundle). */
191
+ workerSelectEffective: boolean;
192
+ /** page_count * page_size. */
193
+ dbSizeBytes?: number;
194
+ /** freelist_count * page_size — reclaimable via VACUUM. */
195
+ freelistBytes?: number;
196
+ tableCounts?: {
197
+ table: string;
198
+ rows: number;
199
+ }[];
200
+ error?: string;
201
+ }
202
+ /**
203
+ * Shared-tabs coordination state. Reported ONLY when `sharedTabs: true` was
204
+ * configured (apps that never asked for it get `null`, so the panel shows
205
+ * nothing). `active: false` with a `reason` is itself the useful signal: the
206
+ * app asked to share one store and this tab is not, so it owns or contends for
207
+ * the OPFS pool alone.
208
+ */
209
+ //#endregion
210
+ //#region src/services/database/cache-engine.d.ts
211
+ /**
212
+ * A materialized row. Keys are field names; values are already decoded to the
213
+ * client's runtime shapes (RecordId stays a RecordId, bytes a Uint8Array, …) so
214
+ * every backend hands `DataModule` the same shape SurrealDB does today.
215
+ */
216
+ type Row = Record<string, unknown>;
217
+ /** A record identifier — a `RecordId` or its stable string form (`table:id`). */
218
+ type Id = unknown;
219
+ /** How an order clause is expressed everywhere in the engine layer. */
220
+ type OrderBy = [field: string, direction: 'asc' | 'desc'][];
221
+ /**
222
+ * Batched relation fetch: "give me every row of `table` whose `matchField` is
223
+ * one of `keys`, filtered by `where`, ordered by `orderBy`". This is the single
224
+ * primitive relation decomposition (§3) leans on — implemented as
225
+ * `SELECT … WHERE <matchField> IN (…)` on SQLite, `SELECT … FROM $keys` /
226
+ * `WHERE <matchField> IN $keys` on SurrealDB, or an index scan elsewhere. Order
227
+ * here is a hint; the resolver re-applies order+limit PER PARENT after grouping.
228
+ */
229
+ interface RelationFetch {
230
+ table: string;
231
+ matchField: string;
232
+ keys: Id[];
233
+ where?: WhereNode[];
234
+ orderBy?: OrderBy;
235
+ select?: string[];
236
+ }
237
+ /**
238
+ * The read side of an engine, minus relation resolution — the surface a
239
+ * {@link RelationResolver} needs. Kept separate so the resolver can be unit
240
+ * tested against an in-memory fake without a full engine.
241
+ */
242
+ interface RowFetcher {
243
+ /** Batched fan-out fetch. See {@link RelationFetch}. */
244
+ fetchRelation(req: RelationFetch): Promise<Row[]>;
245
+ }
246
+ /** A transaction handle — the same verbs as the engine, but atomic. */
247
+ interface EngineTx {
248
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
249
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
250
+ delete(table: string, id: Id): Promise<void>;
251
+ }
252
+ /**
253
+ * A pluggable local cache backend. SurrealDB (the default) and SQLite both
254
+ * implement this; the rest of the client talks verbs, never SurrealQL.
255
+ *
256
+ * Reactivity is NOT part of this contract: the local cache is passive. The SSP
257
+ * (remote) drives change; `DataModule` writes rows here and re-reads them. The
258
+ * `epoch` field preserves the existing bucket-switch fencing (see
259
+ * `LocalDatabaseService.epoch`): an async chain captures it at start and its
260
+ * write is dropped if the epoch moved (a bucket switch) in between.
261
+ */
262
+ interface LocalCacheEngine extends RowFetcher {
263
+ /** Monotonic store generation; bumped on every bucket switch. */
264
+ readonly epoch: number;
265
+ connect(bucketId: string): Promise<void>;
266
+ switchBucket(bucketId: string): Promise<void>;
267
+ close(): Promise<void>;
268
+ /** Run `fn` inside a single atomic transaction. */
269
+ transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T>;
270
+ /**
271
+ * Materialize a query, including its `.related()` tree (via §3
272
+ * decomposition). Params bind `where` `paramRef`s and any windowing id-set.
273
+ */
274
+ select(plan: QueryPlan$1, params?: Record<string, unknown>): Promise<Row[]>;
275
+ /** Fetch rows by primary id, preserving `ids` order; missing ids are skipped. */
276
+ selectByIds(table: string, ids: Id[], opts?: {
277
+ select?: string[];
278
+ orderBy?: OrderBy;
279
+ }): Promise<Row[]>;
280
+ /** Single-record read by primary id, or `null`. */
281
+ getById(table: string, id: Id): Promise<Row | null>;
282
+ upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void>;
283
+ patch(table: string, id: Id, patches: unknown[]): Promise<void>;
284
+ delete(table: string, id: Id): Promise<void>;
285
+ }
286
+ /**
287
+ * The full surface the client's `this.local` field depends on: the
288
+ * engine-neutral {@link LocalCacheEngine} verbs PLUS the legacy
289
+ * SurrealQL/lifecycle methods the not-yet-migrated call sites still use.
290
+ * `SurrealCacheEngine` (subclass of `LocalDatabaseService`) and
291
+ * `SqliteCacheEngine` (via a SurrealQL-vocabulary shim) both satisfy this, so
292
+ * either can back `this.local`.
293
+ *
294
+ * `getClient()` returns the underlying SurrealDB `Surreal` handle where one
295
+ * exists (SurrealDB backend); backends without one (SQLite) throw — it is only
296
+ * used by advanced/DevTools paths, never on the hot path.
297
+ */
298
+ interface LocalStore extends LocalCacheEngine {
299
+ /**
300
+ * Whether this engine needs SurrealQL schema provisioning (`DEFINE TABLE`,
301
+ * `DEFINE FIELD`, …) run against it at init / bucket switch. SurrealDB → true;
302
+ * schemaless engines (SQLite creates tables lazily) → false, so the client
303
+ * skips the `LocalMigrator` entirely for them.
304
+ */
305
+ readonly usesSurqlSchema: boolean;
306
+ query<T extends unknown[]>(query: string, vars?: Record<string, unknown>, opts?: {
307
+ epoch?: number;
308
+ }): Promise<T>;
309
+ execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>, opts?: {
310
+ epoch?: number;
311
+ }): Promise<T>;
312
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
313
+ switchStore(bucketId: string): Promise<void>;
314
+ beginSwitch(): () => void;
315
+ getEvents(): DatabaseEventSystem;
316
+ getClient(): unknown;
317
+ getConfig(): Sp00kyConfig<any>['database'];
318
+ readonly currentBucketId: string;
319
+ /** Which built-in backend this is. OPTIONAL: absent (custom engines) is
320
+ * reported as `'custom'` by DevTools. More robust than `instanceof` for
321
+ * engines constructed outside this package. */
322
+ readonly engineKind?: 'surrealdb' | 'sqlite';
323
+ /** Engine-specific storage numbers for DevTools (DB file size, per-table
324
+ * row counts). OPTIONAL: only engines with something to report implement it. */
325
+ getStorageDiagnostics?(opts?: {
326
+ tableCounts?: boolean;
327
+ }): Promise<EngineStorageDiagnostics>;
328
+ /**
329
+ * Durability of this engine's local store. OPTIONAL: engines that don't
330
+ * report it (SurrealDB, custom engines) are treated as `'unknown'` by the
331
+ * client facade, so adding this needs no change on their side.
332
+ */
333
+ readonly storageHealth?: StorageHealth;
334
+ /** Fires immediately with the current snapshot, then on every change.
335
+ * Returns an unsubscribe function. */
336
+ subscribeToStorageHealth?(cb: (health: StorageHealth) => void): () => void;
337
+ }
338
+ /** Selected local cache backend. Mirrors the `persistenceClient` config pattern. */
339
+ type LocalEngineChoice = 'surrealdb' | 'sqlite' | LocalStore;
340
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
341
+ * a guard against a cyclic schema producing unbounded fan-out. */
342
+ //#endregion
129
343
  //#region src/modules/sync/queue/queue-up.d.ts
130
344
  type CreateEvent = {
131
345
  type: 'create';
@@ -192,22 +406,38 @@ interface PersistenceClient {
192
406
  * Format: number + unit (m=minutes, h=hours, d=days).
193
407
  */
194
408
  type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
409
+ /**
410
+ * Refresh behavior for `preload` when the data is already cached locally (warm).
411
+ * The FIRST load (cold) always fetches + blocks regardless.
412
+ * - `onUse` (default): do nothing when warm — the data freshens on use, when the
413
+ * real `useQuery` mounts and registers its live view. No network on load.
414
+ * - `background`: return instantly, but kick a one-time silent refetch.
415
+ * - `stale`: like `background`, but only if the cached copy is older than
416
+ * `staleTime`.
417
+ */
418
+ type PreloadRefresh = 'onUse' | 'background' | 'stale';
419
+ interface PreloadOptions {
420
+ /** How to refresh when the query is already cached locally. Default `onUse`. */
421
+ refresh?: PreloadRefresh;
422
+ /** For `refresh: 'stale'` — max age before a warm copy is refetched. Default `1h`. */
423
+ staleTime?: QueryTimeToLive;
424
+ }
195
425
  /**
196
426
  * Result object returned when a query is registered or executed.
197
427
  */
198
- interface SpookyQueryResult {
428
+ interface Sp00kyQueryResult {
199
429
  /** The unique hash identifier for the query. */
200
430
  hash: string;
201
431
  }
202
- type SpookyQueryResultPromise = Promise<SpookyQueryResult>;
432
+ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
203
433
  interface EventSubscriptionOptions {
204
434
  priority?: number;
205
435
  }
206
436
  /**
207
- * Configuration options for the Spooky client.
437
+ * Configuration options for the Sp00ky client.
208
438
  * @template S The schema structure type.
209
439
  */
210
- interface SpookyConfig<S extends SchemaStructure> {
440
+ interface Sp00kyConfig<S extends SchemaStructure> {
211
441
  /** Database connection configuration. */
212
442
  database: {
213
443
  /** The SurrealDB endpoint URL. */
@@ -220,27 +450,325 @@ interface SpookyConfig<S extends SchemaStructure> {
220
450
  store?: StoreType;
221
451
  /** Authentication token. */
222
452
  token?: string;
453
+ /**
454
+ * SQLite engine only: execute `select` plans (base rows + relation tree +
455
+ * row parsing) inside the worker as ONE round-trip instead of one hop per
456
+ * table/relation level. Defaults to true; set false to force the legacy
457
+ * multi-hop path (escape hatch while the worker-side path beds in).
458
+ */
459
+ workerSelect?: boolean;
460
+ /**
461
+ * WebSocket reconnect + liveness tuning. All fields optional; the defaults
462
+ * keep the connection alive indefinitely without configuration. See
463
+ * {@link ReconnectConfig}.
464
+ */
465
+ reconnect?: ReconnectConfig;
466
+ /**
467
+ * Deadline (ms) for every remote RPC. Remote queries are serialized through
468
+ * a single promise chain, so one call that never settles (half-open socket:
469
+ * the WebSocket looks open, the peer is gone, no `close` event fires) would
470
+ * otherwise wedge ALL later remote traffic behind it — including the sync
471
+ * poll's own health probe, leaving health pinned at `healthy` with no
472
+ * banner and no self-heal. The deadline turns that into an ordinary network
473
+ * failure the queue retries. `0` disables. Defaults to `60_000`.
474
+ */
475
+ queryTimeoutMs?: number;
223
476
  };
224
- /** Unique client identifier. If not provided, one will be generated. */
225
- clientId?: string;
226
477
  /** The schema definition. */
227
478
  schema: S;
228
479
  /** The compiled SURQL schema string. */
229
480
  schemaSurql: string;
230
481
  /** Logging level. */
231
- logLevel: Level;
482
+ logLevel: Level$1;
232
483
  /**
233
484
  * Persistence client to use.
234
485
  * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
235
486
  */
236
487
  persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
488
+ /**
489
+ * Local cache engine backend. `'surrealdb'` (default) uses the in-browser
490
+ * SurrealDB-WASM store; `'sqlite'` uses official SQLite-WASM in a Worker with
491
+ * OPFS persistence; or pass a custom {@link LocalCacheEngine}. The local cache
492
+ * is a passive queryable store — reactivity is driven by the remote SSP, not
493
+ * this engine. See `services/database/cache-engine.ts`.
494
+ */
495
+ localEngine?: LocalEngineChoice;
496
+ /**
497
+ * Durable cache for bucket file bytes, in OPFS. Enabled by default wherever
498
+ * OPFS is writable; elsewhere the cache degrades to per-tab memory, which is
499
+ * how bucket reads behaved before it existed.
500
+ *
501
+ * Nothing in this cache expires on a timer — an image whose row is still in
502
+ * the local store has to stay available offline. Bytes are only dropped when
503
+ * the app invalidates the path (`bucket.put`/`bucket.delete`), when boot
504
+ * reconcile finds no file behind a row, or when the cache is over budget, in
505
+ * which case the least-recently-used unpinned entries go first. See
506
+ * `services/blobs/blob-cache.ts`.
507
+ */
508
+ blobCache?: {
509
+ /** Default `true`. `false` restores per-tab, non-persistent caching. */
510
+ enabled?: boolean;
511
+ /** Byte budget. Defaults to `min(512 MB, quota × 0.25)` from
512
+ * `navigator.storage.estimate()`. */
513
+ maxBytes?: number;
514
+ /**
515
+ * Delete the signed-out user's cached bytes on `signOut()`. Default
516
+ * `false`, matching the local store: cached files are namespaced per local
517
+ * bucket, so signing back in is warm and no user can read another's cache.
518
+ * Turn on for shared devices.
519
+ */
520
+ clearOnSignOut?: boolean;
521
+ };
522
+ /**
523
+ * Share ONE durable local store across all tabs of this origin (default
524
+ * `false`). Requires `localEngine: 'sqlite'`. A SharedWorker broker elects a
525
+ * leader tab per bucket via Web Locks; the leader owns the OPFS SQLite
526
+ * worker and the sync loop, and follower tabs read/write the same store over
527
+ * MessagePorts, so every tab is durable instead of only the first one.
528
+ *
529
+ * Falls back to solo mode (exactly the flag-off behavior, including the
530
+ * later-tabs in-memory fallback reported via {@link StorageHealth}) whenever
531
+ * SharedWorker, Web Locks, or MessageChannel are unavailable, the engine is
532
+ * not sqlite, or the broker rejects the tab (mixed app versions).
533
+ *
534
+ * Failover: when the leader tab closes or freezes, a follower is promoted
535
+ * within seconds; queries briefly refetch and mutations are never lost once
536
+ * their local write resolved (the shared outbox survives in the store).
537
+ * Inspect via `window.__00__.getState().database.tabs` and `__sqliteStats`.
538
+ */
539
+ sharedTabs?: boolean;
540
+ /**
541
+ * Persist the in-browser SSP circuit (store + view caches) as a snapshot so a
542
+ * reload can restore it instead of re-materializing. Default `false`, and
543
+ * that default is deliberate.
544
+ *
545
+ * The circuit is DERIVED state: the durable local store (OPFS SQLite) is the
546
+ * source of truth, and every first paint already reads row bodies from it
547
+ * (`DataManager.createNewQuery` / `materializeRecords`) using the circuit only
548
+ * for row identity and ordering. A snapshot buys nothing on reload while
549
+ * costing a full deep clone of every row of every ingested table plus a JSON
550
+ * encode of the result, `Circuit::save` in the Rust core, mirroring the
551
+ * server's rule in `ssp-node`: *never per-ingest*.
552
+ *
553
+ * When enabled, snapshots are written on a checkpoint interval
554
+ * ({@link circuitCheckpointMs}) and on `pagehide`, never per ingest or per
555
+ * query registration. Enable only for a workload that has measured a win.
556
+ */
557
+ persistCircuit?: boolean;
558
+ /**
559
+ * Checkpoint interval in milliseconds for {@link persistCircuit}. Defaults to
560
+ * 30000. Ignored when `persistCircuit` is off.
561
+ */
562
+ circuitCheckpointMs?: number;
237
563
  /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
238
564
  otelTransmit?: PinoTransmit;
239
565
  /**
240
- * Debounce time in milliseconds for stream updates.
241
- * Defaults to 100ms.
566
+ * Debounce time in milliseconds for stream updates (the client-side SSP
567
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
568
+ * per-record updates per query before notifying readers).
569
+ * Defaults to 50ms.
242
570
  */
243
571
  streamDebounceTime?: number;
572
+ /**
573
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
574
+ * changes to the remote database. Local writes happen immediately on
575
+ * every keystroke (so reload/offline works), but the remote UPSERT is
576
+ * coalesced over this window. Lower = snappier remote propagation +
577
+ * more network traffic; higher = less traffic + more lag for other
578
+ * collaborators. Defaults to 500ms.
579
+ */
580
+ crdtDebounceMs?: number;
581
+ /**
582
+ * Enable collaborative CRDT fields. When `true`, the `loro-crdt` engine is
583
+ * preloaded at client startup (fetched as a separate chunk on page load) so
584
+ * the first `openCrdtField` is instant. When omitted/`false`, loro is never
585
+ * loaded unless a CRDT field is explicitly opened — keeping the loro chunk
586
+ * out of apps that don't use collaboration. Defaults to `false`.
587
+ */
588
+ crdt?: boolean;
589
+ /**
590
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
591
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
592
+ * convergence + more query load; higher = the inverse. Non-positive
593
+ * values fall back to the default (500ms).
594
+ */
595
+ refSyncIntervalMs?: number;
596
+ /**
597
+ * OPT-IN instant-hydrate for cold queries: when enabled and a query is
598
+ * registered with no server result yet, its surql also runs directly on the
599
+ * remote (one-shot, in the background, OFF the paint path) so rows can land
600
+ * before the full register lifecycle completes. Hydrated rows carry their
601
+ * `_00_rv` versions so the registration's `syncRecords` skips re-pulling
602
+ * unchanged bodies. Regardless of this flag, `useQuery` always resolves and
603
+ * paints from the local cache immediately — however the rows got there
604
+ * (preload, prior sync). Default `false`: the register lifecycle
605
+ * (`fn::query::register` → `_00_list_ref` → record sync) is the single
606
+ * freshness path and no duplicate one-shot fetches are made.
607
+ */
608
+ instantHydrate?: boolean;
609
+ /**
610
+ * Enable realtime sync while signed out. When `true`, the client starts its
611
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
612
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
613
+ * page gets live `useQuery` updates over world-readable tables. Requires the
614
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
615
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
616
+ * one-shot but never sync live.
617
+ */
618
+ enableAnonymousLiveQueries?: boolean;
619
+ /**
620
+ * Surface sustained sync failures as a "degraded" health status that the app
621
+ * can observe via `subscribeToSyncHealth` (or the client-solid
622
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
623
+ *
624
+ * Individual failures — a transient remote 500 on query registration, a
625
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
626
+ * throw at the app. This only controls when a *run* of consecutive failures
627
+ * is reported. Status flips back to `healthy` on the next successful sync
628
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
629
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
630
+ */
631
+ syncHealth?: SyncHealthConfig | false;
632
+ /**
633
+ * Automatic blurhash placeholders for bucket image uploads. On every
634
+ * `bucket.put` of an image path (by extension: webp/png/jpg/jpeg/gif/avif/bmp)
635
+ * the client computes a blurhash and stores it as a tiny sidecar object
636
+ * `<path>.bh` in the same bucket, best-effort. Read it back with
637
+ * `bucket.blurhash(path)` (or the client-solid `useBucketImage`/`BucketImage`
638
+ * helpers) to paint a placeholder until the image is decoded.
639
+ *
640
+ * `true` (the default) enables with 4x3 components; pass
641
+ * `{ componentX, componentY }` to tune detail, or `false` to disable.
642
+ * A per-call `put(path, content, { blurhash })` option overrides this.
643
+ */
644
+ blurhash?: boolean | {
645
+ componentX?: number;
646
+ componentY?: number;
647
+ };
648
+ /**
649
+ * Deadline (ms) for a single outgoing mutation push. Tighter than
650
+ * {@link Sp00kyConfig.database.queryTimeoutMs} because the up-queue drains
651
+ * one mutation at a time behind an `isSyncingUp` flag: a push that never
652
+ * settles stops every later mutation for the session, with no retry and no
653
+ * error. On expiry the push is treated as a network failure and re-queued.
654
+ * `0` disables. Defaults to `30_000`.
655
+ */
656
+ pushTimeoutMs?: number;
657
+ }
658
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
659
+ interface SyncHealthConfig {
660
+ /**
661
+ * Number of consecutive failed sync rounds (up or down) before the status
662
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
663
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
664
+ * disables degraded reporting entirely.
665
+ */
666
+ degradeAfterConsecutiveFailures?: number;
667
+ }
668
+ /**
669
+ * Tunables for WebSocket reconnect and liveness detection. See
670
+ * {@link Sp00kyConfig.database.reconnect}.
671
+ *
672
+ * Two independent mechanisms cooperate here. The SurrealDB SDK reconnects on
673
+ * its own after a socket `close` (`attempts` / `retryDelayMax`), and a
674
+ * supervisor above it re-opens the connection from scratch whenever the SDK
675
+ * gives up or its post-reconnect handshake fails — the SDK terminates the
676
+ * engine permanently in that case, so a supervisor is required, not optional.
677
+ * The heartbeat covers the third case: a socket that never closes at all.
678
+ */
679
+ interface ReconnectConfig {
680
+ /**
681
+ * SDK reconnect attempts after a socket close. `-1` retries forever.
682
+ * Defaults to `-1` (the SDK's own default is `5`, which caps recovery at a
683
+ * ~62s outage and then gives up for the life of the page).
684
+ */
685
+ attempts?: number;
686
+ /** Cap on the SDK's exponential backoff delay. Defaults to `15_000`. */
687
+ retryDelayMax?: number;
688
+ /**
689
+ * Cadence of the application-level liveness probe (`RETURN true`) that
690
+ * detects a half-open socket the transport never reports as closed.
691
+ * `0` disables the heartbeat. Defaults to `20_000`.
692
+ */
693
+ heartbeatIntervalMs?: number;
694
+ /**
695
+ * Deadline for a heartbeat response. Exceeding it means the socket is dead
696
+ * regardless of what its `readyState` claims, so the connection is torn down
697
+ * and rebuilt. Defaults to `10_000`.
698
+ */
699
+ heartbeatTimeoutMs?: number;
700
+ /**
701
+ * Cap on the supervisor's own backoff between `connect()` retries once the
702
+ * SDK has given up. Defaults to `15_000`.
703
+ */
704
+ superviseRetryDelayMaxMs?: number;
705
+ }
706
+ /**
707
+ * Transport-level connection state, independent of {@link SyncHealthStatus}.
708
+ *
709
+ * These answer different questions: `connection` is about the socket,
710
+ * `status` is about whether sync rounds are succeeding. A `connected` socket
711
+ * can still be `degraded` (server erroring), and a `reconnecting` socket is
712
+ * usually still `healthy` for the first few seconds.
713
+ */
714
+ type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
715
+ type SyncHealthStatus = 'healthy' | 'degraded';
716
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
717
+ interface SyncHealth {
718
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
719
+ status: SyncHealthStatus;
720
+ /** Consecutive failed sync rounds at the moment of this report. */
721
+ consecutiveFailures: number;
722
+ /** Classification of the most recent failure (only set while `degraded`). */
723
+ kind?: 'network' | 'application';
724
+ /** Message of the most recent failure (only set while `degraded`). */
725
+ error?: string;
726
+ /**
727
+ * `true` once at least one sync round has succeeded this session. Lets a UI
728
+ * distinguish a first-time "connecting" phase (never reached the server yet,
729
+ * so a cold-start failure run is expected) from a real lost connection after
730
+ * a working session. Never resets back to `false` once set.
731
+ */
732
+ everConnected: boolean;
733
+ /**
734
+ * Live transport state of the remote WebSocket. Distinct from `status`: this
735
+ * one flips the instant the socket drops, whereas `status` only degrades
736
+ * after a sustained run of failed sync rounds. Use it to show "reconnecting…"
737
+ * immediately without waiting for the degrade threshold.
738
+ */
739
+ connection: ConnectionState;
740
+ }
741
+ type StorageHealthStatus = 'unknown' | 'persistent' | 'memory';
742
+ /**
743
+ * Durability of the LOCAL cache, delivered to `subscribeToStorageHealth`
744
+ * subscribers. Separate from {@link SyncHealth}: that one is about reaching the
745
+ * server, this one is about whether the local store survives a reload.
746
+ *
747
+ * Under `localEngine: 'sqlite'` the durable store is the OPFS SAHPool VFS,
748
+ * which only one client per bucket can hold open. When it can't be opened (a
749
+ * second tab of the app already has it, an insecure context, a full pool) the
750
+ * engine keeps working against an in-memory DB, which holds the whole dataset
751
+ * in RAM and loses local writes on reload. `fallback` marks exactly that case,
752
+ * so a UI can warn about it.
753
+ */
754
+ interface StorageHealth {
755
+ /** `'unknown'` until the local cache has opened, or for engines that don't report. */
756
+ status: StorageHealthStatus;
757
+ /**
758
+ * `true` only when durable storage was REQUESTED and could not be opened.
759
+ * Stays `false` for a configured-in-memory store (`store: 'memory'`), which
760
+ * is a choice rather than a failure, so a UI can key off this alone.
761
+ */
762
+ fallback: boolean;
763
+ /** Reason durable storage failed (only set while `fallback` is `true`). */
764
+ error?: string;
765
+ /**
766
+ * Shared-tabs role, set only when `sharedTabs` is active: `'leader'` owns
767
+ * the OPFS worker, `'follower'` shares it over a MessagePort (its data IS
768
+ * durable, hence `status: 'persistent'`), `'solo'` fell back to the
769
+ * single-tab behavior. Absent entirely when the feature is off.
770
+ */
771
+ role?: 'leader' | 'follower' | 'solo';
244
772
  }
245
773
  type QueryHash = string;
246
774
  type RecordVersionArray = Array<[string, number]>;
@@ -271,12 +799,68 @@ interface QueryConfig {
271
799
  id: RecordId$1<string>;
272
800
  /** The SURQL query string. */
273
801
  surql: string;
802
+ /**
803
+ * Engine-neutral plan for `surql` (in-memory only; not persisted to
804
+ * `_00_query`). Present when the query came from the query-builder. Non-
805
+ * SurrealQL local engines (SQLite) materialize via `engine.select(plan)`
806
+ * instead of re-running `surql`, which they cannot parse.
807
+ */
808
+ plan?: QueryPlan;
274
809
  /** Parameters used in the query. */
275
810
  params: Record<string, any>;
276
811
  /** The version array representing the local state of results. */
277
812
  localArray: RecordVersionArray;
278
813
  /** The version array representing the remote (server) state of results. */
279
814
  remoteArray: RecordVersionArray;
815
+ /**
816
+ * In-memory only (never persisted to `_00_query`): version array of the
817
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
818
+ * child-body sync is idempotent across polls. Kept separate from
819
+ * `remoteArray` so related child rows never enter the primary window /
820
+ * `rowCount` / `localArray`.
821
+ */
822
+ subqueryRemoteArray?: RecordVersionArray;
823
+ /**
824
+ * Whether authoritative membership (`remoteArray`) has ever been established
825
+ * for this query — either fetched from `_00_list_ref` this session, or read
826
+ * back from the durable `_00_window` row on a cold start.
827
+ *
828
+ * Tri-state matters: "known and empty" must render an empty list, while
829
+ * "never established" has to fall back to a predicate scan of the local store
830
+ * so a query first run on this device still paints offline. A
831
+ * `remoteArray.length === 0` check cannot tell those apart.
832
+ */
833
+ membershipKnown?: boolean;
834
+ /**
835
+ * Whether a NON-EMPTY id-set has arrived from the server for this query in
836
+ * this session. Gates whether an empty read may be believed.
837
+ *
838
+ * The server publishes `_00_list_ref` asynchronously — the SSP queues a
839
+ * view's initial edges to a coalescing flusher and returns from
840
+ * `fn::query::register` before they land — so an empty read right after
841
+ * registration says nothing about the query being empty. Believing it (and
842
+ * mirroring it to the durable `_00_window` row) blanked lists and kept them
843
+ * blank across reloads. Once a real set has been seen, a later empty one is a
844
+ * genuine transition and must be honoured, or removed rows resurrect.
845
+ *
846
+ * In-memory only: a fresh session must re-earn the right to believe empties.
847
+ */
848
+ remoteSeen?: boolean;
849
+ /**
850
+ * Consecutive empty id-sets read from the server while `remoteSeen` is still
851
+ * false. Bounds how long an unconfirmed empty may be ignored, so a window
852
+ * that genuinely emptied while this device was away is believed on the second
853
+ * read instead of rendering stale rows forever. Reset by any non-empty set.
854
+ * In-memory only.
855
+ */
856
+ emptyReads?: number;
857
+ /**
858
+ * Key of this query's durable `_00_window` membership row: a hash of
859
+ * `{surql, params}` WITHOUT the `session::id()` salt that `id` carries, so it
860
+ * survives a reload (which mints a new session id) and a bucket switch.
861
+ * In-memory only.
862
+ */
863
+ membershipKey?: string;
280
864
  /** Time-To-Live for this query. */
281
865
  ttl: QueryTimeToLive;
282
866
  /** Timestamp when the query was last accessed/active. */
@@ -287,6 +871,17 @@ interface QueryConfig {
287
871
  type QueryConfigRecord = QueryConfig & {
288
872
  id: string;
289
873
  };
874
+ /**
875
+ * Runtime fetch status of a live query.
876
+ * - `idle`: registered, initial sync completed, and not currently fetching
877
+ * missing records — the materialized rows are authoritative (a windowed
878
+ * query's short result really is the end of the list).
879
+ * - `fetching`: the query is registering (a query is born `fetching` until its
880
+ * initial remote sync completes) or the sync engine is fetching/ingesting
881
+ * missing records for it. Any pending debounced result is flushed BEFORE the
882
+ * flip back to `idle`, so idle status never races ahead of the rows.
883
+ */
884
+ type QueryStatus = 'idle' | 'fetching';
290
885
  /**
291
886
  * Internal state of a live query.
292
887
  */
@@ -295,14 +890,89 @@ interface QueryState {
295
890
  config: QueryConfig;
296
891
  /** The current cached records for this query. */
297
892
  records: Record<string, any>[];
893
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
894
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
895
+ hydrated?: boolean;
896
+ /** Set once `notifyQuerySynced` has emitted for this registration lifetime.
897
+ * Ephemeral (unlike the persisted `updateCount`), so a re-registered query
898
+ * always emits at least once even when its records are unchanged — otherwise
899
+ * an empty re-registered window would never notify and stay "loading". */
900
+ syncNotified?: boolean;
298
901
  /** Timer for TTL expiration. */
299
902
  ttlTimer: NodeJS.Timeout | null;
300
903
  /** TTL duration in milliseconds. */
301
904
  ttlDurationMs: number;
302
905
  /** Number of times the query has been updated. */
303
906
  updateCount: number;
907
+ /** Timestamp (ms) of the last user-visible update, or null before the first
908
+ * one. Surfaced to DevTools as `lastUpdate` — must NOT be stamped on read. */
909
+ lastUpdatedAt: number | null;
910
+ /**
911
+ * Rolling window of the most recent materialization-step latencies (ms).
912
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
913
+ * before each persist to `_00_query`. Samples themselves are not persisted.
914
+ */
915
+ materializationSamples: number[];
916
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
917
+ lastIngestLatencyMs: number | null;
918
+ /** Cumulative count of ingest/materialization errors observed for this query. */
919
+ errorCount: number;
920
+ /**
921
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
922
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
923
+ * pulling missing records for this query, otherwise `idle`.
924
+ */
925
+ status: QueryStatus;
926
+ /**
927
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
928
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
929
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
930
+ */
931
+ phaseSamples: Record<string, number[]>;
932
+ /** Most recent sample (ms) per phase, or null. */
933
+ phaseLast: Record<string, number | null>;
934
+ /** One-shot SSP registration timings (ms). */
935
+ registrationTimings: RegistrationTimings;
936
+ }
937
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
938
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
939
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
940
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
941
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
942
+ /** One-shot registration timings (ms), captured once when a query registers. */
943
+ interface RegistrationTimings {
944
+ /** SSP surql→plan parse + permission injection. */
945
+ parseMs: number | null;
946
+ /** SSP operator-DAG build. */
947
+ planMs: number | null;
948
+ /** SSP initial snapshot evaluation. */
949
+ snapshotMs: number | null;
950
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
951
+ wallMs: number | null;
952
+ }
953
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
954
+ interface PhaseStat {
955
+ lastMs: number | null;
956
+ p50: number | null;
957
+ p90: number | null;
958
+ p99: number | null;
959
+ count: number;
960
+ }
961
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
962
+ interface QueryTimings {
963
+ ssp: PhaseStat;
964
+ sspStoreApply: PhaseStat;
965
+ sspCircuitStep: PhaseStat;
966
+ sspTransform: PhaseStat;
967
+ localFetch: PhaseStat;
968
+ remoteFetch: PhaseStat;
969
+ frontend: PhaseStat;
970
+ registration: RegistrationTimings;
971
+ updateCount: number;
972
+ errorCount: number;
304
973
  }
305
974
  type QueryUpdateCallback = (records: Record<string, any>[]) => void;
975
+ type QueryStatusCallback = (status: QueryStatus) => void;
306
976
  type MutationCallback = (mutations: UpEvent[]) => void;
307
977
  type MutationEventType = 'create' | 'update' | 'delete';
308
978
  /**
@@ -331,6 +1001,13 @@ interface RunOptions {
331
1001
  assignedTo?: string;
332
1002
  max_retries?: number;
333
1003
  retry_strategy?: 'linear' | 'exponential';
1004
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
1005
+ timeout?: number;
1006
+ /**
1007
+ * Minimum delay in milliseconds before the job is eligible to run. While
1008
+ * delayed the job stays pending (enqueued) and can still be killed.
1009
+ */
1010
+ delay?: number;
334
1011
  }
335
1012
  /**
336
1013
  * Options for update operations.
@@ -356,4 +1033,4 @@ interface DebounceOptions {
356
1033
  delay?: number;
357
1034
  }
358
1035
  //#endregion
359
- export { Logger$1 as C, UpdateOptions as S, EventSystem as T, RunOptions as _, MutationEvent as a, SpookyQueryResultPromise as b, PinoTransmit as c, QueryHash as d, QueryState as f, RecordVersionDiff as g, RecordVersionArray as h, MutationCallback as i, QueryConfig as l, QueryUpdateCallback as m, EventSubscriptionOptions as n, MutationEventType as o, QueryTimeToLive as p, Level$1 as r, PersistenceClient as s, DebounceOptions as t, QueryConfigRecord as u, SpookyConfig as v, EventDefinition as w, StoreType as x, SpookyQueryResult as y };
1036
+ export { Sp00kyQueryResultPromise as A, LocalStore as B, ReconnectConfig as C, RunOptions as D, RegistrationTimings as E, SyncHealthConfig as F, SyncEventSystem as G, DatabaseEventSystem as H, SyncHealthStatus as I, EventDefinition as K, TimingPhase as L, StorageHealthStatus as M, StoreType as N, Sp00kyConfig as O, SyncHealth as P, UpdateOptions as R, QueryUpdateCallback as S, RecordVersionDiff as T, DatabaseEventTypes as U, SealedQuery as V, Logger$1 as W, QueryState as _, MATERIALIZATION_SAMPLE_WINDOW as a, QueryTimeToLive as b, MutationEventType as c, PinoTransmit as d, PreloadOptions as f, QueryHash as g, QueryConfigRecord as h, Level$1 as i, StorageHealth as j, Sp00kyQueryResult as k, PersistenceClient as l, QueryConfig as m, DebounceOptions as n, MutationCallback as o, PreloadRefresh as p, EventSystem as q, EventSubscriptionOptions as r, MutationEvent as s, ConnectionState as t, PhaseStat as u, QueryStatus as v, RecordVersionArray as w, QueryTimings as x, QueryStatusCallback as y, UpEvent as z };