@spooky-sync/core 0.0.1-canary.24 → 0.0.1-canary.240

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 (303) hide show
  1. package/AGENTS.md +58 -0
  2. package/coverage/lcov-report/base.css +224 -0
  3. package/coverage/lcov-report/block-navigation.js +87 -0
  4. package/coverage/lcov-report/favicon.png +0 -0
  5. package/coverage/lcov-report/index.html +476 -0
  6. package/coverage/lcov-report/prettify.css +1 -0
  7. package/coverage/lcov-report/prettify.js +2 -0
  8. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  9. package/coverage/lcov-report/sorter.js +210 -0
  10. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +271 -0
  11. package/coverage/lcov-report/src/boot/boot.saga.ts.html +469 -0
  12. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +430 -0
  13. package/coverage/lcov-report/src/boot/index.html +161 -0
  14. package/coverage/lcov-report/src/boot/preload.saga.ts.html +178 -0
  15. package/coverage/lcov-report/src/client/bucket-handle.ts.html +766 -0
  16. package/coverage/lcov-report/src/client/index.html +161 -0
  17. package/coverage/lcov-report/src/client/router.ts.html +367 -0
  18. package/coverage/lcov-report/src/client/runtime.ts.html +940 -0
  19. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +1531 -0
  20. package/coverage/lcov-report/src/events/index.html +116 -0
  21. package/coverage/lcov-report/src/events/index.ts.html +877 -0
  22. package/coverage/lcov-report/src/index.html +146 -0
  23. package/coverage/lcov-report/src/index.ts.html +202 -0
  24. package/coverage/lcov-report/src/kernel/constants.ts.html +247 -0
  25. package/coverage/lcov-report/src/kernel/effects.ts.html +562 -0
  26. package/coverage/lcov-report/src/kernel/events.ts.html +250 -0
  27. package/coverage/lcov-report/src/kernel/index.html +176 -0
  28. package/coverage/lcov-report/src/kernel/interpreter.ts.html +514 -0
  29. package/coverage/lcov-report/src/kernel/saga.ts.html +304 -0
  30. package/coverage/lcov-report/src/modules/app-release/index.html +116 -0
  31. package/coverage/lcov-report/src/modules/app-release/index.ts.html +712 -0
  32. package/coverage/lcov-report/src/modules/auth/events/index.html +116 -0
  33. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +142 -0
  34. package/coverage/lcov-report/src/modules/auth/index.html +116 -0
  35. package/coverage/lcov-report/src/modules/auth/index.ts.html +1225 -0
  36. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +967 -0
  37. package/coverage/lcov-report/src/modules/crdt/index.html +146 -0
  38. package/coverage/lcov-report/src/modules/crdt/index.ts.html +1474 -0
  39. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +160 -0
  40. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +1132 -0
  41. package/coverage/lcov-report/src/modules/devtools/index.html +161 -0
  42. package/coverage/lcov-report/src/modules/devtools/index.ts.html +2413 -0
  43. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +589 -0
  44. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +415 -0
  45. package/coverage/lcov-report/src/modules/feature-flag/index.html +116 -0
  46. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +1033 -0
  47. package/coverage/lcov-report/src/modules/index.html +116 -0
  48. package/coverage/lcov-report/src/modules/ref-tables.ts.html +349 -0
  49. package/coverage/lcov-report/src/mutation/index.html +191 -0
  50. package/coverage/lcov-report/src/mutation/jobs.ts.html +208 -0
  51. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +190 -0
  52. package/coverage/lcov-report/src/mutation/push.saga.ts.html +730 -0
  53. package/coverage/lcov-report/src/mutation/rows.ts.html +1216 -0
  54. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +229 -0
  55. package/coverage/lcov-report/src/mutation/write.saga.ts.html +583 -0
  56. package/coverage/lcov-report/src/otel/index.html +116 -0
  57. package/coverage/lcov-report/src/otel/index.ts.html +466 -0
  58. package/coverage/lcov-report/src/query/env.ts.html +253 -0
  59. package/coverage/lcov-report/src/query/fetch.saga.ts.html +412 -0
  60. package/coverage/lcov-report/src/query/hash.ts.html +139 -0
  61. package/coverage/lcov-report/src/query/index.html +281 -0
  62. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +388 -0
  63. package/coverage/lcov-report/src/query/materialize.saga.ts.html +310 -0
  64. package/coverage/lcov-report/src/query/materialize.ts.html +217 -0
  65. package/coverage/lcov-report/src/query/membership.saga.ts.html +709 -0
  66. package/coverage/lcov-report/src/query/membership.ts.html +559 -0
  67. package/coverage/lcov-report/src/query/register.saga.ts.html +655 -0
  68. package/coverage/lcov-report/src/query/render-set.ts.html +265 -0
  69. package/coverage/lcov-report/src/query/sql.ts.html +322 -0
  70. package/coverage/lcov-report/src/query/window-query.ts.html +670 -0
  71. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +1894 -0
  72. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +766 -0
  73. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +1162 -0
  74. package/coverage/lcov-report/src/services/blobs/index.html +161 -0
  75. package/coverage/lcov-report/src/services/blobs/index.ts.html +295 -0
  76. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +664 -0
  77. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +1330 -0
  78. package/coverage/lcov-report/src/services/database/database.ts.html +658 -0
  79. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +184 -0
  80. package/coverage/lcov-report/src/services/database/errors.ts.html +187 -0
  81. package/coverage/lcov-report/src/services/database/events/index.html +116 -0
  82. package/coverage/lcov-report/src/services/database/events/index.ts.html +184 -0
  83. package/coverage/lcov-report/src/services/database/index.html +386 -0
  84. package/coverage/lcov-report/src/services/database/index.ts.html +121 -0
  85. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +703 -0
  86. package/coverage/lcov-report/src/services/database/local.ts.html +1633 -0
  87. package/coverage/lcov-report/src/services/database/plan-render.ts.html +409 -0
  88. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +682 -0
  89. package/coverage/lcov-report/src/services/database/remote.ts.html +1036 -0
  90. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +4132 -0
  91. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +220 -0
  92. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +577 -0
  93. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +499 -0
  94. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +478 -0
  95. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +757 -0
  96. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +1333 -0
  97. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +568 -0
  98. package/coverage/lcov-report/src/services/logger/index.html +116 -0
  99. package/coverage/lcov-report/src/services/logger/index.ts.html +154 -0
  100. package/coverage/lcov-report/src/services/persistence/index.html +146 -0
  101. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +163 -0
  102. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +208 -0
  103. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +271 -0
  104. package/coverage/lcov-report/src/services/stream-processor/index.html +146 -0
  105. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +3313 -0
  106. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +244 -0
  107. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +346 -0
  108. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +934 -0
  109. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +1984 -0
  110. package/coverage/lcov-report/src/services/tabs/index.html +191 -0
  111. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +310 -0
  112. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +871 -0
  113. package/coverage/lcov-report/src/services/tabs/support.ts.html +193 -0
  114. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +2005 -0
  115. package/coverage/lcov-report/src/sp00ky.ts.html +100 -0
  116. package/coverage/lcov-report/src/state/client-state.ts.html +637 -0
  117. package/coverage/lcov-report/src/state/index.html +161 -0
  118. package/coverage/lcov-report/src/state/lifecycle.ts.html +343 -0
  119. package/coverage/lcov-report/src/state/reducers.ts.html +1471 -0
  120. package/coverage/lcov-report/src/state/selectors.ts.html +637 -0
  121. package/coverage/lcov-report/src/sync/connection.saga.ts.html +343 -0
  122. package/coverage/lcov-report/src/sync/index.html +176 -0
  123. package/coverage/lcov-report/src/sync/live.saga.ts.html +232 -0
  124. package/coverage/lcov-report/src/sync/policy.ts.html +1606 -0
  125. package/coverage/lcov-report/src/sync/poll.saga.ts.html +193 -0
  126. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +361 -0
  127. package/coverage/lcov-report/src/types.ts.html +2419 -0
  128. package/coverage/lcov-report/src/utils/blurhash.ts.html +355 -0
  129. package/coverage/lcov-report/src/utils/error-classification.ts.html +244 -0
  130. package/coverage/lcov-report/src/utils/index.html +191 -0
  131. package/coverage/lcov-report/src/utils/index.ts.html +820 -0
  132. package/coverage/lcov-report/src/utils/parser.ts.html +313 -0
  133. package/coverage/lcov-report/src/utils/semver.ts.html +175 -0
  134. package/coverage/lcov-report/src/utils/surql.ts.html +667 -0
  135. package/coverage/lcov.info +19079 -0
  136. package/dist/index.d.ts +2946 -140
  137. package/dist/index.js +13424 -2356
  138. package/dist/otel/index.d.ts +2 -2
  139. package/dist/otel/index.js +6 -6
  140. package/dist/sqlite-open.js +322 -0
  141. package/dist/sqlite-worker.d.ts +1 -0
  142. package/dist/sqlite-worker.js +439 -0
  143. package/dist/tabs-broker-worker.d.ts +8 -0
  144. package/dist/tabs-broker-worker.js +472 -0
  145. package/dist/types.d.ts +769 -11
  146. package/package.json +11 -7
  147. package/scripts/check-broker-bundle.mjs +33 -0
  148. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  149. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  150. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  151. package/src/bucket-blurhash.test.ts +148 -0
  152. package/src/build-globals.d.ts +12 -0
  153. package/src/events/events.test.ts +2 -1
  154. package/src/events/index.ts +3 -0
  155. package/src/index.ts +36 -2
  156. package/src/modules/app-release/index.test.ts +125 -0
  157. package/src/modules/app-release/index.ts +201 -0
  158. package/src/modules/auth/auth.local-first.test.ts +141 -0
  159. package/src/modules/auth/events/index.ts +2 -1
  160. package/src/modules/auth/index.ts +138 -25
  161. package/src/modules/cache/cache.relay.test.ts +95 -0
  162. package/src/modules/cache/index.ts +163 -43
  163. package/src/modules/cache/types.ts +2 -2
  164. package/src/modules/crdt/crdt-field.ts +294 -0
  165. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  166. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  167. package/src/modules/crdt/index.ts +463 -0
  168. package/src/modules/crdt/loro-loader.ts +25 -0
  169. package/src/modules/data/data.activity.test.ts +109 -0
  170. package/src/modules/data/data.authority.test.ts +122 -0
  171. package/src/modules/data/data.heartbeat-wake.test.ts +115 -0
  172. package/src/modules/data/data.hydration.test.ts +142 -0
  173. package/src/modules/data/data.membership.test.ts +623 -0
  174. package/src/modules/data/data.notify-table.test.ts +41 -0
  175. package/src/modules/data/data.pending-ids.test.ts +199 -0
  176. package/src/modules/data/data.rebind.test.ts +170 -0
  177. package/src/modules/data/data.rematerialize.test.ts +114 -0
  178. package/src/modules/data/data.run.test.ts +113 -0
  179. package/src/modules/data/data.settled-writes.test.ts +235 -0
  180. package/src/modules/data/data.status.test.ts +249 -0
  181. package/src/modules/data/id-set-plan.test.ts +122 -0
  182. package/src/modules/data/index.ts +2031 -150
  183. package/src/modules/data/mutation-id.test.ts +25 -0
  184. package/src/modules/data/mutation-id.ts +35 -0
  185. package/src/modules/data/window-query.test.ts +52 -0
  186. package/src/modules/data/window-query.ts +194 -0
  187. package/src/modules/devtools/flags.ts +349 -0
  188. package/src/modules/devtools/index.ts +451 -46
  189. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  190. package/src/modules/devtools/state-shape.test.ts +146 -0
  191. package/src/modules/devtools/storage-info.test.ts +79 -0
  192. package/src/modules/devtools/storage-info.ts +168 -0
  193. package/src/modules/devtools/versions.test.ts +74 -0
  194. package/src/modules/devtools/versions.ts +110 -0
  195. package/src/modules/feature-flag/index.test.ts +251 -0
  196. package/src/modules/feature-flag/index.ts +308 -0
  197. package/src/modules/ref-tables.test.ts +91 -0
  198. package/src/modules/ref-tables.ts +88 -0
  199. package/src/modules/sync/engine.ts +170 -86
  200. package/src/modules/sync/events/index.ts +9 -2
  201. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  202. package/src/modules/sync/queue/queue-down.ts +108 -13
  203. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  204. package/src/modules/sync/queue/queue-up.ts +241 -57
  205. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  206. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  207. package/src/modules/sync/scheduler.ts +215 -13
  208. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  209. package/src/modules/sync/sync.health.test.ts +167 -0
  210. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  211. package/src/modules/sync/sync.list-ref-meta.test.ts +193 -0
  212. package/src/modules/sync/sync.live-removal.test.ts +289 -0
  213. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  214. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  215. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  216. package/src/modules/sync/sync.subquery.test.ts +82 -0
  217. package/src/modules/sync/sync.tabs.test.ts +249 -0
  218. package/src/modules/sync/sync.ts +2350 -133
  219. package/src/modules/sync/utils.test.ts +322 -2
  220. package/src/modules/sync/utils.ts +286 -16
  221. package/src/otel/index.ts +13 -10
  222. package/src/services/blobs/blob-cache.test.ts +359 -0
  223. package/src/services/blobs/blob-cache.ts +603 -0
  224. package/src/services/blobs/blob-manifest.ts +227 -0
  225. package/src/services/blobs/blob-store.test.ts +77 -0
  226. package/src/services/blobs/blob-store.ts +359 -0
  227. package/src/services/blobs/blob.fixture.ts +90 -0
  228. package/src/services/blobs/index.ts +70 -0
  229. package/src/services/database/cache-engine.ts +193 -0
  230. package/src/services/database/connection-supervisor.test.ts +289 -0
  231. package/src/services/database/connection-supervisor.ts +415 -0
  232. package/src/services/database/database.query-timeout.test.ts +140 -0
  233. package/src/services/database/database.ts +130 -62
  234. package/src/services/database/engine-factory.ts +33 -0
  235. package/src/services/database/errors.ts +34 -0
  236. package/src/services/database/events/index.ts +2 -1
  237. package/src/services/database/index.ts +7 -0
  238. package/src/services/database/local-migrator.ts +30 -27
  239. package/src/services/database/local.test.ts +64 -0
  240. package/src/services/database/local.ts +484 -67
  241. package/src/services/database/plan-render.test.ts +159 -0
  242. package/src/services/database/plan-render.ts +108 -0
  243. package/src/services/database/relation-resolver.test.ts +467 -0
  244. package/src/services/database/relation-resolver.ts +0 -0
  245. package/src/services/database/remote.ts +222 -15
  246. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  247. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  248. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  249. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  250. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  251. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  252. package/src/services/database/sqlite-lock-verify.ts +45 -0
  253. package/src/services/database/sqlite-open.test.ts +150 -0
  254. package/src/services/database/sqlite-open.ts +164 -0
  255. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  256. package/src/services/database/sqlite-plan-sql.ts +138 -0
  257. package/src/services/database/sqlite-projection.test.ts +99 -0
  258. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  259. package/src/services/database/sqlite-select.test.ts +246 -0
  260. package/src/services/database/sqlite-select.ts +131 -0
  261. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  262. package/src/services/database/sqlite-transport.ts +224 -0
  263. package/src/services/database/sqlite-worker.ts +437 -0
  264. package/src/services/database/surql-translate.ts +416 -0
  265. package/src/services/database/surreal-cache-engine.ts +161 -0
  266. package/src/services/logger/index.ts +3 -2
  267. package/src/services/persistence/localstorage.ts +2 -2
  268. package/src/services/persistence/resilient.ts +11 -4
  269. package/src/services/persistence/surrealdb.ts +10 -10
  270. package/src/services/stream-processor/index.ts +796 -84
  271. package/src/services/stream-processor/permissions.test.ts +47 -0
  272. package/src/services/stream-processor/permissions.ts +53 -0
  273. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  274. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  275. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  276. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  277. package/src/services/stream-processor/wasm-types.ts +59 -3
  278. package/src/services/tabs/broker-client.ts +283 -0
  279. package/src/services/tabs/broker.test.ts +327 -0
  280. package/src/services/tabs/coordinator.test.ts +365 -0
  281. package/src/services/tabs/coordinator.ts +633 -0
  282. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  283. package/src/services/tabs/leader-locks.ts +75 -0
  284. package/src/services/tabs/protocol.ts +258 -0
  285. package/src/services/tabs/support.ts +36 -0
  286. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  287. package/src/sp00ky.auth-order.test.ts +112 -0
  288. package/src/sp00ky.init-query.test.ts +183 -0
  289. package/src/sp00ky.local-first.test.ts +60 -0
  290. package/src/sp00ky.ts +1854 -0
  291. package/src/types.ts +548 -13
  292. package/src/utils/blurhash.ts +90 -0
  293. package/src/utils/error-classification.test.ts +54 -0
  294. package/src/utils/error-classification.ts +25 -0
  295. package/src/utils/index.ts +79 -13
  296. package/src/utils/parser.test.ts +49 -120
  297. package/src/utils/parser.ts +32 -2
  298. package/src/utils/semver.test.ts +32 -0
  299. package/src/utils/semver.ts +30 -0
  300. package/src/utils/surql.ts +30 -18
  301. package/src/utils/withRetry.test.ts +1 -1
  302. package/tsdown.config.ts +86 -1
  303. package/src/spooky.ts +0 -395
package/dist/index.d.ts CHANGED
@@ -1,81 +1,328 @@
1
- import { C as Logger$1, S as UpdateOptions, T as EventSystem, _ as RunOptions, a as MutationEvent, b as SpookyQueryResultPromise, c as PinoTransmit, d as QueryHash, f as QueryState, g as RecordVersionDiff, h as RecordVersionArray, i as MutationCallback, l as QueryConfig, m as QueryUpdateCallback, n as EventSubscriptionOptions, o as MutationEventType, p as QueryTimeToLive, r as Level, s as PersistenceClient, t as DebounceOptions, u as QueryConfigRecord, v as SpookyConfig, w as EventDefinition, x as StoreType, y as SpookyQueryResult } from "./types.js";
1
+ import { A as ServerViewMeta, B as TimingPhase, C as QueryTimings, D as RecordVersionDiff, E as RecordVersionArray, F as StorageHealthStatus, G as DatabaseEventSystem, H as UpEvent, I as StoreType, J as SyncEventSystem, K as DatabaseEventTypes, L as SyncHealth, M as Sp00kyQueryResult, N as Sp00kyQueryResultPromise, O as RegistrationTimings, P as StorageHealth, R as SyncHealthConfig, S as QueryTimeToLive, T as ReconnectConfig, U as LocalStore, V as UpdateOptions, W as SealedQuery, X as EventSystem, Y as EventDefinition, _ as QueryConfigRecord, a as MATERIALIZATION_SAMPLE_WINDOW, b as QueryStatus, c as MutationEvent, d as PhaseStat, f as PinoTransmit, g as QueryConfig, h as QueryAuthorityCallback, i as Level, j as Sp00kyConfig, k as RunOptions, l as MutationEventType, m as PreloadRefresh, n as DebounceOptions, o as MembershipOutcome, p as PreloadOptions, q as Logger$1, r as EventSubscriptionOptions, s as MutationCallback, t as ConnectionState, u as PersistenceClient, v as QueryHash, w as QueryUpdateCallback, x as QueryStatusCallback, y as QueryState, z as SyncHealthStatus } from "./types.js";
2
2
  import * as surrealdb0 from "surrealdb";
3
- import { Duration, RecordId, Surreal, SurrealTransaction } from "surrealdb";
4
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
3
+ import { Duration, RecordId, Surreal as Surreal$1, SurrealEvents, SurrealTransaction } from "surrealdb";
4
+ import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
5
5
  import { Logger } from "pino";
6
+ import { decode, encode, isBlurhashValid } from "blurhash";
7
+ import { LoroDoc } from "loro-crdt";
6
8
 
7
- //#region src/services/database/events/index.d.ts
8
- declare const DatabaseEventTypes: {
9
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
10
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
11
- };
12
- interface DatabaseQueryEventPayload {
13
- query: string;
14
- vars?: Record<string, unknown>;
15
- duration: number;
16
- success: boolean;
17
- error?: string;
18
- timestamp: number;
19
- }
20
- type DatabaseEventTypeMap = {
21
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
22
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
23
- };
24
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
25
- //#endregion
26
- //#region src/utils/surql.d.ts
27
- interface SealedQuery<T = void> {
28
- readonly sql: string;
29
- readonly extract: (results: unknown[]) => T;
30
- }
31
- //#endregion
32
9
  //#region src/services/database/database.d.ts
33
10
  declare abstract class AbstractDatabaseService {
34
- protected client: Surreal;
11
+ protected client: Surreal$1;
35
12
  protected logger: Logger$1;
36
13
  protected events: DatabaseEventSystem;
14
+ /**
15
+ * Per-query deadline in ms; `0` disables. The remote service sets it from
16
+ * `queryTimeoutMs` (see `RemoteDatabaseService`), the local one from
17
+ * `localOpTimeoutMs` (see `LocalDatabaseService`): a local query can be
18
+ * legitimately slow, but it must never be endless - every query waits on the
19
+ * previous link of {@link query}'s chain, and one that never settled wedged
20
+ * every later local op behind it.
21
+ */
22
+ protected queryTimeoutMs: number;
23
+ /** The error a deadline expiry rejects with; the local service substitutes
24
+ * its typed `LocalOpTimeoutError`. "timed out" in the message is
25
+ * load-bearing either way: `classifySyncError` keys off it. */
26
+ protected timeoutError(_query: string): Error;
37
27
  protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
38
- constructor(client: Surreal, logger: Logger$1, events: DatabaseEventSystem);
28
+ constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
39
29
  abstract connect(): Promise<void>;
40
- getClient(): Surreal;
30
+ getClient(): Surreal$1;
41
31
  getEvents(): DatabaseEventSystem;
42
32
  tx(): Promise<SurrealTransaction>;
43
- private queryQueue;
44
33
  /**
45
- * Execute a query with serialized execution to prevent WASM transaction issues.
34
+ * How many statements may be in flight at once.
35
+ *
36
+ * `1` serializes every statement behind the previous one. The local engines
37
+ * need that: overlapping ops trip the WASM / SQLite transaction layer. The
38
+ * remote service raises it (`RemoteDatabaseService`): a SurrealDB socket
39
+ * multiplexes requests by id, and serializing them capped the client at one
40
+ * statement per round trip (~5/s at 170ms RTT), so the `_00_list_ref` poll
41
+ * alone could hold every registration behind it and one slow one-shot read
42
+ * stalled the whole client. The scheduler's `MAX_CONCURRENT_DOWN` only means
43
+ * something when this is above 1.
44
+ */
45
+ protected maxConcurrentQueries: number;
46
+ private inFlightQueries;
47
+ private queryWaiters;
48
+ /** FIFO slot acquisition, so `maxConcurrentQueries = 1` keeps strict order. */
49
+ private acquireQuerySlot;
50
+ private releaseQuerySlot;
51
+ /**
52
+ * Hook run right before a statement is sent, inside its slot. The remote
53
+ * service uses it to hold statements while a connect is in flight, so a
54
+ * query never runs on a socket that is open but has not had its namespace
55
+ * and token applied yet. The default does nothing.
56
+ */
57
+ protected beforeQuery(): Promise<void>;
58
+ /**
59
+ * Execute a statement under {@link maxConcurrentQueries}.
60
+ *
61
+ * A statement that never settles would hold its slot forever, and with a
62
+ * limit of 1 that blocks every later statement behind it. {@link
63
+ * queryTimeoutMs} bounds each one: on expiry this promise rejects and the
64
+ * slot is released, even though the underlying RPC is still parked in the
65
+ * SDK's pending map.
46
66
  */
47
67
  query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
48
68
  execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
49
69
  close(): Promise<void>;
50
70
  }
51
71
  //#endregion
52
- //#region src/services/database/local.d.ts
53
- declare class LocalDatabaseService extends AbstractDatabaseService {
54
- private config;
55
- protected eventType: "DATABASE_LOCAL_QUERY";
56
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
57
- getConfig(): SpookyConfig<any>['database'];
58
- connect(): Promise<void>;
59
- }
60
- //#endregion
61
72
  //#region src/services/database/remote.d.ts
73
+ /** Transport events the SDK publishes, mapped 1:1 to {@link ConnectionState}. */
74
+ type RemoteConnectionEvent = ConnectionState | 'error';
62
75
  declare class RemoteDatabaseService extends AbstractDatabaseService {
63
76
  private config;
64
77
  protected eventType: "DATABASE_REMOTE_QUERY";
65
- constructor(config: SpookyConfig<any>['database'], logger: Logger$1);
66
- getConfig(): SpookyConfig<any>['database'];
78
+ private readonly reconnectConfig;
79
+ /**
80
+ * In-flight `connect()`, so concurrent callers (boot + supervisor revive +
81
+ * an `online` event landing at the same moment) share one attempt instead of
82
+ * racing two sockets. Cleared on settle, so a later call always reconnects.
83
+ */
84
+ private connecting;
85
+ /**
86
+ * The token to re-authenticate a freshly opened socket with, kept current by
87
+ * {@link setAuthToken}.
88
+ *
89
+ * `config.token` is fixed at construction and most apps never set it: they
90
+ * sign in later, which authenticates the socket that happens to be open at
91
+ * the time. That is enough for the SDK's OWN reconnects (it replays
92
+ * `version`/`use`/`authenticate` itself), but not for the supervisor's revive
93
+ * loop, which builds a socket from scratch. Without this the revived socket
94
+ * came back UNAUTHENTICATED and stayed that way for the life of the page,
95
+ * while the client's `currentUserId` — restored from local storage — kept
96
+ * reporting the user as signed in.
97
+ *
98
+ * The visible damage is silent and total: `fn::query::register` sends
99
+ * `<string>($auth.id OR '')`, so every view registered afterwards is stamped
100
+ * with an empty identity, and every `$auth.id` predicate in it resolves
101
+ * false. Public tables keep returning rows while everything owned by the user
102
+ * returns nothing, on a page that still looks signed in.
103
+ */
104
+ private authToken;
105
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
106
+ getConfig(): Sp00kyConfig<any>['database'];
107
+ /**
108
+ * Send one SurrealQL statement so that it survives the page going away.
109
+ *
110
+ * A WebSocket `send()` during `pagehide` is not guaranteed to flush — the
111
+ * browser may tear the socket down first, and the frame is simply lost.
112
+ * Measured: an unload-time release over the live socket reached the server
113
+ * zero times out of one. `fetch` with `keepalive` is the primitive the
114
+ * platform actually guarantees here, so this goes over SurrealDB's HTTP
115
+ * `/sql` endpoint instead of the RPC socket.
116
+ *
117
+ * Best-effort by design: no await, no retry, errors swallowed. Every caller
118
+ * must have a server-side fallback that makes a lost beacon a non-event.
119
+ */
120
+ beaconSql(sql: string): void;
121
+ /**
122
+ * Record the token every future connect should authenticate with, or `null`
123
+ * on sign-out. See {@link authToken}.
124
+ *
125
+ * Does not touch the CURRENT socket: callers authenticate that themselves
126
+ * (sign-in and session restore both already do). This only makes the next
127
+ * from-scratch connect reproduce that state.
128
+ */
129
+ setAuthToken(token: string | null): void;
130
+ /** Resolved reconnect tunables; the supervisor reads its own knobs here. */
131
+ getReconnectConfig(): Required<ReconnectConfig>;
132
+ /** Current transport state as reported by the SDK. */
133
+ getStatus(): ConnectionState;
134
+ /**
135
+ * Observe transport events. Thin passthrough so callers (the supervisor,
136
+ * sync, CRDT) don't have to reach through `getClient()`.
137
+ */
138
+ subscribeConnection<K extends RemoteConnectionEvent>(event: K, cb: (...payload: SurrealEvents[K]) => void): () => void;
139
+ /**
140
+ * Tear the socket down on purpose. Used by the heartbeat watchdog when a
141
+ * socket stops answering but never closes: `close()` makes the SDK publish
142
+ * `disconnected`, which is what drives the supervisor's revive loop.
143
+ */
144
+ forceClose(): Promise<void>;
145
+ /**
146
+ * Hold statements while a connect is in flight.
147
+ *
148
+ * `connect()` opens the socket, then selects the namespace/database, then
149
+ * authenticates - three round trips. The SDK considers the connection ready
150
+ * after the first, so a query queued during the other two ran on a socket
151
+ * with no namespace ("Specify a namespace to use") or, worse, no identity.
152
+ * Seen 2026-09-06 after the supervisor rebuilt a socket: a collection
153
+ * recount failed with exactly that error. Waiting on the in-flight connect
154
+ * costs nothing when no connect is running; a failed connect is not
155
+ * swallowed here - the query then fails on its own, as before.
156
+ */
157
+ protected beforeQuery(): Promise<void>;
158
+ /**
159
+ * Open (or re-open) the remote connection.
160
+ *
161
+ * Safe to call repeatedly: concurrent calls share the in-flight attempt, and
162
+ * a call after a `disconnected` builds a fresh socket. `use()` and
163
+ * `authenticate()` are re-applied here for the cold path; the SDK also
164
+ * replays them itself on its own internal reconnects.
165
+ */
67
166
  connect(): Promise<void>;
167
+ private doConnect;
68
168
  signin(params: any): Promise<any>;
69
169
  signup(params: any): Promise<any>;
70
170
  authenticate(token: string): Promise<any>;
71
171
  invalidate(): Promise<void>;
72
172
  }
73
173
  //#endregion
174
+ //#region src/services/database/connection-supervisor.d.ts
175
+ /**
176
+ * Keeps the remote WebSocket alive for the whole life of the page.
177
+ *
178
+ * The SurrealDB SDK reconnects on its own after a socket `close`, but that
179
+ * covers only one of three ways the connection dies:
180
+ *
181
+ * 1. **Socket closes, SDK recovers.** Handled entirely by the SDK. This
182
+ * supervisor only observes it (to report `reconnecting` upward).
183
+ * 2. **Socket closes, SDK gives up.** With `attempts: -1` this shouldn't happen
184
+ * from exhaustion — but the SDK also terminates the engine permanently when
185
+ * its post-reconnect handshake throws (it re-runs `version()`, `use()`,
186
+ * `authenticate()` on every reconnect and closes the engine on any error).
187
+ * One transient hiccup there would otherwise kill the page's connection for
188
+ * good. The revive loop re-opens from scratch.
189
+ * 3. **Socket never closes at all.** A half-open connection: the peer is gone
190
+ * (NAT timeout, wifi switch, laptop sleep) but no FIN ever arrives, so
191
+ * `readyState` stays OPEN and the SDK's own 30s ping — fire-and-forget, no
192
+ * response deadline — never notices. Nothing ever fires a `close` event, so
193
+ * nothing ever triggers a reconnect. The heartbeat detects this and forces
194
+ * the teardown that case 2's loop then repairs.
195
+ *
196
+ * Plus wake triggers: coming back `online` or un-hiding the tab probes
197
+ * immediately rather than waiting out a backoff that was scheduled while the
198
+ * network was known-down.
199
+ */
200
+ declare class ConnectionSupervisor {
201
+ private readonly remote;
202
+ private readonly logger;
203
+ private readonly config;
204
+ private state;
205
+ private subscribers;
206
+ private started;
207
+ private disposed;
208
+ private heartbeatTimer;
209
+ private heartbeatInFlight;
210
+ /** Consecutive failed probes. See {@link FAILURES_BEFORE_TEARDOWN}. */
211
+ private heartbeatFailures;
212
+ private reviveTimer;
213
+ private reviveAttempts;
214
+ /** Timestamp of the last wake-triggered probe, for rate limiting. */
215
+ private lastWakeProbeAt;
216
+ private reviving;
217
+ /**
218
+ * Set while the browser reports itself offline. Retrying a socket against a
219
+ * down interface only burns backoff, so the loop parks until `online` fires.
220
+ */
221
+ private suspended;
222
+ private teardown;
223
+ private static readonly REVIVE_BASE_MS;
224
+ /**
225
+ * How many consecutive heartbeat failures it takes to tear the socket down.
226
+ *
227
+ * The probe rides the same serialized queue as every other RPC (deliberately
228
+ * — see {@link beat}), which means it cannot distinguish a WEDGED queue from
229
+ * a merely BUSY one. A single slow window (a large sync burst, one heavy
230
+ * app query) used to be enough to force-close a perfectly healthy socket,
231
+ * and the resulting reconnect re-registered every active query about a
232
+ * second later. That self-inflicted teardown manufactured the very reconnect
233
+ * storms this class exists to survive. A genuinely dead socket still fails
234
+ * every probe, so it is torn down one interval later than before.
235
+ */
236
+ private static readonly FAILURES_BEFORE_TEARDOWN;
237
+ /** Retry delay after an inconclusive (first) heartbeat failure. */
238
+ private static readonly HEARTBEAT_RETRY_MS;
239
+ /** Floor between probes triggered by wake events (tab focus, pageshow). */
240
+ private static readonly WAKE_PROBE_MIN_INTERVAL_MS;
241
+ constructor(remote: RemoteDatabaseService, logger: Logger$1, config?: Required<ReconnectConfig>);
242
+ /** Latest observed transport state. */
243
+ get connection(): ConnectionState;
244
+ /**
245
+ * Observe transport state. Fires immediately with the current value and again
246
+ * on every change. Returns an unsubscribe.
247
+ */
248
+ subscribe(cb: (state: ConnectionState) => void): () => void;
249
+ /**
250
+ * Begin supervising. Call once, after the initial {@link
251
+ * RemoteDatabaseService.connect}. Idempotent.
252
+ */
253
+ start(): void;
254
+ /** Stop all timers and listeners. Safe to call more than once. */
255
+ dispose(): void;
256
+ private setState;
257
+ private clearReviveTimer;
258
+ /**
259
+ * Queue the next `connect()` attempt on exponential backoff, capped at
260
+ * `superviseRetryDelayMaxMs`. Never gives up — the page is expected to
261
+ * outlive any outage.
262
+ */
263
+ private scheduleRevive;
264
+ private revive;
265
+ private stopHeartbeat;
266
+ private startHeartbeat;
267
+ /**
268
+ * Probe the server end-to-end. Deliberately goes through
269
+ * `remote.query` — the same serialized queue every other remote call uses —
270
+ * so a queue wedged behind a stuck RPC also fails the heartbeat instead of
271
+ * being invisible to it.
272
+ */
273
+ private beat;
274
+ /**
275
+ * A restored network or an un-hidden tab is the strongest available hint that
276
+ * a reconnect will now succeed, so probe immediately instead of waiting out a
277
+ * backoff scheduled under worse conditions.
278
+ */
279
+ private installWakeTriggers;
280
+ /**
281
+ * Reset the backoff and act on whichever problem is present: reconnect if the
282
+ * socket is gone, otherwise probe it (it may be half-open — which is exactly
283
+ * what a sleep/wake cycle produces).
284
+ */
285
+ private wake;
286
+ }
287
+ //#endregion
288
+ //#region src/modules/sync/queue/queue-down.d.ts
289
+ type RegisterEvent = {
290
+ type: 'register';
291
+ payload: {
292
+ hash: string;
293
+ };
294
+ };
295
+ type SyncEvent = {
296
+ type: 'sync';
297
+ payload: {
298
+ hash: string;
299
+ };
300
+ };
301
+ type HeartbeatEvent = {
302
+ type: 'heartbeat';
303
+ payload: {
304
+ hash: string;
305
+ };
306
+ };
307
+ type CleanupEvent = {
308
+ type: 'cleanup';
309
+ payload: {
310
+ hash: string;
311
+ };
312
+ };
313
+ type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
314
+ //#endregion
74
315
  //#region src/services/stream-processor/wasm-types.d.ts
75
316
  interface WasmStreamUpdate {
76
317
  query_id: string;
77
318
  result_hash: string;
78
319
  result_data: RecordVersionArray;
320
+ timing_store_apply_ms?: number;
321
+ timing_circuit_step_ms?: number;
322
+ timing_transform_ms?: number;
323
+ timing_parse_ms?: number;
324
+ timing_plan_ms?: number;
325
+ timing_snapshot_ms?: number;
79
326
  }
80
327
  //#endregion
81
328
  //#region src/services/stream-processor/index.d.ts
@@ -96,6 +343,33 @@ interface StreamUpdate {
96
343
  queryHash: string;
97
344
  localArray: RecordVersionArray;
98
345
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
346
+ /**
347
+ * Client-internal: not from the circuit. A membership-only change that
348
+ * needed no fetch is re-materialized through this same path so it cannot
349
+ * race a real update (DataModule.scheduleRematerialize). Carries the last
350
+ * known `localArray`; consumers that describe an INGEST (persist, metrics,
351
+ * devtools events) skip it.
352
+ */
353
+ synthetic?: boolean;
354
+ /**
355
+ * End-to-end ingest latency for the WASM call that produced this update,
356
+ * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
357
+ * for the initial register_view snapshot.
358
+ */
359
+ materializationTimeMs?: number;
360
+ /** SSP internal sub-phase timings (ms) for this ingest, from the WASM binding. */
361
+ storeApplyMs?: number;
362
+ circuitStepMs?: number;
363
+ transformMs?: number;
364
+ /**
365
+ * One-shot registration timings (ms). Only set on the StreamUpdate returned
366
+ * by `registerQueryPlan` (the register_view snapshot), not on ingest updates.
367
+ */
368
+ registration?: {
369
+ parseMs: number;
370
+ planMs: number;
371
+ snapshotMs: number;
372
+ };
99
373
  }
100
374
  type StreamProcessorEvents = {
101
375
  stream_update: EventDefinition<'stream_update', StreamUpdate[]>;
@@ -107,34 +381,204 @@ type StreamProcessorEvents = {
107
381
  interface StreamUpdateReceiver {
108
382
  onStreamUpdate(update: StreamUpdate): void;
109
383
  }
384
+ /** One row change in the shape `ingestMany` consumes. */
385
+ interface IngestRecord {
386
+ table: string;
387
+ /** `MERGE` overlays the given fields on the stored row (projection widening). */
388
+ op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
389
+ id: string;
390
+ record: any;
391
+ }
392
+ /**
393
+ * What the boot-time prime needs from the client: which tables to walk, how
394
+ * to recognise a snapshot written under a different schema, and which rows'
395
+ * local `_00_rv` must not be reported as the server's.
396
+ */
397
+ interface CircuitPrimeContext {
398
+ tables: string[];
399
+ schemaHash: string;
400
+ /** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
401
+ * locally and may exceed the server's next version). */
402
+ pendingIds: Set<string>;
403
+ /** Receives every `(id, rv)` the prime put into the circuit, per table, so
404
+ * the sync layer can skip re-downloading bodies it already has. */
405
+ onVersions?: (table: string, entries: [string, number][]) => void;
406
+ }
407
+ /** Storage key of the circuit snapshot inside the local store. */
408
+
110
409
  declare class StreamProcessorService {
111
410
  events: EventSystem<StreamProcessorEvents>;
112
411
  private db;
113
- private persistenceClient;
114
412
  private logger;
115
413
  private processor;
116
414
  private isInitialized;
117
415
  private receivers;
118
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
416
+ private batching;
417
+ private batchBuffer;
418
+ private sessionAuth;
419
+ private stateGeneration;
420
+ private persistState;
421
+ private persistCircuit;
422
+ private checkpointMs;
423
+ private checkpointTimer;
424
+ private snapshotDirty;
425
+ private dirtyRows;
426
+ private hideHandler;
427
+ private checkpointInFlight;
428
+ private projection;
429
+ private primed;
430
+ private schemaHash;
431
+ private widenQueue;
432
+ private widenPending;
433
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, logger: Logger);
119
434
  /**
120
435
  * Add a receiver for stream updates.
121
436
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
122
437
  */
123
438
  addReceiver(receiver: StreamUpdateReceiver): void;
124
439
  private notifyUpdates;
440
+ private dispatchUpdates;
441
+ /**
442
+ * Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
443
+ * affected query once every record has been ingested. Use this whenever
444
+ * multiple records land at once (sync fetching N rows, the boot prime).
445
+ *
446
+ * The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
447
+ * circuit step per chunk (a step walks every registered view, so per-record
448
+ * ingest paid that fixed cost N times), but never the whole batch at once,
449
+ * because the wasm side has to hold every parsed row of a call at the same
450
+ * time and wasm32 dlmalloc never returns that peak.
451
+ *
452
+ * Returns the records that were ingested. A chunk that fails is reported
453
+ * and skipped, not retried (a retry would double-apply whatever the failed
454
+ * step already committed), and the remaining chunks still run.
455
+ */
456
+ ingestMany(records: IngestRecord[]): IngestRecord[];
457
+ /**
458
+ * Open a coalescing window. While open, the per-record stream updates
459
+ * emitted by `ingest` are buffered (one entry per queryHash) instead of
460
+ * dispatched. Always paired with `flushCoalescing()` in a try/finally by
461
+ * `ingestMany` so the window always closes — otherwise the processor stays
462
+ * stuck buffering forever.
463
+ *
464
+ * No-op if a window is already open (nested batches aren't expected here).
465
+ */
466
+ private beginCoalescing;
467
+ /**
468
+ * Close the coalescing window and flush: dispatch one coalesced
469
+ * `StreamUpdate` per buffered queryHash, then persist processor state once
470
+ * for the whole batch (instead of once per ingest).
471
+ */
472
+ private flushCoalescing;
125
473
  /**
126
474
  * Initialize the WASM module and processor.
127
475
  * This must be called before using other methods.
128
476
  */
129
477
  init(): Promise<void>;
130
- loadState(): Promise<void>;
131
- saveState(): Promise<void>;
478
+ /**
479
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
480
+ * local-bucket switches: the old circuit holds the previous user's rows AND
481
+ * views registered with the previous `$auth` context, so neither may survive.
482
+ * Deliberately loads nothing: the snapshot in the store being swapped away
483
+ * from belongs to the previous bucket; the caller primes the new bucket's
484
+ * circuit (`primeFromLocal`) once its store is open, and the DataModule
485
+ * rebind re-registers every live view against this fresh processor. Caller
486
+ * must re-seed `setPermissions` afterwards (a fresh circuit default-denies
487
+ * every table).
488
+ */
489
+ reset(): Promise<void>;
490
+ /**
491
+ * Release the wasm circuit and stop checkpointing. Call when the client is
492
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
493
+ * one full circuit per instance.
494
+ */
495
+ dispose(): void;
496
+ /**
497
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
498
+ * not expose `free`, and a double free must not take the app down.
499
+ */
500
+ private freeProcessor;
501
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
502
+ setPersistenceEnabled(enabled: boolean): void;
503
+ /**
504
+ * Snapshot persistence (`persistCircuit`). When on, the circuit's store is
505
+ * written to the local store on a checkpoint interval and when the page
506
+ * goes hidden, and restored by {@link primeFromLocal} on the next boot.
507
+ */
508
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
509
+ /**
510
+ * Field projection (`circuitProjection`, default on). Takes effect on the
511
+ * next processor (`init`/`reset`) and on rows written after that.
512
+ */
513
+ configureProjection(enabled: boolean): void;
514
+ private applyProjection;
515
+ /** Resolves once the boot-time prime has finished (or was skipped). */
516
+ whenPrimed(): Promise<void>;
517
+ /**
518
+ * Fill the circuit from the LOCAL store, in the background.
519
+ *
520
+ * With a usable snapshot: install it under whatever views have registered
521
+ * meanwhile (`load_store_state` re-primes them), then `reconcile` each table
522
+ * against the store's `(id, rv)` list so rows deleted since the checkpoint
523
+ * are stepped out and only rows added or changed since are read back and
524
+ * ingested. Without one: read every row and ingest it, chunked.
525
+ *
526
+ * Either way the circuit ends up equal to the local store without touching
527
+ * the network, so the first sync diff is a real delta rather than "fetch
528
+ * everything". The returned promise never rejects; `whenPrimed` gates on it.
529
+ */
530
+ primeFromLocal(ctx: CircuitPrimeContext): Promise<void>;
531
+ private runPrime;
532
+ /** Publish wasm updates produced outside an ingest (restore, reconcile). */
533
+ private dispatchWasmUpdates;
534
+ /**
535
+ * Record that the circuit changed by `rows` rows. Cheap; the snapshot is
536
+ * deferred to the checkpoint timer and skipped entirely when `persistCircuit`
537
+ * is off.
538
+ */
539
+ private markSnapshotDirty;
540
+ private startCheckpoints;
541
+ /** Stop checkpointing and drop the visibility listeners. */
542
+ stopCheckpoints(): void;
543
+ /**
544
+ * Write the circuit's store to the local store as a snapshot. Compacts the
545
+ * row arena first when dead bytes outweigh live ones. Serialised: a second
546
+ * call while one is in flight joins it. No-op unless persistence is on, this
547
+ * tab owns the store, and the engine can hold a snapshot.
548
+ */
549
+ checkpoint(reason?: string): Promise<void>;
550
+ private runCheckpoint;
551
+ /**
552
+ * Projection widening: a newly registered view evaluates fields that rows
553
+ * already in the circuit were stored without. Merge just those fields in,
554
+ * table by table, from the local store. The view registered against what
555
+ * was present and converges as the merges step through.
556
+ */
557
+ private scheduleWiden;
558
+ private runWiden;
559
+ /**
560
+ * Seed per-table `select` permission predicates ({ [table]: whereText }).
561
+ * Must run after the processor exists and before any `register_view`, else
562
+ * non-`_00_` tables are default-denied and registration fails.
563
+ */
564
+ setPermissions(permissions: Record<string, string>): void;
565
+ /**
566
+ * Set the current session's auth identity for permission injection,
567
+ * mirroring the server's `fn::query::register`
568
+ * (`object::extend(params, { auth: { id: $auth.id }, access: $access })`).
569
+ * Stored as strings (empty when logged out) and applied to every
570
+ * `register_view` in {@link registerQueryPlan}. Must be set before a
571
+ * `$auth`-gated query registers (and re-set on auth state changes), or the
572
+ * in-browser SSP's `permission_inject` rejects it with
573
+ * "requires $auth but registration params lack it".
574
+ */
575
+ setSessionAuth(authId: string | null, access: string | null): void;
132
576
  /**
133
577
  * Ingest a record change into the processor.
134
578
  * Emits 'stream_update' event if materialized views are affected.
135
579
  * @param isOptimistic true = local mutation (increment versions), false = remote sync (keep versions)
136
580
  */
137
- ingest(table: string, op: 'CREATE' | 'UPDATE' | 'DELETE', id: string, record: any): WasmStreamUpdate[];
581
+ ingest(table: string, op: IngestRecord['op'], id: string, record: any): WasmStreamUpdate[];
138
582
  /**
139
583
  * Register a new query plan.
140
584
  * Emits 'stream_update' with the initial result.
@@ -147,116 +591,2478 @@ declare class StreamProcessorService {
147
591
  private normalizeValue;
148
592
  }
149
593
  //#endregion
150
- //#region src/modules/auth/events/index.d.ts
151
- declare const AuthEventTypes: {
152
- readonly AuthStateChanged: "AUTH_STATE_CHANGED";
594
+ //#region src/modules/cache/types.d.ts
595
+ type RecordWithId = Record<string, any> & {
596
+ id: RecordId<string>;
153
597
  };
154
- type AuthEventTypeMap = {
155
- [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
156
- };
157
- type AuthEventSystem = EventSystem<AuthEventTypeMap>;
158
- declare function createAuthEventSystem(): AuthEventSystem;
598
+ interface QueryConfig$1 {
599
+ queryHash: string;
600
+ surql: string;
601
+ params: Record<string, any>;
602
+ ttl: QueryTimeToLive | Duration;
603
+ lastActiveAt: Date;
604
+ }
605
+ interface CacheRecord {
606
+ table: string;
607
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
608
+ record: RecordWithId;
609
+ version: number;
610
+ }
159
611
  //#endregion
160
- //#region src/modules/auth/index.d.ts
161
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
162
- type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
163
- type ExtractAccessParams<S extends SchemaStructure, Name extends keyof S['access'], Method extends 'signIn' | 'signup'> = S['access'] extends undefined ? never : S['access'][Name] extends AccessDefinition ? Prettify<{ [K in keyof S['access'][Name][Method]['params']]: MapColumnType<S['access'][Name][Method]['params'][K]> }> : never;
164
- declare class AuthService<S extends SchemaStructure> {
165
- private schema;
166
- private remote;
167
- private persistenceClient;
612
+ //#region src/modules/cache/index.d.ts
613
+ /**
614
+ * CacheModule - Centralized storage and DBSP ingestion
615
+ *
616
+ * Single responsibility: Handle all local storage operations and DBSP ingestion.
617
+ * This module acts as the bridge between data operations and persistence.
618
+ */
619
+ /** One ingested change, in exactly the shape `ingestMany` consumes. Shared
620
+ * with the tabs protocol so a leader can relay its ingests to followers. */
621
+ interface CacheIngestTuple {
622
+ table: string;
623
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
624
+ id: string;
625
+ record: Record<string, unknown>;
626
+ }
627
+ declare class CacheModule implements StreamUpdateReceiver {
628
+ private local;
629
+ private streamProcessor;
168
630
  private logger;
169
- token: string | null;
170
- currentUser: any | null;
171
- isAuthenticated: boolean;
172
- isLoading: boolean;
173
- private events;
174
- get eventSystem(): AuthEventSystem;
175
- constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
176
- init(): Promise<void>;
177
- getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
631
+ private streamUpdateCallback;
632
+ private versionLookups;
633
+ /** Shared-tabs leader: fan every committed ingest out to follower circuits.
634
+ * Fired AFTER the local tx (the rows are already in the shared store, so a
635
+ * follower only needs the circuit feed). A follower relays its own
636
+ * mutations to the leader the same way, see {@link setIngestRelay}. */
637
+ private ingestRelay;
638
+ /** See {@link setIngestRelay}. */
639
+ private relayLocalWritesOnly;
640
+ constructor(local: LocalStore, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
178
641
  /**
179
- * Subscribe to auth state changes.
180
- * callback is called immediately with current value and whenever validation status changes.
642
+ * Implements StreamUpdateReceiver interface
643
+ * Called directly by StreamProcessor when views change
181
644
  */
182
- subscribe(cb: (userId: string | null) => void): () => void;
183
- private notifyListeners;
645
+ onStreamUpdate(update: StreamUpdate): void;
184
646
  /**
185
- * Check for existing session and validate
647
+ * Fan every committed ingest out to the other tabs. The leader relays
648
+ * everything (its sync fetches are the only copy the followers get). A
649
+ * follower relays with `localWritesOnly`: just the mutation path, which is
650
+ * the only thing it knows that the leader does not. Its sync-fetched
651
+ * batches are the leader's data coming back and must not be re-broadcast,
652
+ * or every follower registration would fan its whole working set to
653
+ * every tab.
186
654
  */
187
- check(accessToken?: string): Promise<void>;
655
+ setIngestRelay(cb: ((tuples: CacheIngestTuple[]) => void) | null, opts?: {
656
+ localWritesOnly?: boolean;
657
+ }): void;
188
658
  /**
189
- * Sign out and clear session
659
+ * Shared-tabs follower: feed relayed tuples into THIS tab's circuit only.
660
+ * The rows are already in the shared store (the leader wrote them), so no
661
+ * local write happens here; the normal chain then runs: SSP -> stream update
662
+ * -> DataModule debounce -> materializeRecords (re-reads via the port
663
+ * transport) -> this tab's subscriptions fire with this tab's hashes.
190
664
  */
191
- signOut(): Promise<void>;
192
- private setSession;
193
- signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
194
- signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
665
+ applyRelayedIngest(tuples: CacheIngestTuple[]): void;
666
+ lookup(recordId: string): number;
667
+ /**
668
+ * Seed the version memo from rows the circuit was primed with out of the
669
+ * local store, so the first post-reload sync diff does not re-download
670
+ * bodies the browser already has. Only rows the prime actually put into the
671
+ * circuit belong here: a memo entry with no circuit row would make the diff
672
+ * flag the id forever while nothing ever fetches it.
673
+ */
674
+ primeVersions(entries: [string, number][]): void;
675
+ /** Drop the version cache on a bucket switch — a stale version would make
676
+ * the sync diff skip fetching a body the new bucket legitimately needs. */
677
+ clearVersionLookups(): void;
678
+ /**
679
+ * Save a single record to local DB and ingest into DBSP
680
+ * Used by mutations (create/update)
681
+ */
682
+ save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
683
+ /**
684
+ * Save multiple records in a batch
685
+ * More efficient than calling save() multiple times
686
+ * Used by sync operations
687
+ */
688
+ saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
689
+ /**
690
+ * Delete a record from local DB and ingest deletion into DBSP
691
+ */
692
+ delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
693
+ /**
694
+ * Register a query with DBSP to create a materialized view
695
+ * Returns the initial result array
696
+ */
697
+ registerQuery(config: QueryConfig$1): {
698
+ localArray: RecordVersionArray;
699
+ registrationTimings?: {
700
+ parseMs: number;
701
+ planMs: number;
702
+ snapshotMs: number;
703
+ };
704
+ };
705
+ /**
706
+ * Unregister a query from DBSP
707
+ */
708
+ unregisterQuery(queryHash: string): void;
195
709
  }
196
710
  //#endregion
197
- //#region src/spooky.d.ts
198
- declare class BucketHandle {
199
- private bucketName;
200
- private remote;
201
- constructor(bucketName: string, remote: RemoteDatabaseService);
202
- put(path: string, content: string | Uint8Array | Blob): Promise<void>;
203
- get(path: string): Promise<unknown>;
204
- delete(path: string): Promise<void>;
205
- exists(path: string): Promise<boolean>;
206
- head(path: string): Promise<Record<string, unknown>>;
207
- copy(sourcePath: string, targetPath: string): Promise<void>;
208
- rename(sourcePath: string, targetPath: string): Promise<void>;
209
- list(prefix?: string): Promise<string[]>;
711
+ //#region src/modules/data/index.d.ts
712
+ /**
713
+ * DataModule - Unified query and mutation management
714
+ *
715
+ * Merges the functionality of QueryManager and MutationManager.
716
+ * Uses CacheModule for all storage operations.
717
+ */
718
+ /** A `_00_window` row as read back: the id-set and whether the server vouched
719
+ * for it (which is what allows an empty set to count as known membership). */
720
+ interface DurableMembership {
721
+ ids: RecordVersionArray;
722
+ confirmed: boolean;
210
723
  }
211
- declare class SpookyClient<S extends SchemaStructure> {
212
- private config;
213
- private local;
214
- private remote;
215
- private persistenceClient;
216
- private migrator;
724
+ declare class DataModule<S extends SchemaStructure> {
217
725
  private cache;
218
- private dataModule;
219
- private sync;
220
- private devTools;
726
+ private local;
727
+ private schema;
728
+ private streamDebounceTime;
729
+ /** Tab identity baked into mutation ids (shared-tabs rollback routing);
730
+ * undefined in solo mode, where mutation-id falls back to a session id. */
731
+ private tabId;
732
+ private activeQueries;
733
+ private pendingQueries;
734
+ private subscriptions;
735
+ private statusSubscriptions;
736
+ /** Observers of a query's authority (`membershipKnown`) flips, keyed like `statusSubscriptions`. */
737
+ private authoritySubscriptions;
738
+ private mutationCallbacks;
739
+ private debounceTimers;
740
+ private pendingStreamUpdates;
741
+ private fetchDepth;
742
+ /**
743
+ * Observers of the AGGREGATE fetch activity: how many queries are mid-fetch
744
+ * right now. What a "downloading" indicator in the app chrome hangs off,
745
+ * instead of subscribing to every query's status one by one.
746
+ */
747
+ private activitySubscriptions;
221
748
  private logger;
222
- auth: AuthService<S>;
223
- streamProcessor: StreamProcessorService;
224
- get remoteClient(): Surreal;
225
- get localClient(): Surreal;
226
- get pendingMutationCount(): number;
227
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
228
- constructor(config: SpookyConfig<S>);
229
749
  /**
230
- * Setup direct callbacks instead of event subscriptions
750
+ * Optional observer notified whenever a query's fetch status changes.
751
+ * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
752
+ * settable field (rather than a constructor arg) because DevTools is
753
+ * constructed after DataModule.
231
754
  */
232
- private setupCallbacks;
233
- init(): Promise<void>;
234
- close(): Promise<void>;
235
- authenticate(token: string): Promise<surrealdb0.Tokens>;
236
- deauthenticate(): Promise<void>;
237
- query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, SpookyQueryResultPromise>;
238
- private initQuery;
239
- queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
240
- subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
755
+ onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
756
+ /**
757
+ * Optional observer invoked when a still-subscribed query's TTL heartbeat
758
+ * fires (~90% of the TTL). Wired by Sp00kyClient to
759
+ * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
760
+ * row's `lastActiveAt` so an actively-watched query never expires. Settable
761
+ * field (not a constructor arg) because the sync engine is wired after
762
+ * DataModule is constructed — mirrors `onQueryStatusChange`.
763
+ */
764
+ onHeartbeat?: (hash: QueryHash) => void;
765
+ /**
766
+ * Fired once per episode when the server's `_00_query` row for a query we
767
+ * hold membership for is found missing (see `updateQueryRemoteArray`). Wired
768
+ * by Sp00kyClient to enqueue a `register` down-event so the SSP rebuilds the
769
+ * view; the client keeps rendering what it has meanwhile.
770
+ */
771
+ onViewLost?: (hash: QueryHash) => void;
772
+ /** DevTools observer for authority flips; mirrors `onQueryStatusChange`. */
773
+ onQueryAuthorityChange?: (hash: QueryHash, known: boolean) => void;
774
+ /**
775
+ * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
776
+ * viewport-windowed list cancelling an off-screen window) loses its last
777
+ * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
778
+ * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
779
+ * instead of leaving it for the TTL sweep. The local view + state are freed in
780
+ * {@link finalizeDeregister} only after that remote delete, so a fast
781
+ * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
782
+ */
783
+ onDeregister?: (hash: QueryHash) => void;
784
+ private sessionId;
785
+ private currentUserId;
786
+ constructor(cache: CacheModule, local: LocalStore, schema: S, logger: Logger$1, streamDebounceTime?: number);
787
+ init(sessionId: string): Promise<void>;
788
+ /**
789
+ * Update the session salt used in query-id hashing. Call this when the
790
+ * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
791
+ * registered queries will get fresh, session-scoped IDs.
792
+ */
793
+ setSessionId(sessionId: string): void;
794
+ /** Shared-tabs: bake this tab's identity into mutation ids so a rollback of
795
+ * a follower's mutation routes back to the tab that made it. */
796
+ setTabId(tabId: string): void;
797
+ /**
798
+ * Update the authenticated user record id. Pass `null` on sign-out.
799
+ * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
800
+ * the poll route to the same per-user `_00_list_ref_user_<id>` the
801
+ * SSP writes to.
802
+ */
803
+ setCurrentUserId(userId: string | null): void;
804
+ /** Read-only view of the authenticated user id used for per-user
805
+ * `_00_list_ref` routing. Other modules consult this so they pick the
806
+ * same table name DataModule does. */
807
+ getCurrentUserId(): string | null;
808
+ /**
809
+ * Register a query and return its hash for subscriptions
810
+ */
811
+ query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive, plan?: QueryPlan): Promise<QueryHash>;
812
+ /**
813
+ * Subscribe to query updates
814
+ */
815
+ subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
241
816
  immediate?: boolean;
242
- }): Promise<() => void>;
243
- run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
244
- bucket<B extends BucketNames<S>>(name: B): BucketHandle;
245
- create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
246
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
247
- [x: string]: /*elided*/any;
248
- }>;
249
- delete(table: string, id: string): Promise<void>;
250
- useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
251
- private persistClientId;
252
- private loadOrGenerateClientId;
253
- }
254
- //#endregion
255
- //#region src/utils/index.d.ts
256
- declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
817
+ }): () => void;
818
+ /**
819
+ * Subscribe to a query's fetch-status changes (idle/fetching).
820
+ * With `{ immediate: true }` the callback fires synchronously with the
821
+ * current status (defaults to `idle` if the query isn't registered yet).
822
+ */
823
+ subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
824
+ immediate?: boolean;
825
+ }): () => void;
826
+ /**
827
+ * Subscribe to a query's authority flips: whether server membership is known
828
+ * for it. With `{ immediate: true }` the callback fires synchronously with
829
+ * the current value (`false` for an unknown query).
830
+ */
831
+ subscribeAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
832
+ immediate?: boolean;
833
+ }): () => void;
834
+ /** Whether server membership is known for `queryHash` (see `QueryConfig.membershipKnown`). */
835
+ isAuthoritative(queryHash: string): boolean;
836
+ /**
837
+ * The single writer of `config.membershipKnown` for a live query. Fans out
838
+ * to `subscribeAuthority` listeners and DevTools on a change; no-op when
839
+ * unchanged or the query is unknown.
840
+ */
841
+ private setMembershipKnown;
842
+ /**
843
+ * Set a query's fetch status and notify status observers (DevTools +
844
+ * `subscribeStatus` listeners). No-op when the status is unchanged or the
845
+ * query is unknown.
846
+ */
847
+ setQueryStatus(queryHash: string, status: QueryStatus): void;
848
+ /**
849
+ * Enter a fetch cycle for a query. Refcounted: registration and concurrent
850
+ * poll/LIVE sync rounds can overlap on the same hash, and only the OUTERMOST
851
+ * cycle may flip the status — 0→1 emits `fetching`, and `endFetching`'s 1→0
852
+ * emits `idle`. Always pair with `endFetching` in a `finally`.
853
+ */
854
+ beginFetching(queryHash: string): void;
855
+ /** Leave a fetch cycle started with {@link beginFetching}; emits `idle` on the last exit. */
856
+ endFetching(queryHash: string): void;
857
+ /** How many queries are mid-fetch right now (see {@link subscribeActivity}). */
858
+ get fetchingQueryCount(): number;
859
+ /**
860
+ * Observe the number of queries currently fetching. Fires on every change of
861
+ * that number (a query entering or leaving its outermost fetch cycle), and
862
+ * synchronously with the current value when `immediate` is set. One
863
+ * subscription per indicator, however many queries the page holds.
864
+ */
865
+ subscribeActivity(callback: (fetching: number) => void, options?: {
866
+ immediate?: boolean;
867
+ }): () => void;
868
+ private notifyActivity;
869
+ /**
870
+ * Subscribe to mutations (for sync)
871
+ */
872
+ onMutation(callback: MutationCallback): () => void;
873
+ /**
874
+ * Handle stream updates from DBSP (via CacheModule)
875
+ */
876
+ onStreamUpdate(update: StreamUpdate): Promise<void>;
877
+ /** Coalesce `update` onto the query's trailing timer (see onStreamUpdate). */
878
+ private queueStreamUpdate;
879
+ /**
880
+ * Re-materialize + notify a query whose MEMBERSHIP changed without any row
881
+ * needing to be fetched, i.e. without the SSP stream update that normally
882
+ * carries the notify. That is every row this client wrote itself: the local
883
+ * CREATE memoized it at `_00_rv = 1`, the server publishes it at 1, so the
884
+ * sync engine rightly fetches nothing - and then nobody told the subscribers
885
+ * that `remoteArray` now holds the id. The row appeared on reload only.
886
+ *
887
+ * Routed through the same per-query debounce as a real stream update, so it
888
+ * cannot race one: a pending real update already materializes against the
889
+ * current `remoteArray` and wins. The synthetic update re-uses the circuit's
890
+ * last `localArray` and skips the persist/metrics that describe an ingest.
891
+ */
892
+ scheduleRematerialize(queryHash: string): void;
893
+ /**
894
+ * Process a query's pending (debounced) stream update NOW instead of on the
895
+ * trailing edge. Called by the sync engine before it flips a query back to
896
+ * `idle`, so the status change never races ahead of the rows it fetched.
897
+ * No-op when nothing is pending. The pending entry is removed before the
898
+ * await so a concurrently-firing timer can't process it twice.
899
+ */
900
+ flushPendingStreamUpdate(queryHash: string): Promise<boolean>;
901
+ /**
902
+ * Materialize a query's result rows from the local store.
903
+ *
904
+ * A query's rows are its MEMBERSHIP — the id-set the server put in
905
+ * `_00_list_ref` (`remoteArray`) — not "every local body that matches the
906
+ * WHERE". Those two disagree, and the disagreement was the bug: when a row
907
+ * leaves a query's window but still exists upstream, `handleRemovedRecords`
908
+ * keeps its local body and never re-fetches it, so a predicate re-scan finds
909
+ * that stale body still matching and keeps rendering the row. Selecting the
910
+ * id-set directly is also the only correct thing for a windowed query, where
911
+ * re-applying `START m` against the shared local store skips the window's own
912
+ * rows entirely (sparse windowing) and returns nothing.
913
+ *
914
+ * The rendered set is:
915
+ *
916
+ * (membership ∪ (pendingWrites ∩ localArray)) − pendingDeletes
917
+ *
918
+ * The middle term keeps optimistic writes visible without re-admitting stale
919
+ * rows. Every local write is fed to the SSP (`cache.saveBatch` →
920
+ * `ingestMany`), so `localArray` answers "does this row match the predicate
921
+ * per LOCAL truth". A pending write that moves a row into the window is in
922
+ * `localArray` and shows; one that moves a row out is absent and does not; a
923
+ * stale body the server dropped has no pending write at all, so it stays out.
924
+ * `pendingDeletes` covers the reverse lag — the server still lists a row whose
925
+ * DELETE is sitting in our outbox.
926
+ *
927
+ * Falls back to the predicate scan only when membership has never been
928
+ * established (a query first run on this device), so an offline first paint
929
+ * still shows something.
930
+ */
931
+ private materializeRecords;
932
+ /**
933
+ * The materialization itself, without the DevTools timing wrapper. Split out so
934
+ * cold-start seeding can use it before a `QueryState` exists.
935
+ */
936
+ private materializeFromConfig;
937
+ /**
938
+ * The authoritative membership list to render from, or `null` when membership
939
+ * has never been established and the caller must fall back to a scan.
940
+ *
941
+ * A windowed query has no usable fallback — re-running its `START m` locally
942
+ * returns the wrong rows — so it renders from whatever id-set is on hand
943
+ * (SSP's included) rather than degrading to a scan. That is the pre-existing
944
+ * behavior for windows and is preserved.
945
+ */
946
+ private resolveMembership;
947
+ private readonly settledWrites;
948
+ private readonly settledDeletes;
949
+ private pendingIds;
950
+ private pendingIdsAt;
951
+ private pendingIdsInflight;
952
+ private static readonly PENDING_IDS_TTL_MS;
953
+ private pendingIdsGen;
954
+ private static readonly PENDING_IDS_MAX_REREADS;
955
+ /** Drop the cached outbox ids. Cheap; call it on anything that could change
956
+ * `_00_pending_mutations`. */
957
+ private invalidatePendingIds;
958
+ /**
959
+ * Grace period for a settled write. Long enough to cover an SSP round trip
960
+ * that is running slowly (seconds, not milliseconds, when the edge path is
961
+ * backed up), short enough that a write the server silently dropped cannot
962
+ * linger misleadingly.
963
+ *
964
+ * The rejection case does NOT rely on this expiring: an application error
965
+ * rolls the mutation back and never reports it settled, so it vanishes at
966
+ * once. This deadline only bounds the case where the write succeeded and its
967
+ * membership never arrived at all.
968
+ *
969
+ * 30 s, up from 10 s. At 10 s every server hiccup longer than a scheduler
970
+ * drain plus one slow database commit showed up as the user's own chat
971
+ * message vanishing and coming back a minute later. 30 s covers a drain and
972
+ * a stalled commit end to end; a membership that takes longer than that is
973
+ * a server fault the admin heartbeat reports, not something to paper over.
974
+ */
975
+ private static readonly SETTLED_WRITE_GRACE_MS;
976
+ /**
977
+ * Whether any settled write or delete is still waiting for membership to
978
+ * catch up. The sync poll keeps its fast cadence while this is true, so a
979
+ * missed LIVE notification for the edge is picked up on the next poll tick
980
+ * rather than after the idle backoff.
981
+ */
982
+ hasSettledWritesPending(): boolean;
983
+ /**
984
+ * Report that a mutation was accepted by the server and its outbox row
985
+ * removed. Called only on the SUCCESS path — a rolled-back mutation must
986
+ * disappear immediately, which is what makes this safe.
987
+ */
988
+ noteWriteSettled(recordId: string, mutationType: string): void;
989
+ /** Drop entries past their deadline. */
990
+ private pruneSettled;
991
+ /** Apply the pending-write union and pending-delete subtraction, and map to
992
+ * RecordIds for the engines' id-set path. */
993
+ private buildRenderIds;
994
+ private processStreamUpdate;
995
+ /**
996
+ * Compute p55/p90/p99 from a rolling window of materialization samples.
997
+ * Returns nulls for any percentile that has no samples yet so SurrealDB
998
+ * `option<float>` columns stay NONE rather than 0 before the first ingest.
999
+ */
1000
+ private computeMaterializationPercentiles;
1001
+ /** Record a per-phase timing sample (ms) on a query's rolling window. */
1002
+ private recordPhase;
1003
+ /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
1004
+ recordRemoteFetch(hash: string, ms: number): void;
1005
+ /**
1006
+ * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
1007
+ * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
1008
+ */
1009
+ recordFrontendTiming(hash: string, ms: number): void;
1010
+ /**
1011
+ * Build the per-query processing-time breakdown surfaced to the DevTools panel
1012
+ * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
1013
+ * the rest come from the per-phase rolling windows + one-shot registration timings.
1014
+ */
1015
+ phaseTimings(q: QueryState): QueryTimings;
1016
+ /**
1017
+ * Get query state (for sync and devtools)
1018
+ */
1019
+ getQueryByHash(hash: string): QueryState | undefined;
1020
+ /**
1021
+ * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
1022
+ * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
1023
+ * We gate on `remoteArray`, not local `records`: a windowed query is often
1024
+ * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
1025
+ * but it still hasn't loaded its own full window from the server — so it should
1026
+ * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
1027
+ */
1028
+ isCold(hash: string): boolean;
1029
+ /**
1030
+ * Walk a hydrated record's fields and append any EMBEDDED child records to
1031
+ * `batch` (recursing for nested related fields). An embedded child is a
1032
+ * value that is itself a record — a non-null object whose `id` is a
1033
+ * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
1034
+ * bare `RecordId` (a foreign-key reference) or any other value is skipped,
1035
+ * so this never mistakes a FK column for an embedded body. Children are
1036
+ * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
1037
+ * to their table's real columns (which strips the alias/related fields).
1038
+ * `seen` dedupes within the batch.
1039
+ */
1040
+ private collectEmbeddedChildren;
1041
+ /**
1042
+ * Prepare a subquery-bearing row (preload / hydration) for the schemafull
1043
+ * local store: replace an embedded FORWARD-relation object (`author = { id, … }`)
1044
+ * with its RecordId so a `record<…>` field coerces, and DROP reverse-subquery
1045
+ * ARRAYS (`comments = [ … ]`) since their rows are cached separately as their
1046
+ * own bodies. A flat record — as the live `SELECT * FROM $ids` sync returns,
1047
+ * with relations already RecordIds — passes through unchanged.
1048
+ */
1049
+ private flattenRelationsForStorage;
1050
+ /**
1051
+ * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
1052
+ * surql run directly) so the query DISPLAYS immediately, while the full realtime
1053
+ * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
1054
+ * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
1055
+ * `remoteArray` so windowed queries materialize the correct window (no sparse
1056
+ * local-circuit issue). Runs at most once per query (the `hydrated` flag).
1057
+ */
1058
+ applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
1059
+ /**
1060
+ * Build the cache batch for a set of one-shot rows and persist it to the
1061
+ * local DB + in-browser SSP. Maps each row to a `CREATE` op on its own table
1062
+ * and extracts EMBEDDED related children (any nesting depth) as their own
1063
+ * records — a `.related()` query returns its children embedded, and a later
1064
+ * correlated re-materialization needs them present as standalone rows.
1065
+ * Shared by `applyHydration` (live registration) and `persistSnapshot`
1066
+ * (preload).
1067
+ */
1068
+ private buildAndSaveCacheBatch;
1069
+ /**
1070
+ * Preload/prewarm: persist one-shot rows (and their embedded related children)
1071
+ * into the local cache WITHOUT registering a query — no `activeQueries` entry,
1072
+ * no `_00_query` view, no TTL heartbeat. The rows live in the local DB as
1073
+ * ordinary bodies (never GC'd on their own) so a later `useQuery` seeds its
1074
+ * first paint from them instantly, then registers a live view to freshen.
1075
+ */
1076
+ persistSnapshot(tableName: string, rows: RecordWithId[]): Promise<void>;
1077
+ /**
1078
+ * Read the durable preload freshness marker for a query hash, or null if this
1079
+ * query was never preloaded in the current bucket. Co-located with the cached
1080
+ * rows (per-bucket `_00_preload` table) so a bucket switch that clears the
1081
+ * data also clears the marker — a stale marker can't claim "warm" when the
1082
+ * rows are gone. Any read error is treated as cold.
1083
+ */
1084
+ getPreloadMarker(hash: string): Promise<{
1085
+ fetchedAt: number;
1086
+ rowCount: number;
1087
+ } | null>;
1088
+ /** Stamp the preload freshness marker after a successful snapshot fetch. */
1089
+ writePreloadMarker(hash: string, rowCount: number): Promise<void>;
1090
+ /**
1091
+ * Read the durable membership row, or `null` if this query has never had
1092
+ * authoritative membership on this device. Any read error is treated as
1093
+ * "unknown" so a broken row degrades to the predicate scan rather than
1094
+ * rendering an empty list.
1095
+ *
1096
+ * `confirmed` is true only for rows written after the server itself vouched
1097
+ * for the set (a non-empty id-set, or an empty one it reported a row count of
1098
+ * zero for, or an empty one that followed a non-empty one in the same
1099
+ * session). Rows written before the marker existed, including the `[]` rows a
1100
+ * pre-`ea56f50e` client mirrored from an unflushed read, read as unconfirmed.
1101
+ */
1102
+ getWindowMembership(key: string): Promise<DurableMembership | null>;
1103
+ /**
1104
+ * Persist the durable membership row. Best-effort: callers must not fail a
1105
+ * sync round because the mirror write failed.
1106
+ *
1107
+ * `confirmed` says whether a cold start may trust this row even when it is
1108
+ * empty. A confirmed empty is a real answer ("the server says this query has
1109
+ * no rows") and stays empty across a reload; an unconfirmed empty is the
1110
+ * retry budget's guess and falls back to the predicate scan on the next boot,
1111
+ * exactly as every empty row did before the marker existed.
1112
+ */
1113
+ writeWindowMembership(key: string, ids: RecordVersionArray, confirmed: boolean): Promise<void>;
1114
+ /**
1115
+ * Record ids with a mutation still in the outbox, split by direction.
1116
+ *
1117
+ * Both halves feed {@link materializeRecords}: `writes` keeps optimistic
1118
+ * creates/updates visible before the server has acknowledged them, and
1119
+ * `deletes` suppresses rows the server still lists because our DELETE hasn't
1120
+ * been processed yet. Reading `_00_pending_mutations` (rather than tracking
1121
+ * ids in memory) is what makes both survive a reload.
1122
+ *
1123
+ * On failure returns empty sets: membership alone then decides, which can
1124
+ * briefly hide an optimistic write but never resurrects a deleted row.
1125
+ */
1126
+ getPendingRecordIds(): Promise<{
1127
+ writes: Set<string>;
1128
+ deletes: Set<string>;
1129
+ }>;
1130
+ /** The uncached read. Also the reload path after an invalidation, so the ids
1131
+ * still survive a reload exactly as before. `gen` is the generation the read
1132
+ * was issued under; the result is cached only if it is still current. */
1133
+ private readPendingRecordIds;
1134
+ /** True while ≥1 live subscriber is watching this query (refcount guard). */
1135
+ hasSubscribers(hash: string): boolean;
1136
+ /**
1137
+ * Opt-in eager teardown for a query whose LAST subscriber just left — used by
1138
+ * viewport-windowed lists to cancel off-screen windows instead of leaving
1139
+ * their remote views to expire on the TTL sweep. No-op while any subscriber
1140
+ * remains (refcount). Only enqueues the remote cleanup here; the local WASM
1141
+ * view + in-memory state are freed in {@link finalizeDeregister} after the
1142
+ * remote delete completes, so a re-subscribe in between aborts/heals it.
1143
+ *
1144
+ * NOTE: most queries should NOT use this — the default keep-alive on
1145
+ * unsubscribe avoids re-registration churn on navigation.
1146
+ */
1147
+ deregisterQuery(hash: string): void;
1148
+ /**
1149
+ * Final local teardown after the remote `_00_query` row was deleted: free the
1150
+ * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
1151
+ * (`cleanupQuery`) guarantees no subscriber remains.
1152
+ */
1153
+ finalizeDeregister(hash: string): void;
1154
+ /**
1155
+ * Get query state by id (for sync and devtools)
1156
+ */
1157
+ getQueryById(id: RecordId<string>): QueryState | undefined;
1158
+ /**
1159
+ * Get all active queries (for devtools)
1160
+ */
1161
+ getActiveQueries(): QueryState[];
1162
+ getActiveQueryHashes(): QueryHash[];
1163
+ updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
1164
+ updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray, opts?: {
1165
+ /** The `_00_query` row as read in the same round trip as the edges. */
1166
+ meta?: ServerViewMeta;
1167
+ /**
1168
+ * The caller verified upstream that the ids missing from `remoteArray`
1169
+ * no longer exist (see `Sp00kySync` LIVE removal handling); an empty set
1170
+ * is then a real answer even without a readable row.
1171
+ */
1172
+ verifiedRemoval?: boolean;
1173
+ }): Promise<MembershipOutcome>;
1174
+ /**
1175
+ * Cancel every armed timer ahead of a local-bucket switch: stream-update
1176
+ * debounce timers (their pending updates carry the OLD bucket's id-sets) and
1177
+ * per-query TTL heartbeats (they'd refresh the previous user's remote
1178
+ * `_00_query` rows under the new session). The rebind re-arms heartbeats.
1179
+ */
1180
+ quiesce(): void;
1181
+ /**
1182
+ * Re-home every active query in a freshly-opened bucket, KEEPING its hash —
1183
+ * `useQuery` subscriptions are keyed by hash and don't re-register on auth
1184
+ * changes, so the hooks must stay attached. Per query:
1185
+ * 1. reset the sync arrays + hydration flag and drop the previous user's
1186
+ * records, notifying subscribers with the new-bucket materialization
1187
+ * (usually empty) so their rows leave the UI immediately;
1188
+ * 2. recreate the `_00_query` row in the new bucket;
1189
+ * 3. re-register the SSP view on the (fresh, post-reset) processor — this
1190
+ * also rebinds the view to the NEW `$auth` context;
1191
+ * 4. restart the TTL heartbeat.
1192
+ * Returns the hashes so the caller can enqueue remote re-registration, which
1193
+ * refills records from the server via the normal register→sync→notify path.
1194
+ */
1195
+ rebindAfterBucketSwitch(): Promise<QueryHash[]>;
1196
+ /**
1197
+ * Called after a query's initial sync completes.
1198
+ * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
1199
+ */
1200
+ notifyQuerySynced(queryHash: string): Promise<void>;
1201
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
1202
+ /**
1203
+ * Build the outbox job record + resolve its table for a backend route.
1204
+ *
1205
+ * Every job is a single execution. Recurring work is declared server-side
1206
+ * (`schedules:` in sp00ky.yml) and the scheduler creates a fresh row per cycle,
1207
+ * so nothing here needs to know about schedules.
1208
+ */
1209
+ private buildJobRecord;
1210
+ /**
1211
+ * Create a new record
1212
+ */
1213
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
1214
+ /**
1215
+ * Update an existing record
1216
+ */
1217
+ update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
1218
+ /**
1219
+ * Delete a record
1220
+ */
1221
+ delete(table: string, id: string): Promise<void>;
1222
+ /**
1223
+ * Rollback a failed optimistic create by deleting the record locally
1224
+ */
1225
+ rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
1226
+ /**
1227
+ * Rollback a failed optimistic update by restoring the previous record state
1228
+ */
1229
+ rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
1230
+ /**
1231
+ * Force a re-materialize + notify of every active query on `tableName`.
1232
+ * Used after a DELETE landed in the local store (this tab's own, or one
1233
+ * relayed from another tab): the SSP may not emit a view update for a
1234
+ * DELETE ingest, and the re-materialize reads the store, which already
1235
+ * excludes the row. Each query is isolated so one failing re-materialize
1236
+ * can't stop the others.
1237
+ */
1238
+ notifyTableQueries(tableName: string): Promise<void>;
1239
+ /**
1240
+ * Remove a record from all active query states and notify subscribers
1241
+ */
1242
+ private removeRecordFromQueries;
1243
+ private createAndRegisterQuery;
1244
+ private createNewQuery;
1245
+ private calculateHash;
1246
+ /**
1247
+ * Session-independent counterpart of {@link calculateHash}: the key for a
1248
+ * query's durable `_00_window` membership row.
1249
+ *
1250
+ * Deliberately the SAME inputs minus the `session::id()` salt, so the two keys
1251
+ * can never drift apart. The salt is right for `_00_query` (two tabs must not
1252
+ * fight over one row) and wrong for membership, which has to be recognizable
1253
+ * after a reload — a reload mints a new session id, and offline the salt is
1254
+ * `''`, so a salted key can never match what the previous session wrote.
1255
+ */
1256
+ private calculateMembershipKey;
1257
+ private sha256;
1258
+ private startTTLHeartbeat;
1259
+ /**
1260
+ * Heartbeat every watched query NOW and re-anchor its timer.
1261
+ *
1262
+ * The TTL timer is the only thing keeping a view alive on the server, and
1263
+ * browsers throttle timers in hidden tabs (Chrome aligns them to one-minute
1264
+ * ticks after five minutes hidden, and suspends them outright on some
1265
+ * mobile platforms). A tab that comes back after a long stretch may have
1266
+ * missed its beat by more than the server's slack, and the sweep will have
1267
+ * taken the row and its edges. The client does not blank on that any more
1268
+ * (`updateQueryRemoteArray` treats a missing row as "view lost"), but the
1269
+ * sooner it finds out, the sooner the view is rebuilt: `heartbeatQuery`
1270
+ * re-registers a query whose row is gone. Called on `visibilitychange` (to
1271
+ * visible) and `online`.
1272
+ *
1273
+ * Queries beaten within the last `minGapMs` are skipped, so a flurry of
1274
+ * wake events costs one beat per query. There is deliberately no local
1275
+ * expiry anywhere in this module: the TTL is the server's, and the client's
1276
+ * only duty is to keep asserting liveness while something is watching.
1277
+ */
1278
+ heartbeatOnWake(minGapMs?: number): number;
1279
+ private replaceRecordInQueries;
1280
+ }
1281
+ /**
1282
+ * Parse update options to generate push event options
1283
+ */
1284
+ //#endregion
1285
+ //#region src/services/tabs/protocol.d.ts
1286
+ type TabId = string;
1287
+ type TabRole = 'solo' | 'leader' | 'follower';
1288
+ /** Broker pings every tab at this cadence. */
1289
+
1290
+ /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
1291
+ * consumes, so relayed batches feed follower circuits without reshaping. */
1292
+ interface IngestTuple {
1293
+ table: string;
1294
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
1295
+ id: string;
1296
+ record: Record<string, unknown>;
1297
+ }
1298
+ type FollowerToLeaderMessage = {
1299
+ type: 'sync-hello';
1300
+ tabId: TabId;
1301
+ }
1302
+ /** The follower committed an outbox row (through the shared store) and the
1303
+ * leader should drain it. Idempotent; a new leader's loadFromDatabase is
1304
+ * the backstop for a notify lost in a failover window. */ | {
1305
+ type: 'mutation-enqueued';
1306
+ mutationId: string;
1307
+ } | {
1308
+ type: 'request-poll';
1309
+ }
1310
+ /** An optimistic write this follower committed to the SHARED store and
1311
+ * ingested into its own circuit. The leader ingests it (no DB write, the
1312
+ * row is already there) and fans it out to every OTHER follower as
1313
+ * `ingest-relay`, so a follower's write lands in every tab in one hop
1314
+ * instead of after the server round-trip. */ | {
1315
+ type: 'ingest';
1316
+ tuples: IngestTuple[];
1317
+ };
1318
+ type LeaderToFollowerMessage = {
1319
+ type: 'db-ready';
1320
+ leadershipId: number;
1321
+ bucketId: string;
1322
+ storageHealth: StorageHealth;
1323
+ }
1324
+ /** Every ingest the leader's CacheModule committed, so follower circuits
1325
+ * stay live without their own fetch. seq detects gaps. */ | {
1326
+ type: 'ingest-relay';
1327
+ tuples: IngestTuple[];
1328
+ leadershipId: number;
1329
+ seq: number;
1330
+ }
1331
+ /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
1332
+ * queryId against its own DataModule and ignores foreign queries. */ | {
1333
+ type: 'list-ref-change';
1334
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
1335
+ queryId: string;
1336
+ recordId: string;
1337
+ version: number;
1338
+ parent: boolean;
1339
+ }
1340
+ /** The leader's drain rolled back a mutation owned by this tab. */ | {
1341
+ type: 'mutation-rolled-back';
1342
+ mutationId: string;
1343
+ recordId: string;
1344
+ eventType: 'create' | 'update' | 'delete';
1345
+ error: string;
1346
+ }
1347
+ /** The leader's drain pushed a mutation and deleted its outbox row from the
1348
+ * SHARED store. Every follower starts its settled-write grace so a row it
1349
+ * was rendering as a pending write does not blink out before its
1350
+ * `_00_list_ref` membership arrives. */ | {
1351
+ type: 'mutation-settled';
1352
+ mutationId: string;
1353
+ recordId: string;
1354
+ eventType: 'create' | 'update' | 'delete';
1355
+ };
1356
+ //#endregion
1357
+ //#region src/services/tabs/coordinator.d.ts
1358
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
1359
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
1360
+ declare class LeaderSyncHub {
1361
+ readonly leadershipId: number;
1362
+ private logger;
1363
+ private followers;
1364
+ private seq;
1365
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1366
+ onFollowerDetached: ((tabId: TabId) => void) | null;
1367
+ constructor(leadershipId: number, logger: Logger$1);
1368
+ attach(tabId: TabId, port: MessagePort): void;
1369
+ detach(tabId: TabId): void;
1370
+ detachAll(): void;
1371
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1372
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1373
+ /** Stamped ingest relay; seq lets followers detect gaps. */
1374
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1375
+ get followerCount(): number;
1376
+ get relayedBatches(): number;
1377
+ }
1378
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
1379
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
1380
+ * backstopped by the new leader reloading the shared outbox from the store. */
1381
+ declare class SyncForwarder {
1382
+ private tabId;
1383
+ private port;
1384
+ private queued;
1385
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1386
+ constructor(tabId: TabId);
1387
+ rebind(port: MessagePort): void;
1388
+ unbind(): void;
1389
+ private post;
1390
+ mutationEnqueued(mutationId: string): void;
1391
+ /** An optimistic write this tab just ingested. Deliberately NOT queued while
1392
+ * detached: a new leader primes its circuit from the shared store, which
1393
+ * already holds the row, and replaying a stale tuple at it later would put
1394
+ * an older `_00_rv` in its version memo. */
1395
+ ingest(tuples: IngestTuple[]): void;
1396
+ requestPoll(): void;
1397
+ }
1398
+ //#endregion
1399
+ //#region src/modules/sync/sync.d.ts
1400
+ /**
1401
+ * Tunables for `Sp00kySync` construction.
1402
+ */
1403
+ interface Sp00kySyncOptions {
1404
+ /**
1405
+ * Cadence (ms) for the `_00_list_ref` poll fallback that catches
1406
+ * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
1407
+ * values fall back to the default; see
1408
+ * {@link resolveListRefPollInterval}.
1409
+ */
1410
+ refSyncIntervalMs?: number;
1411
+ /**
1412
+ * Enable realtime sync for unauthenticated clients against the shared
1413
+ * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
1414
+ * Defaults to `false`.
1415
+ */
1416
+ anonymousLiveQueries?: boolean;
1417
+ /**
1418
+ * Consecutive failed sync rounds before sync health flips to `degraded`.
1419
+ * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
1420
+ * Defaults to `3`.
1421
+ */
1422
+ degradeAfterConsecutiveFailures?: number;
1423
+ /**
1424
+ * Max time a single mutation push may take before it is treated as a network
1425
+ * failure and retried. Guards against an RPC that never settles wedging the
1426
+ * up-queue for the session. Defaults to 30000; `0` disables the timeout.
1427
+ */
1428
+ pushTimeoutMs?: number;
1429
+ /**
1430
+ * Max time a single down event (`register`/`sync`/`cleanup`) may take before
1431
+ * it is treated as a network failure and retried. The mirror of
1432
+ * {@link pushTimeoutMs} for the read side, which had no such guard: a
1433
+ * `fn::query::register` that never settled held its slot in the down drain,
1434
+ * and every later registration behind it, for the rest of the session.
1435
+ * Defaults to 30000; `0` disables the timeout.
1436
+ */
1437
+ downTimeoutMs?: number;
1438
+ /**
1439
+ * Transport supervisor. Sync reads its state to report `connection` in
1440
+ * {@link SyncHealth} so a UI can show "reconnecting…" the instant the socket
1441
+ * drops, without waiting for the degrade threshold. Optional: omitted in
1442
+ * tests, where `connection` then reports `connected`.
1443
+ */
1444
+ connectionSupervisor?: ConnectionSupervisor;
1445
+ }
1446
+ /**
1447
+ * The main synchronization engine for Sp00ky.
1448
+ * Handles the bidirectional synchronization between the local database and the remote backend.
1449
+ * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
1450
+ * @template S The schema structure type.
1451
+ */
1452
+ declare class Sp00kySync<S extends SchemaStructure> {
1453
+ private local;
1454
+ private remote;
1455
+ private cache;
1456
+ private dataModule;
1457
+ private schema;
1458
+ private upQueue;
1459
+ private downQueue;
1460
+ private isInit;
1461
+ private logger;
1462
+ private syncEngine;
1463
+ /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
1464
+ * from `this.events`, which carries Sp00kySync-level events like
1465
+ * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
1466
+ get engineEvents(): SyncEventSystem;
1467
+ private scheduler;
1468
+ /**
1469
+ * Set by any event that means the socket we registered on is gone, so the
1470
+ * next `connected` knows it must re-subscribe rather than treat itself as the
1471
+ * initial connect. See {@link subscribeToReconnect}.
1472
+ */
1473
+ private needsResubscribe;
1474
+ /** When the last reconnect-driven full refetch ran, for burst coalescing. */
1475
+ private lastReconnectRefetchAt;
1476
+ /**
1477
+ * Minimum gap between reconnect-driven full refetches. Long enough to absorb
1478
+ * a flapping socket (the SDK reconnect ladder starts at 1s), short enough
1479
+ * that a genuine drop minutes later still refetches.
1480
+ */
1481
+ private static readonly RECONNECT_REFETCH_COOLDOWN_MS;
1482
+ /** Poll interval while waiting for a reconnected session to re-authenticate. */
1483
+ private static readonly AUTH_READY_RETRY_MS;
1484
+ /** Attempts before giving up on re-auth and skipping the refetch entirely. */
1485
+ private static readonly AUTH_READY_MAX_ATTEMPTS;
1486
+ events: SyncEventSystem;
1487
+ private currentUserId;
1488
+ private tabRole;
1489
+ private tabId;
1490
+ private hub;
1491
+ private forwarder;
1492
+ private refMode;
1493
+ private readonly anonLiveEnabled;
1494
+ private currentLiveQueryUuid;
1495
+ private liveQueryUnsubscribe;
1496
+ private listRefPollTimer;
1497
+ private listRefPollRunning;
1498
+ private listRefPollInFlight;
1499
+ readonly refSyncIntervalMs: number;
1500
+ private listRefIdleStreak;
1501
+ private listRefPolledAt;
1502
+ private stillRemoteStreaks;
1503
+ private lastLiveEventAt;
1504
+ private _liveRetryCount;
1505
+ get liveRetryCount(): number;
1506
+ get isSyncing(): boolean;
1507
+ get pendingMutationCount(): number;
1508
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
1509
+ private readonly degradeAfterFailures;
1510
+ /** Per-push RPC deadline; see {@link withPushTimeout}. */
1511
+ private readonly pushTimeoutMs;
1512
+ private readonly downTimeoutMs;
1513
+ private consecutiveSyncFailures;
1514
+ private syncHealthStatus;
1515
+ private lastSyncErrorKind;
1516
+ private lastSyncErrorMessage;
1517
+ private hasSyncedOnce;
1518
+ private selfHealTimer;
1519
+ private selfHealAttempts;
1520
+ private static readonly SELF_HEAL_BASE_MS;
1521
+ private static readonly SELF_HEAL_MAX_MS;
1522
+ /**
1523
+ * Transport supervisor, when one was supplied. Sync only reads state from it;
1524
+ * it never drives reconnects itself.
1525
+ */
1526
+ private readonly connectionSupervisor?;
1527
+ /**
1528
+ * Mirror of the supervisor's state. Defaults to `connected` so a client
1529
+ * constructed without a supervisor (tests, embedders) reports the same health
1530
+ * shape it always has rather than a permanent false "disconnected".
1531
+ */
1532
+ private connectionState;
1533
+ /** Current sync-health snapshot. */
1534
+ get syncHealth(): SyncHealth;
1535
+ /**
1536
+ * Observe sync health. The callback fires immediately with the current
1537
+ * status and again on every healthy↔degraded transition. Returns an
1538
+ * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
1539
+ */
1540
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1541
+ private emitSyncHealth;
1542
+ /**
1543
+ * Mirror the supervisor's transport state into {@link SyncHealth} and emit on
1544
+ * every change, so a UI can react to a dropped socket immediately instead of
1545
+ * waiting for `degradeAfterFailures` failed rounds. `status` is untouched:
1546
+ * a brief reconnect is not a degradation.
1547
+ *
1548
+ * No explicit unsubscribe: the supervisor is owned by the same client and
1549
+ * drops all subscribers in its own `dispose()`, which `Sp00kyClient.close()`
1550
+ * calls first.
1551
+ */
1552
+ private subscribeToConnectionState;
1553
+ /**
1554
+ * Fed by the scheduler once per drained sync round. Individual failures are
1555
+ * absorbed by the queue's retry; only a run of `degradeAfterFailures`
1556
+ * consecutive failures flips the status to `degraded`, and the next clean
1557
+ * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
1558
+ * is 0).
1559
+ */
1560
+ private recordSyncOutcome;
1561
+ /**
1562
+ * Begin self-heal retries (no-op if already running). Started on the
1563
+ * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
1564
+ */
1565
+ private startSelfHeal;
1566
+ private scheduleSelfHeal;
1567
+ private stopSelfHeal;
1568
+ /**
1569
+ * Release a deregistered query's remote view immediately instead of leaving
1570
+ * it to the TTL sweep. Off by default; see the reasoning in
1571
+ * {@link cleanupQuery}. Kept as a field rather than deleted so the eager path
1572
+ * can be re-enabled in a test once the subquery-body repair path exists.
1573
+ */
1574
+ private readonly releaseQueriesEagerly;
1575
+ constructor(local: LocalStore, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
1576
+ /**
1577
+ * Initializes the synchronization system.
1578
+ * Starts the scheduler and initiates the initial sync cycles.
1579
+ * @throws Error if already initialized.
1580
+ */
1581
+ init(): Promise<void>;
1582
+ /** Set BEFORE init(): shapes what init boots (a follower loads no outbox and
1583
+ * never starts LIVE; its own registration/poll paths stay untouched). */
1584
+ setTabContext(role: 'solo' | 'leader' | 'follower', tabId: string | null): void;
1585
+ /** In-flight {@link resumeLeaderDuties}, so a second call joins the first
1586
+ * instead of double-draining the outbox. */
1587
+ private leaderDutiesInFlight;
1588
+ /** Resolves once the in-browser circuit has been primed from the local
1589
+ * store. Every sync diff waits on it: diffing against an empty circuit
1590
+ * classifies the whole working set as missing and re-downloads it. */
1591
+ private primeGate;
1592
+ /** The prime we last waited on. `whenPrimed` hands out one promise per
1593
+ * prime, so a new identity means a new prime (boot, bucket switch) ran. */
1594
+ private settledPrime;
1595
+ setPrimeGate(gate: () => Promise<void>): void;
1596
+ /**
1597
+ * Leader WIRING only, and deliberately synchronous.
1598
+ *
1599
+ * The coordinator publishes the leader role and tells the broker
1600
+ * `leader-ready` the moment the store is adopted, and the broker can mint a
1601
+ * follower's ports on the very next tick. So the follower-message handler
1602
+ * has to be live before this returns, or a mutation forwarded in that window
1603
+ * is dropped. Everything that can block (outbox reload, LIVE restart) moved
1604
+ * to {@link resumeLeaderDuties}: a promotion that waits on the network holds
1605
+ * `leader-ready` back, and a broker whose leader never reports ready serves
1606
+ * no follower ports and re-elects no one, which wedges the whole namespace.
1607
+ */
1608
+ promoteToLeader(hub: LeaderSyncHub): void;
1609
+ /** Leader duties: drain the shared outbox, own the single list_ref LIVE,
1610
+ * relay LIVE events and rollbacks to followers. Idempotent for a boot-time
1611
+ * leader; a runtime promotion (failover) reloads the outbox, which now
1612
+ * holds EVERY tab's rows, and restarts LIVE under this session. Runs in the
1613
+ * background off the promotion path, so however long it takes (or if it
1614
+ * never finishes) the tab is already a working leader. */
1615
+ resumeLeaderDuties(): Promise<void>;
1616
+ /** Follower duties: no outbox drain, no LIVE. Mutations forward to the
1617
+ * leader; everything else (registration, per-query sync, poll) runs
1618
+ * against this tab's own remote session as usual. */
1619
+ demoteToFollower(forwarder: SyncForwarder): void;
1620
+ /**
1621
+ * A pending mutation was discarded because it can never be sent.
1622
+ *
1623
+ * This is a lost write, so it must not stay invisible. Every failure in this
1624
+ * chain used to be a `logger.error` an app running `logLevel: 'fatal'` never
1625
+ * shows, which is how an outbox could sit undrained for hours with the UI
1626
+ * reporting nothing. Surfaces as a rollback event (the mutation will never
1627
+ * apply, which is what a subscriber needs to know) and degrades sync health.
1628
+ */
1629
+ private onMutationDropped;
1630
+ /** A forwarded outbox row from a follower: load + drain it. Idempotent. */
1631
+ enqueueForwardedMutation(mutationId: string): Promise<void>;
1632
+ /**
1633
+ * Tuples another tab already committed to the shared store: feed them to
1634
+ * THIS tab's circuit (no local write). A DELETE additionally forces a
1635
+ * re-materialize of the table's queries, exactly as the writing tab does
1636
+ * for itself, because the SSP may not emit a view update for it.
1637
+ */
1638
+ private applyRelayedIngest;
1639
+ /** A relayed `_00_list_ref` LIVE event: resolve against THIS tab's queries
1640
+ * and run the exact same handling the LIVE subscription would have. */
1641
+ private applyRelayedListRefChange;
1642
+ /** One immediate poll cycle (failover convergence). */
1643
+ forcePollRound(): Promise<void>;
1644
+ /**
1645
+ * Quiesce all sync activity ahead of a local-bucket switch. After this
1646
+ * resolves, nothing in the sync module writes to the local store: the poll
1647
+ * loop is stopped AND its in-flight tick awaited, LIVE is killed, debounce
1648
+ * timers are cancelled (their outbox rows are already persisted), and the
1649
+ * scheduler has drained its in-flight queue item — including that item's
1650
+ * outbox-row delete, which must land in the OLD bucket. Queued down-events
1651
+ * are dropped (they reference old-bucket query rows; the post-switch rebind
1652
+ * re-enqueues registrations). The old user's un-pushed outbox is deliberately
1653
+ * NOT drained: the remote session already belongs to the next user.
1654
+ */
1655
+ prepareBucketSwitch(): Promise<void>;
1656
+ /**
1657
+ * Resume syncing against the freshly-opened bucket: reload the mutation
1658
+ * outbox from ITS `_00_pending_mutations` (the new user's own un-pushed
1659
+ * offline work) and restart the scheduler. LIVE + the list_ref poll restart
1660
+ * via the `setCurrentUserId` call that follows in the auth listener.
1661
+ */
1662
+ completeBucketSwitch(): Promise<void>;
1663
+ /**
1664
+ * Push the authenticated user's record id from the parent client's
1665
+ * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
1666
+ * any) and re-registers it under the new user's dedicated table so
1667
+ * SurrealDB binds the permission rule under the post-flip auth
1668
+ * context. Pass `null` on sign-out.
1669
+ *
1670
+ * The dedicated `_00_list_ref_user_<id>` table is created lazily by
1671
+ * the SSP when the first query registration arrives, which may be
1672
+ * concurrent with this call. We retry the LIVE registration with a
1673
+ * short backoff so a "table not found" race resolves without
1674
+ * surfacing as a permanent auth-loading hang.
1675
+ */
1676
+ setCurrentUserId(userId: string | null): Promise<void>;
1677
+ private startListRefPoll;
1678
+ private stopListRefPoll;
1679
+ /**
1680
+ * One poll cycle: refetch `_00_list_ref` for the active queries that are due,
1681
+ * one round trip per chunk (see `planListRefPollChunks`). Returns whether ANY
1682
+ * query's remoteArray actually changed — the scheduler uses this to drive the
1683
+ * adaptive idle backoff.
1684
+ *
1685
+ * Also the ONLY health signal that runs while the page is idle. Sync health is
1686
+ * otherwise activity-driven (mutations/registrations via the scheduler,
1687
+ * reconnect re-registration, self-heal), so on a quiet page a stale `degraded`
1688
+ * would linger until the next mutation and a genuine idle drop would be
1689
+ * invisible. We fold the cycle's aggregate reachability into `recordSyncOutcome`
1690
+ * so idle health self-recovers (and self-degrades) with no user action. A clean
1691
+ * cycle is idempotent when already healthy (`recordSyncOutcome` early-returns at
1692
+ * `consecutiveSyncFailures === 0`), so a healthy idle page pays nothing.
1693
+ */
1694
+ private pollListRefForActiveQueries;
1695
+ /**
1696
+ * The server's current `_00_list_ref` state for a chunk of queries in ONE
1697
+ * round trip: primary edges, subquery-child edges and `_00_query.rowCount`.
1698
+ * Every hash whose query still exists gets an entry (empty arrays and
1699
+ * `rowCount: null` when nothing was readable), so a caller can tell "no
1700
+ * edges" from "not asked". A hash is left out only when the select did not
1701
+ * come back as an array at all — the old per-query code skipped the apply in
1702
+ * that case too, since a non-array is not a membership set.
1703
+ *
1704
+ * Guarded against a batch that silently matches nothing: if the select
1705
+ * returned no edge at all while the client holds edges for a query the
1706
+ * server still reports rows for, the batch is not trusted and the chunk is
1707
+ * re-read one query at a time with the single-query select. An empty set
1708
+ * taken at face value would be recorded as the removal of every row.
1709
+ */
1710
+ private fetchListRefSnapshots;
1711
+ /**
1712
+ * Single-query form of {@link fetchListRefSnapshots}: the selects the
1713
+ * registration path has always used, in one statement batch. `null` when
1714
+ * the primary select did not come back as an array.
1715
+ */
1716
+ private fetchListRefSnapshot;
1717
+ /**
1718
+ * Land one poll snapshot for `queryHash`: diff the server's edges against the
1719
+ * cached `remoteArray`, sync any added/updated rows through the SyncEngine,
1720
+ * persist the new remoteArray and converge the subquery children. This is
1721
+ * the same shape `createRemoteQuery` does for its initial fetch and what
1722
+ * `handleRemoteListRefChange` does per-LIVE-event — we reuse it on a timer
1723
+ * as a fallback for missed LIVE notifications. Returns whether membership
1724
+ * changed.
1725
+ */
1726
+ private applyListRefSnapshot;
1727
+ /**
1728
+ * Re-read ONE query's server state now (edges + `_00_query` row) and land
1729
+ * it through {@link applyListRefSnapshot}. The targeted form of the poll,
1730
+ * for the moments that cannot wait for the next tick: a registration that
1731
+ * answered `materializing`, and a LIVE removal that has to be checked
1732
+ * against the row before it may empty a painted list.
1733
+ */
1734
+ private refetchListRefForQuery;
1735
+ /** Per-query pending targeted re-reads: one timer and the ladder still to walk. */
1736
+ private listRefRefetches;
1737
+ /**
1738
+ * Schedule a targeted re-read of `queryHash` after `delays[0]` ms. If the
1739
+ * read still says the server is publishing (`materializing`), the next rung
1740
+ * of the ladder is armed; any other outcome ends it. Re-scheduling a hash
1741
+ * that already has a timer replaces it (latest wins), so bursts coalesce.
1742
+ */
1743
+ private scheduleListRefRefetch;
1744
+ private clearListRefRefetch;
1745
+ private clearListRefRefetches;
1746
+ /**
1747
+ * Resolve the current `_00_list_ref` table name for the active auth
1748
+ * context. Public so the `createRemoteQuery` initial-fetch path can
1749
+ * read from the right per-user table.
1750
+ *
1751
+ * Reads the user id from `DataModule` rather than the local mirror,
1752
+ * because `DataModule.setCurrentUserId` runs synchronously from the
1753
+ * auth callback (before any `await`), whereas `sync.setCurrentUserId`
1754
+ * is async — the userQuery's initial fetch can fire between those
1755
+ * two points and we need the correct table name immediately.
1756
+ */
1757
+ listRefTable(): string;
1758
+ private killRefLiveQuery;
1759
+ private restartRefLiveQuery;
1760
+ /**
1761
+ * Drop local LIVE bookkeeping without issuing a `KILL`.
1762
+ *
1763
+ * Called when the socket dies. The server-side subscription is scoped to that
1764
+ * WebSocket session and died with it, so there is nothing left to kill — and
1765
+ * by the time the reconnect handler runs, the client reports `connected`
1766
+ * again, which would otherwise send a `KILL` for a stale uuid on the *new*
1767
+ * session and hold up the restart queued behind it.
1768
+ */
1769
+ private invalidateRefLiveQuery;
1770
+ private subscribeToReconnect;
1771
+ /**
1772
+ * Whether the REMOTE SESSION currently carries `$auth.id`.
1773
+ *
1774
+ * Not the same question as `currentUserId`, and that gap is the whole point:
1775
+ * `currentUserId` is this client's own record of who signed in and survives a
1776
+ * socket drop untouched, while `$auth` lives on the WebSocket session and has
1777
+ * to be re-applied after every reconnect. Registering in the window between
1778
+ * the two is silently destructive, because `fn::query::register` sends
1779
+ * `<string>($auth.id OR '')` and the SSP stores that value write-once: the
1780
+ * view's edges then route to the global `_00_list_ref` stamped `auth_id = ''`,
1781
+ * which that table's own permission rule (`auth_id = $auth.id`) makes
1782
+ * unreadable to the very user who registered it.
1783
+ *
1784
+ * Signed-out clients answer `true`: `''` is the honest identity there, not a
1785
+ * race.
1786
+ */
1787
+ private remoteAuthEstablished;
1788
+ /**
1789
+ * Wait for the reconnected session to carry an identity again, then
1790
+ * re-register every active query and re-bind LIVE.
1791
+ *
1792
+ * Giving up without registering is deliberately better than registering
1793
+ * anyway: a registration made with no `$auth.id` produces a view its own
1794
+ * owner cannot read, and it is write-once, so it stays that way. Skipping
1795
+ * leaves the query unregistered and visibly loading, which the next
1796
+ * reconnect or heartbeat retries.
1797
+ */
1798
+ private refetchAfterReconnect;
1799
+ private startRefLiveQueries;
1800
+ private handleRemoteListRefChange;
1801
+ /** LIVE removals awaiting verification, per query, with their coalescing timer. */
1802
+ private pendingLiveRemovals;
1803
+ /**
1804
+ * Hold a LIVE `_00_list_ref` DELETE for {@link LIVE_REMOVAL_COALESCE_MS},
1805
+ * then verify the batch (see {@link flushLiveRemovals}). A sweep or a
1806
+ * republish delivers a view's whole set as one burst, so one verification
1807
+ * round covers it.
1808
+ */
1809
+ private queueLiveRemoval;
1810
+ /**
1811
+ * Verify a coalesced batch of LIVE removals against the upstream records.
1812
+ * Ids that no longer exist upstream are dropped from membership (the body
1813
+ * delete already happened inside `syncRecords`) and the query re-renders.
1814
+ * Anything still present upstream - or a verification that could not run -
1815
+ * is settled by a targeted re-read of the server's set for this query,
1816
+ * where the `_00_query` row decides: gone = view lost (keep rows,
1817
+ * re-register), `materializing` = wait, `ready` = adopt the smaller set.
1818
+ */
1819
+ private flushLiveRemovals;
1820
+ private clearLiveRemovals;
1821
+ /**
1822
+ * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
1823
+ * `parent` set) for a `.related()` query. Unlike primary rows, child rows
1824
+ * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
1825
+ * keep the child BODY fresh in the local cache so the in-browser SSP's
1826
+ * subquery-table dependency re-materializes the parent view.
1827
+ *
1828
+ * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
1829
+ * no-op: a child leaving this query's set must not delete a body another
1830
+ * query may still show (see `syncSubqueryChildren` deletion-safety note);
1831
+ * a genuine record delete propagates via the normal delete path.
1832
+ */
1833
+ private handleRemoteSubqueryChange;
1834
+ /**
1835
+ * Enqueues a 'down' event (from remote to local) for processing.
1836
+ * @param event The DownEvent to enqueue.
1837
+ */
1838
+ enqueueDownEvent(event: DownEvent): void;
1839
+ /**
1840
+ * Bound a mutation push so it always settles.
1841
+ *
1842
+ * `SyncScheduler.syncUp` early-returns while `isSyncingUp` is true, and that
1843
+ * flag only clears in the `finally` of the drain loop. A push whose RPC never
1844
+ * settles (socket dropped mid-flight, response lost) therefore wedges the
1845
+ * up-queue for the rest of the session: no retry, no error, no further
1846
+ * mutation ever sent. A timeout turns that into an ordinary network failure,
1847
+ * which `UpQueue.next` re-queues for the next trigger. The message deliberately
1848
+ * contains "timed out" so `classifySyncError` treats it as `network` and
1849
+ * retries rather than rolling the mutation back.
1850
+ */
1851
+ private withPushTimeout;
1852
+ private processUpEvent;
1853
+ /**
1854
+ * A mutation the server accepted, reported once its outbox row is gone.
1855
+ *
1856
+ * Keeps the written row in the render set until its membership arrives.
1857
+ * Without this the row is briefly in neither term of
1858
+ * `(membership ∪ pendingWrites) − pendingDeletes` — the outbox delete is
1859
+ * tied to the push, while membership waits on the SSP ingesting the row,
1860
+ * materializing the view, writing the `_00_list_ref` edge and this client
1861
+ * reading it back. The writer therefore watched its own comment appear,
1862
+ * vanish, and return, while every other client showed it throughout.
1863
+ */
1864
+ private handleMutationSettled;
1865
+ private handleRollback;
1866
+ private processDownEvent;
1867
+ private withDownTimeout;
1868
+ private runDownEvent;
1869
+ /**
1870
+ * Synchronizes a specific query by hash.
1871
+ * Compares local and remote version arrays and fetches differences.
1872
+ * @param hash The hash of the query to sync.
1873
+ */
1874
+ syncQuery(hash: string): Promise<void>;
1875
+ /**
1876
+ * Run a sync for a single query while reflecting its fetch status. Marks the
1877
+ * query `fetching` for the duration when the diff actually pulls records
1878
+ * (added/updated), then resets to `idle` in a `finally` so a failed sync
1879
+ * never leaves a query stuck `fetching`. Part A's notification coalescing
1880
+ * means the single resulting UI update lands after this completes.
1881
+ */
1882
+ private runSyncForQuery;
1883
+ /**
1884
+ * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1885
+ * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1886
+ * server's `_00_list_ref` still lists them until it's processed, and the diff
1887
+ * would otherwise resurrect a just-deleted record.
1888
+ */
1889
+ private getPendingDeleteIds;
1890
+ /**
1891
+ * Enqueues a list of mutations (up events) to be sent to the remote.
1892
+ * @param mutations Array of UpEvents (create/update/delete) to enqueue.
1893
+ */
1894
+ enqueueMutation(mutations: UpEvent[]): Promise<void>;
1895
+ /**
1896
+ * Best-effort release of THIS tab's views as the page goes away.
1897
+ *
1898
+ * Without it a closed tab's views stay materialized on the SSP for a full
1899
+ * TTL (10 minutes by default), because nothing else tears them down:
1900
+ * `releaseQueriesEagerly` is off, so the TTL sweep is the only reclaim path.
1901
+ * On a busy tenant that is a generation of live views per reload, each still
1902
+ * being stepped by every ingest, for ten minutes after the last human left.
1903
+ *
1904
+ * This is NOT `releaseQueriesEagerly` re-enabled. That released views
1905
+ * mid-session on a viewport change and tore the window out from under a live
1906
+ * page (see `cleanupQuery`); this runs only when the page itself is going
1907
+ * away and nothing is left to render.
1908
+ *
1909
+ * Safe against other tabs by construction: `fn::query::unsubscribe` drops
1910
+ * only this session from `subscribers` and deletes the row solely when it
1911
+ * was the last one, so a second tab of the same user keeps its view.
1912
+ *
1913
+ * One statement, not one per id: an unload handler gets a few milliseconds,
1914
+ * and N round trips would not survive it. Fire-and-forget — if the frame
1915
+ * does not make it out, the TTL sweep still reclaims exactly as before, so
1916
+ * the worst case is today's behaviour.
1917
+ */
1918
+ releaseViewsOnUnload(): void;
1919
+ private registerQuery;
1920
+ private createRemoteQuery;
1921
+ /**
1922
+ * Sync the BODIES of a `.related()` query's subquery child rows into the
1923
+ * local cache, separately from the primary window array. The SSP writes
1924
+ * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
1925
+ * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
1926
+ * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
1927
+ * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
1928
+ * them into the local DB AND the in-browser SSP, whose subquery-table
1929
+ * dependency then re-materializes the parent view (no explicit notify).
1930
+ *
1931
+ * Deletion safety: we pass `removed: []` deliberately. A child body can be
1932
+ * shared by other queries; letting `handleRemovedRecords` delete one that
1933
+ * merely left THIS query's child set would clobber data another query still
1934
+ * shows. Genuine record deletes flow through the normal delete path; a
1935
+ * lingering orphan body is invisible (the correlated WHERE stops matching).
1936
+ *
1937
+ * Kept off `runSyncForQuery` on purpose so child fetches never flip the
1938
+ * query to `fetching` or skew its DevTools timings.
1939
+ */
1940
+ private syncSubqueryChildren;
1941
+ /**
1942
+ * Converge a `.related()` query's child bodies onto `fresh` (the server's
1943
+ * current child edges). Shared by the registration path above and the poll,
1944
+ * which reads the child edges in its batched round trip. See
1945
+ * {@link syncSubqueryChildren} for the deletion-safety rules.
1946
+ */
1947
+ private applySubqueryChildren;
1948
+ heartbeatQuery(queryHash: string): Promise<void>;
1949
+ private cleanupQuery;
1950
+ }
1951
+ //#endregion
1952
+ //#region src/modules/auth/events/index.d.ts
1953
+ declare const AuthEventTypes: {
1954
+ readonly AuthStateChanged: "AUTH_STATE_CHANGED";
1955
+ };
1956
+ type AuthEventTypeMap = {
1957
+ [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
1958
+ };
1959
+ type AuthEventSystem = EventSystem<AuthEventTypeMap>;
1960
+ declare function createAuthEventSystem(): AuthEventSystem;
1961
+ //#endregion
1962
+ //#region src/modules/auth/index.d.ts
1963
+ type Prettify<T> = { [K in keyof T]: T[K] } & {};
1964
+ type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
1965
+ type ExtractAccessParams<S extends SchemaStructure, Name extends keyof S['access'], Method extends 'signIn' | 'signup'> = S['access'] extends undefined ? never : S['access'][Name] extends AccessDefinition ? Prettify<{ [K in keyof S['access'][Name][Method]['params']]: MapColumnType<S['access'][Name][Method]['params'][K]> }> : never;
1966
+ declare class AuthService<S extends SchemaStructure> {
1967
+ private schema;
1968
+ private remote;
1969
+ private persistenceClient;
1970
+ private logger;
1971
+ token: string | null;
1972
+ currentUser: any | null;
1973
+ isAuthenticated: boolean;
1974
+ /**
1975
+ * The record-access method name for the current session (e.g. `"account"`),
1976
+ * derived from the token's `AC` claim. Consumed by the in-browser SSP's
1977
+ * permission injection so `$access`-gated table predicates resolve locally,
1978
+ * mirroring the server's `$access`. Null when logged out.
1979
+ */
1980
+ access: string | null;
1981
+ isLoading: boolean;
1982
+ private events;
1983
+ get eventSystem(): AuthEventSystem;
1984
+ constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
1985
+ init(): Promise<void>;
1986
+ getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
1987
+ /**
1988
+ * Subscribe to auth state changes.
1989
+ * callback is called immediately with current value and whenever validation status changes.
1990
+ */
1991
+ subscribe(cb: (userId: string | null) => void): () => void;
1992
+ private notifyListeners;
1993
+ /**
1994
+ * Restore a session from the locally cached JWT, with NO network.
1995
+ *
1996
+ * This is what makes a warm boot paint instantly and what makes an offline
1997
+ * boot possible at all: the token is in local storage, and it already carries
1998
+ * both the access method and the `$auth.id` record id. Everything the client
1999
+ * needs to route queries (`setCurrentUserId`) and to satisfy `$auth`-gated
2000
+ * permission predicates in the in-browser SSP (`setSessionAuth`) is therefore
2001
+ * available before a socket exists.
2002
+ *
2003
+ * The session is OPTIMISTIC: the token is unverified here. `check()` runs
2004
+ * afterwards in the background and downgrades to a real sign-out if the
2005
+ * server rejects it. Nothing is trusted that the server has not also seen -
2006
+ * the local store only ever holds rows the server previously sent.
2007
+ *
2008
+ * Returns the restored user id, or null when there is no usable token.
2009
+ */
2010
+ restoreSessionFromToken(): Promise<string | null>;
2011
+ /**
2012
+ * Check for existing session and validate
2013
+ */
2014
+ check(accessToken?: string): Promise<void>;
2015
+ /**
2016
+ * Sign out and clear session
2017
+ */
2018
+ signOut(): Promise<void>;
2019
+ private setSession;
2020
+ /** Fallback when the token carries no `AC` claim: if the schema defines
2021
+ * exactly one record-access method, assume the session used it. */
2022
+ private defaultAccessName;
2023
+ signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
2024
+ signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
2025
+ }
2026
+ //#endregion
2027
+ //#region src/modules/crdt/crdt-field.d.ts
2028
+ declare const CURSOR_COLORS: string[];
2029
+ declare function cursorColorFromName(name: string): string;
2030
+ declare class CrdtField {
2031
+ private fieldName;
2032
+ private doc;
2033
+ private pushTimer;
2034
+ private local;
2035
+ private remote;
2036
+ private recordId;
2037
+ private sessionId;
2038
+ private unsubscribe;
2039
+ private lastPushTime;
2040
+ private lastCursorPushTime;
2041
+ private loadedFromCrdt;
2042
+ private pushRetryCount;
2043
+ private logger;
2044
+ private cursorsEnabled;
2045
+ /** Remote-push debounce. Local writes happen immediately on every Loro
2046
+ * update; the remote UPSERT is coalesced over this window. Configured
2047
+ * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
2048
+ private remoteDebounceMs;
2049
+ private _onCursorUpdate;
2050
+ private pendingCursorUpdate;
2051
+ /** Callback set by the editor to receive remote cursor updates.
2052
+ * Any cursor data that arrived before this callback was set will be replayed. */
2053
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
2054
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
2055
+ /**
2056
+ * @param LoroDocClass the `LoroDoc` constructor, injected by the caller after
2057
+ * awaiting {@link loadLoro} — keeps `loro-crdt` out of this module's static
2058
+ * import graph so it only ships to apps that use CRDT fields.
2059
+ */
2060
+ constructor(fieldName: string, cursorsEnabled: boolean, LoroDocClass: typeof LoroDoc, initialState?: Uint8Array, logger?: Logger$1 | null);
2061
+ getDoc(): LoroDoc;
2062
+ /** Whether the LoroDoc was loaded from saved CRDT state */
2063
+ hasContent(): boolean;
2064
+ startSync(local: LocalStore, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
2065
+ /**
2066
+ * Stop syncing this field. Flushes one final remote push by default so the
2067
+ * last keystrokes aren't lost. Pass `{ flush: false }` on a bucket switch —
2068
+ * the remote session already belongs to the NEXT user, and pushing this
2069
+ * (previous user's) snapshot under it would clobber the record remotely.
2070
+ */
2071
+ stopSync(options?: {
2072
+ flush?: boolean;
2073
+ }): void;
2074
+ importRemote(state: Uint8Array): void;
2075
+ exportSnapshot(): Uint8Array;
2076
+ /** Push this session's cursor blob into the parent row at
2077
+ * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
2078
+ * field — the editor still calls this method optimistically, but
2079
+ * without `@cursor` on the schema there's nowhere to store the blob.
2080
+ * The UPDATE itself fires the parent table's LIVE feed, so other
2081
+ * browsers receive the cursor change without a separate `_00_rv` bump. */
2082
+ pushCursorState(encoded: Uint8Array): Promise<void>;
2083
+ /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
2084
+ importRemoteCursor(base64State: string): void;
2085
+ private scheduleRemotePush;
2086
+ /** SET path inside a parent row for the current snapshot. `@crdt`-only
2087
+ * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
2088
+ * fields hold a `{ state, cursors }` object so the snapshot lives at
2089
+ * `<field>.state` next to per-session cursor blobs. */
2090
+ private statePath;
2091
+ /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
2092
+ * every local update and every remote import so reloads (online or
2093
+ * offline) see the freshest content immediately. Failures are
2094
+ * swallowed — a stale local write must never block user input. */
2095
+ private persistLocal;
2096
+ private pushToRemote;
2097
+ }
2098
+ //#endregion
2099
+ //#region src/modules/crdt/index.d.ts
2100
+ /**
2101
+ * CrdtManager manages active CrdtField instances and their sync channels.
2102
+ *
2103
+ * Collaborative state lives in two dedicated tables (defined in
2104
+ * `apps/cli/src/meta_tables_remote.surql`):
2105
+ * - `_00_crdt` { record_id, field, state } — one row per (record, field)
2106
+ * - `_00_cursor` { record_id, session_id, field, state } — one row per
2107
+ * (record, session, field)
2108
+ *
2109
+ * Splitting them off the parent row is what makes offline edits mergeable:
2110
+ * each (record, field) gets its own row, so concurrent offline writes don't
2111
+ * collide on the parent's last-write-wins semantics.
2112
+ *
2113
+ * Cross-browser delivery still rides the parent table's existing LIVE feed
2114
+ * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
2115
+ * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
2116
+ * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
2117
+ * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
2118
+ * via subquery. Permission inheritance happens server-side via
2119
+ * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
2120
+ */
2121
+ declare class CrdtManager {
2122
+ private schema;
2123
+ private local;
2124
+ private remote;
2125
+ private debounceMs;
2126
+ private fields;
2127
+ private liveByTable;
2128
+ private pendingLive;
2129
+ private staleTables;
2130
+ private connectionGeneration;
2131
+ private connectionUnsubscribes;
2132
+ private logger;
2133
+ private sessionId;
2134
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
2135
+ /**
2136
+ * Re-establish table LIVEs after a socket drop.
2137
+ *
2138
+ * A LIVE subscription lives and dies with its WebSocket session, and
2139
+ * `ensureTableSubscription` is memoized on `liveByTable` — so without this,
2140
+ * the first reconnect leaves CRDT realtime permanently dead: the map still
2141
+ * holds a uuid for a subscription the server has forgotten, so every later
2142
+ * `open()` short-circuits and no LIVE is ever re-issued.
2143
+ *
2144
+ * Both drop events matter: the SDK publishes `reconnecting` (not
2145
+ * `disconnected`) when it intends to recover on its own, and `disconnected`
2146
+ * only once it has given up.
2147
+ */
2148
+ private subscribeToReconnect;
2149
+ /** Stop observing transport events. Separate from {@link closeAll}, which also
2150
+ * runs on a bucket switch where the manager keeps being used. */
2151
+ dispose(): void;
2152
+ private hasOpenFieldFor;
2153
+ /** Set the session id that scopes this client's cursor entries. Must be
2154
+ * called before `open()` for cursors to be pushed under a stable key.
2155
+ * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
2156
+ * for the data-module salt). */
2157
+ setSessionId(sessionId: string): void;
2158
+ /**
2159
+ * Open a CRDT field for collaborative editing.
2160
+ *
2161
+ * @param table - Table name
2162
+ * @param recordId - Full record ID (e.g., "thread:abc")
2163
+ * @param field - Field name (e.g., "title", "content")
2164
+ * @param fallbackText - Current plain text from the record, used to seed the
2165
+ * LoroDoc if no CRDT state exists yet (migration path)
2166
+ */
2167
+ open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2168
+ close(table: string, recordId: string, field: string): void;
2169
+ /**
2170
+ * Close every open field + table LIVE. Fields flush a final remote push by
2171
+ * default; pass `{ flush: false }` on a bucket switch, where that flush
2172
+ * would push the previous user's snapshot under the next user's session.
2173
+ */
2174
+ closeAll(options?: {
2175
+ flush?: boolean;
2176
+ }): void;
2177
+ /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
2178
+ * every open CrdtField on `table`. */
2179
+ private ensureTableSubscription;
2180
+ /** Apply a parent-row payload from a non-LIVE source (e.g. the
2181
+ * list_ref-driven sync engine, when the cross-user LIVE on the
2182
+ * parent table is filtered out by the SurrealDB cross-session
2183
+ * permission gap). Same semantics as the internal `dispatchRow`. */
2184
+ applyRow(table: string, row: Record<string, unknown>): void;
2185
+ /** Dispatch a parent-row LIVE event to every open CrdtField on that
2186
+ * record. Each open field reads its slice of the row directly — the
2187
+ * CRDT snapshot is a column on the parent now, so there is no
2188
+ * follow-up subquery. */
2189
+ private dispatchRow;
2190
+ /** One-shot remote fetch for a row whose CRDT field hasn't synced
2191
+ * locally yet (fresh device, memory-backed local DB after reload, …).
2192
+ * Used by `open()` when the local read came up empty. Subsequent
2193
+ * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
2194
+ private fetchAndDispatchRow;
2195
+ /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
2196
+ * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
2197
+ private fieldHasCursor;
2198
+ /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
2199
+ * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
2200
+ * `{ state, cursors }` where `state` carries the snapshot bytes. */
2201
+ private extractSnapshot;
2202
+ private killTableSubscription;
2203
+ private makeKey;
2204
+ /**
2205
+ * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
2206
+ * typos, removed annotations, and stale schema codegen at the call site instead
2207
+ * of silently producing a non-CRDT writer.
2208
+ */
2209
+ private assertCrdtField;
2210
+ }
2211
+ //#endregion
2212
+ //#region src/modules/feature-flag/index.d.ts
2213
+ interface FeatureFlagSnapshot {
2214
+ variant: string | undefined;
2215
+ payload: unknown | undefined;
2216
+ }
2217
+ interface FeatureFlagOptions {
2218
+ fallback?: string;
2219
+ ttl?: QueryTimeToLive;
2220
+ }
2221
+ /**
2222
+ * A locally forced variant. Applies to THIS browser only and is never sent to
2223
+ * the server — the assignment in `_00_user_feature` is untouched, so clearing
2224
+ * the override restores whatever the server says.
2225
+ */
2226
+ interface FeatureFlagOverride {
2227
+ variant: string;
2228
+ payload?: unknown;
2229
+ }
2230
+ declare class FeatureFlagHandle {
2231
+ readonly key: string;
2232
+ readonly fallback: string | undefined;
2233
+ private latest;
2234
+ private listeners;
2235
+ private unsubscribeFn;
2236
+ private onCloseFn;
2237
+ private closed;
2238
+ constructor(key: string, fallback: string | undefined);
2239
+ attach(unsubscribe: () => void): void;
2240
+ detach(): void;
2241
+ set(snapshot: FeatureFlagSnapshot): void;
2242
+ variant(): string | undefined;
2243
+ payload<T = unknown>(): T | undefined;
2244
+ enabled(): boolean;
2245
+ subscribe(cb: (s: FeatureFlagSnapshot) => void): () => void;
2246
+ onClose(cb: () => void): void;
2247
+ close(): void;
2248
+ }
2249
+ interface FeatureFlagModuleDeps<S extends SchemaStructure> {
2250
+ dataModule: DataModule<S>;
2251
+ sync: Sp00kySync<S>;
2252
+ auth: AuthService<S>;
2253
+ logger: Logger$1;
2254
+ }
2255
+ declare class FeatureFlagModule<S extends SchemaStructure> {
2256
+ private deps;
2257
+ private logger;
2258
+ private handles;
2259
+ private authUnsubscribe;
2260
+ private lastUserId;
2261
+ private querySubscription;
2262
+ private starting;
2263
+ private ttl;
2264
+ private snapshots;
2265
+ private loaded;
2266
+ private overrides;
2267
+ constructor(deps: FeatureFlagModuleDeps<S>);
2268
+ init(): void;
2269
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2270
+ closeAll(): Promise<void>;
2271
+ /** Auth changed: drop the old user's query/snapshots and re-observe. */
2272
+ private refresh;
2273
+ private teardownQuery;
2274
+ /** Start the single shared live query (idempotent; no-op with no handles). */
2275
+ private ensureStarted;
2276
+ /** Live query result → per-key snapshots → push to every active handle. */
2277
+ private applyRecords;
2278
+ /**
2279
+ * Force `key` to `variant` in THIS browser. Pass `null` to clear.
2280
+ *
2281
+ * Nothing is written to the server: the `_00_user_feature` assignment is
2282
+ * untouched, so clearing restores whatever the server says. Persisted to
2283
+ * localStorage on the page origin, so it survives a reload.
2284
+ */
2285
+ setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
2286
+ clearLocalOverrides(): void;
2287
+ getLocalOverrides(): Record<string, FeatureFlagOverride>;
2288
+ /** The assignment for `key`, with any local override taking precedence. */
2289
+ private resolve;
2290
+ private pushAll;
2291
+ private loadOverrides;
2292
+ private persistOverrides;
2293
+ }
2294
+ //#endregion
2295
+ //#region src/modules/app-release/index.d.ts
2296
+ interface AppReleaseSnapshot {
2297
+ /** Latest announced version for the app, or undefined when no row exists. */
2298
+ version: string | undefined;
2299
+ /** Clients should clear SW/caches when reloading onto this version. */
2300
+ cacheBust: boolean;
2301
+ /** Clients should reload/update immediately instead of asking. */
2302
+ mandatory: boolean;
2303
+ releasedAt: string | undefined;
2304
+ }
2305
+ interface AppReleaseOptions {
2306
+ ttl?: QueryTimeToLive;
2307
+ }
2308
+ declare class AppReleaseHandle {
2309
+ readonly app: string;
2310
+ private latest;
2311
+ private listeners;
2312
+ private onCloseFn;
2313
+ private closed;
2314
+ constructor(app: string);
2315
+ set(snapshot: AppReleaseSnapshot): void;
2316
+ snapshot(): AppReleaseSnapshot;
2317
+ version(): string | undefined;
2318
+ /** True when the announced version is semver-newer than `currentVersion`. */
2319
+ updateAvailable(currentVersion: string): boolean;
2320
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
2321
+ onClose(cb: () => void): void;
2322
+ close(): void;
2323
+ }
2324
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
2325
+ dataModule: DataModule<S>;
2326
+ sync: Sp00kySync<S>;
2327
+ auth: AuthService<S>;
2328
+ logger: Logger$1;
2329
+ }
2330
+ declare class AppReleaseModule<S extends SchemaStructure> {
2331
+ private deps;
2332
+ private logger;
2333
+ private handles;
2334
+ private authUnsubscribe;
2335
+ private lastUserId;
2336
+ private querySubscription;
2337
+ private starting;
2338
+ private ttl;
2339
+ private snapshots;
2340
+ private loaded;
2341
+ constructor(deps: AppReleaseModuleDeps<S>);
2342
+ init(): void;
2343
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2344
+ closeAll(): Promise<void>;
2345
+ private refresh;
2346
+ private teardownQuery;
2347
+ private ensureStarted;
2348
+ private applyRecords;
2349
+ }
2350
+ //#endregion
2351
+ //#region src/services/blobs/blob-store.d.ts
2352
+ /**
2353
+ * Byte storage for cached bucket files.
2354
+ *
2355
+ * The default implementation is OPFS. Bucket files never arrive over HTTP in
2356
+ * this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
2357
+ * neither the browser's HTTP cache nor the Cache API can hold them. We persist
2358
+ * the bytes ourselves, and OPFS is the cheapest place to put them: a read is
2359
+ * `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
2360
+ * without ever moving the bytes through the JS heap.
2361
+ *
2362
+ * Layout is real nested directories rather than one hashed filename:
2363
+ *
2364
+ * sp00ky-blobs/<namespace>/<bucket>/<...path segments>
2365
+ *
2366
+ * That costs a `getDirectoryHandle` per segment on write, and buys the property
2367
+ * the whole orphan story rests on: the full `(bucket, path)` key is recoverable
2368
+ * from a directory walk alone. The `_00_blob` manifest can therefore be wiped
2369
+ * (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
2370
+ * rebuilt from disk instead of taking the cached bytes down with it.
2371
+ */
2372
+ /** Identifies one cached file: the bucket it lives in and its path within. */
2373
+ interface BlobKey {
2374
+ bucket: string;
2375
+ path: string;
2376
+ }
2377
+ /** What a directory walk can tell us about a stored file, with no manifest. */
2378
+ interface BlobStat {
2379
+ key: BlobKey;
2380
+ size: number;
2381
+ /** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
2382
+ mtime: number;
2383
+ }
2384
+ interface BlobStore {
2385
+ /** False for {@link MemoryBlobStore} and for OPFS-less environments: the
2386
+ * cache still dedupes and serves within a tab, but nothing survives reload. */
2387
+ readonly persistent: boolean;
2388
+ /** Namespace (the local bucketId) all keys are resolved under. */
2389
+ readonly namespace: string;
2390
+ read(key: BlobKey): Promise<Blob | null>;
2391
+ /** Returns the number of bytes written. Throws on quota exhaustion. */
2392
+ write(key: BlobKey, bytes: Blob): Promise<number>;
2393
+ remove(key: BlobKey): Promise<void>;
2394
+ /** Every committed file under the current namespace. Sweeps torn writes. */
2395
+ list(): Promise<BlobStat[]>;
2396
+ /** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
2397
+ clear(): Promise<void>;
2398
+ /** Point at another namespace. Does not touch the bytes of the old one. */
2399
+ setNamespace(namespace: string): void;
2400
+ }
2401
+ //#endregion
2402
+ //#region src/services/blobs/blob-manifest.d.ts
2403
+ interface BlobEntry {
2404
+ /** `${bucket}/${path}` — also the `_00_blob` row id. */
2405
+ id: string;
2406
+ bucket: string;
2407
+ path: string;
2408
+ size: number;
2409
+ contentType: string;
2410
+ createdAt: number;
2411
+ lastAccess: number;
2412
+ hits: number;
2413
+ /** Exempt from pressure eviction. Never expires on its own. */
2414
+ pinned: boolean;
2415
+ }
2416
+ declare class BlobManifest {
2417
+ private local;
2418
+ private entries;
2419
+ /** Ids whose in-memory state has not been written back yet. */
2420
+ private dirty;
2421
+ private removed;
2422
+ private flushing;
2423
+ constructor(local: LocalStore);
2424
+ /**
2425
+ * Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
2426
+ * this never needs a full-table scan (and therefore never needs a QueryPlan).
2427
+ * Any read failure yields an empty manifest: reconcile then rebuilds every
2428
+ * row from disk, which is exactly the desired degradation.
2429
+ */
2430
+ load(ids: string[]): Promise<void>;
2431
+ get(key: BlobKey): BlobEntry | undefined;
2432
+ getById(id: string): BlobEntry | undefined;
2433
+ all(): BlobEntry[];
2434
+ totalBytes(): number;
2435
+ pinnedBytes(): number;
2436
+ put(entry: BlobEntry): void;
2437
+ touch(id: string, now: number): void;
2438
+ setPinned(id: string, pinned: boolean): boolean;
2439
+ remove(id: string): void;
2440
+ /** Forget everything without scheduling deletes — for a bucket switch, where
2441
+ * the rows belong to the store we are leaving and must stay put. */
2442
+ reset(): void;
2443
+ hasPendingWrites(): boolean;
2444
+ /**
2445
+ * Write back pending changes. Serialized: a second concurrent flush awaits
2446
+ * the first rather than racing it into the same rows. Failures are swallowed
2447
+ * on purpose — a lost metadata write costs an LRU timestamp, and the entry is
2448
+ * rebuilt from disk on the next reconcile.
2449
+ */
2450
+ flush(): Promise<void>;
2451
+ private doFlush;
2452
+ }
2453
+ //#endregion
2454
+ //#region src/services/blobs/blob-cache.d.ts
2455
+ interface BlobUrlLease {
2456
+ url: string;
2457
+ release(): void;
2458
+ }
2459
+ interface BlobReadOptions {
2460
+ /** Write through to L1 on a miss. Default true. */
2461
+ persist?: boolean;
2462
+ /** Mark the entry exempt from pressure eviction. */
2463
+ pin?: boolean;
2464
+ /**
2465
+ * Default `'never'`: a bucket path is treated as immutable, which is how the
2466
+ * client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
2467
+ * `head()` to compare sizes before trusting L1.
2468
+ */
2469
+ revalidate?: 'never' | 'head';
2470
+ /** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
2471
+ reload?: boolean;
2472
+ }
2473
+ interface BlobCacheStats {
2474
+ entries: number;
2475
+ totalBytes: number;
2476
+ budgetBytes: number;
2477
+ pinnedBytes: number;
2478
+ evictedEntries: number;
2479
+ evictedBytes: number;
2480
+ reconciledEntries: number;
2481
+ hits: number;
2482
+ misses: number;
2483
+ persistent: boolean;
2484
+ /** True when pinned bytes alone exceed the budget: new entries stop being
2485
+ * written rather than pinned ones being thrown away. */
2486
+ persistPaused: boolean;
2487
+ }
2488
+ interface BlobCacheOptions {
2489
+ store: BlobStore;
2490
+ manifest: BlobManifest;
2491
+ /** L2 read. Resolves to null when the file does not exist remotely. */
2492
+ fetchRemote(key: BlobKey): Promise<Blob | null>;
2493
+ /** L2 metadata, for `revalidate: 'head'`. */
2494
+ headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
2495
+ logger: Logger$1;
2496
+ maxBytes: number;
2497
+ now?: () => number;
2498
+ /** Injected so the URL layer is exercisable off a DOM (node tests). */
2499
+ urls?: {
2500
+ create(blob: Blob): string;
2501
+ revoke(url: string): void;
2502
+ };
2503
+ }
2504
+ declare class BlobCache {
2505
+ private readonly store;
2506
+ private readonly manifest;
2507
+ private readonly fetchRemote;
2508
+ private readonly headRemote?;
2509
+ private readonly logger;
2510
+ private readonly now;
2511
+ private readonly urlFactory;
2512
+ private maxBytes;
2513
+ private persistPaused;
2514
+ /** Set after a quota failure survives one forced eviction. */
2515
+ private persistDisabled;
2516
+ private readonly urls;
2517
+ /** Ids at zero references, oldest first — the hot-URL window. */
2518
+ private idleUrls;
2519
+ private readonly inflight;
2520
+ private flushTimer;
2521
+ private readonly onPageHide;
2522
+ /**
2523
+ * Resolves once the manifest has been reconciled against disk. Reads await
2524
+ * it, so `start()` does NOT have to be awaited on the boot path — blocking
2525
+ * boot on an OPFS directory walk delayed the WebSocket connect (and with it
2526
+ * the connection supervisor) for no benefit.
2527
+ */
2528
+ private ready;
2529
+ private hits;
2530
+ private misses;
2531
+ private evictedEntries;
2532
+ private evictedBytes;
2533
+ private reconciledEntries;
2534
+ constructor(opts: BlobCacheOptions);
2535
+ /** Coalesce manifest write-back. Metadata only, so losing the tail costs an
2536
+ * LRU timestamp that reconcile reseeds from the file mtime. */
2537
+ private scheduleFlush;
2538
+ /**
2539
+ * Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
2540
+ * Returns null when the file does not exist remotely and is not cached.
2541
+ */
2542
+ read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
2543
+ /**
2544
+ * An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
2545
+ * revoked once the last holder lets go and it falls out of the hot window.
2546
+ */
2547
+ acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
2548
+ private lease;
2549
+ private releaseUrl;
2550
+ private revokeUrl;
2551
+ /** L1 lookup with the size check that catches torn and cross-tab writes. */
2552
+ private readLocal;
2553
+ /** True when the remote agrees with the cached size, or cannot be reached. */
2554
+ private headMatches;
2555
+ private fetchDeduped;
2556
+ private persist;
2557
+ private writeThrough;
2558
+ /** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
2559
+ invalidate(key: BlobKey): Promise<void>;
2560
+ private dropLocal;
2561
+ setPinned(key: BlobKey, pinned: boolean): void;
2562
+ /**
2563
+ * Bring total bytes under budget by dropping the least recently used
2564
+ * entries. Pinned entries and anything with a live object URL are skipped —
2565
+ * evicting bytes that a mounted `<img>` is displaying would blank it.
2566
+ */
2567
+ private enforceBudget;
2568
+ /** Evict LRU-first until at or below `target`. Returns the resulting total. */
2569
+ private evictTo;
2570
+ /**
2571
+ * Rebuild the manifest from what is actually on disk. OPFS wins on existence
2572
+ * in both directions: files with no row get a row (seeded from mtime), rows
2573
+ * are only loaded for files that exist, and torn `.part-` writes are swept by
2574
+ * the walk itself.
2575
+ *
2576
+ * Rows whose file vanished outside our control (a browser origin eviction)
2577
+ * are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
2578
+ * found on disk — and are overwritten if that path is cached again.
2579
+ */
2580
+ reconcile(): Promise<void>;
2581
+ /** Warm the cache for offline use. Skips anything already cached. */
2582
+ prefetch(keys: BlobKey[]): Promise<void>;
2583
+ /** Bind to the boot bucket and hydrate the manifest from disk. Separate from
2584
+ * {@link setNamespace} because boot must reconcile even when the namespace
2585
+ * it lands on is the one the store was constructed with. */
2586
+ start(namespace: string): Promise<void>;
2587
+ /** Repoint at another local bucket. The bytes of the old one stay on disk so
2588
+ * switching back (or signing back in) is still warm. */
2589
+ setNamespace(namespace: string): Promise<void>;
2590
+ setMaxBytes(maxBytes: number): void;
2591
+ /** Delete every cached byte in the current namespace. */
2592
+ clear(): Promise<void>;
2593
+ flush(): Promise<void>;
2594
+ /** Flush metadata and drop every object URL. Must run before the local store
2595
+ * closes — the flush writes through it. */
2596
+ close(): Promise<void>;
2597
+ stats(): BlobCacheStats;
2598
+ }
2599
+ //#endregion
2600
+ //#region src/utils/blurhash.d.ts
2601
+ /**
2602
+ * Blurhash generation settings. `true` enables with the defaults below, `false`
2603
+ * disables. Resolution order for a put: per-call option > client config >
2604
+ * default ON. See {@link Sp00kyConfig.blurhash}.
2605
+ */
2606
+ type BlurhashSetting = boolean | BlurhashEncodeOptions;
2607
+ interface BlurhashEncodeOptions {
2608
+ /** Horizontal detail components, 1-9. Defaults to 4. */
2609
+ componentX?: number;
2610
+ /** Vertical detail components, 1-9. Defaults to 3. */
2611
+ componentY?: number;
2612
+ }
2613
+ /**
2614
+ * Where an image's blurhash lives: a tiny sidecar object in the same bucket.
2615
+ * Buckets have no per-object metadata channel (`put` is just `.put($content)`),
2616
+ * so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
2617
+ */
2618
+ declare function blurhashSidecarPath(path: string): string;
2619
+ /** Extensions `bucket.put` treats as images worth hashing. */
2620
+ declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
2621
+ declare function isImagePath(path: string): boolean;
2622
+ /**
2623
+ * Decode `content` as an image and compute its blurhash. Browser-only: returns
2624
+ * null (never throws) when image decoding is unavailable (node, workers without
2625
+ * canvas), when the bytes are not a decodable image, or on any other failure —
2626
+ * a missing hash must never break the upload that triggered it.
2627
+ */
2628
+ declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
2629
+ //#endregion
2630
+ //#region src/sp00ky.d.ts
2631
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
2632
+ declare function bucketContentToBlob(content: unknown): Blob | null;
2633
+ interface BucketPutOptions {
2634
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
2635
+ blurhash?: BlurhashSetting;
2636
+ }
2637
+ interface BucketPutResult {
2638
+ /** The computed blurhash when the content was a hashable image; else null. */
2639
+ blurhash: string | null;
2640
+ }
2641
+ interface BucketHandleSettings {
2642
+ blurhash?: BlurhashSetting;
2643
+ logger?: {
2644
+ warn: (obj: unknown, msg?: string) => void;
2645
+ };
2646
+ }
2647
+ declare class BucketHandle {
2648
+ private bucketName;
2649
+ private remote;
2650
+ /** Absent on the raw handle the cache itself reads through. */
2651
+ private blobs?;
2652
+ private settings?;
2653
+ constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
2654
+ blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined);
2655
+ /** Effective blurhash setting: per-call option > client config > default ON. */
2656
+ private resolveBlurhash;
2657
+ put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
2658
+ /**
2659
+ * The blurhash stored alongside an uploaded image (see
2660
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
2661
+ * blob cache, so a warm client answers from OPFS without a network hop, and
2662
+ * misses are remembered per tab so a hashless image costs at most one
2663
+ * serialized remote read per session.
2664
+ */
2665
+ blurhash(path: string): Promise<string | null>;
2666
+ get(path: string): Promise<unknown>;
2667
+ /**
2668
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
2669
+ * {@link get} this survives a reload and works offline. Returns null when the
2670
+ * file exists in neither place.
2671
+ */
2672
+ read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
2673
+ /**
2674
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
2675
+ * MUST call `release()` when the URL goes off screen. Returns null when the
2676
+ * file does not exist, or when object URLs are unavailable (non-browser).
2677
+ */
2678
+ url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
2679
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
2680
+ pin(path: string): void;
2681
+ unpin(path: string): void;
2682
+ /** Drop `path` from the local cache without touching the remote file. */
2683
+ evict(path: string): Promise<void>;
2684
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
2685
+ prefetch(paths: string[]): Promise<void>;
2686
+ delete(path: string): Promise<void>;
2687
+ exists(path: string): Promise<boolean>;
2688
+ head(path: string): Promise<Record<string, unknown>>;
2689
+ copy(sourcePath: string, targetPath: string): Promise<void>;
2690
+ rename(sourcePath: string, targetPath: string): Promise<void>;
2691
+ list(prefix?: string): Promise<string[]>;
2692
+ }
2693
+ declare class Sp00kyClient<S extends SchemaStructure> {
2694
+ private config;
2695
+ private local;
2696
+ private remote;
2697
+ private blobs;
2698
+ private connectionSupervisor;
2699
+ private persistenceClient;
2700
+ private migrator;
2701
+ private cache;
2702
+ private dataModule;
2703
+ private sync;
2704
+ private devTools;
2705
+ private crdtManager;
2706
+ /**
2707
+ * True once the LOCAL half of boot is done and the client can serve reads
2708
+ * from the local store. Distinct from being connected: `syncHealth` covers
2709
+ * reaching the server and `storageHealth` covers whether the local store is
2710
+ * durable, but neither says "usable". Consumers gate their first paint on
2711
+ * this, which is what makes a warm boot instant and an offline boot possible.
2712
+ */
2713
+ private localReady;
2714
+ private saltUserId;
2715
+ private featureFlags;
2716
+ private appReleases;
2717
+ private preloadedHashes;
2718
+ private pendingQueryInits;
2719
+ private logger;
2720
+ auth: AuthService<S>;
2721
+ streamProcessor: StreamProcessorService;
2722
+ private tabsCoordinator;
2723
+ private sharedActive;
2724
+ /** Current shared-tabs role, or null when the feature is off/fell back. */
2725
+ get tabRole(): TabRole | null;
2726
+ get remoteClient(): surrealdb0.Surreal;
2727
+ get localClient(): unknown;
2728
+ get pendingMutationCount(): number;
2729
+ /** Number of times the initial list_ref LIVE subscription retried on
2730
+ * the most recent `setCurrentUserId` call. 0 when the SSP's
2731
+ * pre-emptive user-table creation got there first; >0 when LIVE
2732
+ * registration hit a "table not found" race. Exposed so the e2e
2733
+ * suite can guard the pre-emptive path against regression. */
2734
+ get liveRetryCount(): number;
2735
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
2736
+ /** Number of queries mid-fetch right now. See {@link subscribeToFetchActivity}. */
2737
+ get fetchingQueryCount(): number;
2738
+ /**
2739
+ * Observe how many queries are fetching from the server. Fires immediately
2740
+ * with the current count and again on every change, so one subscription can
2741
+ * drive a "downloading" indicator for the whole app. Pair with
2742
+ * {@link subscribeToPendingMutations} for the "uploading" half.
2743
+ */
2744
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
2745
+ /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
2746
+ get syncHealth(): SyncHealth;
2747
+ /**
2748
+ * Observe sync health. Fires immediately with the current status and again
2749
+ * on every healthy↔degraded transition. Returns an unsubscribe.
2750
+ */
2751
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2752
+ /** Durability of the local cache. See {@link StorageHealth}. `'unknown'` for
2753
+ * engines that don't report it. */
2754
+ get storageHealth(): StorageHealth;
2755
+ /**
2756
+ * Observe local-store durability. Fires immediately with the current snapshot
2757
+ * and again on every change (at most once per bucket open in practice).
2758
+ * Returns an unsubscribe.
2759
+ */
2760
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2761
+ constructor(config: Sp00kyConfig<S>);
2762
+ /** The shared-tabs role machinery, wired to this client's modules. */
2763
+ private buildTabsCoordinator;
2764
+ /**
2765
+ * Setup direct callbacks instead of event subscriptions
2766
+ */
2767
+ private setupCallbacks;
2768
+ init(): Promise<void>;
2769
+ /**
2770
+ * The network half of boot: connect, verify the restored session, and let the
2771
+ * sync engine catch up. Runs in the background after `init()` has already
2772
+ * resolved, so nothing here is on the paint path.
2773
+ *
2774
+ * Every step is best-effort. A failure leaves the client in exactly the state
2775
+ * a warm offline boot is in - local reads working, writes queued in the
2776
+ * outbox - and the connection supervisor keeps retrying underneath.
2777
+ */
2778
+ private initRemote;
2779
+ /**
2780
+ * Write the signed-in user's own row, as the SERVER just returned it, into
2781
+ * the local store.
2782
+ *
2783
+ * `AuthService.check()` (boot verification, sign-in, an app-driven refresh)
2784
+ * runs `SELECT * FROM ONLY $auth.id` and keeps the answer on
2785
+ * `auth.currentUser`; nothing consumed it beyond the id. Meanwhile the app's
2786
+ * own `user` query paints local-first from whatever body the store holds,
2787
+ * and that body is only refreshed when the server's row version reaches
2788
+ * this client through membership (`_00_list_ref`). While the SSP is down or
2789
+ * bootstrapping that never happens, so a device that registered before the
2790
+ * account was verified kept rendering a row without `email_verified` and
2791
+ * the app parked the user on "Verify your email" over a server that said
2792
+ * "already verified". The authoritative row was already in hand.
2793
+ *
2794
+ * MERGE semantics (`CacheModule.saveBatch`) keep local-only fields, and
2795
+ * re-using the memoized version keeps the sync dedup honest: this is a
2796
+ * field refresh, not a version claim. `notifyTableQueries` re-materializes
2797
+ * the `user` queries so the gate flips without waiting for a stream update.
2798
+ * Best-effort: a failure here leaves things exactly as they were.
2799
+ */
2800
+ private persistVerifiedUser;
2801
+ private bucketSwitchChain;
2802
+ private pendingBucketTarget;
2803
+ /**
2804
+ * Ensure the local store is this user's bucket, switching if needed. Called
2805
+ * from the auth listener on every auth flip; concurrent calls are chained
2806
+ * and superseded intermediates are skipped (latest target wins).
2807
+ */
2808
+ private ensureLocalBucket;
2809
+ /**
2810
+ * The bucket-switch choreography: drain → swap → rebind.
2811
+ *
2812
+ * Drain: sync quiesced (poll/LIVE stopped, in-flight round awaited so its
2813
+ * outbox delete lands in the OLD bucket, debounce timers cancelled),
2814
+ * DataModule timers cleared, CRDT fields closed WITHOUT their final flush
2815
+ * (the remote session already belongs to the next user).
2816
+ *
2817
+ * Swap: gate closes so any local query issued mid-switch (sibling auth
2818
+ * subscribers, FeatureFlagModule) waits and then runs against the NEW
2819
+ * bucket; store swaps open-new-before-close-old; schema provisions
2820
+ * (no-op for a returning bucket); stale `_00_query` rows are wiped (dead
2821
+ * sessionId-salted hashes with stale arrays — record bodies stay warm);
2822
+ * SSP resets to a fresh circuit with re-seeded permissions.
2823
+ *
2824
+ * Rebind: auth token re-persisted (the surrealdb persistence client wrote it
2825
+ * into the OLD bucket's `_00_kv` before this listener ran), active queries
2826
+ * re-homed keeping their hashes, sync resumed on the new bucket's own
2827
+ * outbox, and every query re-registered remotely to refill from the server.
2828
+ */
2829
+ private doSwitchBucket;
2830
+ /** Removes the `pagehide` listener installed in `init`; see `close`. */
2831
+ private detachUnloadRelease;
2832
+ close(): Promise<void>;
2833
+ /**
2834
+ * Subscribe to a feature flag for the current user. Returns a
2835
+ * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
2836
+ * accessors reflect the latest assignment from `_00_user_feature`,
2837
+ * and whose `subscribe(cb)` fires whenever that assignment changes.
2838
+ *
2839
+ * Permissions are enforced by SurrealDB: a client can only ever see
2840
+ * its own row, and cannot create or modify assignments.
2841
+ */
2842
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2843
+ /**
2844
+ * Force a feature flag to `variant` in THIS browser only; `null` clears it.
2845
+ *
2846
+ * Nothing is sent to the server — the `_00_user_feature` assignment is
2847
+ * untouched, so clearing restores whatever the server says. Persisted to
2848
+ * localStorage, survives reloads, and applies while signed out. Backs the
2849
+ * DevTools Access tab, and is a convenient hook for tests.
2850
+ *
2851
+ * To change a flag for OTHER users you need admin rights (`spky admin add`)
2852
+ * and the DevTools Access tab, or `spky flag`.
2853
+ */
2854
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2855
+ /** Drop every local feature flag override set via `setFeatureOverride`. */
2856
+ clearFeatureOverrides(): void;
2857
+ /** The local feature flag overrides currently in effect, keyed by flag. */
2858
+ getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2859
+ /**
2860
+ * Observe the announced release of an app (`_00_app_release:<app>`, written
2861
+ * by `spky deploy` / `spky release`). The handle's `snapshot()` carries the
2862
+ * announced version plus the cache-bust/mandatory flags, and
2863
+ * `updateAvailable(currentVersion)` compares it semver-wise against the
2864
+ * running build. World-readable; writes are root-only.
2865
+ */
2866
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2867
+ authenticate(token: string): Promise<surrealdb0.Tokens>;
2868
+ /**
2869
+ * Open a CRDT field for collaborative editing.
2870
+ * Returns a CrdtField with a LoroDoc that can be bound to any editor.
2871
+ * Also starts a LIVE SELECT on the parent table for real-time sync;
2872
+ * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
2873
+ */
2874
+ openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2875
+ /**
2876
+ * Close a CRDT field when editing is done.
2877
+ */
2878
+ closeCrdtField(table: string, recordId: string, field: string): void;
2879
+ deauthenticate(): Promise<void>;
2880
+ query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
2881
+ private initQuery;
2882
+ /**
2883
+ * Background tail of {@link initQuery}: enqueue the `register` down-event,
2884
+ * then instant-hydrate (opt-in via `config.instantHydrate`, and only when
2885
+ * the query is cold). Never rejects — both halves catch and log, so
2886
+ * `void`-ing the returned promise can't produce an unhandled rejection. By
2887
+ * default (hydrate off) the register lifecycle is the single freshness path;
2888
+ * the one-shot fetch is an optimization apps enable explicitly, and it runs
2889
+ * regardless of preload state — cache-first delivery never depends on WHY
2890
+ * rows are cached.
2891
+ *
2892
+ * Register goes first on purpose. The hydrate used to run strictly before
2893
+ * the enqueue, so a windowed list's one-shot read (a full-table scan when
2894
+ * the app has no matching index) held its own registration back by seconds
2895
+ * per window. Now whichever answer lands first paints; a hydrate that
2896
+ * arrives after the registration is dropped (`applyHydration`).
2897
+ */
2898
+ private finishQueryInit;
2899
+ /**
2900
+ * Smart, awaitable preload/prewarm into the LOCAL cache — without registering a
2901
+ * live view (NO `_00_query`, NO subscription, NO TTL heartbeat).
2902
+ *
2903
+ * Cache-aware via a durable per-bucket freshness marker (`_00_preload`):
2904
+ * - COLD (never preloaded in this bucket): fetch the query one-shot from the
2905
+ * remote, persist the rows (+ embedded `.related()` children), stamp the
2906
+ * marker — and AWAIT it. This is the "smart waiting" first load: callers can
2907
+ * `await db.preload(...)` to hold the UI until the data is ready.
2908
+ * - WARM (marker present): return instantly — NEVER blocks. `refresh` decides
2909
+ * whether to also kick a one-time silent refetch (see {@link PreloadOptions}).
2910
+ * Default `onUse` does nothing; the data freshens when the real `useQuery`
2911
+ * mounts and registers its live view.
2912
+ *
2913
+ * Best-effort: any fetch failure (offline, etc.) is a no-op warn (no marker
2914
+ * written, so it's retried next load). Deduped per session by query hash.
2915
+ */
2916
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
2917
+ /**
2918
+ * One-shot remote fetch + local persist for a preload query. Returns the row
2919
+ * count on success, or -1 on failure (best-effort: logged, never thrown) so
2920
+ * the caller skips stamping the freshness marker and retries next load.
2921
+ */
2922
+ private fetchAndPersist;
2923
+ queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
2924
+ subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
2925
+ immediate?: boolean;
2926
+ }): Promise<() => void>;
2927
+ /**
2928
+ * Opt-in eager teardown for a query whose last subscriber has gone away
2929
+ * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
2930
+ * while any subscriber remains. Tears down the remote `_00_query` view +
2931
+ * local WASM view instead of waiting for the TTL sweep. Default behavior
2932
+ * (no call here) keeps the view resident for cheap re-subscription.
2933
+ */
2934
+ deregisterQuery(queryHash: string): void;
2935
+ /**
2936
+ * Subscribe to a query's fetch-status changes (idle/fetching). With
2937
+ * `{ immediate: true }` the callback fires synchronously with the current
2938
+ * status. Powers the `useQuery` hook's `isFetching()` accessor.
2939
+ */
2940
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
2941
+ immediate?: boolean;
2942
+ }): () => void;
2943
+ /**
2944
+ * Subscribe to a query's authority flips: `true` once server membership is
2945
+ * known for it (a registration or poll landed, or a durable `_00_window`
2946
+ * seed was read on boot), `false` when it is reset (bucket switch). With
2947
+ * `{ immediate: true }` the callback fires synchronously with the current
2948
+ * value. Powers the bindings' `isAuthoritative()` / cold-only `isLoading()`.
2949
+ */
2950
+ subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
2951
+ immediate?: boolean;
2952
+ }): () => void;
2953
+ /**
2954
+ * Report the frontend processing time (ms) a client framework spent applying
2955
+ * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
2956
+ * surface the "frontend" phase of the per-query timing breakdown.
2957
+ */
2958
+ reportFrontendTiming(queryHash: string, ms: number): void;
2959
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
2960
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2961
+ /** Cache-free handle. The blob cache reads the remote through this, so a
2962
+ * cache miss can't loop back into the cache. */
2963
+ private rawBucket;
2964
+ /** Blob cache counters for DevTools. */
2965
+ getBlobCacheStats(): BlobCacheStats;
2966
+ create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
2967
+ update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
2968
+ [x: string]: /*elided*/any;
2969
+ }>;
2970
+ delete(table: string, id: string): Promise<void>;
2971
+ /**
2972
+ * Whether the local store is initialized and reads can be served. See the
2973
+ * `localReady` field: this is deliberately independent of connectivity.
2974
+ */
2975
+ isLocalReady(): boolean;
2976
+ useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
2977
+ /**
2978
+ * Run one raw SurrealQL statement on the remote through the client's own
2979
+ * query path: the connect gate (it never runs on a socket whose namespace
2980
+ * and token are not applied yet), the per-statement timeout and the
2981
+ * concurrency limit. Prefer this over {@link useRemote} for one-shot reads
2982
+ * such as counts; `useRemote` hands out the bare SDK client and raced a
2983
+ * reconnect with "Specify a namespace to use".
2984
+ */
2985
+ remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
2986
+ /**
2987
+ * Mint the salt used for query-id hashing, so two sessions registering the
2988
+ * same logical query get distinct `_00_query` rows.
2989
+ *
2990
+ * Generated LOCALLY, deliberately. This used to be `RETURN <string>session::id()`,
2991
+ * which cost a serial round trip on the critical boot path and resolved to
2992
+ * `''` offline. The value never needed to come from the server: the server
2993
+ * derives its own `clientId` inside `fn::query::register` and *ignores*
2994
+ * whatever the caller passed, and the permission rules that matter gate on
2995
+ * `auth_id = $auth.id` rather than the session (`_00_list_ref`). Session
2996
+ * scoping via `clientId = session::id()` was in fact removed upstream because
2997
+ * it broke a user with two tabs open. All this value has to be is unique per
2998
+ * browser session, which `randomUUID` gives us for free and offline.
2999
+ */
3000
+ /**
3001
+ * The current principal as the `"table:id"` string the in-browser SSP wants
3002
+ * for `$auth.id`, or null when signed out.
3003
+ *
3004
+ * Tolerates BOTH shapes `currentUser.id` can take, which is the point:
3005
+ * a session restored from the cached token carries a plain string (the JWT's
3006
+ * `ID` claim), while one verified by the server carries a RecordId. Passing
3007
+ * the former to `encodeRecordId` reads `.table` off a string and throws
3008
+ * during boot.
3009
+ */
3010
+ /**
3011
+ * Prime the in-browser circuit from the local store. Builds the context the
3012
+ * stream processor needs: every synced table (the app schema plus the
3013
+ * server-written meta tables that sync down), a schema hash so a snapshot
3014
+ * projected under another schema is not trusted, and the ids whose local
3015
+ * `_00_rv` was bumped by an unsettled mutation.
3016
+ */
3017
+ private primeCircuit;
3018
+ private sessionAuthId;
3019
+ private mintSessionSalt;
3020
+ }
3021
+ //#endregion
3022
+ //#region src/utils/semver.d.ts
3023
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
3024
+ declare function semverGt(a: unknown, b: unknown): boolean;
3025
+ //#endregion
3026
+ //#region src/services/database/errors.d.ts
3027
+ /**
3028
+ * A local-store operation that did not answer within its deadline.
3029
+ *
3030
+ * The local write path (`db.create` / `db.update` / `db.delete`, every local
3031
+ * query behind them) used to have no deadline anywhere: the SQLite worker
3032
+ * transport parks a call until the worker replies, the surrealdb engine's
3033
+ * query chain waits on the previous link, and `withRetry` retries without a
3034
+ * clock. One op that never settled (a worker starved behind a long select, a
3035
+ * lock verification awaiting `navigator.locks.query()` forever) left the
3036
+ * caller's promise pending for the tab's lifetime - a chat composer that never
3037
+ * re-enabled, a call that never got past "Connecting".
3038
+ *
3039
+ * The message says "timed out" on purpose: `classifySyncError` keys off it and
3040
+ * treats the failure as transient (re-queue), never as an application error
3041
+ * that rolls the mutation back. `retryable: false` keeps `withRetry` from
3042
+ * spinning on it: the op is still running in the engine, retrying queues a
3043
+ * second copy behind it.
3044
+ */
3045
+ declare class LocalOpTimeoutError extends Error {
3046
+ readonly name = "LocalOpTimeoutError";
3047
+ readonly retryable = false;
3048
+ readonly op: string;
3049
+ readonly timeoutMs: number;
3050
+ constructor(op: string, timeoutMs: number);
3051
+ }
3052
+ /** Default deadline for one local-store operation. Generous: a cold 4k-row
3053
+ * select on a throttled tab is seconds, not tens of seconds. */
3054
+ declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
3055
+ //#endregion
3056
+ //#region src/utils/index.d.ts
3057
+ declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
3058
+ /**
3059
+ * Convert plain text to simple HTML paragraphs.
3060
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
3061
+ */
3062
+ declare function textToHtml(text: string): string;
257
3063
  /**
258
3064
  * Helper for retrying DB operations with exponential backoff
259
3065
  */
260
3066
 
261
3067
  //#endregion
262
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, DebounceOptions, EventSubscriptionOptions, Level, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryTimeToLive, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RunOptions, SpookyClient, SpookyConfig, SpookyQueryResult, SpookyQueryResultPromise, StoreType, UpdateOptions, createAuthEventSystem, fileToUint8Array };
3068
+ export { AppReleaseHandle, AppReleaseModule, type AppReleaseOptions, type AppReleaseSnapshot, AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BLURHASH_IMAGE_EXTENSIONS, type BlobCacheStats, type BlobEntry, type BlobKey, type BlobReadOptions, type BlobUrlLease, type BlurhashEncodeOptions, type BlurhashSetting, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, Level, LocalOpTimeoutError, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, ServerViewMeta, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, isBlurhashValid, isImagePath, semverGt, textToHtml };