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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
package/dist/index.d.ts CHANGED
@@ -1,119 +1,240 @@
1
- import { A as SyncHealthStatus, C as RunOptions, D as StoreType, E as Sp00kyQueryResultPromise, F as SyncEventSystem, I as EventDefinition, L as EventSystem, M as UpdateOptions, N as UpEvent, O as SyncHealth, P as Logger$1, S as RegistrationTimings, T as Sp00kyQueryResult, _ as QueryTimeToLive, a as MutationCallback, b as RecordVersionArray, c as PersistenceClient, d as QueryConfig, f as QueryConfigRecord, g as QueryStatusCallback, h as QueryStatus, i as MATERIALIZATION_SAMPLE_WINDOW, j as TimingPhase, k as SyncHealthConfig, l as PhaseStat, m as QueryState, n as EventSubscriptionOptions, o as MutationEvent, p as QueryHash, r as Level, s as MutationEventType, t as DebounceOptions, u as PinoTransmit, v as QueryTimings, w as Sp00kyConfig, x as RecordVersionDiff, y as QueryUpdateCallback } from "./types.js";
1
+ import { $ as WebPushInfo, $t as ChannelRelayConfig, A as RecordVersionArray, At as AuthEventTypeMap, B as StorageHealthStatus, Bt as ImpersonationTimerHost, C as QueryState, Ct as AuthService, D as QueryTimings, Dt as SignOutContext, E as QueryTimeToLive, Et as SIGN_OUT_HOOK_TIMEOUT_MS, F as Sp00kyChannel, Ft as SealedQuery, G as TimingPhase, Gt as decodeTokenClaims, H as SyncHealth, Ht as ORIGIN_TOKEN_KEY, I as Sp00kyConfig, It as EventDefinition, J as PushDeviceKind, Jt as sameImpersonation, K as UpdateOptions, Kt as impersonationFromToken, L as Sp00kyQueryResult, Lt as EventSystem, M as RegistrationTimings, Mt as createAuthEventSystem, N as RunOptions, Nt as RemoteDatabaseService, O as QueryUpdateCallback, Ot as SignOutHook, P as ServerViewMeta, Pt as LocalStore, Q as WebPushErrorCode, Qt as ChannelOp, R as Sp00kyQueryResultPromise, Rt as IMPERSONATION_ACCESS, S as QueryHash, St as ActiveImpersonation, T as QueryStatusCallback, Tt as REFUSAL_RECHECK_MIN_MS, U as SyncHealthConfig, Ut as SESSION_POLL_MS, V as StoreType, Vt as ImpersonationTimers, W as SyncHealthStatus, Wt as TokenClaims, X as WebPushDevice, Xt as ChannelHandle, Y as WebPushConfig, Yt as ChannelAcceptRule, Z as WebPushError, Zt as ChannelMessage, _ as PreloadOptions, _t as PushPayload, a as EventSubscriptionOptions, an as ChannelTransport, at as WebPushSyncOptions, b as QueryConfig, bt as WebPushClientMessage, c as LocalWorkers, cn as ChannelsConfig, ct as WebPushUnsupportedReason, d as MutationCallback, dn as TransportHooks, dt as BridgeSignOutMessage, en as ChannelScope, et as WebPushMessage, f as MutationEvent, fn as matchesWhere, ft as BridgeTokenMessage, g as PinoTransmit, gt as PushOp, h as PhaseStat, hn as Logger$1, ht as PushNotificationAction, i as EdgeDelta, in as ChannelStatus, it as WebPushSupport, j as RecordVersionDiff, jt as AuthEventTypes, k as ReconnectConfig, kt as AuthEventSystem, l as MATERIALIZATION_SAMPLE_WINDOW, ln as InterestMessage, lt as WebPushUpdateOptions, m as PersistenceClient, mn as LogTap, mt as PushNotification, n as ConnectionState, nn as ChannelShareRule, nt as WebPushModule, o as InlineRow, on as ChannelTransportFactory, ot as WebPushSyncStatus, p as MutationEventType, pn as unusedArgs, pt as PUSH_PAYLOAD_VERSION, q as PUSH_ENDPOINT_KEY, qt as renewDelayMs, r as DebounceOptions, rn as ChannelState, rt as WebPushSubscribeOptions, s as Level, sn as ChannelWire, st as WebPushUnsubscribeOptions, t as ChannelQuery, tn as ChannelShareConfig, tt as WebPushMessageInput, u as MembershipOutcome, un as PeerRef, ut as detectWebPushSupport, v as PreloadRefresh, vt as PushPayloadKind, w as QueryStatus, wt as ImpersonationCandidate, x as QueryConfigRecord, xt as isPushPayload, y as QueryAuthorityCallback, yt as PushUrgency, z as StorageHealth, zt as ImpersonationInfo } from "./types.js";
2
+ import { BackendNames, BackendRoutes, BucketNames, ChannelPeer, ChannelTableNames, FinalQuery, GetTable, QueryBuilder, QueryOptions, QueryPlan, RecordId, RoutePayload, SchemaStructure, TableModel, TableNames } from "@spooky-sync/query-builder";
2
3
  import * as surrealdb0 from "surrealdb";
3
- import { Duration, RecordId, Surreal as Surreal$1, SurrealTransaction } from "surrealdb";
4
- import { AccessDefinition, BackendNames, BackendRoutes, BucketNames, ColumnSchema, GetTable, QueryBuilder, QueryOptions, RoutePayload, SchemaStructure, TableModel, TableNames, TypeNameToTypeMap } from "@spooky-sync/query-builder";
4
+ import { Duration, RecordId as RecordId$1, Surreal } from "surrealdb";
5
5
  import { Logger } from "pino";
6
+ import { decode, encode, isBlurhashValid } from "blurhash";
6
7
  import { LoroDoc } from "loro-crdt";
7
8
 
8
- //#region src/services/database/events/index.d.ts
9
- declare const DatabaseEventTypes: {
10
- readonly LocalQuery: "DATABASE_LOCAL_QUERY";
11
- readonly RemoteQuery: "DATABASE_REMOTE_QUERY";
12
- };
13
- interface DatabaseQueryEventPayload {
14
- query: string;
15
- vars?: Record<string, unknown>;
16
- duration: number;
17
- success: boolean;
18
- error?: string;
19
- timestamp: number;
20
- }
21
- type DatabaseEventTypeMap = {
22
- [DatabaseEventTypes.LocalQuery]: EventDefinition<typeof DatabaseEventTypes.LocalQuery, DatabaseQueryEventPayload>;
23
- [DatabaseEventTypes.RemoteQuery]: EventDefinition<typeof DatabaseEventTypes.RemoteQuery, DatabaseQueryEventPayload>;
9
+ //#region src/services/tabs/protocol.d.ts
10
+
11
+ type TabId = string;
12
+ type TabRole$1 = 'solo' | 'leader' | 'follower';
13
+ /** Broker pings every tab at this cadence. */
14
+
15
+ /** Matches `CacheIngestTuple` (modules/cache): exactly what `ingestMany`
16
+ * consumes, so relayed batches feed follower circuits without reshaping. */
17
+ interface IngestTuple {
18
+ table: string;
19
+ op: 'CREATE' | 'UPDATE' | 'DELETE';
20
+ id: string;
21
+ record: Record<string, unknown>;
22
+ }
23
+ type FollowerToLeaderMessage = {
24
+ type: 'sync-hello';
25
+ tabId: TabId;
26
+ }
27
+ /** The follower committed an outbox row (through the shared store) and the
28
+ * leader should drain it. Idempotent; a new leader's loadFromDatabase is
29
+ * the backstop for a notify lost in a failover window. */ | {
30
+ type: 'mutation-enqueued';
31
+ mutationId: string;
32
+ } | {
33
+ type: 'request-poll';
34
+ }
35
+ /** An optimistic write this follower committed to the SHARED store and
36
+ * ingested into its own circuit. The leader ingests it (no DB write, the
37
+ * row is already there) and fans it out to every OTHER follower as
38
+ * `ingest-relay`, so a follower's write lands in every tab in one hop
39
+ * instead of after the server round-trip. */ | {
40
+ type: 'ingest';
41
+ tuples: IngestTuple[];
24
42
  };
25
- type DatabaseEventSystem = EventSystem<DatabaseEventTypeMap>;
26
- //#endregion
27
- //#region src/utils/surql.d.ts
28
- interface SealedQuery<T = void> {
29
- readonly sql: string;
30
- readonly extract: (results: unknown[]) => T;
43
+ type LeaderToFollowerMessage = {
44
+ type: 'db-ready';
45
+ leadershipId: number;
46
+ bucketId: string;
47
+ storageHealth: StorageHealth;
31
48
  }
32
- //#endregion
33
- //#region src/services/database/database.d.ts
34
- declare abstract class AbstractDatabaseService {
35
- protected client: Surreal$1;
36
- protected logger: Logger$1;
37
- protected events: DatabaseEventSystem;
38
- protected abstract eventType: typeof DatabaseEventTypes.LocalQuery | typeof DatabaseEventTypes.RemoteQuery;
39
- constructor(client: Surreal$1, logger: Logger$1, events: DatabaseEventSystem);
40
- abstract connect(): Promise<void>;
41
- getClient(): Surreal$1;
42
- getEvents(): DatabaseEventSystem;
43
- tx(): Promise<SurrealTransaction>;
44
- private queryQueue;
45
- /**
46
- * Execute a query with serialized execution to prevent WASM transaction issues.
47
- */
48
- query<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T>;
49
- execute<T>(query: SealedQuery<T>, vars?: Record<string, unknown>): Promise<T>;
50
- close(): Promise<void>;
49
+ /** Every ingest the leader's CacheModule committed, so follower circuits
50
+ * stay live without their own fetch. seq detects gaps. */ | {
51
+ type: 'ingest-relay';
52
+ tuples: IngestTuple[];
53
+ leadershipId: number;
54
+ seq: number;
55
+ }
56
+ /** A `_00_list_ref` LIVE event, relayed verbatim. Each follower resolves the
57
+ * queryId against its own DataModule and ignores foreign queries. */ | {
58
+ type: 'list-ref-change';
59
+ action: 'CREATE' | 'UPDATE' | 'DELETE';
60
+ queryId: string;
61
+ recordId: string;
62
+ version: number;
63
+ parent: boolean;
64
+ }
65
+ /** The leader's drain rolled back a mutation owned by this tab. */ | {
66
+ type: 'mutation-rolled-back';
67
+ mutationId: string;
68
+ recordId: string;
69
+ eventType: 'create' | 'update' | 'delete';
70
+ error: string;
71
+ }
72
+ /** The leader's drain pushed a mutation and deleted its outbox row from the
73
+ * SHARED store. Every follower keeps the row in its overlay until its
74
+ * `_00_list_ref` membership arrives. */ | {
75
+ type: 'mutation-settled';
76
+ mutationId: string;
77
+ recordId: string;
78
+ eventType: 'create' | 'update' | 'delete';
79
+ }
80
+ /** The leader's LIVE saw edges of these queries change; followers re-read
81
+ * membership for the ones they hold. */ | {
82
+ type: 'membership-dirty';
83
+ hashes: string[];
51
84
  }
85
+ /** The failed-writes tray changed size on the shared store. */ | {
86
+ type: 'failed-mutations-changed';
87
+ count: number;
88
+ };
52
89
  //#endregion
53
- //#region src/services/database/local.d.ts
54
- declare class LocalDatabaseService extends AbstractDatabaseService {
55
- private config;
56
- protected eventType: "DATABASE_LOCAL_QUERY";
57
- constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
58
- getConfig(): Sp00kyConfig<any>['database'];
59
- connect(): Promise<void>;
60
- private unloadCloseRegistered;
61
- /**
62
- * Close the local DB on page unload so the SurrealDB-WASM worker releases its
63
- * IndexedDB connection cleanly. Without this, the previous page's connection
64
- * lingers; the next load's `client.connect` opens the store but the first
65
- * write transaction in `client.use` hits an "IndexedDB error" — which then
66
- * (mis)triggered the corrupt-store recovery and WIPED the cache on every
67
- * reload, making warm loads as slow as cold ones. `pagehide` is the reliable
68
- * unload signal (fires on bfcache + normal navigation); `close()` is async but
69
- * the WASM worker initiates the IndexedDB connection teardown synchronously.
70
- */
71
- private registerUnloadClose;
72
- private openStore;
73
- }
74
- /** True for the SurrealDB-WASM error raised when its IndexedDB-backed key-value
75
- * store can't be opened (corrupt / version-incompatible / blocked). Exported
76
- * for unit testing the error-message match. */
90
+ //#region src/services/database/connection-supervisor.d.ts
91
+ /**
92
+ * Keeps the remote WebSocket alive for the whole life of the page.
93
+ *
94
+ * The SurrealDB SDK reconnects on its own after a socket `close`, but that
95
+ * covers only one of three ways the connection dies:
96
+ *
97
+ * 1. **Socket closes, SDK recovers.** Handled entirely by the SDK. This
98
+ * supervisor only observes it (to report `reconnecting` upward).
99
+ * 2. **Socket closes, SDK gives up.** With `attempts: -1` this shouldn't happen
100
+ * from exhaustion — but the SDK also terminates the engine permanently when
101
+ * its post-reconnect handshake throws (it re-runs `version()`, `use()`,
102
+ * `authenticate()` on every reconnect and closes the engine on any error).
103
+ * One transient hiccup there would otherwise kill the page's connection for
104
+ * good. The revive loop re-opens from scratch.
105
+ * 3. **Socket never closes at all.** A half-open connection: the peer is gone
106
+ * (NAT timeout, wifi switch, laptop sleep) but no FIN ever arrives, so
107
+ * `readyState` stays OPEN and the SDK's own 30s ping — fire-and-forget, no
108
+ * response deadline — never notices. Nothing ever fires a `close` event, so
109
+ * nothing ever triggers a reconnect. The heartbeat detects this and forces
110
+ * the teardown that case 2's loop then repairs.
111
+ *
112
+ * Plus wake triggers: coming back `online` or un-hiding the tab probes
113
+ * immediately rather than waiting out a backoff that was scheduled while the
114
+ * network was known-down.
115
+ */
116
+ declare class ConnectionSupervisor {
117
+ private readonly remote;
118
+ private readonly logger;
119
+ private readonly config;
120
+ private state;
121
+ private subscribers;
122
+ private started;
123
+ private disposed;
124
+ private heartbeatTimer;
125
+ private heartbeatInFlight;
126
+ /** Consecutive failed probes. See {@link FAILURES_BEFORE_TEARDOWN}. */
127
+ private heartbeatFailures;
128
+ private reviveTimer;
129
+ private reviveAttempts;
130
+ /** Timestamp of the last wake-triggered probe, for rate limiting. */
131
+ private lastWakeProbeAt;
132
+ private reviving;
133
+ /**
134
+ * Set while the browser reports itself offline. Retrying a socket against a
135
+ * down interface only burns backoff, so the loop parks until `online` fires.
136
+ */
137
+ private suspended;
138
+ private teardown;
139
+ private static readonly REVIVE_BASE_MS;
140
+ /**
141
+ * How many consecutive heartbeat failures it takes to tear the socket down.
142
+ *
143
+ * The probe rides the same serialized queue as every other RPC (deliberately
144
+ * — see {@link beat}), which means it cannot distinguish a WEDGED queue from
145
+ * a merely BUSY one. A single slow window (a large sync burst, one heavy
146
+ * app query) used to be enough to force-close a perfectly healthy socket,
147
+ * and the resulting reconnect re-registered every active query about a
148
+ * second later. That self-inflicted teardown manufactured the very reconnect
149
+ * storms this class exists to survive. A genuinely dead socket still fails
150
+ * every probe, so it is torn down one interval later than before.
151
+ */
152
+ private static readonly FAILURES_BEFORE_TEARDOWN;
153
+ /** Retry delay after an inconclusive (first) heartbeat failure. */
154
+ private static readonly HEARTBEAT_RETRY_MS;
155
+ /** Floor between probes triggered by wake events (tab focus, pageshow). */
156
+ private static readonly WAKE_PROBE_MIN_INTERVAL_MS;
157
+ constructor(remote: RemoteDatabaseService, logger: Logger$1, config?: Required<ReconnectConfig>);
158
+ /** Latest observed transport state. */
159
+ get connection(): ConnectionState;
160
+ /**
161
+ * Observe transport state. Fires immediately with the current value and again
162
+ * on every change. Returns an unsubscribe.
163
+ */
164
+ subscribe(cb: (state: ConnectionState) => void): () => void;
165
+ /**
166
+ * Begin supervising. Call once, after the initial {@link
167
+ * RemoteDatabaseService.connect}. Idempotent.
168
+ */
169
+ start(): void;
170
+ /** Stop all timers and listeners. Safe to call more than once. */
171
+ dispose(): void;
172
+ private setState;
173
+ private clearReviveTimer;
174
+ /**
175
+ * Queue the next `connect()` attempt on exponential backoff, capped at
176
+ * `superviseRetryDelayMaxMs`. Never gives up — the page is expected to
177
+ * outlive any outage.
178
+ */
179
+ private scheduleRevive;
180
+ private revive;
181
+ private stopHeartbeat;
182
+ private startHeartbeat;
183
+ /**
184
+ * Probe the server end-to-end. Deliberately goes through
185
+ * `remote.query` — the same serialized queue every other remote call uses —
186
+ * so a queue wedged behind a stuck RPC also fails the heartbeat instead of
187
+ * being invisible to it.
188
+ */
189
+ private beat;
190
+ /**
191
+ * A restored network or an un-hidden tab is the strongest available hint that
192
+ * a reconnect will now succeed, so probe immediately instead of waiting out a
193
+ * backoff scheduled under worse conditions.
194
+ */
195
+ private installWakeTriggers;
196
+ /**
197
+ * Reset the backoff and act on whichever problem is present: reconnect if the
198
+ * socket is gone, otherwise probe it (it may be half-open — which is exactly
199
+ * what a sleep/wake cycle produces).
200
+ */
201
+ private wake;
202
+ }
77
203
  //#endregion
78
- //#region src/services/database/remote.d.ts
79
- declare class RemoteDatabaseService extends AbstractDatabaseService {
80
- private config;
81
- protected eventType: "DATABASE_REMOTE_QUERY";
82
- constructor(config: Sp00kyConfig<any>['database'], logger: Logger$1);
83
- getConfig(): Sp00kyConfig<any>['database'];
84
- connect(): Promise<void>;
85
- signin(params: any): Promise<any>;
86
- signup(params: any): Promise<any>;
87
- authenticate(token: string): Promise<any>;
88
- invalidate(): Promise<void>;
204
+ //#region src/services/database/local-migrator.d.ts
205
+ declare class LocalMigrator {
206
+ private localDb;
207
+ private logger;
208
+ constructor(localDb: LocalStore, logger: Logger$1);
209
+ provision(schemaSurql: string): Promise<void>;
210
+ private readKeptRows;
211
+ private restoreKeptRows;
212
+ private isSchemaUpToDate;
213
+ private recreateDatabase;
214
+ private splitStatements;
215
+ private createHashRecord;
89
216
  }
90
217
  //#endregion
91
- //#region src/modules/sync/queue/queue-down.d.ts
92
- type RegisterEvent = {
93
- type: 'register';
94
- payload: {
95
- hash: string;
96
- };
97
- };
98
- type SyncEvent = {
99
- type: 'sync';
100
- payload: {
101
- hash: string;
102
- };
103
- };
104
- type HeartbeatEvent = {
105
- type: 'heartbeat';
106
- payload: {
107
- hash: string;
108
- };
109
- };
110
- type CleanupEvent = {
111
- type: 'cleanup';
112
- payload: {
113
- hash: string;
114
- };
115
- };
116
- type DownEvent = RegisterEvent | SyncEvent | HeartbeatEvent | CleanupEvent;
218
+ //#region src/services/database/rows-prewarm.d.ts
219
+
220
+ /**
221
+ * Start the row store's worker and open the last bucket NOW, before the app
222
+ * has loaded. A worker takes about 10 ms to start and the store a few more to
223
+ * open; started from the first bytes of the page, that happens while the
224
+ * bundle downloads and parses, and by the time the client connects the store
225
+ * is open, its indexes are in memory and the answers to the app's first reads
226
+ * are already in the page. The engine finds the worker and adopts it; if
227
+ * anything about it is wrong (a new release, another bucket, a failed start)
228
+ * it starts its own, as it would have without this.
229
+ *
230
+ * Call it as early as the app can, or inline {@link ROWS_PREWARM_SNIPPET} in
231
+ * the page's `<head>`, which is this function without the bundle. A no-op on
232
+ * a first visit: the worker's URL is learned from the engine's first open.
233
+ */
234
+ declare function prewarmRows(): void;
235
+ /** {@link prewarmRows} as a script to inline in `<head>`, ahead of the app's bundle. */
236
+ declare const ROWS_PREWARM_SNIPPET: string;
237
+ /** The prewarmed worker, once: whoever takes it owns it. */
117
238
  //#endregion
118
239
  //#region src/services/stream-processor/wasm-types.d.ts
119
240
  interface WasmStreamUpdate {
@@ -146,6 +267,14 @@ interface StreamUpdate {
146
267
  queryHash: string;
147
268
  localArray: RecordVersionArray;
148
269
  op?: 'CREATE' | 'UPDATE' | 'DELETE';
270
+ /**
271
+ * Client-internal: not from the circuit. A membership-only change that
272
+ * needed no fetch is re-materialized through this same path so it cannot
273
+ * race a real update (DataModule.scheduleRematerialize). Carries the last
274
+ * known `localArray`; consumers that describe an INGEST (persist, metrics,
275
+ * devtools events) skip it.
276
+ */
277
+ synthetic?: boolean;
149
278
  /**
150
279
  * End-to-end ingest latency for the WASM call that produced this update,
151
280
  * in milliseconds. Populated by StreamProcessorService.ingest. Undefined
@@ -176,10 +305,38 @@ type StreamProcessorEvents = {
176
305
  interface StreamUpdateReceiver {
177
306
  onStreamUpdate(update: StreamUpdate): void;
178
307
  }
308
+ /** One row change in the shape `ingestMany` consumes. */
309
+ interface IngestRecord {
310
+ table: string;
311
+ /** `MERGE` overlays the given fields on the stored row (projection widening). */
312
+ op: 'CREATE' | 'UPDATE' | 'DELETE' | 'MERGE';
313
+ id: string;
314
+ record: any;
315
+ }
316
+ /**
317
+ * What the boot-time prime needs from the client: which tables to walk, how
318
+ * to recognise a snapshot written under a different schema, and which rows'
319
+ * local `_00_rv` must not be reported as the server's.
320
+ */
321
+ interface CircuitPrimeContext {
322
+ tables: string[];
323
+ schemaHash: string;
324
+ /** Encoded ids with an unsettled local mutation (their `_00_rv` was bumped
325
+ * locally and may exceed the server's next version). */
326
+ pendingIds: Set<string>;
327
+ /** Each table's client column set (`columnFingerprints`). An engine that
328
+ * keeps bodies across schema changes resets the versions of a table whose
329
+ * set changed before they are read, so its rows are fetched again whole. */
330
+ columnFingerprints?: Record<string, string>;
331
+ /** Receives every `(id, rv)` the prime put into the circuit, per table, so
332
+ * the sync layer can skip re-downloading bodies it already has. */
333
+ onVersions?: (table: string, entries: [string, number][]) => void;
334
+ }
335
+ /** Storage key of the circuit snapshot inside the local store. */
336
+
179
337
  declare class StreamProcessorService {
180
338
  events: EventSystem<StreamProcessorEvents>;
181
339
  private db;
182
- private persistenceClient;
183
340
  private logger;
184
341
  private processor;
185
342
  private isInitialized;
@@ -187,7 +344,21 @@ declare class StreamProcessorService {
187
344
  private batching;
188
345
  private batchBuffer;
189
346
  private sessionAuth;
190
- constructor(events: EventSystem<StreamProcessorEvents>, db: LocalDatabaseService, persistenceClient: PersistenceClient, logger: Logger);
347
+ private stateGeneration;
348
+ private persistState;
349
+ private persistCircuit;
350
+ private checkpointMs;
351
+ private checkpointTimer;
352
+ private snapshotDirty;
353
+ private dirtyRows;
354
+ private hideHandler;
355
+ private checkpointInFlight;
356
+ private projection;
357
+ private primed;
358
+ private schemaHash;
359
+ private widenQueue;
360
+ private widenPending;
361
+ constructor(events: EventSystem<StreamProcessorEvents>, db: LocalStore, logger: Logger);
191
362
  /**
192
363
  * Add a receiver for stream updates.
193
364
  * Multiple receivers can be registered (DataManager, DevTools, etc.)
@@ -196,23 +367,21 @@ declare class StreamProcessorService {
196
367
  private notifyUpdates;
197
368
  private dispatchUpdates;
198
369
  /**
199
- * Ingest a batch of record changes as a single bulk operation, firing only
200
- * one coalesced `StreamUpdate` per affected query once every record has been
201
- * ingested (instead of one update per record). Use this whenever multiple
202
- * records land at once — e.g. sync fetching N missing rows — so a list query
203
- * re-runs and the UI re-renders once for the whole batch rather than
204
- * row-by-row.
370
+ * Ingest a batch of record changes, firing one coalesced `StreamUpdate` per
371
+ * affected query once every record has been ingested. Use this whenever
372
+ * multiple records land at once (sync fetching N rows, the boot prime).
373
+ *
374
+ * The batch is fed to the wasm side in chunks of {@link INGEST_CHUNK}: one
375
+ * circuit step per chunk (a step walks every registered view, so per-record
376
+ * ingest paid that fixed cost N times), but never the whole batch at once,
377
+ * because the wasm side has to hold every parsed row of a call at the same
378
+ * time and wasm32 dlmalloc never returns that peak.
205
379
  *
206
- * Internally opens a coalescing window, ingests each record, then flushes;
207
- * processor state is persisted once for the whole batch. No-op for an empty
208
- * batch.
380
+ * Returns the records that were ingested. A chunk that fails is reported
381
+ * and skipped, not retried (a retry would double-apply whatever the failed
382
+ * step already committed), and the remaining chunks still run.
209
383
  */
210
- ingestMany(records: Array<{
211
- table: string;
212
- op: 'CREATE' | 'UPDATE' | 'DELETE';
213
- id: string;
214
- record: any;
215
- }>): void;
384
+ ingestMany(records: IngestRecord[]): IngestRecord[];
216
385
  /**
217
386
  * Open a coalescing window. While open, the per-record stream updates
218
387
  * emitted by `ingest` are buffered (one entry per queryHash) instead of
@@ -234,7 +403,87 @@ declare class StreamProcessorService {
234
403
  * This must be called before using other methods.
235
404
  */
236
405
  init(): Promise<void>;
237
- loadState(): Promise<void>;
406
+ /**
407
+ * Drop the current WASM processor and start a fresh, empty circuit. Used on
408
+ * local-bucket switches: the old circuit holds the previous user's rows AND
409
+ * views registered with the previous `$auth` context, so neither may survive.
410
+ * Deliberately loads nothing: the snapshot in the store being swapped away
411
+ * from belongs to the previous bucket; the caller primes the new bucket's
412
+ * circuit (`primeFromLocal`) once its store is open, and the DataModule
413
+ * rebind re-registers every live view against this fresh processor. Caller
414
+ * must re-seed `setPermissions` afterwards (a fresh circuit default-denies
415
+ * every table).
416
+ */
417
+ reset(): Promise<void>;
418
+ /**
419
+ * Release the wasm circuit and stop checkpointing. Call when the client is
420
+ * torn down; a recreated client (provider remount, HMR) would otherwise stack
421
+ * one full circuit per instance.
422
+ */
423
+ dispose(): void;
424
+ /**
425
+ * Explicitly run the wasm-bindgen destructor. Guarded: stale wasm builds may
426
+ * not expose `free`, and a double free must not take the app down.
427
+ */
428
+ private freeProcessor;
429
+ /** Toggle circuit-state persistence (shared-tabs follower/leader role). */
430
+ setPersistenceEnabled(enabled: boolean): void;
431
+ /**
432
+ * Snapshot persistence (`persistCircuit`). When on, the circuit's store is
433
+ * written to the local store on a checkpoint interval and when the page
434
+ * goes hidden, and restored by {@link primeFromLocal} on the next boot.
435
+ */
436
+ configureCircuitPersistence(enabled: boolean, checkpointMs?: number): void;
437
+ /**
438
+ * Field projection (`circuitProjection`, default on). Takes effect on the
439
+ * next processor (`init`/`reset`) and on rows written after that.
440
+ */
441
+ configureProjection(enabled: boolean): void;
442
+ private applyProjection;
443
+ /** Resolves once the boot-time prime has finished (or was skipped). */
444
+ whenPrimed(): Promise<void>;
445
+ /**
446
+ * Fill the circuit from the LOCAL store, in the background.
447
+ *
448
+ * With a usable snapshot: install it under whatever views have registered
449
+ * meanwhile (`load_store_state` re-primes them), then `reconcile` each table
450
+ * against the store's `(id, rv)` list so rows deleted since the checkpoint
451
+ * are stepped out and only rows added or changed since are read back and
452
+ * ingested. Without one: read every row and ingest it, chunked.
453
+ *
454
+ * Either way the circuit ends up equal to the local store without touching
455
+ * the network, so the first sync diff is a real delta rather than "fetch
456
+ * everything". The returned promise never rejects; `whenPrimed` gates on it.
457
+ */
458
+ primeFromLocal(ctx: CircuitPrimeContext): Promise<void>;
459
+ private runPrime;
460
+ /** Publish wasm updates produced outside an ingest (restore, reconcile). */
461
+ private dispatchWasmUpdates;
462
+ /**
463
+ * Record that the circuit changed by `rows` rows. Cheap; the snapshot is
464
+ * deferred to the checkpoint timer and skipped entirely when `persistCircuit`
465
+ * is off.
466
+ */
467
+ private markSnapshotDirty;
468
+ private startCheckpoints;
469
+ /** Stop checkpointing and drop the visibility listeners. */
470
+ stopCheckpoints(): void;
471
+ /**
472
+ * Write the circuit's store to the local store as a snapshot. Compacts the
473
+ * row arena first when dead bytes outweigh live ones. Serialised: a second
474
+ * call while one is in flight joins it. No-op unless persistence is on, this
475
+ * tab owns the store, and the engine can hold a snapshot.
476
+ */
477
+ checkpoint(reason?: string): Promise<void>;
478
+ private runCheckpoint;
479
+ /**
480
+ * Projection widening: a newly registered view evaluates fields that rows
481
+ * already in the circuit were stored without. Merge just those fields in,
482
+ * table by table, from the local store. The view registered against what
483
+ * was present and converges as the merges step through.
484
+ */
485
+ private scheduleWiden;
486
+ private runWiden;
238
487
  /**
239
488
  * Seed per-table `select` permission predicates ({ [table]: whereText }).
240
489
  * Must run after the processor exists and before any `register_view`, else
@@ -252,13 +501,12 @@ declare class StreamProcessorService {
252
501
  * "requires $auth but registration params lack it".
253
502
  */
254
503
  setSessionAuth(authId: string | null, access: string | null): void;
255
- saveState(): Promise<void>;
256
504
  /**
257
505
  * Ingest a record change into the processor.
258
506
  * Emits 'stream_update' event if materialized views are affected.
259
507
  * @param isOptimistic true = local mutation (increment versions), false = remote sync (keep versions)
260
508
  */
261
- ingest(table: string, op: 'CREATE' | 'UPDATE' | 'DELETE', id: string, record: any): WasmStreamUpdate[];
509
+ ingest(table: string, op: IngestRecord['op'], id: string, record: any): WasmStreamUpdate[];
262
510
  /**
263
511
  * Register a new query plan.
264
512
  * Emits 'stream_update' with the initial result.
@@ -271,728 +519,240 @@ declare class StreamProcessorService {
271
519
  private normalizeValue;
272
520
  }
273
521
  //#endregion
274
- //#region src/modules/cache/types.d.ts
275
- type RecordWithId = Record<string, any> & {
276
- id: RecordId<string>;
277
- };
278
- interface QueryConfig$1 {
279
- queryHash: string;
280
- surql: string;
281
- params: Record<string, any>;
282
- ttl: QueryTimeToLive | Duration;
283
- lastActiveAt: Date;
284
- }
285
- interface CacheRecord {
286
- table: string;
287
- op: 'CREATE' | 'UPDATE' | 'DELETE';
288
- record: RecordWithId;
289
- version: number;
290
- }
291
- //#endregion
292
- //#region src/modules/cache/index.d.ts
293
- /**
294
- * CacheModule - Centralized storage and DBSP ingestion
295
- *
296
- * Single responsibility: Handle all local storage operations and DBSP ingestion.
297
- * This module acts as the bridge between data operations and persistence.
298
- */
299
- declare class CacheModule implements StreamUpdateReceiver {
300
- private local;
301
- private streamProcessor;
302
- private logger;
303
- private streamUpdateCallback;
304
- private versionLookups;
305
- constructor(local: LocalDatabaseService, streamProcessor: StreamProcessorService, streamUpdateCallback: (update: StreamUpdate) => void, logger: Logger$1);
306
- /**
307
- * Implements StreamUpdateReceiver interface
308
- * Called directly by StreamProcessor when views change
309
- */
310
- onStreamUpdate(update: StreamUpdate): void;
311
- lookup(recordId: string): number;
312
- /**
313
- * Save a single record to local DB and ingest into DBSP
314
- * Used by mutations (create/update)
315
- */
316
- save(cacheRecord: CacheRecord, skipDbInsert?: boolean): Promise<void>;
317
- /**
318
- * Save multiple records in a batch
319
- * More efficient than calling save() multiple times
320
- * Used by sync operations
321
- */
322
- saveBatch(records: CacheRecord[], skipDbInsert?: boolean): Promise<void>;
323
- /**
324
- * Delete a record from local DB and ingest deletion into DBSP
325
- */
326
- delete(table: string, id: string, skipDbDelete?: boolean, recordData?: Record<string, any>): Promise<void>;
327
- /**
328
- * Register a query with DBSP to create a materialized view
329
- * Returns the initial result array
330
- */
331
- registerQuery(config: QueryConfig$1): {
332
- localArray: RecordVersionArray;
333
- registrationTimings?: {
334
- parseMs: number;
335
- planMs: number;
336
- snapshotMs: number;
337
- };
338
- };
339
- /**
340
- * Unregister a query from DBSP
341
- */
342
- unregisterQuery(queryHash: string): void;
343
- }
344
- //#endregion
345
- //#region src/modules/data/index.d.ts
522
+ //#region src/utils/index.d.ts
523
+ declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
346
524
  /**
347
- * DataModule - Unified query and mutation management
348
- *
349
- * Merges the functionality of QueryManager and MutationManager.
350
- * Uses CacheModule for all storage operations.
525
+ * Convert plain text to simple HTML paragraphs.
526
+ * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
351
527
  */
352
- declare class DataModule<S extends SchemaStructure> {
353
- private cache;
354
- private local;
355
- private schema;
356
- private streamDebounceTime;
357
- private activeQueries;
358
- private pendingQueries;
359
- private subscriptions;
360
- private statusSubscriptions;
361
- private mutationCallbacks;
362
- private debounceTimers;
363
- private logger;
364
- /**
365
- * Optional observer notified whenever a query's fetch status changes.
366
- * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
367
- * settable field (rather than a constructor arg) because DevTools is
368
- * constructed after DataModule.
369
- */
370
- onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
371
- /**
372
- * Optional observer invoked when a still-subscribed query's TTL heartbeat
373
- * fires (~90% of the TTL). Wired by Sp00kyClient to
374
- * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
375
- * row's `lastActiveAt` so an actively-watched query never expires. Settable
376
- * field (not a constructor arg) because the sync engine is wired after
377
- * DataModule is constructed — mirrors `onQueryStatusChange`.
378
- */
379
- onHeartbeat?: (hash: QueryHash) => void;
380
- /**
381
- * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
382
- * viewport-windowed list cancelling an off-screen window) loses its last
383
- * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
384
- * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
385
- * instead of leaving it for the TTL sweep. The local view + state are freed in
386
- * {@link finalizeDeregister} only after that remote delete, so a fast
387
- * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
388
- */
389
- onDeregister?: (hash: QueryHash) => void;
390
- private sessionId;
391
- private currentUserId;
392
- constructor(cache: CacheModule, local: LocalDatabaseService, schema: S, logger: Logger$1, streamDebounceTime?: number);
393
- init(sessionId: string): Promise<void>;
394
- /**
395
- * Update the session salt used in query-id hashing. Call this when the
396
- * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
397
- * registered queries will get fresh, session-scoped IDs.
398
- */
399
- setSessionId(sessionId: string): void;
400
- /**
401
- * Update the authenticated user record id. Pass `null` on sign-out.
402
- * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
403
- * the poll route to the same per-user `_00_list_ref_user_<id>` the
404
- * SSP writes to.
405
- */
406
- setCurrentUserId(userId: string | null): void;
407
- /** Read-only view of the authenticated user id used for per-user
408
- * `_00_list_ref` routing. Other modules consult this so they pick the
409
- * same table name DataModule does. */
410
- getCurrentUserId(): string | null;
411
- /**
412
- * Register a query and return its hash for subscriptions
413
- */
414
- query<T extends TableNames<S>>(tableName: T, surqlString: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<QueryHash>;
415
- /**
416
- * Subscribe to query updates
417
- */
418
- subscribe(queryHash: string, callback: QueryUpdateCallback, options?: {
419
- immediate?: boolean;
420
- }): () => void;
421
- /**
422
- * Subscribe to a query's fetch-status changes (idle/fetching).
423
- * With `{ immediate: true }` the callback fires synchronously with the
424
- * current status (defaults to `idle` if the query isn't registered yet).
425
- */
426
- subscribeStatus(queryHash: string, callback: QueryStatusCallback, options?: {
427
- immediate?: boolean;
428
- }): () => void;
429
- /**
430
- * Set a query's fetch status and notify status observers (DevTools +
431
- * `subscribeStatus` listeners). No-op when the status is unchanged or the
432
- * query is unknown.
433
- */
434
- setQueryStatus(queryHash: string, status: QueryStatus): void;
435
- /**
436
- * Subscribe to mutations (for sync)
437
- */
438
- onMutation(callback: MutationCallback): () => void;
439
- /**
440
- * Handle stream updates from DBSP (via CacheModule)
441
- */
442
- onStreamUpdate(update: StreamUpdate): Promise<void>;
443
- private materializeRecords;
444
- private processStreamUpdate;
445
- /**
446
- * Compute p55/p90/p99 from a rolling window of materialization samples.
447
- * Returns nulls for any percentile that has no samples yet so SurrealDB
448
- * `option<float>` columns stay NONE rather than 0 before the first ingest.
449
- */
450
- private computeMaterializationPercentiles;
451
- /** Record a per-phase timing sample (ms) on a query's rolling window. */
452
- private recordPhase;
453
- /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
454
- recordRemoteFetch(hash: string, ms: number): void;
455
- /**
456
- * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
457
- * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
458
- */
459
- recordFrontendTiming(hash: string, ms: number): void;
460
- /**
461
- * Build the per-query processing-time breakdown surfaced to the DevTools panel
462
- * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
463
- * the rest come from the per-phase rolling windows + one-shot registration timings.
464
- */
465
- phaseTimings(q: QueryState): QueryTimings;
466
- /**
467
- * Get query state (for sync and devtools)
468
- */
469
- getQueryByHash(hash: string): QueryState | undefined;
470
- /**
471
- * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
472
- * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
473
- * We gate on `remoteArray`, not local `records`: a windowed query is often
474
- * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
475
- * but it still hasn't loaded its own full window from the server — so it should
476
- * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
477
- */
478
- isCold(hash: string): boolean;
479
- /**
480
- * Walk a hydrated record's fields and append any EMBEDDED child records to
481
- * `batch` (recursing for nested related fields). An embedded child is a
482
- * value that is itself a record — a non-null object whose `id` is a
483
- * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
484
- * bare `RecordId` (a foreign-key reference) or any other value is skipped,
485
- * so this never mistakes a FK column for an embedded body. Children are
486
- * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
487
- * to their table's real columns (which strips the alias/related fields).
488
- * `seen` dedupes within the batch.
489
- */
490
- private collectEmbeddedChildren;
491
- /**
492
- * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
493
- * surql run directly) so the query DISPLAYS immediately, while the full realtime
494
- * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
495
- * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
496
- * `remoteArray` so windowed queries materialize the correct window (no sparse
497
- * local-circuit issue). Runs at most once per query (the `hydrated` flag).
498
- */
499
- applyHydration(hash: string, rows: RecordWithId[]): Promise<void>;
500
- /** True while ≥1 live subscriber is watching this query (refcount guard). */
501
- hasSubscribers(hash: string): boolean;
502
- /**
503
- * Opt-in eager teardown for a query whose LAST subscriber just left — used by
504
- * viewport-windowed lists to cancel off-screen windows instead of leaving
505
- * their remote views to expire on the TTL sweep. No-op while any subscriber
506
- * remains (refcount). Only enqueues the remote cleanup here; the local WASM
507
- * view + in-memory state are freed in {@link finalizeDeregister} after the
508
- * remote delete completes, so a re-subscribe in between aborts/heals it.
509
- *
510
- * NOTE: most queries should NOT use this — the default keep-alive on
511
- * unsubscribe avoids re-registration churn on navigation.
512
- */
513
- deregisterQuery(hash: string): void;
514
- /**
515
- * Final local teardown after the remote `_00_query` row was deleted: free the
516
- * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
517
- * (`cleanupQuery`) guarantees no subscriber remains.
518
- */
519
- finalizeDeregister(hash: string): void;
520
- /**
521
- * Get query state by id (for sync and devtools)
522
- */
523
- getQueryById(id: RecordId<string>): QueryState | undefined;
524
- /**
525
- * Get all active queries (for devtools)
526
- */
527
- getActiveQueries(): QueryState[];
528
- getActiveQueryHashes(): QueryHash[];
529
- updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void>;
530
- updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void>;
531
- /**
532
- * Called after a query's initial sync completes.
533
- * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
534
- */
535
- notifyQuerySynced(queryHash: string): Promise<void>;
536
- run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, data: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
537
- /**
538
- * Create a new record
539
- */
540
- create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
541
- /**
542
- * Update an existing record
543
- */
544
- update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
545
- /**
546
- * Delete a record
547
- */
548
- delete(table: string, id: string): Promise<void>;
549
- /**
550
- * Rollback a failed optimistic create by deleting the record locally
551
- */
552
- rollbackCreate(recordId: RecordId, tableName: string): Promise<void>;
553
- /**
554
- * Rollback a failed optimistic update by restoring the previous record state
555
- */
556
- rollbackUpdate(recordId: RecordId, tableName: string, beforeRecord: Record<string, unknown>): Promise<void>;
557
- /**
558
- * Remove a record from all active query states and notify subscribers
559
- */
560
- private removeRecordFromQueries;
561
- private createAndRegisterQuery;
562
- private createNewQuery;
563
- private calculateHash;
564
- private startTTLHeartbeat;
565
- private replaceRecordInQueries;
566
- }
528
+ declare function textToHtml(text: string): string;
567
529
  /**
568
- * Parse update options to generate push event options
530
+ * Helper for retrying DB operations with exponential backoff
569
531
  */
570
532
  //#endregion
571
- //#region src/modules/sync/sync.d.ts
572
- /**
573
- * Tunables for `Sp00kySync` construction.
574
- */
575
- interface Sp00kySyncOptions {
576
- /**
577
- * Cadence (ms) for the `_00_list_ref` poll fallback that catches
578
- * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
579
- * values fall back to the default; see
580
- * {@link resolveListRefPollInterval}.
581
- */
582
- refSyncIntervalMs?: number;
583
- /**
584
- * Enable realtime sync for unauthenticated clients against the shared
585
- * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
586
- * Defaults to `false`.
587
- */
588
- anonymousLiveQueries?: boolean;
589
- /**
590
- * Consecutive failed sync rounds before sync health flips to `degraded`.
591
- * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
592
- * Defaults to `3`.
593
- */
594
- degradeAfterConsecutiveFailures?: number;
595
- }
533
+ //#region src/modules/crdt/mirror.d.ts
596
534
  /**
597
- * The main synchronization engine for Sp00ky.
598
- * Handles the bidirectional synchronization between the local database and the remote backend.
599
- * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
600
- * @template S The schema structure type.
535
+ * The plain text a `@crdt` field shows as its column value, rendered the same
536
+ * way the SSP fold renders it (`packages/ssp-node/src/crdt/mirror.rs`).
601
537
  */
602
- declare class Sp00kySync<S extends SchemaStructure> {
603
- private local;
604
- private remote;
605
- private cache;
606
- private dataModule;
607
- private schema;
608
- private upQueue;
609
- private downQueue;
610
- private isInit;
611
- private logger;
612
- private syncEngine;
613
- /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
614
- * from `this.events`, which carries Sp00kySync-level events like
615
- * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
616
- get engineEvents(): SyncEventSystem;
617
- private scheduler;
618
- private wasDisconnected;
619
- events: SyncEventSystem;
620
- private currentUserId;
621
- private refMode;
622
- private readonly anonLiveEnabled;
623
- private currentLiveQueryUuid;
624
- private liveQueryUnsubscribe;
625
- private listRefPollTimer;
626
- private listRefPollRunning;
627
- readonly refSyncIntervalMs: number;
628
- private listRefIdleStreak;
629
- private stillRemoteStreaks;
630
- private lastLiveEventAt;
631
- private _liveRetryCount;
632
- get liveRetryCount(): number;
633
- get isSyncing(): boolean;
634
- get pendingMutationCount(): number;
635
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
636
- private readonly degradeAfterFailures;
637
- private consecutiveSyncFailures;
638
- private syncHealthStatus;
639
- private lastSyncErrorKind;
640
- private lastSyncErrorMessage;
641
- private selfHealTimer;
642
- private selfHealAttempts;
643
- private static readonly SELF_HEAL_BASE_MS;
644
- private static readonly SELF_HEAL_MAX_MS;
645
- /** Current sync-health snapshot. */
646
- get syncHealth(): SyncHealth;
647
- /**
648
- * Observe sync health. The callback fires immediately with the current
649
- * status and again on every healthy↔degraded transition. Returns an
650
- * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
651
- */
652
- subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
653
- private emitSyncHealth;
654
- /**
655
- * Fed by the scheduler once per drained sync round. Individual failures are
656
- * absorbed by the queue's retry; only a run of `degradeAfterFailures`
657
- * consecutive failures flips the status to `degraded`, and the next clean
658
- * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
659
- * is 0).
660
- */
661
- private recordSyncOutcome;
662
- /**
663
- * Begin self-heal retries (no-op if already running). Started on the
664
- * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
665
- */
666
- private startSelfHeal;
667
- private scheduleSelfHeal;
668
- private stopSelfHeal;
669
- constructor(local: LocalDatabaseService, remote: RemoteDatabaseService, cache: CacheModule, dataModule: DataModule<S>, schema: S, logger: Logger$1, options?: Sp00kySyncOptions);
670
- /**
671
- * Initializes the synchronization system.
672
- * Starts the scheduler and initiates the initial sync cycles.
673
- * @throws Error if already initialized.
674
- */
675
- init(): Promise<void>;
676
- /**
677
- * Push the authenticated user's record id from the parent client's
678
- * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
679
- * any) and re-registers it under the new user's dedicated table so
680
- * SurrealDB binds the permission rule under the post-flip auth
681
- * context. Pass `null` on sign-out.
682
- *
683
- * The dedicated `_00_list_ref_user_<id>` table is created lazily by
684
- * the SSP when the first query registration arrives, which may be
685
- * concurrent with this call. We retry the LIVE registration with a
686
- * short backoff so a "table not found" race resolves without
687
- * surfacing as a permanent auth-loading hang.
688
- */
689
- setCurrentUserId(userId: string | null): Promise<void>;
690
- private startListRefPoll;
691
- private stopListRefPoll;
692
- /**
693
- * One poll cycle: refetch `_00_list_ref` for every active query. Returns
694
- * whether ANY query's remoteArray actually changed — the scheduler uses this
695
- * to drive the adaptive idle backoff.
696
- */
697
- private pollListRefForActiveQueries;
698
- /**
699
- * Pull the upstream list_ref entries for `queryHash`, diff them
700
- * against the local `remoteArray` cache, sync any added/updated rows
701
- * through the SyncEngine, then persist the new remoteArray. This is
702
- * the same shape `createRemoteQuery` does for its initial fetch and
703
- * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
704
- * it on a timer as a fallback for missed LIVE notifications.
705
- */
706
- private refetchListRefForQuery;
707
- /**
708
- * Resolve the current `_00_list_ref` table name for the active auth
709
- * context. Public so the `createRemoteQuery` initial-fetch path can
710
- * read from the right per-user table.
711
- *
712
- * Reads the user id from `DataModule` rather than the local mirror,
713
- * because `DataModule.setCurrentUserId` runs synchronously from the
714
- * auth callback (before any `await`), whereas `sync.setCurrentUserId`
715
- * is async — the userQuery's initial fetch can fire between those
716
- * two points and we need the correct table name immediately.
717
- */
718
- listRefTable(): string;
719
- private killRefLiveQuery;
720
- private restartRefLiveQuery;
721
- private subscribeToReconnect;
722
- private startRefLiveQueries;
723
- private handleRemoteListRefChange;
724
- /**
725
- * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
726
- * `parent` set) for a `.related()` query. Unlike primary rows, child rows
727
- * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
728
- * keep the child BODY fresh in the local cache so the in-browser SSP's
729
- * subquery-table dependency re-materializes the parent view.
730
- *
731
- * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
732
- * no-op: a child leaving this query's set must not delete a body another
733
- * query may still show (see `syncSubqueryChildren` deletion-safety note);
734
- * a genuine record delete propagates via the normal delete path.
735
- */
736
- private handleRemoteSubqueryChange;
737
- /**
738
- * Enqueues a 'down' event (from remote to local) for processing.
739
- * @param event The DownEvent to enqueue.
740
- */
741
- enqueueDownEvent(event: DownEvent): void;
742
- private processUpEvent;
743
- private handleRollback;
744
- private processDownEvent;
745
- /**
746
- * Synchronizes a specific query by hash.
747
- * Compares local and remote version arrays and fetches differences.
748
- * @param hash The hash of the query to sync.
749
- */
750
- syncQuery(hash: string): Promise<void>;
751
- /**
752
- * Run a sync for a single query while reflecting its fetch status. Marks the
753
- * query `fetching` for the duration when the diff actually pulls records
754
- * (added/updated), then resets to `idle` in a `finally` so a failed sync
755
- * never leaves a query stuck `fetching`. Part A's notification coalescing
756
- * means the single resulting UI update lands after this completes.
757
- */
758
- private runSyncForQuery;
759
- /**
760
- * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
761
- * Sync must not re-fetch/re-insert these — the remote delete is async, so the
762
- * server's `_00_list_ref` still lists them until it's processed, and the diff
763
- * would otherwise resurrect a just-deleted record.
764
- */
765
- private getPendingDeleteIds;
766
- /**
767
- * Enqueues a list of mutations (up events) to be sent to the remote.
768
- * @param mutations Array of UpEvents (create/update/delete) to enqueue.
769
- */
770
- enqueueMutation(mutations: UpEvent[]): Promise<void>;
771
- private registerQuery;
772
- private createRemoteQuery;
773
- /**
774
- * Sync the BODIES of a `.related()` query's subquery child rows into the
775
- * local cache, separately from the primary window array. The SSP writes
776
- * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
777
- * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
778
- * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
779
- * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
780
- * them into the local DB AND the in-browser SSP, whose subquery-table
781
- * dependency then re-materializes the parent view (no explicit notify).
782
- *
783
- * Deletion safety: we pass `removed: []` deliberately. A child body can be
784
- * shared by other queries; letting `handleRemovedRecords` delete one that
785
- * merely left THIS query's child set would clobber data another query still
786
- * shows. Genuine record deletes flow through the normal delete path; a
787
- * lingering orphan body is invisible (the correlated WHERE stops matching).
788
- *
789
- * Kept off `runSyncForQuery` on purpose so child fetches never flip the
790
- * query to `fetching` or skew its DevTools timings.
791
- */
792
- private syncSubqueryChildren;
793
- heartbeatQuery(queryHash: string): Promise<void>;
794
- private cleanupQuery;
795
- }
796
- //#endregion
797
- //#region src/modules/auth/events/index.d.ts
798
- declare const AuthEventTypes: {
799
- readonly AuthStateChanged: "AUTH_STATE_CHANGED";
800
- };
801
- type AuthEventTypeMap = {
802
- [AuthEventTypes.AuthStateChanged]: EventDefinition<typeof AuthEventTypes.AuthStateChanged, string | null>;
803
- };
804
- type AuthEventSystem = EventSystem<AuthEventTypeMap>;
805
- declare function createAuthEventSystem(): AuthEventSystem;
806
- //#endregion
807
- //#region src/modules/auth/index.d.ts
808
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
809
- type MapColumnType<T extends ColumnSchema> = T['optional'] extends true ? TypeNameToTypeMap[T['type']] | undefined : TypeNameToTypeMap[T['type']];
810
- 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;
811
- declare class AuthService<S extends SchemaStructure> {
812
- private schema;
813
- private remote;
814
- private persistenceClient;
815
- private logger;
816
- token: string | null;
817
- currentUser: any | null;
818
- isAuthenticated: boolean;
819
- /**
820
- * The record-access method name for the current session (e.g. `"account"`),
821
- * derived from the token's `AC` claim. Consumed by the in-browser SSP's
822
- * permission injection so `$access`-gated table predicates resolve locally,
823
- * mirroring the server's `$access`. Null when logged out.
824
- */
825
- access: string | null;
826
- isLoading: boolean;
827
- private events;
828
- get eventSystem(): AuthEventSystem;
829
- constructor(schema: S, remote: RemoteDatabaseService, persistenceClient: PersistenceClient, logger: Logger$1);
830
- init(): Promise<void>;
831
- getAccessDefinition<Name extends keyof S['access']>(name: Name): AccessDefinition | undefined;
832
- /**
833
- * Subscribe to auth state changes.
834
- * callback is called immediately with current value and whenever validation status changes.
835
- */
836
- subscribe(cb: (userId: string | null) => void): () => void;
837
- private notifyListeners;
838
- /**
839
- * Check for existing session and validate
840
- */
841
- check(accessToken?: string): Promise<void>;
842
- /**
843
- * Sign out and clear session
844
- */
845
- signOut(): Promise<void>;
846
- private setSession;
847
- /** Fallback when the token carries no `AC` claim: if the schema defines
848
- * exactly one record-access method, assume the session used it. */
849
- private defaultAccessName;
850
- signUp<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signup'>): Promise<void>;
851
- signIn<Name extends keyof S['access'] & string>(accessName: Name, params: ExtractAccessParams<S, Name, 'signIn'>): Promise<void>;
852
- }
538
+ type CrdtKind = 'text' | 'prosemirror';
853
539
  //#endregion
854
540
  //#region src/modules/crdt/crdt-field.d.ts
855
541
  declare const CURSOR_COLORS: string[];
856
542
  declare function cursorColorFromName(name: string): string;
543
+ /** What a field handle needs from the manager that owns its session. */
544
+ interface CrdtFieldHost {
545
+ pushPresence(state: Uint8Array): void;
546
+ }
547
+ /**
548
+ * An open collaborative field: the Loro document an editor binds to. Edits
549
+ * made on it are sent as the client's own edit-log rows; other clients' rows
550
+ * are imported into it as they arrive. Every open of the same field in one tab
551
+ * shares this document.
552
+ */
857
553
  declare class CrdtField {
858
- private fieldName;
859
- private doc;
860
- private pushTimer;
861
- private local;
862
- private remote;
863
- private recordId;
864
- private sessionId;
865
- private unsubscribe;
866
- private lastPushTime;
867
- private lastCursorPushTime;
868
- private loadedFromCrdt;
869
- private pushRetryCount;
870
- private logger;
871
- private cursorsEnabled;
872
- /** Remote-push debounce. Local writes happen immediately on every Loro
873
- * update; the remote UPSERT is coalesced over this window. Configured
874
- * via `Sp00kyConfig.crdtDebounceMs`, default 500. */
875
- private remoteDebounceMs;
554
+ readonly table: string;
555
+ readonly recordId: string;
556
+ readonly fieldName: string;
557
+ readonly kind: CrdtKind;
558
+ readonly cursorsEnabled: boolean;
559
+ private readonly doc;
560
+ private readonly host;
876
561
  private _onCursorUpdate;
877
562
  private pendingCursorUpdate;
878
- /** Callback set by the editor to receive remote cursor updates.
879
- * Any cursor data that arrived before this callback was set will be replayed. */
880
- set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
881
- get onCursorUpdate(): ((data: Uint8Array) => void) | null;
882
- constructor(fieldName: string, cursorsEnabled: boolean, initialState?: Uint8Array, logger?: Logger$1 | null);
563
+ private loaded;
564
+ private loadedListeners;
565
+ constructor(table: string, recordId: string, fieldName: string, kind: CrdtKind, cursorsEnabled: boolean, doc: LoroDoc, host: CrdtFieldHost);
883
566
  getDoc(): LoroDoc;
884
- /** Whether the LoroDoc was loaded from saved CRDT state */
567
+ /** Whether the document holds anything yet (local state or edits). */
885
568
  hasContent(): boolean;
886
- startSync(local: LocalDatabaseService, remote: RemoteDatabaseService, recordId: string, sessionId: string, debounceMs: number): void;
887
- stopSync(): void;
888
- importRemote(state: Uint8Array): void;
889
- exportSnapshot(): Uint8Array;
890
- /** Push this session's cursor blob into the parent row at
891
- * `<field>.cursors[$sid]`. No-op when cursors aren't enabled on this
892
- * field — the editor still calls this method optimistically, but
893
- * without `@cursor` on the schema there's nowhere to store the blob.
894
- * The UPDATE itself fires the parent table's LIVE feed, so other
895
- * browsers receive the cursor change without a separate `_00_rv` bump. */
896
- pushCursorState(encoded: Uint8Array): Promise<void>;
897
- /** Import remote cursor state (called by CrdtManager from LIVE SELECT) */
898
- importRemoteCursor(base64State: string): void;
899
- private scheduleRemotePush;
900
- /** SET path inside a parent row for the current snapshot. `@crdt`-only
901
- * fields hold the snapshot directly (`<field>`); `@crdt @cursor`
902
- * fields hold a `{ state, cursors }` object so the snapshot lives at
903
- * `<field>.state` next to per-session cursor blobs. */
904
- private statePath;
905
- /** Mirror the LoroDoc snapshot into the parent row locally. Runs on
906
- * every local update and every remote import so reloads (online or
907
- * offline) see the freshest content immediately. Failures are
908
- * swallowed — a stale local write must never block user input. */
909
- private persistLocal;
910
- private pushToRemote;
569
+ /**
570
+ * Whether the document is known: this device had it, it was handed a draft,
571
+ * or the server answered (with content, or that it has none yet). Until then
572
+ * an empty document means "not loaded", not "empty": show the column's text
573
+ * instead, and do not bind an editor (an editor binding an empty document
574
+ * creates structure that competes with the real one).
575
+ */
576
+ isLoaded(): boolean;
577
+ /** Runs `cb` once the field is loaded (at once if it already is). Returns
578
+ * an unsubscribe. */
579
+ onLoaded(cb: () => void): () => void;
580
+ /** @internal The manager calls this when the document became known. */
581
+ markLoaded(): void;
582
+ /** Publish this session's presence (an `EphemeralStore` encoding, e.g. the
583
+ * editor's cursor). No-op unless the field is `@cursor`. */
584
+ pushCursorState(encoded: Uint8Array): void;
585
+ /** Called with every other session's presence blob. A blob that arrives
586
+ * before the editor sets this is replayed when it does. */
587
+ set onCursorUpdate(cb: ((data: Uint8Array) => void) | null);
588
+ get onCursorUpdate(): ((data: Uint8Array) => void) | null;
589
+ /** @internal Deliver one remote presence blob. */
590
+ deliverPresence(data: Uint8Array): void;
911
591
  }
912
592
  //#endregion
913
593
  //#region src/modules/crdt/index.d.ts
914
594
  /**
915
- * CrdtManager manages active CrdtField instances and their sync channels.
595
+ * Collaborative (`@crdt`) fields.
916
596
  *
917
- * Collaborative state lives in two dedicated tables (defined in
918
- * `apps/cli/src/meta_tables_remote.surql`):
919
- * - `_00_crdt` { record_id, field, state } — one row per (record, field)
920
- * - `_00_cursor` { record_id, session_id, field, state } — one row per
921
- * (record, session, field)
597
+ * Each open field is a Loro document. The client never sends the document,
598
+ * only its own edits: every batch of local edits becomes one row of the
599
+ * generated `<table>__crdt_log` table, written through the ordinary outbox
600
+ * (so it survives offline, reloads and retries), and every client receives
601
+ * the other rows through an ordinary query and merges them. Nobody writes the
602
+ * canonical state but the SSP, which folds the log into `_00_crdt_doc` and the
603
+ * parent field's plain text (see `packages/ssp-node/src/crdt`).
922
604
  *
923
- * Splitting them off the parent row is what makes offline edits mergeable:
924
- * each (record, field) gets its own row, so concurrent offline writes don't
925
- * collide on the parent's last-write-wins semantics.
605
+ * A row is imported only if it passes the acceptance rule the fold applies
606
+ * (`./acceptance`), so this tab and the server always hold the same ops.
926
607
  *
927
- * Cross-browser delivery still rides the parent table's existing LIVE feed
928
- * to avoid SurrealDB v3 LIVE bugs around dereference-based permission rules
929
- * (issues 3602, 4026). On every meta UPSERT the writer also bumps the
930
- * parent's `_00_rv` (a no-op assignment); that fires the parent's LIVE
931
- * feed, and the receiver pulls the matching `_00_crdt` / `_00_cursor` rows
932
- * via subquery. Permission inheritance happens server-side via
933
- * `record_id.id != NONE` (SELECT) and `fn::can_update_record` (UPDATE).
608
+ * Edits carry this tab's Loro peer id, claimed for the signed-in user in
609
+ * `_00_crdt_peer` before the first row is sent; the database refuses a row
610
+ * whose peer its author does not own. A tab picks a fresh peer per session.
611
+ * Offline, edits stay local (and in the local snapshot) until the claim and
612
+ * the outbox can go through.
934
613
  */
614
+ /** A followed query: stop following it, and know when the server answered. */
615
+ interface Watch {
616
+ stop: () => void;
617
+ /** Resolves once the server's membership for the query is known and its
618
+ * rows have landed locally (never rejects; may never resolve offline). */
619
+ settled: Promise<void>;
620
+ }
621
+ /** The runtime pieces the manager needs from the client facade. */
622
+ interface CrdtPorts {
623
+ /** Register a query on `table` filtered by `where` and follow its rows. */
624
+ watch(table: string, where: Record<string, unknown>, onRows: (rows: Record<string, unknown>[]) => void): Promise<Watch>;
625
+ /** Optimistic create through the outbox. */
626
+ create(id: string, data: Record<string, unknown>): Promise<unknown>;
627
+ }
935
628
  declare class CrdtManager {
936
629
  private schema;
937
630
  private local;
938
631
  private remote;
632
+ /** First edit after a quiet spell: wait this long to batch the burst. */
939
633
  private debounceMs;
940
- private fields;
941
- private liveByTable;
942
- private pendingLive;
634
+ /** Shortest gap between two sends of one field, while edits keep coming. */
635
+ private sendIntervalMs;
636
+ private sessions;
637
+ private opening;
638
+ /** Closes still saving their field's local state, by session key. */
639
+ private saving;
640
+ private ports;
943
641
  private logger;
944
- private sessionId;
945
- constructor(schema: SchemaStructure, local: LocalDatabaseService, remote: RemoteDatabaseService, logger: Logger$1, debounceMs?: number);
946
- /** Set the session id that scopes this client's cursor entries. Must be
947
- * called before `open()` for cursors to be pushed under a stable key.
948
- * Passed in from `sp00ky.ts` at boot (it already fetches `session::id()`
949
- * for the data-module salt). */
950
- setSessionId(sessionId: string): void;
951
- /**
952
- * Open a CRDT field for collaborative editing.
642
+ private peer;
643
+ /** The current peer's claim: settled once the database holds it for us. */
644
+ private claim;
645
+ private claimRetry;
646
+ private connectionUnsubscribes;
647
+ constructor(schema: SchemaStructure, local: LocalStore, remote: RemoteDatabaseService, logger: Logger$1, /** First edit after a quiet spell: wait this long to batch the burst. */
648
+ debounceMs?: number, /** Shortest gap between two sends of one field, while edits keep coming. */
649
+ sendIntervalMs?: number);
650
+ /** Hand over the runtime ports. Called once by the client facade. */
651
+ attach(ports: CrdtPorts): void;
652
+ /**
653
+ * A new signed-in identity (boot, sign-in, sign-out): edits from here on
654
+ * belong to it, under a peer it claims. Edits already made stay with the
655
+ * peer they were made under.
656
+ */
657
+ setSessionId(_salt: string): void;
658
+ dispose(): void;
659
+ /**
660
+ * Open a collaborative field. Every open of the same field shares one
661
+ * document; close each open with {@link close}.
953
662
  *
954
- * @param table - Table name
955
- * @param recordId - Full record ID (e.g., "thread:abc")
956
- * @param field - Field name (e.g., "title", "content")
957
- * @param fallbackText - Current plain text from the record, used to seed the
958
- * LoroDoc if no CRDT state exists yet (migration path)
959
- */
960
- open(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
961
- close(table: string, recordId: string, field: string): void;
962
- closeAll(): void;
963
- /** Ensure a single `LIVE SELECT * FROM <table>` is running, shared across
964
- * every open CrdtField on `table`. */
965
- private ensureTableSubscription;
966
- /** Apply a parent-row payload from a non-LIVE source (e.g. the
967
- * list_ref-driven sync engine, when the cross-user LIVE on the
968
- * parent table is filtered out by the SurrealDB cross-session
969
- * permission gap). Same semantics as the internal `dispatchRow`. */
970
- applyRow(table: string, row: Record<string, unknown>): void;
971
- /** Dispatch a parent-row LIVE event to every open CrdtField on that
972
- * record. Each open field reads its slice of the row directly — the
973
- * CRDT snapshot is a column on the parent now, so there is no
974
- * follow-up subquery. */
975
- private dispatchRow;
976
- /** One-shot remote fetch for a row whose CRDT field hasn't synced
977
- * locally yet (fresh device, memory-backed local DB after reload, …).
978
- * Used by `open()` when the local read came up empty. Subsequent
979
- * cross-browser updates ride `dispatchRow` via the parent LIVE feed. */
980
- private fetchAndDispatchRow;
981
- /** Schema lookup: does `<table>.<field>` carry a `@cursor` annotation?
982
- * Determines the on-disk shape (plain snapshot vs. `{ state, cursors }`). */
983
- private fieldHasCursor;
984
- /** Pull the LoroDoc snapshot bytes out of a row slice. For `@crdt`-only
985
- * the slice IS the snapshot (Uint8Array); for `@crdt @cursor` it's
986
- * `{ state, cursors }` where `state` carries the snapshot bytes. */
987
- private extractSnapshot;
988
- private killTableSubscription;
989
- private makeKey;
990
- /**
991
- * Throws if `<table>.<field>` is not annotated `@crdt` in the schema. Catches
992
- * typos, removed annotations, and stale schema codegen at the call site instead
993
- * of silently producing a non-CRDT writer.
994
- */
995
- private assertCrdtField;
663
+ * `draft` (from {@link createDraft}) hands over edits made before the record
664
+ * existed: they are merged in and sent like this tab's own.
665
+ */
666
+ open(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField>;
667
+ /**
668
+ * A detached document for a field of a record that does not exist yet (a
669
+ * "new thread" form). Nothing is sent; pass it to {@link open} once the
670
+ * record is created and its edits become the record's first ones.
671
+ */
672
+ createDraft(table: string, field: string): Promise<CrdtField>;
673
+ private adopt;
674
+ /** Close one open. The last close of a field resolves once its unsent
675
+ * edits are in the outbox, or once they are saved on the device when the
676
+ * server does not answer in time (offline: at once). */
677
+ close(table: string, recordId: string, field: string): Promise<void>;
678
+ /** Close every field. `flush: false` (a bucket switch) drops unsent edits
679
+ * from this session's memory; they stay in the local snapshot of the
680
+ * bucket they belong to. */
681
+ closeAll(options?: {
682
+ flush?: boolean;
683
+ }): void;
684
+ private fieldSpec;
685
+ private start;
686
+ private stop;
687
+ /**
688
+ * Wait for server-bound `work`, at most {@link SERVER_WAIT_MS}, and not at
689
+ * all while disconnected: a remote call made then queues behind the
690
+ * reconnect for up to the query timeout, and an offline "new thread" form
691
+ * must not hang on it. The work itself goes on either way.
692
+ */
693
+ private serverWait;
694
+ private ingest;
695
+ /** Mark the field loaded once its content arrived, or the server answered
696
+ * both reads (the published document and the log) with nothing. */
697
+ private checkLoaded;
698
+ private tryImport;
699
+ private refetchCanonical;
700
+ /**
701
+ * A first open reads the published document and the log at the same time,
702
+ * and a fold landing between the two hides the field from both: it
703
+ * publishes its snapshot, then deletes the rows the log query was about to
704
+ * return, after the published-document read came back empty. Nothing seen
705
+ * means nothing to verify, so the editor stayed empty until the next edit
706
+ * (a second device opening a just-created thread, under e2e load). Once the
707
+ * log has answered, a field that is still empty reads the published
708
+ * document again: the fold that took its rows committed before deleting
709
+ * them. Once per open; `first` is the first read (null with a local copy or
710
+ * a draft, which need none).
711
+ */
712
+ private recheckCanonical;
713
+ private scheduleVerify;
714
+ /**
715
+ * After a fold: compare this device's document with the one the server
716
+ * published, at the version the server published. Missing ops (rows this
717
+ * device never got before they were folded away) are repaired by merging
718
+ * the published snapshot in. The same ops giving a different state cannot
719
+ * be merged away; that is logged.
720
+ */
721
+ private verify;
722
+ /**
723
+ * Arm the send. Edits go out on a steady cadence while they keep coming:
724
+ * the first one after a quiet spell waits `debounceMs` (one row for the
725
+ * burst), later ones at least `sendIntervalMs` after the previous send. An
726
+ * armed timer is never pushed back, so continuous typing cannot hold the
727
+ * edits; it is only brought forward (`delay`, e.g. 0 on reconnect).
728
+ */
729
+ private scheduleFlush;
730
+ /** Send what is unsent. A call while a send runs queues one more after it,
731
+ * so edits made during that send are not left waiting for the next edit. */
732
+ private flush;
733
+ /** Send every own peer's ops that are not in the outbox yet, one row per
734
+ * peer. Only the peer's own ops travel (`updates-in-range`): a plain
735
+ * `from: version` export would carry ops imported from others too, and
736
+ * the acceptance rule refuses such a row. */
737
+ private sendOwnEdits;
738
+ private retryLater;
739
+ /** Claim this session's peer once; a failure (offline, signed out) is retried. */
740
+ private ensureClaimed;
741
+ private claimPeer;
742
+ private localId;
743
+ private readLocal;
744
+ private schedulePersist;
745
+ /** Save the merged document. Another tab may have saved too: merge with
746
+ * its snapshot rather than overwrite it, and keep the further of the two
747
+ * outbox marks per peer. */
748
+ private persist;
749
+ private pushPresence;
750
+ /** Presence is the latest state only: no outbox, no offline queue. */
751
+ private sendPresence;
752
+ /** Remove this session's cursor when the field closes; the server's TTL
753
+ * sweep covers a tab that never gets here. */
754
+ private dropPresence;
755
+ private ingestPresence;
996
756
  }
997
757
  //#endregion
998
758
  //#region src/modules/feature-flag/index.d.ts
@@ -1004,6 +764,15 @@ interface FeatureFlagOptions {
1004
764
  fallback?: string;
1005
765
  ttl?: QueryTimeToLive;
1006
766
  }
767
+ /**
768
+ * A locally forced variant. Applies to THIS browser only and is never sent to
769
+ * the server — the assignment in `_00_user_feature` is untouched, so clearing
770
+ * the override restores whatever the server says.
771
+ */
772
+ interface FeatureFlagOverride {
773
+ variant: string;
774
+ payload?: unknown;
775
+ }
1007
776
  declare class FeatureFlagHandle {
1008
777
  readonly key: string;
1009
778
  readonly fallback: string | undefined;
@@ -1023,10 +792,26 @@ declare class FeatureFlagHandle {
1023
792
  onClose(cb: () => void): void;
1024
793
  close(): void;
1025
794
  }
795
+ /** The slice of the query engine this module drives: register a live query
796
+ * locally, ask for its remote registration, subscribe to its rows. */
797
+ interface LiveQueryPort$1 {
798
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
799
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
800
+ immediate?: boolean;
801
+ }): () => void;
802
+ }
803
+ interface RemoteRegisterPort$1 {
804
+ enqueueDownEvent(event: {
805
+ type: 'register';
806
+ payload: {
807
+ hash: string;
808
+ };
809
+ }): void;
810
+ }
1026
811
  interface FeatureFlagModuleDeps<S extends SchemaStructure> {
1027
- dataModule: DataModule<S>;
1028
- sync: Sp00kySync<S>;
1029
- auth: AuthService<S>;
812
+ dataModule: LiveQueryPort$1;
813
+ sync: RemoteRegisterPort$1;
814
+ auth: Pick<AuthService<S>, 'subscribe'>;
1030
815
  logger: Logger$1;
1031
816
  }
1032
817
  declare class FeatureFlagModule<S extends SchemaStructure> {
@@ -1040,6 +825,7 @@ declare class FeatureFlagModule<S extends SchemaStructure> {
1040
825
  private ttl;
1041
826
  private snapshots;
1042
827
  private loaded;
828
+ private overrides;
1043
829
  constructor(deps: FeatureFlagModuleDeps<S>);
1044
830
  init(): void;
1045
831
  feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
@@ -1051,15 +837,1316 @@ declare class FeatureFlagModule<S extends SchemaStructure> {
1051
837
  private ensureStarted;
1052
838
  /** Live query result → per-key snapshots → push to every active handle. */
1053
839
  private applyRecords;
840
+ /**
841
+ * Force `key` to `variant` in THIS browser. Pass `null` to clear.
842
+ *
843
+ * Nothing is written to the server: the `_00_user_feature` assignment is
844
+ * untouched, so clearing restores whatever the server says. Persisted to
845
+ * localStorage on the page origin, so it survives a reload.
846
+ */
847
+ setLocalOverride(key: string, variant: string | null, payload?: unknown): void;
848
+ clearLocalOverrides(): void;
849
+ getLocalOverrides(): Record<string, FeatureFlagOverride>;
850
+ /** The assignment for `key`, with any local override taking precedence. */
851
+ private resolve;
852
+ private pushAll;
853
+ private loadOverrides;
854
+ private persistOverrides;
855
+ }
856
+ //#endregion
857
+ //#region src/modules/app-release/index.d.ts
858
+ interface AppReleaseSnapshot {
859
+ /** Latest announced version for the app, or undefined when no row exists. */
860
+ version: string | undefined;
861
+ /** Clients should clear SW/caches when reloading onto this version. */
862
+ cacheBust: boolean;
863
+ /** Clients should reload/update immediately instead of asking. */
864
+ mandatory: boolean;
865
+ releasedAt: string | undefined;
866
+ }
867
+ interface AppReleaseOptions {
868
+ ttl?: QueryTimeToLive;
869
+ }
870
+ declare class AppReleaseHandle {
871
+ readonly app: string;
872
+ private latest;
873
+ private listeners;
874
+ private onCloseFn;
875
+ private closed;
876
+ constructor(app: string);
877
+ set(snapshot: AppReleaseSnapshot): void;
878
+ snapshot(): AppReleaseSnapshot;
879
+ version(): string | undefined;
880
+ /** True when the announced version is semver-newer than `currentVersion`. */
881
+ updateAvailable(currentVersion: string): boolean;
882
+ subscribe(cb: (s: AppReleaseSnapshot) => void): () => void;
883
+ onClose(cb: () => void): void;
884
+ close(): void;
885
+ }
886
+ /** The slice of the query engine this module drives: register a live query
887
+ * locally, ask for its remote registration, subscribe to its rows. */
888
+ interface LiveQueryPort {
889
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
890
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: {
891
+ immediate?: boolean;
892
+ }): () => void;
893
+ }
894
+ interface RemoteRegisterPort {
895
+ enqueueDownEvent(event: {
896
+ type: 'register';
897
+ payload: {
898
+ hash: string;
899
+ };
900
+ }): void;
901
+ }
902
+ interface AppReleaseModuleDeps<S extends SchemaStructure> {
903
+ dataModule: LiveQueryPort;
904
+ sync: RemoteRegisterPort;
905
+ auth: Pick<AuthService<S>, 'subscribe'>;
906
+ logger: Logger$1;
907
+ }
908
+ declare class AppReleaseModule<S extends SchemaStructure> {
909
+ private deps;
910
+ private logger;
911
+ private handles;
912
+ private authUnsubscribe;
913
+ private lastUserId;
914
+ private querySubscription;
915
+ private starting;
916
+ private ttl;
917
+ private snapshots;
918
+ private loaded;
919
+ constructor(deps: AppReleaseModuleDeps<S>);
920
+ init(): void;
921
+ release(app: string, options?: AppReleaseOptions): AppReleaseHandle;
922
+ closeAll(): Promise<void>;
923
+ private refresh;
924
+ private teardownQuery;
925
+ private ensureStarted;
926
+ private applyRecords;
1054
927
  }
1055
928
  //#endregion
1056
- //#region src/sp00ky.d.ts
929
+ //#region src/kernel/events.d.ts
930
+ /**
931
+ * Inbound events. Everything that can start a saga arrives as one of these
932
+ * through the runtime router: public API calls, adapter callbacks, timers,
933
+ * and `dispatch` effects from other sagas.
934
+ */
935
+ type RuntimeEvent = {
936
+ type: 'EnsureRegistered';
937
+ requireAuth?: boolean;
938
+ attempt?: number;
939
+ } | {
940
+ type: 'RegisterRemote';
941
+ hash: QueryHash;
942
+ retry?: boolean;
943
+ } | {
944
+ type: 'ReleaseSuperseded';
945
+ ids: RecordId$1<string>[];
946
+ } | {
947
+ type: 'SyncOutcome';
948
+ ok: boolean;
949
+ error?: unknown;
950
+ } | {
951
+ type: 'AckPrune';
952
+ } | {
953
+ type: 'ReadDirtyMembership';
954
+ } | {
955
+ type: 'RecoverLostView';
956
+ hash: QueryHash;
957
+ } | {
958
+ type: 'ReadMembership';
959
+ hashes: QueryHash[];
960
+ } | {
961
+ type: 'FetchRows';
962
+ } | {
963
+ type: 'Materialize';
964
+ hash: QueryHash;
965
+ } | {
966
+ type: 'MaterializeDirty';
967
+ } | {
968
+ type: 'LifecycleTick';
969
+ } | {
970
+ type: 'GcTick';
971
+ } | {
972
+ type: 'Drain';
973
+ } | {
974
+ type: 'FlushWrite';
975
+ key: string;
976
+ } | {
977
+ type: 'PeerWriteExpired';
978
+ id: string;
979
+ } | {
980
+ type: 'FlushPendingWrites';
981
+ } | {
982
+ type: 'AdoptPendingWrites';
983
+ } | {
984
+ type: 'PollTick';
985
+ } | {
986
+ type: 'SelfHealTick';
987
+ } | {
988
+ type: 'HeartbeatNow';
989
+ } | {
990
+ type: 'StartRemote';
991
+ } | {
992
+ type: 'PrimeCircuit';
993
+ } | {
994
+ type: 'VersionsPrimed';
995
+ entries: Array<readonly [string, number]>;
996
+ } | {
997
+ type: 'WarmBlobs';
998
+ } | {
999
+ type: 'AuthFlip';
1000
+ userId: string | null;
1001
+ } | {
1002
+ type: 'BucketSwitch';
1003
+ target: string;
1004
+ } | {
1005
+ type: 'PageHide';
1006
+ } | {
1007
+ type: 'ConnectionChanged';
1008
+ state: ConnectionState;
1009
+ } | {
1010
+ type: 'StreamUpdate';
1011
+ update: StreamUpdate;
1012
+ } | {
1013
+ type: 'LiveStart';
1014
+ } | {
1015
+ type: 'LiveChange';
1016
+ hashes: QueryHash[];
1017
+ rows?: InlineRow[];
1018
+ deltas?: EdgeDelta[];
1019
+ } | {
1020
+ type: 'TabRole';
1021
+ role: 'solo' | 'leader' | 'follower';
1022
+ } | {
1023
+ type: 'TabMessage';
1024
+ message: unknown;
1025
+ };
1026
+ type OutEvent = {
1027
+ type: 'query:records';
1028
+ hash: QueryHash;
1029
+ records: ReadonlyArray<Record<string, unknown>>;
1030
+ } | {
1031
+ type: 'query:status';
1032
+ hash: QueryHash;
1033
+ status: QueryStatus;
1034
+ } | {
1035
+ type: 'query:authority';
1036
+ hash: QueryHash;
1037
+ known: boolean;
1038
+ } | {
1039
+ type: 'query:view-lost';
1040
+ hash: QueryHash;
1041
+ } | {
1042
+ type: 'query:evicted';
1043
+ hash: QueryHash;
1044
+ } | {
1045
+ type: 'mutation:event';
1046
+ event: unknown;
1047
+ } | {
1048
+ type: 'mutation:settled';
1049
+ mutationId: string;
1050
+ recordId: string;
1051
+ eventType: string;
1052
+ } | {
1053
+ type: 'mutation:rolled-back';
1054
+ mutationId: string;
1055
+ recordId: string;
1056
+ eventType: string;
1057
+ error: string;
1058
+ } | {
1059
+ type: 'tray:changed';
1060
+ count: number;
1061
+ } | {
1062
+ type: 'health:changed';
1063
+ health: SyncHealth;
1064
+ } | {
1065
+ type: 'activity:changed';
1066
+ fetching: number;
1067
+ pending: number;
1068
+ } | {
1069
+ type: 'tabs:broadcast';
1070
+ message: unknown;
1071
+ } | {
1072
+ type: 'tabs:sendTo';
1073
+ tabId: string;
1074
+ message: unknown;
1075
+ } | {
1076
+ type: 'log';
1077
+ level: 'debug' | 'info' | 'warn' | 'error';
1078
+ message: string;
1079
+ data?: unknown;
1080
+ };
1081
+ //#endregion
1082
+ //#region src/state/lifecycle.d.ts
1083
+ /**
1084
+ * The query lifecycle as one explicit machine.
1085
+ *
1086
+ * `phase` answers "where do this query's rows come from":
1087
+ * - `cold` never resolved on this device: rows come from a local
1088
+ * predicate scan (or the SSP local window), bindings show a loader.
1089
+ * - `cached` a durable `_00_view` row was found: rows come from that id-set.
1090
+ * - `live` a server membership set was accepted this session.
1091
+ * - `view-lost` the server's `_00_query` row vanished while we held
1092
+ * membership; rows are kept, a re-registration is under way.
1093
+ *
1094
+ * `remote` tracks the server-side registration, `fetchDepth` is the refcount
1095
+ * behind `status: 'fetching'`, `notified` says whether subscribers received
1096
+ * at least one materialization this registration.
1097
+ *
1098
+ * `answered` says subscribers have been handed the rows of a known membership
1099
+ * (the server's, or the durable one of an earlier session) at least once:
1100
+ * a materialization ran past `cold`, with no body of a server set still to
1101
+ * download, and the membership it drew was still the one in state when it
1102
+ * committed. Only a re-seed (a new entry, a bucket switch) clears it, so a
1103
+ * reconnect or a lost view does not send a painted query back to loading.
1104
+ * It is what the bindings' `isAuthoritative()` mirrors (see `isAnswered`):
1105
+ * a `cached` seed or a freshly applied server set alone is not enough,
1106
+ * because `records` is still empty (or stale) until `materialize` paints, and
1107
+ * "known and empty" read in that beat made apps create rows that existed.
1108
+ *
1109
+ * `backgroundDepth` is the part of `fetchDepth` that re-verifies rows the
1110
+ * query already shows: a registration of a query that is not `cold`. It still
1111
+ * holds `status: 'fetching'` (results are not yet confirmed), but it is not
1112
+ * traffic the user waits on, so the activity indicator leaves it out.
1113
+ */
1114
+ type QueryPhase = 'cold' | 'cached' | 'live' | 'view-lost';
1115
+ type RemotePhase = 'unregistered' | 'registering' | 'registered' | 'failed';
1116
+ interface QueryLifecycle {
1117
+ readonly phase: QueryPhase;
1118
+ readonly remote: RemotePhase;
1119
+ readonly fetchDepth: number;
1120
+ readonly backgroundDepth: number;
1121
+ readonly notified: boolean;
1122
+ readonly answered: boolean;
1123
+ }
1124
+ //#endregion
1125
+ //#region src/kernel/effects.d.ts
1126
+ type Vars = Record<string, unknown>;
1127
+ /** What the in-browser SSP needs to build a local view. */
1128
+ interface RegisterPlan {
1129
+ queryHash: string;
1130
+ surql: string;
1131
+ params: Vars;
1132
+ ttl: string;
1133
+ tableName: string;
1134
+ involvedTables?: string[];
1135
+ }
1136
+ /** One statement's outcome of a multi-statement remote request. */
1137
+ type StatementResult = {
1138
+ status: 'OK';
1139
+ result: unknown;
1140
+ } | {
1141
+ status: 'ERR';
1142
+ error: string;
1143
+ };
1144
+ /** One entry of an `all` fan-out result (allSettled semantics). */
1145
+
1146
+ /**
1147
+ * Effects are data. A saga yields one and gets its result back on the next
1148
+ * `next()`; the interpreter (client/runtime) is the only place they execute.
1149
+ */
1150
+ type Effect = {
1151
+ kind: 'local.query';
1152
+ sql: string;
1153
+ vars?: Vars;
1154
+ epoch?: number;
1155
+ } | {
1156
+ kind: 'local.select';
1157
+ plan: QueryPlan;
1158
+ params?: Vars;
1159
+ paintKey?: string;
1160
+ } | {
1161
+ kind: 'local.peekSelect';
1162
+ plan: QueryPlan;
1163
+ params?: Vars;
1164
+ paintKey?: string;
1165
+ } | {
1166
+ kind: 'local.execute';
1167
+ query: SealedQuery<unknown>;
1168
+ vars?: Vars;
1169
+ epoch?: number;
1170
+ } | {
1171
+ kind: 'local.getById';
1172
+ table: string;
1173
+ id: unknown;
1174
+ } | {
1175
+ kind: 'local.upsert';
1176
+ table: string;
1177
+ id: unknown;
1178
+ data: Record<string, unknown>;
1179
+ mode: 'replace' | 'merge';
1180
+ } | {
1181
+ kind: 'local.delete';
1182
+ table: string;
1183
+ id: unknown;
1184
+ } | {
1185
+ kind: 'local.epoch';
1186
+ } | {
1187
+ kind: 'remote.query';
1188
+ sql: string;
1189
+ vars?: Vars;
1190
+ timeoutMs?: number;
1191
+ } | {
1192
+ kind: 'remote.live';
1193
+ table: string;
1194
+ } | {
1195
+ kind: 'remote.kill';
1196
+ uuid: string;
1197
+ } | {
1198
+ kind: 'ssp.register';
1199
+ plan: RegisterPlan;
1200
+ } | {
1201
+ kind: 'ssp.unregister';
1202
+ hash: string;
1203
+ } | {
1204
+ kind: 'ssp.ingest';
1205
+ records: IngestRecord[];
1206
+ } | {
1207
+ kind: 'timer.set';
1208
+ key: string;
1209
+ ms: number;
1210
+ event: RuntimeEvent;
1211
+ } | {
1212
+ kind: 'timer.clear';
1213
+ key: string;
1214
+ } | {
1215
+ kind: 'state.read';
1216
+ select: (s: ClientState) => unknown;
1217
+ } | {
1218
+ kind: 'state.update';
1219
+ fn: (s: ClientState) => ClientState;
1220
+ } | {
1221
+ kind: 'state.wait';
1222
+ until: (s: ClientState) => boolean;
1223
+ } | {
1224
+ kind: 'now';
1225
+ } | {
1226
+ kind: 'id';
1227
+ scope: IdScope;
1228
+ } | {
1229
+ kind: 'hash';
1230
+ input: string;
1231
+ } | {
1232
+ kind: 'emit';
1233
+ event: OutEvent;
1234
+ } | {
1235
+ kind: 'dispatch';
1236
+ event: RuntimeEvent;
1237
+ } | {
1238
+ kind: 'all';
1239
+ effects: Effect[];
1240
+ } | {
1241
+ kind: 'service';
1242
+ name: ServiceName;
1243
+ args: unknown[];
1244
+ };
1245
+ /** `mutation`: an outbox row id. `salt`: a query-key salt. `owner`: a page's anonymous-view owner secret. */
1246
+ type IdScope = 'mutation' | 'salt' | 'owner';
1247
+ /**
1248
+ * Calls into the legacy services that are adapters, not state: auth, tabs,
1249
+ * blobs, migrator, crdt, persistence, the SSP lifecycle, the remote socket.
1250
+ * A saga names the call; the runtime binds it to the real service.
1251
+ */
1252
+ interface ServiceCalls {
1253
+ 'hint.read': () => string | null;
1254
+ 'hint.write': (bucketId: string) => void;
1255
+ /** The salt (and owner secret) this tab's previous page left, if minted for `authId`. */
1256
+ 'salt.take': (authId: string | null) => {
1257
+ salt: string;
1258
+ owner: string | null;
1259
+ } | null;
1260
+ 'salt.leave': (salt: string, authId: string | null, owner: string | null) => void;
1261
+ 'local.connect': (bucketId: string) => Promise<void>;
1262
+ 'local.switchStore': (bucketId: string) => Promise<void>;
1263
+ 'local.beginSwitch': () => () => void;
1264
+ 'local.currentBucketId': () => string;
1265
+ 'local.usesSurqlSchema': () => boolean;
1266
+ 'local.dropBucket': (bucketId: string) => Promise<void>;
1267
+ 'migrator.provision': () => Promise<void>;
1268
+ 'blobs.start': (bucketId: string) => Promise<void>;
1269
+ 'blobs.setNamespace': (bucketId: string) => Promise<void>;
1270
+ 'blobs.clear': () => Promise<void>;
1271
+ 'ssp.init': () => Promise<void>;
1272
+ 'ssp.setPermissions': () => void;
1273
+ 'ssp.setSessionAuth': (authId: string | null, access: string | null) => void;
1274
+ 'ssp.prime': (pendingIds: string[]) => Promise<void>;
1275
+ 'ssp.reset': () => Promise<void>;
1276
+ 'ssp.setPersistence': (enabled: boolean) => void;
1277
+ 'auth.restoreSession': () => Promise<string | null>;
1278
+ 'auth.init': () => Promise<void>;
1279
+ 'auth.sessionAuthId': () => string | null;
1280
+ 'auth.access': () => string | null;
1281
+ 'auth.token': () => string | null;
1282
+ 'auth.currentUser': () => Record<string, unknown> | null;
1283
+ 'auth.consumeEndedImpersonation': () => string | null;
1284
+ 'remote.connect': () => Promise<void>;
1285
+ /** The platform reports no network at all (a browser's `navigator.onLine === false`). */
1286
+ 'net.offline': () => boolean;
1287
+ 'remote.releaseViews': (ids: unknown[]) => void;
1288
+ /** `session::id()` of every socket this page has had, oldest first. */
1289
+ 'remote.sessionIds': () => readonly string[];
1290
+ 'supervisor.start': () => void;
1291
+ 'tabs.start': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1292
+ 'tabs.moveToBucket': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
1293
+ 'crdt.setSessionId': (sessionId: string) => void;
1294
+ 'crdt.closeAll': (flush: boolean) => void;
1295
+ 'persistence.set': (key: string, value: unknown) => Promise<void>;
1296
+ 'features.init': () => void;
1297
+ 'releases.init': () => void;
1298
+ 'window.attach': () => void;
1299
+ }
1300
+ type ServiceName = keyof ServiceCalls;
1301
+ /** Typed constructors. Each is one line so the saga reads like the plan. */
1302
+ //#endregion
1303
+ //#region src/kernel/saga.d.ts
1304
+ /**
1305
+ * A saga is a generator that yields effects and receives their results. It
1306
+ * holds no references to adapters or state, so it can be driven by the real
1307
+ * interpreter or by `testing/run-pure` with canned results.
1308
+ */
1309
+ type Saga<R> = Generator<Effect, R, any>;
1310
+ /**
1311
+ * Lanes bound concurrency without a queue object per lane:
1312
+ * - `serial`: runs strictly one at a time per key, in arrival order.
1313
+ * - `dedupe`: a request while one run is active joins that run instead of
1314
+ * starting another.
1315
+ * The bookkeeping is a pure value so the policy is unit-testable; the runtime
1316
+ * owns the promises.
1317
+ */
1318
+ type Lane = {
1319
+ kind: 'serial';
1320
+ key: string;
1321
+ } | {
1322
+ kind: 'dedupe';
1323
+ key: string;
1324
+ };
1325
+ interface LaneState {
1326
+ readonly running: ReadonlySet<string>;
1327
+ readonly waiting: ReadonlyMap<string, number>;
1328
+ }
1329
+ //#endregion
1330
+ //#region src/state/client-state.d.ts
1331
+ type Row = Record<string, unknown>;
1332
+ /** Everything a query is, minus anything that changes after registration. */
1333
+ interface QueryDefinition {
1334
+ /** Session-salted `_00_query:<hash>` record id: the remote view id. */
1335
+ readonly id: RecordId<string>;
1336
+ readonly hash: QueryHash;
1337
+ /** Unsalted `sha256({surql, params})`: key of the durable `_00_view` row. */
1338
+ readonly viewKey: string;
1339
+ readonly surql: string;
1340
+ readonly params: Readonly<Record<string, unknown>>;
1341
+ readonly plan?: QueryPlan;
1342
+ readonly ttl: QueryTimeToLive;
1343
+ readonly ttlMs: number;
1344
+ readonly tableName: string;
1345
+ readonly createdAt: number;
1346
+ }
1347
+ type ServerViewState = 'materializing' | 'ready' | null;
1348
+ interface QueryTelemetry {
1349
+ readonly updateCount: number;
1350
+ readonly errorCount: number;
1351
+ readonly lastUpdatedAt: number | null;
1352
+ readonly materializationSamples: ReadonlyArray<number>;
1353
+ readonly lastIngestLatencyMs: number | null;
1354
+ readonly phaseSamples: Readonly<Record<string, ReadonlyArray<number>>>;
1355
+ readonly phaseLast: Readonly<Record<string, number | null>>;
1356
+ readonly registrationTimings: RegistrationTimings;
1357
+ }
1358
+ interface QueryEntry {
1359
+ readonly def: QueryDefinition;
1360
+ readonly lifecycle: QueryLifecycle;
1361
+ /** Server membership (ids + versions) or the durable seed. */
1362
+ readonly remoteArray: RecordVersionArray;
1363
+ /** The in-browser SSP view's id-set: local truth for "does this row match". */
1364
+ readonly localArray: RecordVersionArray;
1365
+ readonly subqueryRemoteArray: RecordVersionArray;
1366
+ readonly records: ReadonlyArray<Row>;
1367
+ readonly serverState: ServerViewState;
1368
+ readonly subscribers: number;
1369
+ readonly lastSubscriberLeftAt: number | null;
1370
+ readonly lastHeartbeatAt: number | null;
1371
+ readonly lastPolledAt: number | null;
1372
+ readonly registerAttempts: number;
1373
+ /**
1374
+ * Re-registrations issued because the `_00_query` row read as gone, since
1375
+ * the row was last seen. Paces the next one (see `applyMembership`).
1376
+ */
1377
+ readonly viewLostCount: number;
1378
+ /** When the paced re-registration is due; null when none is pending. */
1379
+ readonly viewLostRetryAt: number | null;
1380
+ readonly telemetry: QueryTelemetry;
1381
+ }
1382
+ type OutboxStatus = 'pending' | 'acked';
1383
+ /** In-memory mirror of one `_00_pending_mutations` row plus its push progress. */
1384
+ interface OutboxItem {
1385
+ readonly id: string;
1386
+ readonly type: MutationEventType;
1387
+ readonly recordId: string;
1388
+ readonly table: string;
1389
+ readonly status: OutboxStatus;
1390
+ readonly ackedAt: number | null;
1391
+ readonly attempts: number;
1392
+ /**
1393
+ * A request carrying this row may have committed without the answer
1394
+ * reaching this client: it threw a transport error, or the row was loaded
1395
+ * from the store, so a session that died mid-push may have sent it. Its
1396
+ * CREATE then accepts the row already on the server when that row holds
1397
+ * what it would write (see `remoteBatch`). Absent means false.
1398
+ */
1399
+ readonly inDoubt?: boolean;
1400
+ }
1401
+ type TabRole = 'solo' | 'leader' | 'follower';
1402
+ /** A debounced update accumulating locally until its flush writes the outbox row. */
1403
+ interface PendingWrite {
1404
+ readonly key: string;
1405
+ readonly table: string;
1406
+ readonly recordId: string;
1407
+ readonly data: Readonly<Record<string, unknown>>;
1408
+ readonly before: Readonly<Record<string, unknown>> | null;
1409
+ readonly firstAt: number;
1410
+ /** Its durable copy in `_00_pending_writes`; null when `flushOnHide` is off. */
1411
+ readonly mirrorId: string | null;
1412
+ }
1413
+ /**
1414
+ * A create or delete a channel peer sent, applied here before the server has
1415
+ * it (see `modules/channel`). Shown like an own optimistic write through the
1416
+ * overlay; when `expiresAt` passes it is either confirmed (the server's body
1417
+ * landed) or undone.
1418
+ */
1419
+ interface PeerWrite {
1420
+ readonly kind: 'create' | 'delete';
1421
+ readonly table: string;
1422
+ readonly expiresAt: number;
1423
+ }
1424
+ interface SyncSlice {
1425
+ readonly health: SyncHealth;
1426
+ readonly consecutiveFailures: number;
1427
+ readonly hasSyncedOnce: boolean;
1428
+ readonly selfHealAttempts: number;
1429
+ readonly pollIdleStreak: number;
1430
+ readonly lastReconnectRefetchAt: number | null;
1431
+ readonly needsResubscribe: boolean;
1432
+ readonly fetchAttempts: number;
1433
+ readonly liveUuid: string | null;
1434
+ readonly liveTable: string | null;
1435
+ readonly lanes: LaneState;
1436
+ }
1437
+ interface ClientState {
1438
+ readonly sessionId: string | null;
1439
+ readonly userId: string | null;
1440
+ /** The principal the current session salt was minted for. */
1441
+ readonly saltUserId: string | null;
1442
+ /**
1443
+ * This page's secret, sent with every registration (`$config.owner`). An
1444
+ * anonymous view answers only to the secret it was registered with, so it
1445
+ * lives as long as the page's views: a reconnect keeps it, and a reload
1446
+ * that keeps the salt keeps it too.
1447
+ */
1448
+ readonly ownerSecret: string | null;
1449
+ /** Latest bucket-switch target; an older switch that wakes up to a newer target skips. */
1450
+ readonly pendingBucket: string | null;
1451
+ readonly tabId: string;
1452
+ readonly tabRole: TabRole;
1453
+ readonly bucketId: string | null;
1454
+ readonly localReady: boolean;
1455
+ readonly primed: boolean;
1456
+ readonly queries: ReadonlyMap<QueryHash, QueryEntry>;
1457
+ /** Hashes whose local registration is in flight (dedupes concurrent `query()` calls). */
1458
+ readonly registering: ReadonlySet<QueryHash>;
1459
+ /** Re-read attempts per hash while the server reports a view as `materializing`. */
1460
+ readonly membershipReread: ReadonlyMap<QueryHash, number>;
1461
+ /** Local body versions (`_00_rv`) by encoded record id. */
1462
+ readonly versions: ReadonlyMap<string, number>;
1463
+ /**
1464
+ * What each durable `_00_view` row vouches for, by view key: its members
1465
+ * and subquery children. A body no row names is an orphan: it never paints
1466
+ * before the server answers and the GC deletes it.
1467
+ */
1468
+ readonly views: ReadonlyMap<string, ReadonlyArray<string>>;
1469
+ readonly outbox: ReadonlyArray<OutboxItem>;
1470
+ readonly pendingWrites: ReadonlyMap<string, PendingWrite>;
1471
+ /** Channel peers' unconfirmed creates and deletes, by record id. */
1472
+ readonly peerWrites: ReadonlyMap<string, PeerWrite>;
1473
+ readonly failedCount: number;
1474
+ /** Queries whose render inputs changed since their last materialization. */
1475
+ readonly dirty: ReadonlySet<QueryHash>;
1476
+ /** Queries whose server membership must be re-read. */
1477
+ readonly membershipDirty: ReadonlySet<QueryHash>;
1478
+ readonly sync: SyncSlice;
1479
+ }
1480
+ //#endregion
1481
+ //#region src/modules/ref-tables.d.ts
1482
+ type RefMode = 'single' | 'dedicated';
1483
+ /**
1484
+ * Sentinel user id for unauthenticated clients when anonymous live queries are
1485
+ * enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
1486
+ * so it can never collide with a real user id (those arrive as `user:<id>`);
1487
+ * both sides resolve it to the shared `_00_list_ref_anon` table.
1488
+ */
1489
+ //#endregion
1490
+ //#region src/query/env.d.ts
1491
+ /**
1492
+ * Static configuration the sagas read. Plain data, built once by the runtime
1493
+ * from `Sp00kyConfig`; sagas never see the config object itself.
1494
+ */
1495
+ interface SagaEnv {
1496
+ readonly schema: SchemaStructure;
1497
+ readonly refMode: RefMode;
1498
+ readonly anonLive: boolean;
1499
+ readonly remoteTimeoutMs: number;
1500
+ readonly pushTimeoutMs: number;
1501
+ readonly outboxBatchSize: number;
1502
+ readonly degradeAfter: number;
1503
+ readonly materializeDebounceMs: number;
1504
+ readonly pollBaseMs: number;
1505
+ readonly defaultTtlMs: number;
1506
+ }
1507
+ //#endregion
1508
+ //#region src/mutation/rows.d.ts
1509
+ interface FailedMutationRow {
1510
+ id: string;
1511
+ mutationType: MutationEventType;
1512
+ recordId: string;
1513
+ tableName: string;
1514
+ data?: Record<string, unknown>;
1515
+ beforeRecord?: Record<string, unknown> | null;
1516
+ error: {
1517
+ message: string;
1518
+ kind: 'application' | 'unreplayable';
1519
+ };
1520
+ attempts: number;
1521
+ createdAt: number;
1522
+ failedAt: number;
1523
+ revert: 'full' | 'partial' | 'none';
1524
+ }
1525
+ /**
1526
+ * Parse a record id READ BACK FROM THE STORE, stripping SurrealDB's `⟨⟩`
1527
+ * escaping (outbox ids contain `_`, so they come back escaped).
1528
+ */
1529
+ //#endregion
1530
+ //#region src/kernel/interpreter.d.ts
1531
+ /** The five adapters plus the pure ports, as the interpreter sees them. */
1532
+ interface Adapters {
1533
+ local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'peekSelect' | 'getById' | 'upsert' | 'delete'> & {
1534
+ readonly epoch: number;
1535
+ };
1536
+ remote: {
1537
+ queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
1538
+ /**
1539
+ * Subscribe to `LIVE SELECT * FROM <table>`; the callback receives the
1540
+ * changed query hashes, plus the changed rows themselves when the
1541
+ * subscription was opened with the body joined on (`liveInlineBodies`).
1542
+ */
1543
+ live(table: string, onChange: (hashes: string[], rows?: InlineRow[], deltas?: EdgeDelta[]) => void): Promise<string>;
1544
+ kill(uuid: string): Promise<void>;
1545
+ };
1546
+ ssp: {
1547
+ registerQueryPlan(plan: {
1548
+ queryHash: string;
1549
+ surql: string;
1550
+ params: Record<string, unknown>;
1551
+ ttl: Duration;
1552
+ lastActiveAt: Date;
1553
+ localArray: [];
1554
+ remoteArray: [];
1555
+ meta: {
1556
+ tableName: string;
1557
+ involvedTables?: string[];
1558
+ };
1559
+ }): StreamUpdate | undefined;
1560
+ unregisterQueryPlan(hash: string): void;
1561
+ ingestMany(records: IngestRecord[]): unknown;
1562
+ };
1563
+ timers: {
1564
+ set(key: string, ms: number, fire: () => void): void;
1565
+ clear(key: string): void;
1566
+ };
1567
+ clock: {
1568
+ now(): number;
1569
+ };
1570
+ ids: Record<IdScope, () => string>;
1571
+ hash(input: string): Promise<string>;
1572
+ services: ServiceCalls;
1573
+ }
1574
+ /** What the interpreter needs from the runtime: state, waiting, emitting, dispatching. */
1575
+ //#endregion
1576
+ //#region src/client/runtime.d.ts
1577
+ interface RuntimeOptions {
1578
+ env: SagaEnv;
1579
+ adapters: Adapters;
1580
+ logger: Logger$1;
1581
+ tabId: string;
1582
+ initialState?: ClientState;
1583
+ }
1584
+ /**
1585
+ * The one effectful object of the engine: holds the state, runs sagas on
1586
+ * lanes, fires timers, fans events out to subscribers and schedules
1587
+ * materialization for dirty queries. No decision logic lives here.
1588
+ */
1589
+ declare class Runtime {
1590
+ private stateValue;
1591
+ private readonly interpret;
1592
+ private readonly env;
1593
+ private readonly adapters;
1594
+ private readonly logger;
1595
+ private readonly serialLanes;
1596
+ private readonly dedupeLanes;
1597
+ private readonly waiters;
1598
+ private readonly recordSubs;
1599
+ private readonly statusSubs;
1600
+ private readonly authoritySubs;
1601
+ private readonly lastStatus;
1602
+ private readonly listeners;
1603
+ private readonly scheduledMaterialize;
1604
+ /** When each query last materialized, for the leading-edge throttle in `setState`. */
1605
+ private readonly materializedAt;
1606
+ private readonly timerKeys;
1607
+ private lastActivity;
1608
+ private lastHealth;
1609
+ private disposed;
1610
+ constructor(opts: RuntimeOptions);
1611
+ get state(): ClientState;
1612
+ /** Run a saga, optionally on a lane. Rejections propagate to the caller. */
1613
+ run<R>(saga: Saga<R>, opts?: {
1614
+ lane?: Lane;
1615
+ signal?: AbortSignal;
1616
+ }): Promise<R>;
1617
+ /** Route an event to its saga. Never rejects: failures are logged. */
1618
+ dispatch(event: RuntimeEvent): Promise<void>;
1619
+ private setState;
1620
+ waitFor(until: (s: ClientState) => boolean, signal?: AbortSignal): Promise<void>;
1621
+ /** Deliver an outbound event to its subscribers and listeners. */
1622
+ emit(event: OutEvent): void;
1623
+ private notify;
1624
+ private safely;
1625
+ /** Observe outbound events by type (`'*'` for all). */
1626
+ on(type: OutEvent['type'] | '*', cb: (event: OutEvent) => void): () => void;
1627
+ subscribe(hash: QueryHash, cb: QueryUpdateCallback, options?: {
1628
+ immediate?: boolean;
1629
+ }): () => void;
1630
+ subscribeStatus(hash: QueryHash, cb: QueryStatusCallback, options?: {
1631
+ immediate?: boolean;
1632
+ }): () => void;
1633
+ subscribeAuthority(hash: QueryHash, cb: QueryAuthorityCallback, options?: {
1634
+ immediate?: boolean;
1635
+ }): () => void;
1636
+ /** Apply a reducer outside a saga (facade conveniences such as timing reports). */
1637
+ update(reducer: (s: ClientState) => ClientState): void;
1638
+ dispose(): void;
1639
+ }
1640
+ //#endregion
1641
+ //#region src/services/tabs/coordinator.d.ts
1642
+ interface CoordinatorHooks {
1643
+ /** Become the store owner: spawn the worker, open the pool under the given
1644
+ * per-leadership lock. Returns the resulting health for db-ready relays.
1645
+ * `resumeHeld` = keep the existing live worker (broker-restart path). */
1646
+ adoptOwner(bucketId: string, opts: {
1647
+ workerLockName: string;
1648
+ allowMemoryFallback: boolean;
1649
+ forceTakeover: boolean;
1650
+ resumeHeld: boolean;
1651
+ }): Promise<StorageHealth>;
1652
+ /** Attach to a leader's worker through `dbPort`. */
1653
+ adoptAttached(dbPort: MessagePort, snapshot: {
1654
+ bucketId: string;
1655
+ storageHealth: StorageHealth;
1656
+ leadershipId: number;
1657
+ }): Promise<void>;
1658
+ /** We were leader and got demoted (zombie thaw / stale promotion): tear the
1659
+ * owned worker down so its SAH handles free up. */
1660
+ releaseOwnership(): Promise<void>;
1661
+ /** The leader (or its port) is gone; queue/park ops until a new role lands. */
1662
+ onLeaderLost(reason: string): void;
1663
+ /** Leader side: forward a follower's dbPort into the owned worker. */
1664
+ exposeClientPort(clientId: string, port: MessagePort): Promise<void>;
1665
+ removeClientPort(clientId: string): Promise<void>;
1666
+ /** Sync layer role changes (implemented in the sync module). */
1667
+ /** Synchronous leader WIRING. Must not block: the role is published and
1668
+ * `leader-ready` is sent right after it returns. */
1669
+ becomeSyncLeader(hub: LeaderSyncHub): void;
1670
+ /** The blocking half of the leader handover (outbox drain, LIVE restart),
1671
+ * run in the background once the tab is already a working leader. */
1672
+ resumeSyncLeaderDuties(): Promise<void>;
1673
+ becomeSyncFollower(forwarder: SyncForwarder): void;
1674
+ becomeSyncSolo(): void;
1675
+ /** Current storage health, for db-ready sent to late-joining followers. */
1676
+ currentStorageHealth(): StorageHealth;
1677
+ }
1678
+ /** Leader-side fan-out surface handed to the sync layer. The sync router
1679
+ * (modules/sync/tab-router.ts) registers itself as the message handler. */
1680
+ declare class LeaderSyncHub {
1681
+ readonly leadershipId: number;
1682
+ private logger;
1683
+ private followers;
1684
+ private seq;
1685
+ onFollowerMessage: ((tabId: TabId, msg: FollowerToLeaderMessage) => void) | null;
1686
+ onFollowerDetached: ((tabId: TabId) => void) | null;
1687
+ constructor(leadershipId: number, logger: Logger$1);
1688
+ attach(tabId: TabId, port: MessagePort): void;
1689
+ detach(tabId: TabId): void;
1690
+ detachAll(): void;
1691
+ sendTo(tabId: TabId, msg: LeaderToFollowerMessage): void;
1692
+ broadcast(msg: LeaderToFollowerMessage, exceptTabId?: TabId): void;
1693
+ /** Stamped ingest relay; seq lets followers detect gaps. */
1694
+ relayIngest(tuples: IngestTuple[], exceptTabId?: TabId): void;
1695
+ get followerCount(): number;
1696
+ get relayedBatches(): number;
1697
+ }
1698
+ /** Follower half of the syncPort. Queues while detached (leaderless window)
1699
+ * and flushes on rebind; a lost-in-flight mutation notify is additionally
1700
+ * backstopped by the new leader reloading the shared outbox from the store. */
1701
+ declare class SyncForwarder {
1702
+ private tabId;
1703
+ private port;
1704
+ private queued;
1705
+ onLeaderMessage: ((msg: LeaderToFollowerMessage) => void) | null;
1706
+ constructor(tabId: TabId);
1707
+ rebind(port: MessagePort): void;
1708
+ unbind(): void;
1709
+ private post;
1710
+ mutationEnqueued(mutationId: string): void;
1711
+ /** An optimistic write this tab just ingested. Deliberately NOT queued while
1712
+ * detached: a new leader primes its circuit from the shared store, which
1713
+ * already holds the row, and replaying a stale tuple at it later would put
1714
+ * an older `_00_rv` in its version memo. */
1715
+ ingest(tuples: IngestTuple[]): void;
1716
+ requestPoll(): void;
1717
+ }
1718
+ declare class TabsCoordinator {
1719
+ private deps;
1720
+ role: TabRole$1;
1721
+ leadershipId: number;
1722
+ leaderTabId: TabId | null;
1723
+ brokerRole: 'pending' | TabRole$1;
1724
+ /** Wall time from `become-leader` to `leader-ready` on the last promotion.
1725
+ * Reported in the DevTools role-change event: a slow store adopt (OPFS pool
1726
+ * contention after the previous leader died) shows up here as seconds. */
1727
+ lastPromotionMs: number | null;
1728
+ private fingerprint;
1729
+ private bucketId;
1730
+ private broker;
1731
+ private hub;
1732
+ private forwarder;
1733
+ private roleListeners;
1734
+ private startResolve;
1735
+ private startReject;
1736
+ /** Ports received before start() resolves or between roles. */
1737
+ private promotionChain;
1738
+ private closed;
1739
+ constructor(deps: {
1740
+ tabId: TabId;
1741
+ fingerprint: string;
1742
+ hooks: CoordinatorHooks;
1743
+ logger: Logger$1;
1744
+ /** Fired on pagehide while this tab leads: last-chance OPFS release. */
1745
+ onLeaderPageHide?: () => void;
1746
+ });
1747
+ /** Serialize role transitions; each is small but async (worker opens). */
1748
+ private enqueue;
1749
+ onRoleChange(cb: (role: TabRole$1) => void): () => void;
1750
+ private setRole;
1751
+ /** Connect the broker and resolve once this tab has a usable store role.
1752
+ * Rejects when no role lands in time; the caller then boots solo. */
1753
+ start(bucketId: string): Promise<TabRole$1>;
1754
+ /** Bucket switch: leave the old namespace, join the new one. Resolves when
1755
+ * a role lands in the new namespace. */
1756
+ moveToBucket(bucketId: string): Promise<TabRole$1>;
1757
+ private promote;
1758
+ private demote;
1759
+ private tabLock;
1760
+ private teardownLeader;
1761
+ private teardownFollower;
1762
+ private serveFollower;
1763
+ private attachToLeader;
1764
+ private handleLeaderGone;
1765
+ private fallbackToSolo;
1766
+ get syncHub(): LeaderSyncHub | null;
1767
+ get syncForwarder(): SyncForwarder | null;
1768
+ get tabId(): TabId;
1769
+ stop(): Promise<void>;
1770
+ }
1771
+ //#endregion
1772
+ //#region src/services/blobs/blob-store.d.ts
1773
+ /**
1774
+ * Byte storage for cached bucket files.
1775
+ *
1776
+ * The default implementation is OPFS. Bucket files never arrive over HTTP in
1777
+ * this client — `BucketHandle.get()` is a SurrealQL RPC on the sync socket — so
1778
+ * neither the browser's HTTP cache nor the Cache API can hold them. We persist
1779
+ * the bytes ourselves, and OPFS is the cheapest place to put them: a read is
1780
+ * `getFile()` → a disk-backed lazy `File` that `URL.createObjectURL` can serve
1781
+ * without ever moving the bytes through the JS heap.
1782
+ *
1783
+ * Layout is real nested directories rather than one hashed filename:
1784
+ *
1785
+ * sp00ky-blobs/<namespace>/<bucket>/<...path segments>
1786
+ *
1787
+ * That costs a `getDirectoryHandle` per segment on write, and buys the property
1788
+ * the whole orphan story rests on: the full `(bucket, path)` key is recoverable
1789
+ * from a directory walk alone. The `_00_blob` manifest can therefore be wiped
1790
+ * (memory fallback, SQLite pool wipe, IndexedDB corruption recovery) and be
1791
+ * rebuilt from disk instead of taking the cached bytes down with it.
1792
+ */
1793
+ /** Identifies one cached file: the bucket it lives in and its path within. */
1794
+ interface BlobKey {
1795
+ bucket: string;
1796
+ path: string;
1797
+ }
1798
+ /** What a directory walk can tell us about a stored file, with no manifest. */
1799
+ interface BlobStat {
1800
+ key: BlobKey;
1801
+ size: number;
1802
+ /** File mtime. Seeds `lastAccess` when a manifest row has to be rebuilt. */
1803
+ mtime: number;
1804
+ }
1805
+ interface BlobStore {
1806
+ /** False for {@link MemoryBlobStore} and for OPFS-less environments: the
1807
+ * cache still dedupes and serves within a tab, but nothing survives reload. */
1808
+ readonly persistent: boolean;
1809
+ /** Namespace (the local bucketId) all keys are resolved under. */
1810
+ readonly namespace: string;
1811
+ read(key: BlobKey): Promise<Blob | null>;
1812
+ /** Returns the number of bytes written. Throws on quota exhaustion. */
1813
+ write(key: BlobKey, bytes: Blob): Promise<number>;
1814
+ remove(key: BlobKey): Promise<void>;
1815
+ /** Every committed file under the current namespace. Sweeps torn writes. */
1816
+ list(): Promise<BlobStat[]>;
1817
+ /** Drop the whole namespace (sign-out with `clearOnSignOut`, or a reset). */
1818
+ clear(): Promise<void>;
1819
+ /** Point at another namespace. Does not touch the bytes of the old one. */
1820
+ setNamespace(namespace: string): void;
1821
+ }
1822
+ //#endregion
1823
+ //#region src/services/blobs/blob-manifest.d.ts
1824
+ interface BlobEntry {
1825
+ /** `${bucket}/${path}` — also the `_00_blob` row id. */
1826
+ id: string;
1827
+ bucket: string;
1828
+ path: string;
1829
+ size: number;
1830
+ contentType: string;
1831
+ createdAt: number;
1832
+ lastAccess: number;
1833
+ hits: number;
1834
+ /** Exempt from pressure eviction. Never expires on its own. */
1835
+ pinned: boolean;
1836
+ }
1837
+ declare class BlobManifest {
1838
+ private local;
1839
+ private entries;
1840
+ /** Ids whose in-memory state has not been written back yet. */
1841
+ private dirty;
1842
+ private removed;
1843
+ private flushing;
1844
+ constructor(local: LocalStore);
1845
+ /**
1846
+ * Hydrate from the rows matching `keys`. Ids come from the OPFS listing, so
1847
+ * this never needs a full-table scan (and therefore never needs a QueryPlan).
1848
+ * Any read failure yields an empty manifest: reconcile then rebuilds every
1849
+ * row from disk, which is exactly the desired degradation.
1850
+ */
1851
+ load(ids: string[]): Promise<void>;
1852
+ get(key: BlobKey): BlobEntry | undefined;
1853
+ getById(id: string): BlobEntry | undefined;
1854
+ all(): BlobEntry[];
1855
+ totalBytes(): number;
1856
+ pinnedBytes(): number;
1857
+ put(entry: BlobEntry): void;
1858
+ touch(id: string, now: number): void;
1859
+ setPinned(id: string, pinned: boolean): boolean;
1860
+ remove(id: string): void;
1861
+ /** Forget everything without scheduling deletes — for a bucket switch, where
1862
+ * the rows belong to the store we are leaving and must stay put. */
1863
+ reset(): void;
1864
+ hasPendingWrites(): boolean;
1865
+ /**
1866
+ * Write back pending changes. Serialized: a second concurrent flush awaits
1867
+ * the first rather than racing it into the same rows. Failures are swallowed
1868
+ * on purpose — a lost metadata write costs an LRU timestamp, and the entry is
1869
+ * rebuilt from disk on the next reconcile.
1870
+ */
1871
+ flush(): Promise<void>;
1872
+ private doFlush;
1873
+ }
1874
+ //#endregion
1875
+ //#region src/services/blobs/blob-cache.d.ts
1876
+ interface BlobUrlLease {
1877
+ url: string;
1878
+ release(): void;
1879
+ }
1880
+ interface BlobReadOptions {
1881
+ /** Write through to L1 on a miss. Default true. */
1882
+ persist?: boolean;
1883
+ /** Mark the entry exempt from pressure eviction. */
1884
+ pin?: boolean;
1885
+ /**
1886
+ * Default `'never'`: a bucket path is treated as immutable, which is how the
1887
+ * client writes them (`crypto.randomUUID() + ext`). `'head'` spends a remote
1888
+ * `head()` to compare sizes before trusting L1.
1889
+ */
1890
+ revalidate?: 'never' | 'head';
1891
+ /** Skip L0/L1 entirely and refill from remote. Backs `refetch()`. */
1892
+ reload?: boolean;
1893
+ }
1894
+ interface BlobCacheStats {
1895
+ entries: number;
1896
+ totalBytes: number;
1897
+ budgetBytes: number;
1898
+ pinnedBytes: number;
1899
+ evictedEntries: number;
1900
+ evictedBytes: number;
1901
+ reconciledEntries: number;
1902
+ hits: number;
1903
+ misses: number;
1904
+ persistent: boolean;
1905
+ /** True when pinned bytes alone exceed the budget: new entries stop being
1906
+ * written rather than pinned ones being thrown away. */
1907
+ persistPaused: boolean;
1908
+ }
1909
+ interface BlobCacheOptions {
1910
+ store: BlobStore;
1911
+ manifest: BlobManifest;
1912
+ /** L2 read. Resolves to null when the file does not exist remotely. */
1913
+ fetchRemote(key: BlobKey): Promise<Blob | null>;
1914
+ /** L2 metadata, for `revalidate: 'head'`. */
1915
+ headRemote?(key: BlobKey): Promise<Record<string, unknown> | null>;
1916
+ logger: Logger$1;
1917
+ maxBytes: number;
1918
+ now?: () => number;
1919
+ /** Injected so the URL layer is exercisable off a DOM (node tests). */
1920
+ urls?: {
1921
+ create(blob: Blob): string;
1922
+ revoke(url: string): void;
1923
+ };
1924
+ }
1925
+ declare class BlobCache {
1926
+ private readonly store;
1927
+ private readonly manifest;
1928
+ private readonly fetchRemote;
1929
+ private readonly headRemote?;
1930
+ private readonly logger;
1931
+ private readonly now;
1932
+ private readonly urlFactory;
1933
+ private maxBytes;
1934
+ private persistPaused;
1935
+ /** Set after a quota failure survives one forced eviction. */
1936
+ private persistDisabled;
1937
+ private readonly urls;
1938
+ /** Ids at zero references, oldest first — the hot-URL window. */
1939
+ private idleUrls;
1940
+ private readonly inflight;
1941
+ private flushTimer;
1942
+ private readonly onPageHide;
1943
+ /**
1944
+ * Resolves once the manifest has been reconciled against disk. Reads await
1945
+ * it, so `start()` does NOT have to be awaited on the boot path — blocking
1946
+ * boot on an OPFS directory walk delayed the WebSocket connect (and with it
1947
+ * the connection supervisor) for no benefit.
1948
+ */
1949
+ private ready;
1950
+ private hits;
1951
+ private misses;
1952
+ private evictedEntries;
1953
+ private evictedBytes;
1954
+ private reconciledEntries;
1955
+ constructor(opts: BlobCacheOptions);
1956
+ /** Coalesce manifest write-back. Metadata only, so losing the tail costs an
1957
+ * LRU timestamp that reconcile reseeds from the file mtime. */
1958
+ private scheduleFlush;
1959
+ /**
1960
+ * Resolve the bytes for `key`, filling L1 on the way when `persist` is on.
1961
+ * Returns null when the file does not exist remotely and is not cached.
1962
+ */
1963
+ read(key: BlobKey, options?: BlobReadOptions): Promise<Blob | null>;
1964
+ /**
1965
+ * An object URL for `key`, refcounted. Callers MUST `release()`; the URL is
1966
+ * revoked once the last holder lets go and it falls out of the hot window.
1967
+ */
1968
+ acquireUrl(key: BlobKey, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
1969
+ private lease;
1970
+ private releaseUrl;
1971
+ private revokeUrl;
1972
+ /** L1 lookup with the size check that catches torn and cross-tab writes. */
1973
+ private readLocal;
1974
+ /** True when the remote agrees with the cached size, or cannot be reached. */
1975
+ private headMatches;
1976
+ private fetchDeduped;
1977
+ private persist;
1978
+ private writeThrough;
1979
+ /** Forget one path everywhere. Called on `bucket.put()`/`bucket.delete()`. */
1980
+ invalidate(key: BlobKey): Promise<void>;
1981
+ private dropLocal;
1982
+ setPinned(key: BlobKey, pinned: boolean): void;
1983
+ /**
1984
+ * Bring total bytes under budget by dropping the least recently used
1985
+ * entries. Pinned entries and anything with a live object URL are skipped —
1986
+ * evicting bytes that a mounted `<img>` is displaying would blank it.
1987
+ */
1988
+ private enforceBudget;
1989
+ /** Evict LRU-first until at or below `target`. Returns the resulting total. */
1990
+ private evictTo;
1991
+ /**
1992
+ * Rebuild the manifest from what is actually on disk. OPFS wins on existence
1993
+ * in both directions: files with no row get a row (seeded from mtime), rows
1994
+ * are only loaded for files that exist, and torn `.part-` writes are swept by
1995
+ * the walk itself.
1996
+ *
1997
+ * Rows whose file vanished outside our control (a browser origin eviction)
1998
+ * are left in `_00_blob`. They are inert — `load()` only ever asks for ids it
1999
+ * found on disk — and are overwritten if that path is cached again.
2000
+ */
2001
+ reconcile(): Promise<void>;
2002
+ /** Warm the cache for offline use. Skips anything already cached. */
2003
+ prefetch(keys: BlobKey[]): Promise<void>;
2004
+ /** Bind to the boot bucket and hydrate the manifest from disk. Separate from
2005
+ * {@link setNamespace} because boot must reconcile even when the namespace
2006
+ * it lands on is the one the store was constructed with. */
2007
+ start(namespace: string): Promise<void>;
2008
+ /** Repoint at another local bucket. The bytes of the old one stay on disk so
2009
+ * switching back (or signing back in) is still warm. */
2010
+ setNamespace(namespace: string): Promise<void>;
2011
+ setMaxBytes(maxBytes: number): void;
2012
+ /** Delete every cached byte in the current namespace. */
2013
+ clear(): Promise<void>;
2014
+ flush(): Promise<void>;
2015
+ /** Flush metadata and drop every object URL. Must run before the local store
2016
+ * closes — the flush writes through it. */
2017
+ close(): Promise<void>;
2018
+ stats(): BlobCacheStats;
2019
+ }
2020
+ //#endregion
2021
+ //#region src/client/services.d.ts
2022
+ /** Everything the facade talks to besides the runtime. */
2023
+ interface Services<S extends SchemaStructure> {
2024
+ logger: Logger$1;
2025
+ /** What the logger wrote, for the DevTools Logs tab. Absent in test fakes. */
2026
+ logTap?: LogTap;
2027
+ local: LocalStore;
2028
+ remote: RemoteDatabaseService;
2029
+ connectionSupervisor: ConnectionSupervisor;
2030
+ blobs: BlobCache;
2031
+ persistence: PersistenceClient;
2032
+ streamProcessor: StreamProcessorService;
2033
+ migrator: LocalMigrator;
2034
+ crdt: CrdtManager;
2035
+ auth: AuthService<S>;
2036
+ tabs: TabsCoordinator | null;
2037
+ tabsUnsupportedReason: string | undefined;
2038
+ tabId: string;
2039
+ }
2040
+ /** What the services need back from the runtime once it exists. */
2041
+ //#endregion
2042
+ //#region src/utils/blurhash.d.ts
2043
+ /**
2044
+ * Blurhash generation settings. `true` enables with the defaults below, `false`
2045
+ * disables. Resolution order for a put: per-call option > client config >
2046
+ * default ON. See {@link Sp00kyConfig.blurhash}.
2047
+ */
2048
+ type BlurhashSetting = boolean | BlurhashEncodeOptions;
2049
+ interface BlurhashEncodeOptions {
2050
+ /** Horizontal detail components, 1-9. Defaults to 4. */
2051
+ componentX?: number;
2052
+ /** Vertical detail components, 1-9. Defaults to 3. */
2053
+ componentY?: number;
2054
+ }
2055
+ /**
2056
+ * Where an image's blurhash lives: a tiny sidecar object in the same bucket.
2057
+ * Buckets have no per-object metadata channel (`put` is just `.put($content)`),
2058
+ * so the hash for `covers/x_t.webp` is the text object `covers/x_t.webp.bh`.
2059
+ */
2060
+ declare function blurhashSidecarPath(path: string): string;
2061
+ /** Extensions `bucket.put` treats as images worth hashing. */
2062
+ declare const BLURHASH_IMAGE_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif", "avif", "bmp"];
2063
+ declare function isImagePath(path: string): boolean;
2064
+ /**
2065
+ * Decode `content` as an image and compute its blurhash. Browser-only: returns
2066
+ * null (never throws) when image decoding is unavailable (node, workers without
2067
+ * canvas), when the bytes are not a decodable image, or on any other failure —
2068
+ * a missing hash must never break the upload that triggered it.
2069
+ */
2070
+ declare function encodeImageToBlurhash(content: string | Uint8Array | Blob, options?: BlurhashEncodeOptions): Promise<string | null>;
2071
+ //#endregion
2072
+ //#region src/client/bucket-handle.d.ts
2073
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
2074
+ declare function bucketContentToBlob(content: unknown): Blob | null;
2075
+ interface BucketPutOptions {
2076
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
2077
+ blurhash?: BlurhashSetting;
2078
+ }
2079
+ interface BucketPutResult {
2080
+ /** The computed blurhash when the content was a hashable image; else null. */
2081
+ blurhash: string | null;
2082
+ }
2083
+ interface BucketHandleSettings {
2084
+ blurhash?: BlurhashSetting;
2085
+ logger?: {
2086
+ warn: (obj: unknown, msg?: string) => void;
2087
+ };
2088
+ /** The bucket's backend as generated (`'r2'`: files live with the SSP). */
2089
+ backend?: string;
2090
+ /** {@link Sp00kyConfig.files}: where `r2` bucket files are read and written. */
2091
+ files?: {
2092
+ endpoint?: string;
2093
+ };
2094
+ }
2095
+ /** A handle's settings from the client config and the bucket's generated schema. */
2096
+
1057
2097
  declare class BucketHandle {
1058
2098
  private bucketName;
1059
- private remote;
1060
- constructor(bucketName: string, remote: RemoteDatabaseService);
1061
- put(path: string, content: string | Uint8Array | Blob): Promise<void>;
2099
+ /** Absent on the raw handle the cache itself reads through. */
2100
+ private blobs?;
2101
+ private settings?;
2102
+ /**
2103
+ * Resolves once the client is open; nothing to wait for when it already
2104
+ * is. Every call below awaits it, so a file asked for by a component that
2105
+ * rendered before the client was ready (a provider's `eager` mode) is
2106
+ * fetched then, where it used to fail for want of a connection.
2107
+ */
2108
+ private opened?;
2109
+ private io;
2110
+ constructor(bucketName: string, remote: RemoteDatabaseService, /** Absent on the raw handle the cache itself reads through. */
2111
+ blobs?: (BlobCache | null) | undefined, settings?: BucketHandleSettings | undefined,
2112
+ /**
2113
+ * Resolves once the client is open; nothing to wait for when it already
2114
+ * is. Every call below awaits it, so a file asked for by a component that
2115
+ * rendered before the client was ready (a provider's `eager` mode) is
2116
+ * fetched then, where it used to fail for want of a connection.
2117
+ */
2118
+ opened?: (() => Promise<void> | undefined) | undefined);
2119
+ /** Effective blurhash setting: per-call option > client config > default ON. */
2120
+ private resolveBlurhash;
2121
+ put(path: string, content: string | Uint8Array | Blob, options?: BucketPutOptions): Promise<BucketPutResult>;
2122
+ /**
2123
+ * The blurhash stored alongside an uploaded image (see
2124
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
2125
+ * blob cache, so a warm client answers from OPFS without a network hop, and
2126
+ * misses are remembered per tab so a hashless image costs at most one
2127
+ * serialized remote read per session.
2128
+ */
2129
+ blurhash(path: string): Promise<string | null>;
1062
2130
  get(path: string): Promise<unknown>;
2131
+ /**
2132
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
2133
+ * {@link get} this survives a reload and works offline. Returns null when the
2134
+ * file exists in neither place.
2135
+ */
2136
+ read(path: string, options?: BlobReadOptions): Promise<Blob | null>;
2137
+ /**
2138
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
2139
+ * MUST call `release()` when the URL goes off screen. Returns null when the
2140
+ * file does not exist, or when object URLs are unavailable (non-browser).
2141
+ */
2142
+ url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null>;
2143
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
2144
+ pin(path: string): void;
2145
+ unpin(path: string): void;
2146
+ /** Drop `path` from the local cache without touching the remote file. */
2147
+ evict(path: string): Promise<void>;
2148
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
2149
+ prefetch(paths: string[]): Promise<void>;
1063
2150
  delete(path: string): Promise<void>;
1064
2151
  exists(path: string): Promise<boolean>;
1065
2152
  head(path: string): Promise<Record<string, unknown>>;
@@ -1067,123 +2154,363 @@ declare class BucketHandle {
1067
2154
  rename(sourcePath: string, targetPath: string): Promise<void>;
1068
2155
  list(prefix?: string): Promise<string[]>;
1069
2156
  }
2157
+ //#endregion
2158
+ //#region src/client/sp00ky-client.d.ts
2159
+ interface Sp00kyClientDeps<S extends SchemaStructure> {
2160
+ services?: Services<S>;
2161
+ runtime?: Runtime;
2162
+ env?: Partial<SagaEnv>;
2163
+ }
1070
2164
  declare class Sp00kyClient<S extends SchemaStructure> {
1071
- private config;
1072
- private local;
1073
- private remote;
1074
- private persistenceClient;
1075
- private migrator;
1076
- private cache;
1077
- private dataModule;
1078
- private sync;
1079
- private devTools;
1080
- private crdtManager;
1081
- private featureFlags;
1082
- private logger;
1083
- auth: AuthService<S>;
1084
- streamProcessor: StreamProcessorService;
1085
- get remoteClient(): surrealdb0.Surreal;
1086
- get localClient(): surrealdb0.Surreal;
1087
- get pendingMutationCount(): number;
1088
- /** Number of times the initial list_ref LIVE subscription retried on
1089
- * the most recent `setCurrentUserId` call. 0 when the SSP's
1090
- * pre-emptive user-table creation got there first; >0 when LIVE
1091
- * registration hit a "table not found" race. Exposed so the e2e
1092
- * suite can guard the pre-emptive path against regression. */
1093
- get liveRetryCount(): number;
1094
- subscribeToPendingMutations(cb: (count: number) => void): () => void;
1095
- /** Current sync-health snapshot. See {@link Sp00kyConfig.syncHealth}. */
1096
- get syncHealth(): SyncHealth;
2165
+ private readonly config;
2166
+ readonly auth: AuthService<S>;
2167
+ readonly streamProcessor: StreamProcessorService;
2168
+ /** Web Push for this browser: subscribe, devices, self-pushes, service worker bridge. */
2169
+ readonly webPush: WebPushModule;
2170
+ /** Peer to peer channels of `-- @channel` tables. */
2171
+ private readonly channels;
2172
+ private readonly services;
2173
+ private readonly env;
2174
+ private readonly runtime;
2175
+ private readonly featureFlags;
2176
+ private readonly appReleases;
2177
+ /** Teardown for subscriptions the client itself owns. */
2178
+ private readonly disposers;
2179
+ /** Assigned in `wireAdapters`, which the constructor always runs. */
2180
+ private impersonationBanner;
2181
+ private readonly devTools;
2182
+ private hub;
2183
+ private forwarder;
2184
+ private detachWindow;
2185
+ private sharedActive;
2186
+ constructor(config: Sp00kyConfig<S>, deps?: Sp00kyClientDeps<S>);
2187
+ /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
2188
+ private wireAdapters;
2189
+ /** Runtime events the DevTools panel follows; query transitions also go to the log. */
2190
+ private forwardToDevTools;
2191
+ /** Settled by `init`: what a call made before the client is open waits on. */
2192
+ private ready;
2193
+ init(): Promise<void>;
1097
2194
  /**
1098
- * Observe sync health. Fires immediately with the current status and again
1099
- * on every healthy↔degraded transition. Returns an unsubscribe.
2195
+ * Resolves once `init()` has finished, and rejects with its error if it
2196
+ * fails. A page that renders before the client is open (a provider's
2197
+ * `eager` mode) awaits this for whatever must not run earlier.
1100
2198
  */
1101
- subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
1102
- constructor(config: Sp00kyConfig<S>);
2199
+ whenReady(): Promise<void>;
1103
2200
  /**
1104
- * Setup direct callbacks instead of event subscriptions
2201
+ * Queries and writes need the open client: its store, its session. Asked
2202
+ * for earlier, they wait for `init()` to finish, so a component may register
2203
+ * a query on its first render and need not know whether the client is open.
1105
2204
  */
1106
- private setupCallbacks;
1107
- init(): Promise<void>;
2205
+ private opened;
1108
2206
  close(): Promise<void>;
2207
+ isLocalReady(): boolean;
2208
+ query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
2209
+ private registerInput;
2210
+ private initQuery;
1109
2211
  /**
1110
- * Subscribe to a feature flag for the current user. Returns a
1111
- * `FeatureFlagHandle` whose `variant()`, `payload()` and `enabled()`
1112
- * accessors reflect the latest assignment from `_00_user_feature`,
1113
- * and whose `subscribe(cb)` fires whenever that assignment changes.
2212
+ * The rows this query rendered the last time this browser had the app open,
2213
+ * handed back at once and with no need for `init()` to have run: something
2214
+ * for a component to render on its first pass, where it would have rendered
2215
+ * an empty list. `null` when the local store keeps no such copy (only
2216
+ * `localEngine: 'rows'` with its paint cache does, and not with shared
2217
+ * tabs), or has none for this query.
1114
2218
  *
1115
- * Permissions are enforced by SurrealDB: a client can only ever see
1116
- * its own row, and cannot create or modify assignments.
2219
+ * They are rows to paint from, not a result. The query still has to be run
2220
+ * and subscribed to; what that delivers is the answer, and it replaces these
2221
+ * rows when it differs.
1117
2222
  */
1118
- feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
1119
- authenticate(token: string): Promise<surrealdb0.Tokens>;
2223
+ peekQuery(finalQuery: FinalQuery<S, any, any, any, any, any>): Record<string, any>[] | null;
1120
2224
  /**
1121
- * Open a CRDT field for collaborative editing.
1122
- * Returns a CrdtField with a LoroDoc that can be bound to any editor.
1123
- * Also starts a LIVE SELECT on the parent table for real-time sync;
1124
- * incoming events trigger a subquery fetch of `_00_crdt` / `_00_cursor`.
2225
+ * The raw remote escape hatches bypass the query builder, so their shapes
2226
+ * can never be on the server's query allowlist. When the generated schema
2227
+ * says the allowlist is on, refuse them unless the app opted in explicitly.
1125
2228
  */
1126
- openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField>;
2229
+ private assertRawRemoteAllowed;
2230
+ queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
1127
2231
  /**
1128
- * Close a CRDT field when editing is done.
2232
+ * Preload = register a query nobody subscribes to. Resolved before on this
2233
+ * device: returns at once. Never resolved: resolves when the server's
2234
+ * membership and every body are local. `signal` aborts the wait.
1129
2235
  */
1130
- closeCrdtField(table: string, recordId: string, field: string): void;
1131
- deauthenticate(): Promise<void>;
1132
- query<Table extends TableNames<S>>(table: Table, options: QueryOptions<TableModel<GetTable<S, Table>>, false>, ttl?: QueryTimeToLive): QueryBuilder<S, Table, Sp00kyQueryResultPromise>;
1133
- private initQuery;
1134
- queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string>;
2236
+ preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void>;
1135
2237
  subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: {
1136
2238
  immediate?: boolean;
1137
2239
  }): Promise<() => void>;
1138
2240
  /**
1139
- * Opt-in eager teardown for a query whose last subscriber has gone away
1140
- * (e.g. a viewport-windowed list cancelling an off-screen window). No-op
1141
- * while any subscriber remains. Tears down the remote `_00_query` view +
1142
- * local WASM view instead of waiting for the TTL sweep. Default behavior
1143
- * (no call here) keeps the view resident for cheap re-subscription.
2241
+ * Open a peer to peer channel to `peers` (your own id is skipped; a
2242
+ * connection forms only when both sides list each other) for the rows
2243
+ * `queries` match, each a query on a `-- @channel` table. Only its `where`
2244
+ * counts, evaluated against each row; the query is never registered. Writes
2245
+ * to matching rows (plain or the channel's own) reach the peers. Close it
2246
+ * when done.
1144
2247
  */
1145
- deregisterQuery(queryHash: string): void;
2248
+ channel<T extends ChannelTableNames<S>>(queries: ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>, peers: Iterable<ChannelPeer>): Sp00kyChannel<S, T>;
1146
2249
  /**
1147
- * Subscribe to a query's fetch-status changes (idle/fetching). With
1148
- * `{ immediate: true }` the callback fires synchronously with the current
1149
- * status. Powers the `useQuery` hook's `isFetching()` accessor.
2250
+ * The link to this user's other devices (`channels.share`): `connected`
2251
+ * with the user's id in `peers` while at least one other tab of theirs, in
2252
+ * another browser, is in the room. `idle` when nothing is shared or nobody
2253
+ * is signed in.
1150
2254
  */
2255
+ shareState(): ChannelState;
2256
+ /** Called at once with `shareState()`, then on every change. */
2257
+ subscribeShareState(callback: (state: ChannelState) => void): () => void;
2258
+ private channelScopes;
2259
+ deregisterQuery(queryHash: string): void;
1151
2260
  subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: {
1152
2261
  immediate?: boolean;
1153
2262
  }): () => void;
1154
- /**
1155
- * Report the frontend processing time (ms) a client framework spent applying
1156
- * an update for a query (e.g. `useQuery`'s `reconcile()`), so DevTools/MCP can
1157
- * surface the "frontend" phase of the per-query timing breakdown.
1158
- */
2263
+ subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: {
2264
+ immediate?: boolean;
2265
+ }): () => void;
1159
2266
  reportFrontendTiming(queryHash: string, ms: number): void;
1160
- run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
1161
- bucket<B extends BucketNames<S>>(name: B): BucketHandle;
1162
- create(id: string, data: Record<string, unknown>): Promise<Record<string, unknown>>;
1163
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions): Promise<{
1164
- [x: string]: /*elided*/any;
1165
- }>;
2267
+ create<T extends Record<string, unknown>>(id: string, data: T): Promise<T>;
2268
+ update<T extends Record<string, unknown>>(table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T>;
1166
2269
  delete(table: string, id: string): Promise<void>;
2270
+ private writeCreate;
2271
+ private writeUpdate;
2272
+ private writeDelete;
2273
+ run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void>;
2274
+ get failedMutationCount(): number;
2275
+ subscribeToFailedMutations(cb: (count: number) => void): () => void;
2276
+ listFailedMutations(): Promise<FailedMutationRow[]>;
2277
+ retryFailedMutation(mutationId: string): Promise<boolean>;
2278
+ discardFailedMutation(mutationId: string): Promise<boolean>;
2279
+ get tabRole(): TabRole$1 | null;
2280
+ get remoteClient(): Surreal;
2281
+ get localClient(): unknown;
2282
+ get pendingMutationCount(): number;
2283
+ /** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
2284
+ get liveRetryCount(): number;
2285
+ subscribeToPendingMutations(cb: (count: number) => void): () => void;
2286
+ get fetchingQueryCount(): number;
2287
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void;
2288
+ get syncHealth(): SyncHealth;
2289
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void;
2290
+ get storageHealth(): StorageHealth;
2291
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void;
2292
+ /** The engine state, read-only. For tests and DevTools. */
2293
+ get state(): ClientState;
2294
+ /** Feed an event into the engine. For adapters, tests and DevTools. */
2295
+ dispatch(event: RuntimeEvent): Promise<void>;
2296
+ authenticate(token: string): Promise<surrealdb0.Tokens>;
2297
+ deauthenticate(): Promise<void>;
1167
2298
  useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T>;
2299
+ remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
1168
2300
  /**
1169
- * Fetch SurrealDB's `session::id()` as a string. Used as a salt for
1170
- * query-id hashing so two sessions for the same user get distinct
1171
- * `_00_query` rows. Returns empty string if the query fails (we still
1172
- * boot, just without session scoping for IDs).
2301
+ * Tell the client that the app's own impersonation banner is on screen.
2302
+ * Only meaningful with `impersonationBanner: { mode: 'custom' }`, where it
2303
+ * cancels the fallback that would otherwise show the built-in banner. Call
2304
+ * it while the custom banner is rendered (the Solid `useImpersonation`
2305
+ * hook does it for you with `rendersBanner: true`).
1173
2306
  */
1174
- private fetchSessionId;
2307
+ acknowledgeImpersonationBanner(): void;
2308
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle;
2309
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void;
2310
+ clearFeatureOverrides(): void;
2311
+ getFeatureOverrides(): Record<string, FeatureFlagOverride>;
2312
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle;
2313
+ /** Open a `@crdt` field for editing. `draft` (from {@link createCrdtDraft})
2314
+ * hands over edits made before the record existed. */
2315
+ openCrdtField(table: string, recordId: string, field: string, draft?: CrdtField): Promise<CrdtField>;
2316
+ /** A detached `@crdt` document for a record not created yet; see
2317
+ * {@link openCrdtField}. */
2318
+ createCrdtDraft(table: string, field: string): Promise<CrdtField>;
2319
+ /** Close a `@crdt` field. The last close resolves once its unsent edits
2320
+ * are queued in the outbox; offline, once they are saved on the device. */
2321
+ closeCrdtField(table: string, recordId: string, field: string): Promise<void>;
2322
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle;
2323
+ getBlobCacheStats(): BlobCacheStats;
1175
2324
  }
1176
2325
  //#endregion
1177
- //#region src/utils/index.d.ts
1178
- declare function fileToUint8Array(file: File | Blob): Promise<Uint8Array>;
2326
+ //#region src/modules/channel/room.d.ts
1179
2327
  /**
1180
- * Convert plain text to simple HTML paragraphs.
1181
- * Useful for seeding a rich-text editor (e.g. TipTap/ProseMirror) with fallback content.
2328
+ * The link between the browsers of one user.
2329
+ *
2330
+ * Every browser keeps one socket to the room relay (`sp00ky-relay`, see
2331
+ * `apps/relay`). The relay proves the user from the session token, puts the
2332
+ * socket into that user's room and forwards what the members send each
2333
+ * other without reading it. So a message is there after one hop to the relay
2334
+ * and one back, whatever network each device sits in, and nothing waits for
2335
+ * a connection to be negotiated.
2336
+ *
2337
+ * Two browsers alone in a room also open a WebRTC data channel to each other
2338
+ * (its offer and answer travel through the relay) and use it while it is up:
2339
+ * on one network that is a millisecond instead of a trip to the relay. A
2340
+ * third browser joining ends that, and everybody talks through the room.
2341
+ *
2342
+ * Nothing here is kept or retried: a message lost on the way is one the
2343
+ * normal sync delivers a moment later.
1182
2344
  */
1183
- declare function textToHtml(text: string): string;
2345
+ /** A browser in the room, by the id it joined with. */
2346
+ type RoomPeer = string;
2347
+ interface RoomLinkHooks {
2348
+ /** Who this browser is, or null while signed out. */
2349
+ self(): {
2350
+ user: string;
2351
+ peer: RoomPeer;
2352
+ } | null;
2353
+ onPeer(peer: RoomPeer, up: boolean): void;
2354
+ onMessage(from: RoomPeer, data: unknown): void;
2355
+ onStatus(status: 'connecting' | 'connected' | 'failed'): void;
2356
+ }
2357
+ interface RoomLink {
2358
+ /** Send to these browsers of the room, or (`null`) to all of them. Fire and forget. */
2359
+ send(to: ReadonlyArray<RoomPeer> | null, data: unknown): void;
2360
+ close(): void;
2361
+ }
2362
+ type RoomLinkFactory = (hooks: RoomLinkHooks) => RoomLink;
2363
+ interface RoomLinkOptions {
2364
+ /** The relay's WebSocket address. */
2365
+ url: string;
2366
+ /** The session token the relay proves the user with; null while there is none. */
2367
+ token: () => string | null;
2368
+ /** `false`: never open the direct link. */
2369
+ direct?: boolean;
2370
+ iceServers?: RTCIceServer[];
2371
+ logger?: Pick<Logger$1, 'debug' | 'warn'>;
2372
+ /** Injectable for tests and non-browser runtimes. */
2373
+ WebSocket?: typeof WebSocket;
2374
+ RTCPeerConnection?: typeof RTCPeerConnection;
2375
+ }
2376
+ declare function roomLink(hooks: RoomLinkHooks, opts: RoomLinkOptions): RoomLink;
1184
2377
  /**
1185
- * Helper for retrying DB operations with exponential backoff
2378
+ * One transport out of two: the user's own devices are reached through
2379
+ * `own` (the room), everybody else through `others` (the mesh between
2380
+ * users). Without `own`, the user's own devices are simply never reached.
1186
2381
  */
1187
-
2382
+ declare function splitTransport(own: ChannelTransportFactory | null, others: ChannelTransportFactory): ChannelTransportFactory;
2383
+ //#endregion
2384
+ //#region src/modules/channel/hub.d.ts
2385
+ /** The part of `navigator.locks` this needs. */
2386
+ interface HubLocks {
2387
+ request(name: string, callback: () => Promise<void>): Promise<unknown>;
2388
+ request(name: string, options: {
2389
+ mode: 'shared' | 'exclusive';
2390
+ }, callback: () => Promise<void> | void): Promise<unknown>;
2391
+ }
2392
+ /** The part of a `BroadcastChannel` this needs. */
2393
+ interface HubBus {
2394
+ postMessage(message: unknown): void;
2395
+ onmessage: ((event: {
2396
+ data: unknown;
2397
+ }) => void) | null;
2398
+ close(): void;
2399
+ }
2400
+ interface HubOptions {
2401
+ /** Names the room of one user in this browser; the lock and the bus carry it. */
2402
+ scope: (user: string) => string;
2403
+ /** Builds the browser's link. Called in the tab that holds it. */
2404
+ link: RoomLinkFactory;
2405
+ logger?: Pick<Logger$1, 'debug' | 'warn'>;
2406
+ /** `null` forces a link per tab. Default `navigator.locks`. */
2407
+ locks?: HubLocks | null;
2408
+ /** `null` forces a link per tab. Default `BroadcastChannel`. */
2409
+ bus?: ((name: string) => HubBus) | null;
2410
+ supported?: boolean;
2411
+ }
2412
+ declare function hubTransport(hooks: TransportHooks, opts: HubOptions): ChannelTransport;
2413
+ //#endregion
2414
+ //#region src/modules/channel/webrtc.d.ts
2415
+ /**
2416
+ * The default channel transport: one WebRTC data channel per pair of tabs,
2417
+ * set up through signaling rows in the database.
2418
+ *
2419
+ * Signaling (all rows of `_00_channel_signal`, read through one raw LIVE):
2420
+ *
2421
+ * 1. A tab that wants user U writes `hello` to U. Every tab of U hears it.
2422
+ * 2. Of each pair of tabs, the one with the lower `user#peer` key offers.
2423
+ * A tab that hears a hello from a higher key offers at once; one that
2424
+ * hears it from a lower key answers with a `hello` addressed back to that
2425
+ * tab, which then offers. So both orders of arrival connect, and nobody
2426
+ * loops.
2427
+ * 3. `offer` / `answer` carry the SDPs, `ice` batches of candidates
2428
+ * (trickled, so nothing waits for gathering to finish).
2429
+ *
2430
+ * A tab only ever reacts to signals from users it wants itself, so a
2431
+ * connection needs both sides to list each other. The database stamps every
2432
+ * row's `sender`, and the offer carries the DTLS fingerprint of the
2433
+ * connection, so the user on the other end of a data channel is proven.
2434
+ */
2435
+ type SignalKind = 'hello' | 'offer' | 'answer' | 'ice';
2436
+ interface Signal {
2437
+ readonly from: string;
2438
+ readonly fromPeer: string;
2439
+ readonly toPeer: string | null;
2440
+ readonly kind: SignalKind;
2441
+ readonly payload: string | null;
2442
+ }
2443
+ interface OutgoingSignal {
2444
+ readonly to: string;
2445
+ readonly toPeer: string | null;
2446
+ readonly fromPeer: string;
2447
+ readonly kind: SignalKind;
2448
+ readonly payload: string | null;
2449
+ }
2450
+ /** Where signals go and come from. The database by default. */
2451
+ interface SignalPort {
2452
+ send(signal: OutgoingSignal): Promise<void>;
2453
+ listen(self: PeerRef, cb: (signal: Signal) => void): () => void;
2454
+ }
2455
+ interface WebRtcOptions {
2456
+ signal: SignalPort;
2457
+ iceServers?: RTCIceServer[];
2458
+ logger?: Pick<Logger$1, 'debug' | 'warn'>;
2459
+ /** Injectable for tests and non-browser runtimes. */
2460
+ RTCPeerConnection?: typeof RTCPeerConnection;
2461
+ /** Give up on one attempt after this long. Default 15000. */
2462
+ connectTimeoutMs?: number;
2463
+ }
2464
+ declare function webrtcTransport(hooks: TransportHooks, opts: WebRtcOptions): ChannelTransport;
2465
+ /** The bits of the remote service signaling needs. */
2466
+ interface SignalRemote {
2467
+ query<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T>;
2468
+ getClient(): Pick<Surreal, 'liveOf'>;
2469
+ }
2470
+ interface SignalConnection {
2471
+ subscribe(cb: (state: ConnectionState) => void): () => void;
2472
+ }
2473
+ /**
2474
+ * Signals as rows of `_00_channel_signal` (generated for schemas with a
2475
+ * `@channel` table): a CREATE to send, one raw `LIVE SELECT` on rows
2476
+ * addressed to this user to receive. Not the outbox and not a synced query:
2477
+ * each signal costs one round trip, which is what keeps connection setup
2478
+ * short. The LIVE is re-armed whenever the socket reconnects.
2479
+ */
2480
+ declare function surrealSignal(remote: SignalRemote, connection: SignalConnection, logger?: Pick<Logger$1, 'debug' | 'warn'>): SignalPort;
2481
+ //#endregion
2482
+ //#region src/utils/semver.d.ts
2483
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
2484
+ declare function semverGt(a: unknown, b: unknown): boolean;
2485
+ //#endregion
2486
+ //#region src/services/database/errors.d.ts
2487
+ /**
2488
+ * A local-store operation that did not answer within its deadline.
2489
+ *
2490
+ * The local write path (`db.create` / `db.update` / `db.delete`, every local
2491
+ * query behind them) used to have no deadline anywhere: the SQLite worker
2492
+ * transport parks a call until the worker replies, the surrealdb engine's
2493
+ * query chain waits on the previous link, and `withRetry` retries without a
2494
+ * clock. One op that never settled (a worker starved behind a long select, a
2495
+ * lock verification awaiting `navigator.locks.query()` forever) left the
2496
+ * caller's promise pending for the tab's lifetime - a chat composer that never
2497
+ * re-enabled, a call that never got past "Connecting".
2498
+ *
2499
+ * The message says "timed out" on purpose: `classifySyncError` keys off it and
2500
+ * treats the failure as transient (re-queue), never as an application error
2501
+ * that rolls the mutation back. `retryable: false` keeps `withRetry` from
2502
+ * spinning on it: the op is still running in the engine, retrying queues a
2503
+ * second copy behind it.
2504
+ */
2505
+ declare class LocalOpTimeoutError extends Error {
2506
+ readonly name = "LocalOpTimeoutError";
2507
+ readonly retryable = false;
2508
+ readonly op: string;
2509
+ readonly timeoutMs: number;
2510
+ constructor(op: string, timeoutMs: number);
2511
+ }
2512
+ /** Default deadline for one local-store operation. Generous: a cold 4k-row
2513
+ * select on a throttled tab is seconds, not tens of seconds. */
2514
+ declare const DEFAULT_LOCAL_OP_TIMEOUT_MS = 30000;
1188
2515
  //#endregion
1189
- export { AuthEventSystem, AuthEventTypeMap, AuthEventTypes, AuthService, BucketHandle, CURSOR_COLORS, CrdtField, CrdtManager, DebounceOptions, EventSubscriptionOptions, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagSnapshot, Level, MATERIALIZATION_SAMPLE_WINDOW, MutationCallback, MutationEvent, MutationEventType, PersistenceClient, PhaseStat, PinoTransmit, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, RecordVersionArray, RecordVersionDiff, RegistrationTimings, RunOptions, Sp00kyClient, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, UpdateOptions, createAuthEventSystem, cursorColorFromName, fileToUint8Array, textToHtml };
2516
+ export { ActiveImpersonation, 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, type BridgeSignOutMessage, type BridgeTokenMessage, BucketHandle, BucketPutOptions, BucketPutResult, CURSOR_COLORS, type ChannelAcceptRule, type ChannelHandle, type ChannelMessage, type ChannelOp, ChannelQuery, type ChannelRelayConfig, type ChannelScope, type ChannelShareConfig, type ChannelShareRule, type ChannelState, type ChannelStatus, type ChannelTransport, type ChannelTransportFactory, type ChannelWire, type ChannelsConfig, ConnectionState, CrdtField, CrdtManager, DEFAULT_LOCAL_OP_TIMEOUT_MS, DebounceOptions, EdgeDelta, EventSubscriptionOptions, type FailedMutationRow as FailedMutation, FeatureFlagHandle, FeatureFlagModule, type FeatureFlagOptions, type FeatureFlagOverride, type FeatureFlagSnapshot, type HubOptions, IMPERSONATION_ACCESS, ImpersonationCandidate, ImpersonationInfo, ImpersonationTimerHost, ImpersonationTimers, InlineRow, type InterestMessage, Level, LocalOpTimeoutError, LocalWorkers, MATERIALIZATION_SAMPLE_WINDOW, MembershipOutcome, MutationCallback, MutationEvent, MutationEventType, ORIGIN_TOKEN_KEY, type OutgoingSignal, PUSH_ENDPOINT_KEY, PUSH_PAYLOAD_VERSION, type PeerRef, PersistenceClient, PhaseStat, PinoTransmit, PreloadOptions, PreloadRefresh, type PushDeviceKind, type PushNotification, type PushNotificationAction, type PushOp, type PushPayload, type PushPayloadKind, type PushUrgency, QueryAuthorityCallback, QueryConfig, QueryConfigRecord, QueryHash, QueryState, QueryStatus, QueryStatusCallback, QueryTimeToLive, QueryTimings, QueryUpdateCallback, REFUSAL_RECHECK_MIN_MS, ROWS_PREWARM_SNIPPET, ReconnectConfig, RecordVersionArray, RecordVersionDiff, RegistrationTimings, type RoomLink, type RoomLinkHooks, type RoomLinkOptions, RunOptions, SESSION_POLL_MS, SIGN_OUT_HOOK_TIMEOUT_MS, ServerViewMeta, SignOutContext, SignOutHook, type Signal, type SignalPort, Sp00kyChannel, Sp00kyClient, Sp00kyClientDeps, Sp00kyConfig, Sp00kyQueryResult, Sp00kyQueryResultPromise, StorageHealth, StorageHealthStatus, StoreType, SyncHealth, SyncHealthConfig, SyncHealthStatus, TimingPhase, TokenClaims, type TransportHooks, UpdateOptions, type WebPushClientMessage, type WebPushConfig, type WebPushDevice, WebPushError, type WebPushErrorCode, type WebPushInfo, type WebPushMessage, type WebPushMessageInput, WebPushModule, type WebPushSubscribeOptions, type WebPushSupport, type WebPushSyncOptions, type WebPushSyncStatus, type WebPushUnsubscribeOptions, type WebPushUnsupportedReason, type WebPushUpdateOptions, blurhashSidecarPath, bucketContentToBlob, createAuthEventSystem, cursorColorFromName, decode as decodeBlurhash, decodeTokenClaims, detectWebPushSupport, encode as encodeBlurhash, encodeImageToBlurhash, fileToUint8Array, hubTransport, impersonationFromToken, isBlurhashValid, isImagePath, isPushPayload, matchesWhere, prewarmRows, renewDelayMs, roomLink, sameImpersonation, semverGt, splitTransport, surrealSignal, textToHtml, unusedArgs, webrtcTransport };