@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

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